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。

merge: integrate main through 4fcd7fcd

Yuewei-LL7449ca8c8045
diff --cc apps/desktop/src/main/cindy-brain/GhostManager.ts
index 74e6a0c390,f6276bc7e5..b573abab64
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@@ -7,13 -6,12 +7,15 @@@ import JSZip from 'jszip'
import {
GHOST_MANIFEST_FILE,
+ GHOST_MANIFEST_MAX_BYTES,
GHOST_LOCALE_MAX_BYTES,
+ GHOST_ICON_MAX_BYTES,
+ GHOST_INSTALL_MANIFEST_MAX_BYTES,
GHOST_SKILL_MD_MAX_BYTES,
ghostLocalePathFor,
+ ghostInstallApprovalToken,
ghostIconMimeType,
+ isOfficialGhostId,
isValidGhostId,
resolveGhostManifestLocale,
validateGhostManifest,
@@@ -24,26 -22,15 +26,27 @@@
type GhostTrustInfo,
type InstalledGhost,
} from '../../shared/ghost.js';
+import { verifyGhostZipSignatures, type GhostTrustRegistry } from './ghostSignature.js';
+import { isPathInsideDir } from './dirDeposit.js';
import {
- verifyGhostZipSignatures,
- type GhostTrustRegistry,
-} from './ghostSignature.js';
-import {
- readBoundedFileFollowLinks,
- readBoundedFileNoFollowSync,
-} from '../utils/readBoundedFile.js';
+ classifyGhostDirEntry,
+ classifyGhostDirEntrySync,
+ collectGhostContentFiles,
+ hashGhostContentBuffers,
+ hashGhostContentFiles,
+ resolveGhostContentPathSync,
+ type GhostDirEntryKind,
+} from './ghostContentTree.js';
++import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
import { checkSkillMdConsistency } from './skillSlot.js';
+import {
+ createGhostInstallReceipt,
+ GhostInstallReceiptStore,
+ hashApprovedSkillContent,
+ readLegacyInstallTrust,
+ type GhostInstallReceipt,
+ type GhostInstallReceiptReadResult,
+} from './ghostInstallReceipt.js';
/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */
export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;
@@@ -1641,58 -114,17 +1650,62 @@@ export class GhostManager
const result: InstalledGhost[] = [];
for (const entry of entries) {
- if (!entry.isDirectory()) continue;
if (entry.name.startsWith('.')) continue; // staging / 系统目录
const dir = path.join(root, entry.name);
- const manifestPath = path.join(dir, GHOST_MANIFEST_FILE);
+ // 判据走 ghostContentTree(lstat 分类),不信 Dirent 类型位:根子项是 junction/
+ // 链接时不算已装插件 —— 与迁移扫描、内容树遍历同一份判据(§3)。
+ try {
+ if (classifyGhostDirEntrySync(dir) !== 'directory') continue;
+ } catch {
+ continue; // lstat 不动(条目消失/权限)= 不算已装
+ }
+ if (!isValidGhostId(entry.name)) {
+ this.options.log?.warn('ghost dir skipped: invalid directory id', { dir });
+ continue;
+ }
+ const approvalResult = this.readApproval(entry.name);
+ if (approvalResult.state === 'approved') {
+ const receipt = approvalResult.receipt;
+ const localizedManifest = this.localizeApprovedManifest(receipt);
+ result.push({
+ manifest: localizedManifest,
+ dir,
+ enabled: this.effectiveEnabled(dir, receipt.enabled),
+ approval: { state: 'approved', revision: receipt.revision },
+ trust: receipt.trust,
+ ...(receipt.manifest.skill?.items.length
+ ? {
+ approvedSkillRoot: this.receiptStore.skillSnapshotRoot(
+ receipt.id,
+ receipt.revision,
+ ),
+ }
+ : {}),
+ ...(receipt.iconDataUrl !== undefined ? { iconDataUrl: receipt.iconDataUrl } : {}),
+ ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),
+ });
+ continue;
+ }
+ if (approvalResult.state === 'invalid') {
+ this.options.log?.warn('ghost approval receipt invalid; plugin kept disabled', {
+ id: entry.name,
+ reason: approvalResult.reason,
+ });
+ }
+
+ // 老安装没有 Host 批准快照,或快照损坏:只读取清单用于设置页恢复,
+ // 不把 live manifest / trust / enabled 当成运行授权。
let raw: unknown;
try {
- // 已安装目录也可能被外部进程/同步盘改动,且 list() 每次市场快照都会
- // 执行:单句柄限量闸(拒链接),不让无界字节进 main。
++ // 我们的逐段 no-follow 路径解析(拒符号链接段)+ main 的单句柄限量读(拒链接、
++ // 拒无界字节):已安装目录可能被外部/同步盘改动,list() 每次市场快照都跑,两道叠加。
+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {
+ expect: 'file',
+ label: 'installed manifest',
+ });
- raw = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ const bytes = readBoundedFileNoFollowSync(manifestPath, MAX_GHOST_MANIFEST_BYTES);
+ if (bytes === null) throw new Error('manifest is not a bounded regular file');
+ raw = JSON.parse(bytes.toString('utf-8'));
} catch (err) {
this.options.log?.warn('ghost dir skipped: unreadable manifest', {
dir,
@@@ -1712,16 -144,19 +1725,25 @@@
});
continue;
}
+ const hostMetadata = this.readInstalledHostMetadata(dir);
+ // 历史 manifest / receipt 中可能保留已移除的资源搜索元数据;它不参与当前
+ // 运行时入口,插件本体与已批准的其它能力仍按现有授权照常可用。
+ const manifest = v.manifest;
// icon 读失败只降级为无图标(warn),不影响意识本体可用。
- const iconDataUrl = this.readInstalledIconDataUrl(dir, manifest);
- const localizedManifest = this.readInstalledLocalizedManifest(dir, manifest);
++ // receipt 模型:无有效批准的安装一律 enabled:false + approval:{state},不按
++ // .disabled 镜像判运行(那是被 revert 的旧模型、#636 漏洞路径)。trust 只在
++ // 已批准投影里由 receipt 给出,legacy 投影不借安装目录 hostMetadata 冒充可信。
+ const iconDataUrl = this.readInstalledIconDataUrl(dir, v.manifest);
+ const localizedManifest = this.readInstalledLocalizedManifest(dir, v.manifest);
result.push({
manifest: localizedManifest,
dir,
- enabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),
+ enabled: false,
+ approval: { state: approvalResult.state },
++ // trust 仅作展示徽标,不授予运行权(运行仍由 enabled:false + approval 门控)。
+ ...(hostMetadata ? { trust: hostMetadata.trust } : {}),
...(iconDataUrl !== null ? { iconDataUrl } : {}),
+ ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),
});
}
result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
@@@ -1776,23 -173,19 +1798,25 @@@
const localePath = ghostLocalePathFor(manifest, requestedLocale);
if (!localePath) return runtimeManifest;
const fallbackPath = manifest.locales?.en;
- const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];
+ const candidates = [
+ ...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value))),
+ ];
for (const candidatePath of candidates) {
try {
- // 逐段解析(判据与批准侧 readApprovedLocaleResources、技能目录同源)。
- // 上一版在这里用 realpath + 目录钳制自成一套:同一件事两种写法,改了一处
- // 忘另一处正是这条链路反复出问题的形态,现在统一成"链接一律拒"。
- const absPath = path.join(dir, ...candidatePath.split('/'));
- // lstat 判完再按路径 readFileSync 是三次独立打开,期间可被换成超大
- // 文件或根外链接。单句柄限量闸 + containWithin 一次完成全部校验。
++ // 逐段 no-follow 解析(判据与批准侧、技能目录同源,链接一律拒)+ 单句柄限量读:
++ // 我们的 resolveGhostContentPathSync 拒符号链接段,main 的 readBoundedFileNoFollowSync
++ // 单句柄一次完成"限量 + no-follow + containWithin",消掉 lstat→readFileSync 的 TOCTOU。
+ const absPath = resolveGhostContentPathSync(dir, candidatePath, {
+ expect: 'file',
+ label: 'ghost locale',
+ });
- const stat = fs.lstatSync(absPath);
- if (stat.size > GHOST_LOCALE_MAX_BYTES) {
- throw new Error(`locale 文件缺失或超过 ${GHOST_LOCALE_MAX_BYTES} 字节`);
+ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {
+ containWithin: fs.realpathSync(dir),
+ });
+ if (bytes === null) {
+ throw new Error(`locale 文件缺失、超过 ${GHOST_LOCALE_MAX_BYTES} 字节或位于插件目录之外`);
}
- const raw = JSON.parse(fs.readFileSync(absPath, 'utf8'));
+ const raw = JSON.parse(bytes.toString('utf8'));
const validated = validateGhostManifestLocaleResource(raw, manifest);
if (!validated.ok) throw new Error(validated.reason);
return resolveGhostManifestLocale(runtimeManifest, validated.resource);
@@@ -1954,22 -237,19 +1978,22 @@@
*/
private readInstalledIconDataUrl(dir: string, manifest: GhostManifest): string | null {
if (manifest.icon === undefined) return null;
- const iconPath = path.join(dir, ...manifest.icon.split('/'));
try {
- // 逐段解析而不是 `stat` 直读:`stat` 静默穿透链接,会把插件目录之外的字节
- // 读成 icon 下发给 renderer 并钉进 receipt。判据与技能目录 / locale 同源。
- // statSync 后再 readFileSync 是两次独立打开:并发方可在其间把 icon 换成
- // 指向宿主任意文件的链接,字节会被包成 dataURL 经 IPC 送进 Renderer。
- // 单句柄限量闸拒链接、限大小;containWithin 堵中间目录链接。
- const bytes = readBoundedFileNoFollowSync(iconPath, GHOST_ICON_MAX_BYTES, {
++ // 逐段 no-follow 解析(拒符号链接段,判据与技能目录 / locale 同源)+ 单句柄限量读:
++ // stat 后再 readFileSync 是两次独立打开,并发方可在其间把 icon 换成指向宿主任意
++ // 文件的链接,字节会被包成 dataURL 经 IPC 送进 Renderer。containWithin 堵中间目录链接。
+ 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,
- });
++ const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {
+ containWithin: fs.realpathSync(dir),
+ });
+ if (bytes === null) {
+ this.options.log?.warn('ghost icon skipped: missing or oversize', { dir, icon: manifest.icon });
return null;
}
- return buildIconDataUrl(manifest.icon, fs.readFileSync(iconPath));
+ return buildIconDataUrl(manifest.icon, bytes);
} catch {
this.options.log?.warn('ghost icon skipped: unreadable', { dir, icon: manifest.icon });
return null;
@@@ -1981,9 -304,13 +2048,11 @@@
* 零副作用。「装意识前弹确认」(README 安全原则)的数据来源 —— 三个装入
* 入口(设置页 / 拖入 / 双击)都先 inspect 给用户看明白,确认后才 install。
*/
- async inspect(
- lizFilePath: string,
- ): Promise<
+ async inspect(lizFilePath: string): Promise<
| {
manifest: GhostManifest;
+ /** 包内原始清单,仅供 Main 安全比较。 */
+ canonicalManifest: GhostManifest;
trust: GhostTrustInfo;
packageSha256: string;
iconDataUrl?: string;
@@@ -2001,11 -329,12 +2071,14 @@@
}
/** 装入的前半程(读文件 / 解包 / 校验清单),inspect 与 install 共用。 */
- private async parse(
- lizFilePath: string,
- ): Promise<
+ private async parse(lizFilePath: string): Promise<
| {
manifest: GhostManifest;
++ // 同一份包内清单的两个名字:approvedManifest 供 receipt 写入(我们),
++ // canonicalManifest 供 inspect/可恢复复核比对(main)。parse 里都置为 v.manifest。
+ approvedManifest: GhostManifest;
+ canonicalManifest: GhostManifest;
+ localeResources: Record<string, GhostManifestLocaleResource>;
trust: GhostTrustInfo;
packageSha256: string;
iconDataUrl?: string;
@@@ -2014,15 -343,13 +2087,17 @@@
}
| { rejection: InstallRejection }
> {
- // 1) 读源文件(带体积上限)
+ // 1) 读源文件(带体积上限)。stat 后再 readFile 是两次独立打开,期间文件
+ // 可被换成超大文件绕过上限——单句柄限量读。允许跟随链接:用户拖入的
+ // .cindy 本身可以是链接,防篡改由 expectedPackageSha256 对账负责。
let buf: Buffer;
try {
- const bytes = await readBoundedFileFollowLinks(lizFilePath, MAX_NODE_CINDY_FILE_BYTES);
- if (bytes === null) {
+ buf = await readRegularFileStableWithLimit(lizFilePath, MAX_NODE_CINDY_FILE_BYTES);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
+ return { rejection: { code: 'source-not-found', reason: '文件不存在' } };
+ }
+ if (err instanceof Error && err.message.includes('exceeds')) {
return {
rejection: {
code: 'file-invalid',
@@@ -2302,8 -611,7 +2377,9 @@@
return {
manifest: localizedManifest,
+ approvedManifest: v.manifest,
+ canonicalManifest: v.manifest,
+ localeResources,
trust: signature.trust,
packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index c61f646275,354e6f5898..c3b250c773
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@@ -471,2950 -183,215 +478,2967 @@@ describe('GhostManager · 存量插件�
});
});
- it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {
- const manifest = {
- ...goodManifest(),
- locales: { en: 'locales/en.json' },
- };
- const missing = await makeCindy('locale-missing.cindy', manifest);
- await expectRejection(await manager.install(missing), 'file-invalid');
+ it('修复 #1080 历史 mixed 状态:有效 receipt 不封死其余 legacy/旧 schema 插件', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest('approved')));
+ const approvedReceiptPath = path.join(workDir, 'ghosts-install-state', 'approved.json');
+ const approvedReceiptBefore = await fs.promises.readFile(approvedReceiptPath, 'utf8');
+
+ // Fixture 模拟曾短暂合入后回滚的 #1080:部分插件已有 v2 receipt,但当时没有
+ // legacy migration ledger;同 owner 下其余旧安装仍无 receipt。删除 ledger 只是
+ // 构造这份历史状态,不代表安装根攻击者能操作状态根。
+ await fs.promises.rm(migrationLedgerPath());
+ await writeLegacyInstall('legacy', goodManifest('legacy'));
+ await writeLegacyInstall('old-schema', goodManifest('old-schema'), { disabled: true });
+ await fs.promises.writeFile(
+ path.join(workDir, 'ghosts-install-state', 'old-schema.json'),
+ JSON.stringify({ schemaVersion: 1, id: 'old-schema', legacy: true }),
+ );
- const invalid = await makeCindy('locale-invalid.cindy', manifest, {
- 'locales/en.json': '{ nope',
- });
- await expectRejection(await manager.install(invalid), 'file-invalid');
+ const outcome = await manager.migrateLegacyApprovalsOnce();
- const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {
- 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),
+ expect(outcome.migrated).toEqual(['legacy', 'old-schema']);
+ expect(await fs.promises.readFile(approvedReceiptPath, 'utf8')).toBe(approvedReceiptBefore);
+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));
+ expect(byId.approved.approval.state).toBe('approved');
+ expect(byId.legacy).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(byId['old-schema']).toMatchObject({
+ enabled: false,
+ approval: { state: 'approved' },
});
- await expectRejection(await manager.install(unknownTool), 'file-invalid');
+ });
- // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。
+ it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const before = await fs.promises.readFile(
+ path.join(workDir, 'ghosts-install-state', 'hello.json'),
+ 'utf8',
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual([]);
+ expect(await fs.promises.readFile(path.join(workDir, 'ghosts-install-state', 'hello.json'), 'utf8')).toBe(
+ before,
+ );
+ });
+
+ it('声明的 locale 文件损坏 → fail closed(装入天然不含坏 locale,读到即装入后损坏)', async () => {
hostLocale = 'en';
- const partial = await makeCindy('locale-partial.cindy', manifest, {
- 'locales/en.json': JSON.stringify({ name: 'English partial' }),
- });
- expect(await manager.install(partial)).toMatchObject({
- ghost: {
- manifest: {
- name: 'English partial',
- resolvedLocale: 'en',
- tools: [{ name: 'do_thing', description: '做点事' }],
- },
- },
+ await writeLegacyInstall(
+ 'hello',
+ { ...goodManifest(), name: 'Base', locales: { en: 'locales/en.json' } },
+ { files: { 'locales/en.json': '{ broken json' } },
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ // 装入流程逐个校验声明的 locale、不合格拒装,所以旧安装不会带坏 locale;迁移时
+ // 读到坏 locale 只能是装入后损坏,属 §5 的"自相矛盾 → fail closed",不写坏 receipt。
+ expect(outcome.failed).toEqual(['hello']);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ });
+});
+
+describe('GhostManager · owner 受管根路径', () => {
+ it('允许 userData 祖先通过 symlink/junction 重定位', async () => {
+ const physicalUserData = path.join(workDir, 'physical-user-data');
+ const linkedUserData = path.join(workDir, 'linked-user-data');
+ await fs.promises.mkdir(path.join(physicalUserData, 'owners', 'owner-a'), { recursive: true });
+ try {
+ await fs.promises.symlink(
+ physicalUserData,
+ linkedUserData,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ const relocated = new GhostManager({
+ getRootDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'cindy-brain'),
+ getStateDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'ghost-install-state'),
});
- const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {
- 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),
+ expect(relocated.list()).toEqual([]);
+ });
+
+ it('允许全新 owner 的多层受管根尚未创建', () => {
+ const freshOwner = path.join(workDir, 'owners', 'fresh-owner');
+ const fresh = new GhostManager({
+ getRootDir: () => path.join(freshOwner, 'cindy-brain'),
+ getStateDir: () => path.join(freshOwner, 'ghost-install-state'),
});
- await expectRejection(await manager.install(aliasedManifest), 'file-invalid');
+
+ expect(fresh.list()).toEqual([]);
});
- it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {
- const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });
- const result = await manager.install(cindy);
- expect('ghost' in result).toBe(true);
- const { ghost } = result as { ghost: InstalledGhost };
- expect(ghost.manifest.id).toBe('hello');
- expect(ghost.dir).toBe(path.join(rootDir, 'hello'));
- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);
+ it('仍拒绝受管根本身是 symlink/junction', async () => {
+ const outside = path.join(workDir, 'outside-root');
+ const linkedRoot = path.join(workDir, 'linked-root');
+ await fs.promises.mkdir(outside, { recursive: true });
+ try {
+ await fs.promises.symlink(outside, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return;
+ }
- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);
- expect(onChanged).toHaveBeenCalledTimes(1);
- expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);
+ expect(
+ () =>
+ new GhostManager({
+ getRootDir: () => linkedRoot,
+ getStateDir: () => path.join(workDir, 'state-root'),
+ }),
+ ).toThrow(/ghost content root is not a real directory/);
});
+});
- it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {
- const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
- const installed = await manager.install(cindy);
+describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {
+ it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {
+ // 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被
+ // in-progress 台账挡住)、bbb 还没动笔时进程死掉。
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await writeLegacyInstall('bbb', goodManifest('bbb'));
+ await manager.migrateLegacyApprovalsOnce();
+ // 手工把状态倒回"崩溃时刻":台账退回 in-progress、bbb 的 receipt 消失。
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['aaa', 'bbb'],
+ }),
+ );
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'bbb.json'));
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ // bbb 被续跑补迁;aaa 已有 receipt,计入 migrated(它就是迁移铸出的)。
+ expect(outcome.migrated).toEqual(['bbb']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId).toEqual({ aaa: 'approved', bbb: 'approved' });
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ migratedIds: string[];
+ };
+ expect(ledger.state).toBe('completed');
+ expect(ledger.migratedIds).toEqual(['aaa', 'bbb']);
+ });
- const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');
- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
+ it('续跑只认动笔前钉死的清单:清单外的无 receipt 目录不被重铸', async () => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ // 迁移窗口期间新装再删 receipt 的插件(不在 pendingIds 里)骗不到续跑。
+ await writeLegacyInstall('ccc', goodManifest('ccc'));
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['aaa'],
+ }),
+ );
- delete metadata.approvedAtResourceProvider;
- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
- expect(manager.list()[0].manifest.tools).toEqual([
- { name: 'do_thing', description: '做点事' },
- ]);
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['aaa']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId.aaa).toBe('approved');
+ expect(byId.ccc).toBe('legacy-unapproved');
+ expect(
+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })
+ .state,
+ ).toBe('completed');
+ });
- metadata.approvedAtResourceProvider = { tool: 'other_tool' };
- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
+ it('receipt 首写的自动落账不覆盖 in-progress 台账(崩溃门不被焊死)', async () => {
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['zzz'],
+ }),
+ );
+ // 迁移窗口内经正常装入流程写 receipt(内部有"缺台账即补写 completed"的守卫)。
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ };
+ expect(ledger.state).toBe('in-progress');
});
- it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {
- const cindy = await makeCindy('hello.cindy', goodManifest());
- const result = await manager.install(cindy, { initiallyEnabled: false });
- expect('ghost' in result).toBe(true);
- expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);
- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
- // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。
- expect(onChanged).toHaveBeenCalledTimes(1);
- expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);
- // 重新启用即撕掉标记。
- await manager.setEnabled('hello', true);
- expect(manager.list()[0].enabled).toBe(true);
+ it('台账存在但读不出:门保守关死,不迁也不重写', async () => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');
+ });
+
+ it.each([
+ ['empty pendingIds', []],
+ ['non-string pending id', [null]],
+ ['path-traversal pending id', ['../x']],
+ ['mixed valid and invalid pending ids', ['aaa', '../x']],
+ ])('非法 in-progress 台账(%s)保守关门且不被重写成 completed', async (_label, pendingIds) => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });
+ const raw = JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds,
+ });
+ await fs.promises.writeFile(migrationLedgerPath(), raw);
+
+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({
+ migrated: [],
+ skipped: [],
+ failed: [],
+ retryPending: [],
+ });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe(raw);
+ });
+
+ it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。
+ const marker = path.join(rootDir, 'hello', '.disabled');
+ await fs.promises.writeFile(marker, '');
+ expect(manager.list()[0].enabled).toBe(false);
+
+ // receipt 落盘的 rename 失败(状态根抖动):启用必须整体失败且镜像原样放回。
+ const realRename = fs.promises.rename;
+ const spy = vi
+ .spyOn(fs.promises, 'rename')
+ .mockImplementation(async (from, to) => {
+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');
+ return realRename(from, to);
+ });
+ try {
+ const result = await manager.setEnabled('hello', true);
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(fs.existsSync(marker)).toBe(true);
+ expect(manager.list()[0].enabled).toBe(false);
+ });
+
+ it('进程内隔离按状态根命名空间:A 账号的隔离不污染 B,切回 A 仍生效', async () => {
+ let stateDir = path.join(workDir, 'owner-a-state');
+ const owned = new GhostManager({
+ getRootDir: () => rootDir,
+ getStateDir: () => stateDir,
+ getLocale: () => hostLocale,
+ });
+ await owned.install(await makeCindy('a.cindy', goodManifest()));
+ // 撤销失败 → A 的进程内隔离。
+ const realRm = fs.promises.rm;
+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, opts) => {
+ if (String(target).endsWith('hello.json')) throw new Error('EACCES');
+ return realRm(target as never, opts as never);
+ });
+ try {
+ await owned.removeInstallApproval('hello');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(owned.list()[0].approval.state).toBe('invalid');
+
+ // 切到 B 账号(状态根变了):同 id 不被 A 的隔离污染 —— B 没有 receipt,
+ // 如实是 legacy-unapproved 而不是 invalid。
+ stateDir = path.join(workDir, 'owner-b-state');
+ expect(owned.list()[0].approval.state).toBe('legacy-unapproved');
+
+ // 切回 A:隔离仍在(盘上那份陈旧 receipt 不得复活)。
+ stateDir = path.join(workDir, 'owner-a-state');
+ expect(owned.list()[0].approval.state).toBe('invalid');
+ });
+
+ it('安装根下的 junction 不算已装插件:迁移不迁它,list 不列它', async () => {
+ await writeLegacyInstall('real', goodManifest('real'));
+ const outside = path.join(workDir, 'outside-plugin');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'ghost.json'), JSON.stringify(goodManifest('planted')));
+ try {
+ fs.symlinkSync(outside, path.join(rootDir, 'planted'), 'junction');
+ } catch {
+ return; // 环境建不了链接则跳过;判据逻辑平台无关。
+ }
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['real']);
+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['real']);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'planted.json'))).toBe(false);
+ });
+});
+
+describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {
+ it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {
+ // 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,
+ // 本地包用户没有市场路线;第三条路必须能不找文件恢复。
+ await writeLegacyInstall('hello', goodManifest());
+ await manager.migrateLegacyApprovalsOnce();
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ expect(inspected.manifest.id).toBe('hello');
+ expect(inspected.manifestSha256).toMatch(/^[a-f0-9]{64}$/);
+
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ // 启停镜像同步维护(回滚到旧客户端不错位)。
+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
+ });
+
+ it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+
+ // 攻击窗口:用户看的是权限集 A,confirm 落地前清单被换成声明更多权限的 B。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), name: 'Changed after review' }),
+ );
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('state-changed');
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ });
+
+ it.each(['skill', 'locale', 'icon', 'trust'] as const)(
+ '确认间隙 %s 批准投影被换 → 拒绝重新确认',
+ async (kind) => {
+ const manifest = {
+ ...goodManifest(),
+ author: 'Original author',
+ icon: 'assets/icon.png',
+ locales: { en: 'locales/en.json' },
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ };
+ await writeLegacyInstall('hello', manifest, {
+ files: {
+ 'assets/icon.png': 'ORIGINAL ICON',
+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),
+ 'skills/demo/SKILL.md':
+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',
+ },
+ });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+
+ if (kind === 'skill') {
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',
+ );
+ } else if (kind === 'locale') {
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'locales', 'en.json'),
+ JSON.stringify({ name: 'Replaced name' }),
+ );
+ } else if (kind === 'icon') {
+ await fs.promises.writeFile(path.join(rootDir, 'hello', 'assets', 'icon.png'), 'REPLACED ICON');
+ } else {
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', '.cindy-trust.json'),
+ JSON.stringify({
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Different publisher',
+ }),
+ );
+ }
+
+ const result = await manager.reapproveInstalled('hello', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('state-changed');
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ },
+ );
+
+ it('随包插件拒走人工重新确认(由启动对账自动补批准)', async () => {
+ const guarded = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => id === 'hello',
+ });
+ await writeLegacyInstall('hello', goodManifest());
+ const inspected = await guarded.inspectInstalledReapproval('hello');
+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');
+ });
+
+ it('已是 approved 的插件拒重复确认(不给覆盖既有批准开口子)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');
+ });
+
+ it('信任镜像自称 cindy-official 一律封顶拒收(非随包目录不可能合法持有官方档)', async () => {
+ await writeLegacyInstall('hello', goodManifest(), {
+ trust: {
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ },
+ });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ expect(inspected.trust.level).toBe('unverified');
+ });
+});
+
+describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
+ it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect(manager.list()[0].enabled).toBe(true);
+
+ // 状态根不可写(AV/权限/磁盘故障):receipt 的 rename 提交失败。
+ const realRename = fs.promises.rename;
+ const renameSpy = vi
+ .spyOn(fs.promises, 'rename')
+ .mockImplementation(async (from, to) => {
+ if (String(to).includes('ghosts-install-state')) {
+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ // 停用必须永远能成功:镜像已落盘,如实返回 ok,而不是 io + 回滚镜像(fail open)。
+ expect(await manager.setEnabled('hello', false)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(false);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ // "重启"(新实例,内存态清零):镜像在盘上,停用不复活。
+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+ expect(restarted.list()[0].enabled).toBe(false);
+ // 启用方向照旧要求 receipt 写成功(此时状态根已恢复可写)。
+ expect(await manager.setEnabled('hello', true)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(true);
+ });
+
+ it('P0-5:嵌套 skill dir(祖先包含子项)装入/快照/校验全通,不撞 COPYFILE_EXCL', async () => {
+ const nested = {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [
+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },
+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },
+ ],
+ },
+ };
+ const files = {
+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',
+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',
+ };
+ const result = await manager.install(await makeCindy('nested.cindy', nested, files));
+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));
+ const ghost = manager.list()[0];
+ expect(ghost.approval.state).toBe('approved');
+ // 两个 item 的字节指纹都能对上(嵌套项的根就在祖先拷出的快照树里)。
+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);
+ });
+
+ it('P0-5:嵌套 skill dir 的旧安装迁移同样成功(存量兼容红线)', async () => {
+ await writeLegacyInstall(
+ 'skilled',
+ {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [
+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },
+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },
+ ],
+ },
+ },
+ {
+ files: {
+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',
+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',
+ },
+ },
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['skilled']);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ });
+
+ it('P0-2:安装根为空/未诞生时不落台账,legacy 恢复流程随后搬入仍可迁移', async () => {
+ // 首轮:根目录还不存在(owner 命名空间刚建立,旧目录尚未被恢复流程搬入)。
+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({
+ migrated: [],
+ skipped: [],
+ failed: [],
+ retryPending: [],
+ });
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+ // 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。
+ await writeLegacyInstall('hello', goodManifest());
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second.migrated).toEqual(['hello']);
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ });
+
+ it('P0-2:首个 receipt 写入即自动落台账 —— "装插件→删 receipt"骗不到迁移', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 新模型首次活动(装入写 receipt)时台账已经落了,不等下一轮 reconcile。
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ // 攻击:改写安装目录 manifest 扩权,再删掉 receipt,指望迁移按新 manifest 重铸批准。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'ghost.json'),
+ JSON.stringify({
+ ...goodManifest(),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 's', name: 's', description: 's' }] },
+ }),
+ );
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ });
+
+ it('P0-2:首次批准先提交 migration ledger,落账失败时不留下有效 receipt', async () => {
+ const renameTargets: string[] = [];
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ const target = String(to);
+ renameTargets.push(target);
+ if (target.endsWith('.legacy-migration.json')) {
+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ } finally {
+ renameSpy.mockRestore();
+ }
+
+ expect(renameTargets.some((target) => target.endsWith('.legacy-migration.json'))).toBe(true);
+ expect(renameTargets.some((target) => target.endsWith(`${path.sep}hello.json`))).toBe(false);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ // Ledger commit failed before the receipt became visible, so the install
+ // transaction rolls back the final directory as well; no ghost is listed.
+ expect(manager.list()).toEqual([]);
+ });
+
+ it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {
+ const finalDir = path.join(rootDir, 'hello');
+ const pendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');
+ const realRename = fs.promises.rename;
+ const realRm = fs.promises.rm;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith('.legacy-migration.json')) {
+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (path.resolve(String(target)) === path.resolve(finalDir)) {
+ throw Object.assign(new Error('EBUSY: installed directory locked'), { code: 'EBUSY' });
+ }
+ return realRm(target, options);
+ });
+ try {
+ await expect(manager.install(await makeCindy('a.cindy', goodManifest()))).resolves.toMatchObject(
+ { rejection: { code: 'io' } },
+ );
+ } finally {
+ renameSpy.mockRestore();
+ rmSpy.mockRestore();
+ }
+
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(pendingPath)).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+
+ const migration = await manager.migrateLegacyApprovalsOnce();
+ expect(migration.migrated).toEqual([]);
+ expect(migration.skipped).toContain('hello');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
+ expect(recovered.list()).toEqual([]);
+ expect(fs.existsSync(finalDir)).toBe(false);
+ expect(fs.existsSync(pendingPath)).toBe(false);
+ });
+
+ it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const realReaddir = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, opts: never) => {
+ if (String(dir) === rootDir) {
+ throw Object.assign(new Error('EACCES: install root locked'), { code: 'EACCES' });
+ }
+ return realReaddir(dir, opts);
+ }) as never);
+ try {
+ await expect(manager.migrateLegacyApprovalsOnce()).rejects.toThrow(/EACCES/);
+ } finally {
+ spy.mockRestore();
+ }
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+ // 环境恢复后下一轮照常迁移。
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['hello']);
+ });
+
+ it('P0-2:恢复旁路只补给定 id,台账门对其余目录照常生效', async () => {
+ // 台账已落(首轮迁移空跑一个插件)。
+ await writeLegacyInstall('first', goodManifest('first'));
+ await manager.migrateLegacyApprovalsOnce();
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ // 恢复流程搬入两个目录,但只把 recovered 声明为其中一个。
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ await writeLegacyInstall('planted', goodManifest('planted'));
+ const out = await manager.backfillRecoveredLegacyGhosts(['recovered']);
+ expect(out.migrated).toEqual(['recovered']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId.recovered).toBe('approved');
+ expect(byId.planted).toBe('legacy-unapproved');
+ });
+
+ it('closes the recovery ledger when a queued id is already approved', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['hello'],
+ }),
+ );
+
+ await expect(manager.backfillRecoveredLegacyGhosts(['hello'])).resolves.toEqual({
+ migrated: [],
+ failed: [],
+ });
+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({
+ state: 'completed',
+ });
+ });
+
+ it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');
+ await fs.promises.rm(migrationLedgerPath());
+ const realLstatSync = fs.lstatSync;
+ const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {
+ lstatSpy.mockRestore();
+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });
+ }
+ return realLstatSync(target, options as never);
+ });
+
+ expect(await manager.backfillRecoveredLegacyGhosts(['hello'])).toEqual({
+ migrated: [],
+ failed: [],
+ });
+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);
+ expect(
+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),
+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });
+ });
+
+ it('persists transient recovered-legacy backfill failures in the migration work queue', async () => {
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const realRename = fs.promises.rename;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith(`${path.sep}recovered.json`)) {
+ renameSpy.mockRestore();
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return realRename(from, to);
+ });
+
+ const first = await manager.backfillRecoveredLegacyGhosts(['recovered']);
+ expect(first).toEqual({ migrated: [], failed: [] });
+ const pendingLedger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ pendingIds?: string[];
+ };
+ expect(pendingLedger.state).toBe('in-progress');
+ expect(pendingLedger.pendingIds).toEqual(['recovered']);
+
+ const second = await manager.backfillRecoveredLegacyGhosts(['recovered']);
+ expect(second.migrated).toEqual(['recovered']);
+ const completedLedger = JSON.parse(
+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),
+ ) as { state?: string; pendingIds?: string[] };
+ expect(completedLedger.state).toBe('completed');
+ expect(completedLedger.pendingIds).toBeUndefined();
+ });
+
+ it('persists recovered ids before the first receipt write starts', async () => {
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const realRename = fs.promises.rename;
+ let queueSeenBeforeReceipt = false;
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(to).endsWith(`${path.sep}recovered.json`)) {
+ const ledger = JSON.parse(
+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),
+ ) as { state?: string; pendingIds?: string[] };
+ queueSeenBeforeReceipt =
+ ledger.state === 'in-progress' && ledger.pendingIds?.includes('recovered') === true;
+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;
+ err.code = 'EACCES';
+ throw err;
+ }
+ return realRename(from, to);
+ });
+
+ try {
+ await manager.backfillRecoveredLegacyGhosts(['recovered']);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ expect(queueSeenBeforeReceipt).toBe(true);
+ });
+
+ it('does not overwrite an existing recovery queue when the migration ledger is unreadable', async () => {
+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });
+ const originalLedger = {
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['existing'],
+ };
+ await fs.promises.writeFile(migrationLedgerPath(), JSON.stringify(originalLedger));
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ const realReadFileSync = fs.readFileSync;
+ const readSpy = vi.spyOn(fs, 'readFileSync').mockImplementation((target, options) => {
+ if (path.resolve(String(target)) === path.resolve(migrationLedgerPath())) {
+ throw Object.assign(new Error('EIO: ledger temporarily unreadable'), { code: 'EIO' });
+ }
+ return realReadFileSync(target, options as never);
+ });
+
+ try {
+ await expect(manager.backfillRecoveredLegacyGhosts(['recovered'])).rejects.toThrow(
+ /ledger exists but is unreadable/,
+ );
+ } finally {
+ readSpy.mockRestore();
+ }
+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toEqual(
+ originalLedger,
+ );
+ });
+
+ it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {
+ await manager.install(
+ await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),
+ );
+ await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));
+ const inspected = await manager.inspectInstalledReapproval('clasher');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const result = await manager.reapproveInstalled('clasher', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('command-conflict');
+ });
+
+ it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {
+ await writeLegacyInstall('brokered', {
+ ...goodManifest('brokered'),
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'token',
+ source: 'oauth',
+ oauth: { tokenBroker: 'github' },
+ },
+ ],
+ },
+ });
+ const inspected = await manager.inspectInstalledReapproval('brokered');
+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');
+ });
+
+ it('P1-7:重新确认的启停默认值取镜像读数,不重置用户停用偏好', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const inspected = await manager.inspectInstalledReapproval('hello');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ expect(inspected.previouslyEnabled).toBe(false);
+ });
+
+ it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const realRename = fs.promises.rename;
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ // staging→final 与 backup→final 都失败(Windows 文件锁/AV 的典型形态)。
+ if (path.resolve(String(to)) === path.resolve(finalDir)) {
+ throw Object.assign(new Error('EPERM: dir locked'), { code: 'EPERM' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ const bumped = await makeCindy('b.cindy', { ...goodManifest(), version: '1.0.1' });
+ const result = await updateGhost(bumped);
+ expect('rejection' in result).toBe(true);
+ if (!('rejection' in result)) return;
+ expect(result.rejection.code).toBe('io');
+ expect(result.rejection.code === 'io' && result.rejection.rollbackFailed).toBe(true);
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ ).toBe(true);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
+
+describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {
+ const pendingMarkerPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);
+ const receiptPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `${id}.json`);
+ /** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */
+ const freshManager = () =>
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+
+ it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {
+ // install 在 rename(staging→final) 之后、写 receipt 之前崩溃:finalDir 完整、无
+ // receipt、无 ledger。若不处理,迁移会把它(崩溃窗口内可能被改过 manifest)当 legacy
+ // 批准掉。事务标记让恢复识别它是"未完成安装"并删除。
+ await writeLegacyInstall('hello', goodManifest());
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256: 'a'.repeat(64) }),
+ );
+
+ const recovered = freshManager(); // 构造期恢复:删掉未完成安装
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ const outcome = await recovered.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual([]); // 目录已被删,迁移无对象
+ });
+
+ it('keeps a committed builtin restore successful and retries tombstone clearing from its journal', async () => {
+ trustedBundledIds.add('hello');
+ const clearBuiltinTombstone = vi
+ .fn<(id: string) => void>()
+ .mockImplementationOnce(() => {
+ throw new Error('state root temporarily unavailable');
+ })
+ .mockImplementation(() => undefined);
+ const restoringManager = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => trustedBundledIds.has(id),
+ clearBuiltinTombstone,
+ });
+
+ const installed = await restoringManager.install(
+ await makeCindy('builtin-restore.cindy', goodManifest()),
+ );
+
+ expect('ghost' in installed).toBe(true);
+ expect(restoringManager.list()[0]).toMatchObject({ approval: { state: 'approved' } });
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(JSON.parse(await fs.promises.readFile(pendingMarkerPath(), 'utf8'))).toMatchObject({
+ kind: 'install',
+ clearBuiltinTombstone: true,
+ });
+
+ const recoveredAfterClearFailure = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => trustedBundledIds.has(id),
+ clearBuiltinTombstone,
+ });
+
+ expect(clearBuiltinTombstone).toHaveBeenCalledTimes(2);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(recoveredAfterClearFailure.list()[0]).toMatchObject({
+ approval: { state: 'approved' },
+ });
+ });
+
+ it('install 恢复必须用 packageSha256 证明旧 receipt 属于这次安装', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ await fs.promises.rm(finalDir, { recursive: true, force: true });
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(finalDir, 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),
+ );
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'install',
+ packageSha256: 'f'.repeat(64),
+ }),
+ );
+
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+ expect(fs.existsSync(finalDir)).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('非法 pending marker 会阻断 orphan backup 启发式,不删除待人工恢复的 backup', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-abcdef12';
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: '..\\outside',
+ }),
+ );
+
+ const recovered = freshManager();
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('invalid pending marker filename blocks orphan-backup heuristics', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.rename(finalDir, backupDir);
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');
+ const invalidMarker = path.join(path.dirname(pendingMarkerPath()), '.pending-BAD!.json');
+ await fs.promises.writeFile(invalidMarker, '{}');
+
+ const recovered = freshManager();
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(invalidMarker)).toBe(true);
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('pending marker JSON 为 null 时按 invalid 保留现场,不让构造期恢复崩溃', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.rename(finalDir, backupDir);
+ await fs.promises.mkdir(finalDir, { recursive: true });
+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');
+ await fs.promises.writeFile(pendingMarkerPath(), 'null');
+
+ const recovered = freshManager();
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('状态根 journal 扫描 EACCES 时跳过全部恢复启发式,任何现场都不动', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const stateRoot = path.dirname(pendingMarkerPath());
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.mkdir(stagingDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realReaddirSync = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
+ if (path.resolve(String(target)) === path.resolve(stateRoot)) {
+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });
+ }
+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);
+ }) as typeof fs.readdirSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ // 未提交 update 已先移除 final;backup 不可读时保留整笔 journal,
+ // 因而此刻 final 仍缺失,等待下次可读时再由 recovery 收敛。
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(stagingDir)).toBe(true);
+ });
+
+ it('journal root unreadable blocks the whole owner even when installed ids cannot be enumerated yet', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const stateRoot = path.dirname(pendingMarkerPath());
+ const realReaddirSync = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {
+ const resolved = path.resolve(String(target));
+ if (resolved === path.resolve(stateRoot) || resolved === path.resolve(rootDir)) {
+ throw Object.assign(new Error('EACCES: managed root locked'), { code: 'EACCES' });
+ }
+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);
+ }) as typeof fs.readdirSync);
+
+ let recovered: GhostManager;
+ try {
+ recovered = freshManager();
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
+ it('pending marker 读取 EACCES 时保留 marker/final/backup,不降级到 orphan cleanup', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realReadFileSync = fs.readFileSync;
+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(pendingMarkerPath())) {
+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });
+ }
+ return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.readFileSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ });
+
+ it('已提交 install 的 receipt 瞬时不可读时保留 final/receipt/journal 等待重试', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ }).packageSha256;
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256 }),
+ );
+ const realReadFileSync = fs.readFileSync;
+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
+ }
+ return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.readFileSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('已提交 update 的 receipt lstat EACCES 时保留 final/backup/receipt/journal', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ }).packageSha256;
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256,
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realLstatSync = fs.lstatSync;
+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
+ }
+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.lstatSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('update backup lstat EACCES 时保留整笔 journal,不清 marker 继续猜恢复', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');
+ await fs.promises.mkdir(backupDir, { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: path.basename(backupDir),
+ }),
+ );
+ const realLstatSync = fs.lstatSync;
+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {
+ if (path.resolve(String(target)) === path.resolve(backupDir)) {
+ throw Object.assign(new Error('EACCES: backup locked'), { code: 'EACCES' });
+ }
+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.lstatSync);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(backupDir)).toBe(true);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('动态 owner 根切换时,首次读取会先恢复新 owner 的 pending mutation', async () => {
+ const rootA = rootDir;
+ const rootB = path.join(workDir, 'ghosts-b');
+ const stateA = path.join(workDir, 'state-a');
+ const stateB = path.join(workDir, 'state-b');
+ let activeRoot = rootA;
+ let activeState = stateA;
+ const backupName = '.cindy-updating-hello-abcdef12';
+ const finalDir = path.join(rootB, 'hello');
+ await fs.promises.mkdir(path.join(rootB, backupName), { recursive: true });
+ await fs.promises.writeFile(path.join(rootB, backupName, 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(rootB, backupName, 'main.js'), 'old');
+ await fs.promises.mkdir(stateB, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(stateB, '.pending-hello.json'),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: backupName,
+ }),
+ );
+ const owned = new GhostManager({
+ getRootDir: () => activeRoot,
+ getStateDir: () => activeState,
+ getLocale: () => hostLocale,
+ });
+ activeRoot = rootB;
+ activeState = stateB;
+ expect(owned.list().map((ghost) => ghost.manifest.id)).toEqual(['hello']);
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(path.join(rootB, backupName))).toBe(false);
+ });
+
+ it('排队中的 mutation 在 owner 代际变化后拒绝执行', async () => {
+ const rootA = rootDir;
+ const rootB = path.join(workDir, 'ghosts-b');
+ const stateA = path.join(workDir, 'state-a');
+ const stateB = path.join(workDir, 'state-b');
+ let activeRoot = rootA;
+ let activeState = stateA;
+ let ownerGeneration = 0;
+ const owned = new GhostManager({
+ getRootDir: () => activeRoot,
+ getStateDir: () => activeState,
+ getOwnerContextKey: () => `owner:${ownerGeneration}`,
+ getLocale: () => hostLocale,
+ });
+
+ let markStarted!: () => void;
+ let releaseFirst!: () => void;
+ const started = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ const first = owned.runExclusiveMutation(async () => {
+ markStarted();
+ await new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ });
+ await started;
+
+ const second = owned.runExclusiveMutation(async () => {
+ await fs.promises.mkdir(activeRoot, { recursive: true });
+ await fs.promises.writeFile(path.join(activeRoot, 'queued-write'), 'must not run');
+ });
+ const rejected = expect(second).rejects.toThrow(/owner context changed/);
+ activeRoot = rootB;
+ activeState = stateB;
+ ownerGeneration += 1;
+ releaseFirst();
+
+ await first;
+ await rejected;
+ expect(fs.existsSync(path.join(rootA, 'queued-write'))).toBe(false);
+ expect(fs.existsSync(path.join(rootB, 'queued-write'))).toBe(false);
+ });
+
+ it('执行中的独占 mutation 钉住 owner 内容根与状态根,不把后半段写进新 owner', async () => {
+ const rootA = path.join(workDir, 'owned-a');
+ const rootB = path.join(workDir, 'owned-b');
+ const stateA = path.join(workDir, 'owned-state-a');
+ const stateB = path.join(workDir, 'owned-state-b');
+ let activeRoot = rootA;
+ let activeState = stateA;
+ let ownerGeneration = 0;
+ const owned = new GhostManager({
+ getRootDir: () => activeRoot,
+ getStateDir: () => activeState,
+ getOwnerContextKey: () => `owner:${ownerGeneration}`,
+ getLocale: () => hostLocale,
+ });
+ await owned.install(await makeCindy('owned.cindy', goodManifest()));
+ await fs.promises.mkdir(path.join(rootB, 'hello'), { recursive: true });
+ await fs.promises.writeFile(path.join(rootB, 'hello', 'ghost.json'), JSON.stringify(goodManifest()));
+ await fs.promises.writeFile(path.join(rootB, 'hello', 'main.js'), 'owner-b');
+
+ await owned.runExclusiveMutation(async (mutation) => {
+ activeRoot = rootB;
+ activeState = stateB;
+ ownerGeneration += 1;
+ expect(await mutation.uninstall('hello', { notify: false })).toEqual({ ok: true });
+ });
+
+ expect(fs.existsSync(path.join(rootA, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(stateA, 'hello.json'))).toBe(false);
+ expect(fs.existsSync(path.join(rootB, 'hello', 'main.js'))).toBe(true);
+ expect(owned.list().find((ghost) => ghost.manifest.id === 'hello')?.approval.state).toBe(
+ 'legacy-unapproved',
+ );
+ });
+
+ it('未提交的更新(新字节+旧 receipt+update 标记)回滚到 backup,不固化成按旧批准跑新代码', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-abcdef12';
+
+ // 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,
+ // receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir);
+ await fs.promises.writeFile(
+ path.join(finalDir, 'ghost.json'),
+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),
+ );
+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: backupName,
+ }),
+ );
+
+ freshManager(); // 构造期恢复:未提交 → 回滚到 backup
+ const restored = JSON.parse(await fs.promises.readFile(path.join(finalDir, 'ghost.json'), 'utf8'));
+ expect(restored.version).toBe('1.0.0'); // 旧字节搬回
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ // receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。
+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);
+ });
+
+ it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ revision: string;
+ };
+ const backupName = '.cindy-updating-hello-abcdef34';
+ await fs.promises.mkdir(path.join(rootDir, backupName));
+ await fs.promises.writeFile(path.join(rootDir, backupName, 'stale.txt'), 'old');
+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: committedReceipt.packageSha256,
+ receiptRevision: committedReceipt.revision,
+ backupDirName: backupName,
+ phase: 'published',
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false); // 陈旧 backup 回收
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true); // 新版保留
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('approved');
+ });
+
+ it('same-hash backed-up update restores the only backup instead of deleting it', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');
+ const receipt = JSON.parse(receiptBefore) as { packageSha256: string };
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-acde0011';
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: receipt.packageSha256,
+ oldPackageSha256: receipt.packageSha256,
+ receiptRevision: '11111111-1111-4111-8111-111111111111',
+ backupDirName: backupName,
+ phase: 'backed-up',
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);
+ });
+
+ it('same-hash backed-up update rolls back a final whose receipt revision is still old', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ };
+ const finalDir = path.join(rootDir, 'hello');
+ const backupName = '.cindy-updating-hello-acde0022';
+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));
+ await fs.promises.mkdir(finalDir);
+ await fs.promises.writeFile(path.join(finalDir, 'new.txt'), 'uncommitted');
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: receipt.packageSha256,
+ oldPackageSha256: receipt.packageSha256,
+ receiptRevision: '22222222-2222-4222-8222-222222222222',
+ backupDirName: backupName,
+ phase: 'backed-up',
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(path.join(finalDir, 'new.txt'))).toBe(false);
+ expect(fs.existsSync(path.join(finalDir, 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('legacy install marker with an old same-hash receipt and no final stays isolated', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256: string;
+ };
+ await fs.promises.rm(path.join(rootDir, 'hello'), { recursive: true, force: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'install',
+ packageSha256: receipt.packageSha256,
+ }),
+ );
+
+ freshManager();
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(manager.list()).toEqual([]);
+ });
+
+ it('卸载先撤批准再删目录:删目录失败时不留"孤立 approved receipt + 目录在"(防借尸还魂)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect(manager.list()[0].approval.state).toBe('approved');
+ // 让内容目录的 rm 失败(模拟句柄占用),但放行 receipt/快照的 rm。
+ const realRm = fs.promises.rm;
+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation((async (p: fs.PathLike, ...rest: unknown[]) => {
+ if (String(p) === path.join(rootDir, 'hello')) {
+ rmSpy.mockRestore();
+ const err = new Error('EBUSY: resource busy') as NodeJS.ErrnoException;
+ err.code = 'EBUSY';
+ throw err;
+ }
+ return (realRm as (...a: unknown[]) => Promise<void>)(p, ...rest);
+ }) as typeof fs.promises.rm);
+
+ const res = await manager.uninstall('hello');
+ await expectRejection(res, 'io');
+ // 关键:撤批准在删目录之前 —— receipt 已没了,目录还在但 fail closed(list 报
+ // legacy-unapproved),不会被这份 receipt 授权。孤立标记留给启动恢复收尾。
+ expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);
+ });
+
+ it('卸载崩在撤批准之后、删目录之前:恢复据 uninstall 标记删净残留目录', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 模拟崩溃现场:receipt 已撤(revoke 先行),目录还在,uninstall 标记在。
+ await fs.promises.rm(receiptPath(), { force: true });
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),
+ );
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+
+ freshManager(); // 构造期恢复
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('卸载崩在撤批准之前:恢复据 uninstall 标记把 receipt 与目录都删净', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 崩在写标记之后、撤批准之前:receipt 与目录都还在。
+ await fs.promises.writeFile(
+ pendingMarkerPath(),
+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),
+ );
+ expect(fs.existsSync(receiptPath())).toBe(true);
+
+ freshManager();
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);
+ });
+
+ it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ await fs.promises.writeFile(path.join(rootDir, 'foo'), 'not a dir');
+ const result = await manager.setEnabled('foo', false);
+ await expectRejection(result, 'not-installed');
+ });
+
+ it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const dir = path.join(rootDir, 'hello');
+ const outside = path.join(workDir, 'outside-target');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.rm(dir, { recursive: true, force: true });
+ try {
+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return; // 无 symlink 权限(Windows 未开发者模式):生产守卫仍由 classify 钉死。
+ }
+ const result = await manager.setEnabled('hello', false);
+ await expectRejection(result, 'not-installed');
+ // 关键:没有往 junction 目标(安装根之外)写 .disabled。
+ expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);
+ });
+});
+
+describe('GhostManager · update pre-rename recovery', () => {
+ it('marker 落盘但尚未 rename 时保留旧 final 与 receipt', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const finalDir = path.join(rootDir, 'hello');
+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');
+ await fs.promises.mkdir(stagingDir, { recursive: true });
+ const stateReceiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');
+ const statePendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');
+ const receipt = JSON.parse(await fs.promises.readFile(stateReceiptPath, 'utf8')) as {
+ packageSha256?: string;
+ };
+ await fs.promises.writeFile(
+ statePendingPath,
+ JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'update',
+ packageSha256: 'f'.repeat(64),
+ backupDirName: '.cindy-updating-hello-deadbeef',
+ phase: 'prepared',
+ oldPackageSha256: receipt.packageSha256,
+ }),
+ );
+
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });
+
+ expect(fs.existsSync(finalDir)).toBe(true);
+ expect(fs.existsSync(stateReceiptPath)).toBe(true);
+ expect(fs.existsSync(statePendingPath)).toBe(false);
+ expect(fs.existsSync(stagingDir)).toBe(false);
+ });
+});
+
+describe('GhostManager · install', () => {
+ it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
+ const manifest = {
+ ...goodManifest(),
+ name: 'Base name',
+ description: 'Base description',
+ locales: {
+ en: 'locales/en.json',
+ 'zh-CN': 'locales/zh-CN.json',
+ },
+ };
+ const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({
+ name,
+ description,
+ tools: { do_thing: { description: toolDescription } },
+ });
+ const cindy = await makeCindy('localized.cindy', manifest, {
+ 'locales/en.json': locale('English name', 'English description', 'English tool'),
+ 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),
+ });
+ const result = await manager.install(cindy);
+ expect(result).toMatchObject({
+ ghost: {
+ manifest: {
+ name: '中文名称',
+ description: '中文说明',
+ resolvedLocale: 'zh-CN',
+ tools: [{ name: 'do_thing', description: '中文工具' }],
+ },
+ },
+ });
+
+ hostLocale = 'ja';
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'English name',
+ description: 'English description',
+ resolvedLocale: 'ja',
+ tools: [{ name: 'do_thing', description: 'English tool' }],
+ });
+ hostLocale = 'fr-FR';
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'English name',
+ resolvedLocale: 'en',
+ });
+ });
+
+ it('installed locale symlinks cannot replace the Host-approved locale snapshot', async () => {
+ hostLocale = 'en';
+ const manifest = {
+ ...goodManifest(),
+ name: 'Base name',
+ locales: { en: 'locales/en.json' },
+ };
+ const locale = (name: string) => JSON.stringify({
+ name,
+ tools: { do_thing: { description: 'Localized tool' } },
+ });
+ const cindy = await makeCindy('localized-symlink.cindy', manifest, {
+ 'locales/en.json': locale('Packaged name'),
+ });
+ await manager.install(cindy);
+ const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');
+ const outsidePath = path.join(workDir, 'outside-locale.json');
+ await fs.promises.writeFile(outsidePath, locale('Outside name'));
+ await fs.promises.rm(localePath);
+ try {
+ await fs.promises.symlink(outsidePath, localePath, 'file');
+ } catch {
+ return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。
+ }
+
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'Packaged name',
+ resolvedLocale: 'en',
+ tools: [{ name: 'do_thing', description: 'Localized tool' }],
+ });
+
+ const localesDir = path.dirname(localePath);
+ const outsideLocalesDir = path.join(workDir, 'outside-locales');
+ await fs.promises.rm(localesDir, { recursive: true, force: true });
+ await fs.promises.mkdir(outsideLocalesDir);
+ await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));
+ await fs.promises.symlink(
+ outsideLocalesDir,
+ localesDir,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ expect(manager.list()[0].manifest).toMatchObject({
+ name: 'Packaged name',
+ resolvedLocale: 'en',
+ });
+ });
+
+ it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {
+ const manifest = {
+ ...goodManifest(),
+ locales: { en: 'locales/en.json' },
+ };
+ const missing = await makeCindy('locale-missing.cindy', manifest);
+ await expectRejection(await manager.install(missing), 'file-invalid');
+
+ const invalid = await makeCindy('locale-invalid.cindy', manifest, {
+ 'locales/en.json': '{ nope',
+ });
+ await expectRejection(await manager.install(invalid), 'file-invalid');
+
+ const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {
+ 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),
+ });
+ await expectRejection(await manager.install(unknownTool), 'file-invalid');
+
+ // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。
+ hostLocale = 'en';
+ const partial = await makeCindy('locale-partial.cindy', manifest, {
+ 'locales/en.json': JSON.stringify({ name: 'English partial' }),
+ });
+ expect(await manager.install(partial)).toMatchObject({
+ ghost: {
+ manifest: {
+ name: 'English partial',
+ resolvedLocale: 'en',
+ tools: [{ name: 'do_thing', description: '做点事' }],
+ },
+ },
+ });
+
+ const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {
+ 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),
+ });
+ await expectRejection(await manager.install(aliasedManifest), 'file-invalid');
+ });
+
+ it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {
+ const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });
+ const result = await manager.install(cindy);
+ expect('ghost' in result).toBe(true);
+ const { ghost } = result as { ghost: InstalledGhost };
+ expect(ghost.manifest.id).toBe('hello');
+ expect(ghost.dir).toBe(path.join(rootDir, 'hello'));
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);
+
+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);
+ });
+
+ it('returns the quarantined projection when install journal cleanup fails', async () => {
+ const store = (
+ manager as unknown as {
+ receiptStore: { clearPendingMutation(id: string): Promise<void> };
+ }
+ ).receiptStore;
+ const clearSpy = vi
+ .spyOn(store, 'clearPendingMutation')
+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));
+ let result: Awaited<ReturnType<GhostManager['install']>>;
+ try {
+ result = await manager.install(await makeCindy('valid.cindy', goodManifest()));
+ } finally {
+ clearSpy.mockRestore();
+ }
+ expect('ghost' in result).toBe(true);
+ if (!('ghost' in result)) throw new Error('expected committed install projection');
+ expect(result.ghost).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
+ expect(recovered.list()[0]).toMatchObject({ approval: { state: 'approved' } });
+ });
+
++ it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {
++ const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
++ const installed = await manager.install(cindy);
++
++ const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');
++ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
++
++ delete metadata.approvedAtResourceProvider;
++ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
++ expect(manager.list()[0].manifest.tools).toEqual([
++ { name: 'do_thing', description: '做点事' },
++ ]);
++
++ metadata.approvedAtResourceProvider = { tool: 'other_tool' };
++ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
++ });
++
+ it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {
+ const cindy = await makeCindy('hello.cindy', goodManifest());
+ const result = await manager.install(cindy, { initiallyEnabled: false });
+ expect('ghost' in result).toBe(true);
+ expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
+ // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);
+ // 重新启用即撕掉标记。
+ await manager.setEnabled('hello', true);
+ expect(manager.list()[0].enabled).toBe(true);
+ });
+
+ it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {
+ const zip = new JSZip();
+ zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));
+ zip.file('hello-pack/assets/a.txt', 'a');
+ const out = path.join(workDir, 'wrapped.cindy');
+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));
+
+ const result = await manager.install(out);
+ expect('ghost' in result).toBe(true);
+ // 包裹层被剥掉:内容直接落在 <root>/hello/ 下
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);
+ });
+
+ it('源文件不存在 → source-not-found', async () => {
+ await expectRejection(await manager.install(path.join(workDir, 'nope.cindy')), 'source-not-found');
+ });
+
+ it('不是 zip 的文件 → file-invalid', async () => {
+ const bad = path.join(workDir, 'bad.cindy');
+ await fs.promises.writeFile(bad, 'this is not a zip');
+ await expectRejection(await manager.install(bad), 'file-invalid');
+ });
+
+ it('缺 ghost.json → file-invalid', async () => {
+ const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ });
+
+ it('ghost.json 不是合法 JSON → file-invalid', async () => {
+ const zip = new JSZip();
+ zip.file('ghost.json', '{ not json');
+ const out = path.join(workDir, 'badjson.cindy');
+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));
+ await expectRejection(await manager.install(out), 'file-invalid');
+ });
+
+ it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {
+ const cindy = await makeCindy('decl.cindy', {
+ schemaVersion: 1,
+ id: 'legacy',
+ name: '老声明型',
+ version: '1.0.0',
+ kind: 'declaration',
+ panel: { title: '静态面板', body: '一段文字' },
+ });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ });
+
+ it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {
+ const manifest = {
+ ...goodManifest(),
+ slots: ['node'],
+ tools: undefined,
+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },
+ };
+ const cindy = await makeCindy('missing-node.cindy', manifest);
+ expect(await manager.inspect(cindy)).toMatchObject({
+ rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },
+ });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ });
+
+ it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(
+ '包不能自带主机保留文件 %s',
+ async (reservedFile) => {
+ const cindy = await makeCindy('reserved.cindy', goodManifest(), {
+ [reservedFile]: '{}',
+ });
+ expect(await manager.inspect(cindy)).toMatchObject({
+ rejection: {
+ code: 'file-invalid',
+ reason: expect.stringContaining('主机保留文件'),
+ },
+ });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ },
+ );
+
+ it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {
+ const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。
+ it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(
+ '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',
+ async (entryName) => {
+ // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字
+ // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。
+ const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });
+ const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {
+ [entryName]: evilManifest,
+ });
+ expect(await manager.inspect(cindy)).toMatchObject({
+ rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },
+ });
+ await expectRejection(await manager.install(cindy), 'file-invalid');
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(onChanged).not.toHaveBeenCalled();
+ },
+ );
+
+ it('重复装入同 id → already-installed,原安装不受影响', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ onChanged.mockClear();
+ await expectRejection(await manager.install(await makeCindy('b.cindy', goodManifest())), 'already-installed');
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {
+ await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));
+ await expectRejection(
+ await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),
+ 'command-conflict',
+ );
+ expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘
+ const ok = await manager.install(await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')));
+ expect('ghost' in ok).toBe(true);
+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);
+ });
+});
+
+describe('GhostManager · uninstall', () => {
+ it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ onChanged.mockClear();
+
+ const result = await manager.uninstall('hello');
+ expect('ok' in result).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(manager.list()).toEqual([]);
+ expect(onChanged).toHaveBeenCalledTimes(1);
+ expect(onChanged.mock.calls[0][0]).toEqual([]);
+ });
+
+ it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ onChanged.mockClear();
+
+ const result = await manager.uninstall('hello', { notify: false });
+
+ expect('ok' in result).toBe(true);
+ expect(manager.list()).toEqual([]);
+ expect(onChanged).not.toHaveBeenCalled();
+ });
+
+ it('persists builtin tombstone intent before removing approval or installed bytes', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ trustedBundledIds.add('hello');
+ recordBuiltinTombstone.mockImplementationOnce(() => {
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);
+ });
+
+ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });
+
+ expect(recordBuiltinTombstone).toHaveBeenCalledWith('hello');
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ });
+
+ it('does not turn Host reconciliation cleanup into a user builtin tombstone', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ trustedBundledIds.add('hello');
+
+ await expect(
+ manager.uninstall('hello', { notify: false, recordBuiltinTombstone: false }),
+ ).resolves.toEqual({ ok: true });
+
+ expect(recordBuiltinTombstone).not.toHaveBeenCalled();
+ expect(manager.list()).toEqual([]);
+ });
+
+ it('keeps builtin uninstall journal and bytes quarantined when tombstone persistence fails', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ trustedBundledIds.add('hello');
+ recordBuiltinTombstone.mockImplementationOnce(() => {
+ const error = new Error('access denied') as NodeJS.ErrnoException;
+ error.code = 'EACCES';
+ throw error;
+ });
+
+ await expect(manager.uninstall('hello', { notify: false })).resolves.toMatchObject({
+ rejection: { code: 'io' },
+ });
+
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);
+ expect(manager.list()[0]).toMatchObject({
+ manifest: { id: 'hello' },
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ expect(
+ JSON.parse(
+ await fs.promises.readFile(
+ path.join(workDir, 'ghosts-install-state', '.pending-hello.json'),
+ 'utf8',
+ ),
+ ),
+ ).toMatchObject({ kind: 'uninstall', builtinTombstone: true });
+ });
+
+ it('recovers a crashed builtin uninstall by persisting its tombstone before deletion', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const stateDir = path.join(workDir, 'ghosts-install-state');
+ await fs.promises.mkdir(stateDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(stateDir, '.pending-hello.json'),
+ `${JSON.stringify({
+ version: 1,
+ id: 'hello',
+ kind: 'uninstall',
+ builtinTombstone: true,
+ })}\n`,
+ );
+ const recoveredTombstone = vi.fn(() => {
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);
+ });
+
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: (id) => id === 'hello',
+ recordBuiltinTombstone: recoveredTombstone,
+ });
+
+ expect(recoveredTombstone).toHaveBeenCalledWith('hello');
+ expect(recovered.list()).toEqual([]);
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ expect(fs.existsSync(path.join(stateDir, '.pending-hello.json'))).toBe(false);
+ });
+
+ it('卸未装的 id → not-installed', async () => {
+ const result = await manager.uninstall('ghost');
+ expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');
+ });
+
+ it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {
+ await fs.promises.mkdir(rootDir, { recursive: true });
+ const sibling = path.join(workDir, 'victim');
+ await fs.promises.mkdir(sibling);
+ for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {
+ const result = await manager.uninstall(id);
+ expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');
+ }
+ expect(fs.existsSync(sibling)).toBe(true);
+ });
+
+ it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {
+ const cindy = await makeCindy('a.cindy', goodManifest());
+ await manager.install(cindy);
+ await manager.uninstall('hello');
+ const result = await manager.install(cindy);
+ expect('ghost' in result).toBe(true);
+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);
+ });
+});
+
+describe('GhostManager · list', () => {
+ it('根目录不存在 → 空清单(不报错)', () => {
+ expect(manager.list()).toEqual([]);
+ });
+
+ it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 手工捏三个坏目录
+ await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));
+ await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));
+ await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');
+ await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));
+ await fs.promises.writeFile(
+ path.join(rootDir, 'wrong-name', 'ghost.json'),
+ JSON.stringify(goodManifest('other-id')),
+ );
+ // 隐藏目录(staging 残留形态)也不进清单
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));
+
+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);
+ });
+
+ it('多意识按 id 排序', async () => {
+ await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));
+ await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));
+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);
+ });
+});
+
+describe('GhostManager · Host approval receipt', () => {
+ /** 真实 copyFile 引用:mock 复制行为的用例要靠它放行非目标文件。 */
+ const realCopyFile = fs.promises.copyFile;
+ const receiptPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `${id}.json`);
+ const writeBundledSource = async (
+ manifest: InstalledGhost['manifest'],
+ files: Record<string, string> = { 'main.js': '// bundled seed' },
+ ): Promise<{ sourceDir: string }> => {
+ const sourceDir = path.join(workDir, 'bundled-seeds', manifest.id);
+ await fs.promises.rm(sourceDir, { recursive: true, force: true });
+ await fs.promises.mkdir(sourceDir, { recursive: true });
+ trustedBundledIds.add(manifest.id);
+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(manifest));
+ for (const [relativePath, content] of Object.entries(files)) {
+ const target = path.join(sourceDir, relativePath);
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
+ await fs.promises.writeFile(target, content);
+ }
+ return { sourceDir };
+ };
+
+ /** 带 skill 槽的清单 + 配套包内文件(技能快照相关用例共用)。 */
+ const skillManifest = (): Record<string, unknown> => ({
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],
+ },
+ });
+ const skillFiles = (): Record<string, string> => ({
+ 'skills/demo/SKILL.md':
+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ });
+
+ it('keeps manifest, enabled state, and trust independent from mutable install files', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest()));
+ const before = manager.list()[0];
+ expect(fs.existsSync(receiptPath())).toBe(true);
+ expect(path.dirname(receiptPath())).not.toBe(rootDir);
+
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'ghost.json'),
+ JSON.stringify({
+ ...goodManifest(),
+ version: '99.0.0',
+ slots: ['node'],
+ node: { entry: 'evil.cjs', protocol: 'json-rpc-stdio' },
+ }),
+ );
+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', '.cindy-trust.json'),
+ JSON.stringify({
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ }),
+ );
+
+ const after = manager.list()[0];
+ expect(after.manifest).toEqual(before.manifest);
+ // 启停是**非对称**的例外:`.disabled` 镜像允许把启停态往下拉(停用必须永远能
+ // 成功,状态根不可写时镜像是唯一落点),但 manifest/trust/批准态不受安装目录
+ // 影响,镜像也不能把插件往"启用"方向翻。
+ expect(after.enabled).toBe(false);
+ expect(after.trust).toEqual(before.trust);
+ expect(after.approval.state).toBe('approved');
+
+ // 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。
+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+ expect(manager.list()[0].enabled).toBe(true);
+ });
+
+ it('fails legacy and corrupt receipts closed until a fully reviewed update replaces them', async () => {
+ const legacyDir = path.join(rootDir, 'hello');
+ await fs.promises.mkdir(legacyDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(legacyDir, 'ghost.json'),
+ JSON.stringify(goodManifest()),
+ );
+ await fs.promises.writeFile(path.join(legacyDir, 'main.js'), '// legacy');
+
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'legacy-unapproved' },
+ });
+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');
+
+ const reviewed = await updateGhost(
+ await makeCindy('reviewed.cindy', { ...goodManifest(), version: '2.0.0' }),
+ );
+ expect(reviewed).toMatchObject({
+ ghost: {
+ manifest: { version: '2.0.0' },
+ approval: { state: 'approved' },
+ },
+ });
+
+ await fs.promises.writeFile(receiptPath(), '{ broken');
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');
+ });
+
+ it('rejects an update when the approved revision changed after review', async () => {
+ await manager.install(await makeCindy('v1.cindy', goodManifest()));
+ const staleApproval = ghostInstallApprovalToken(manager.list()[0].approval);
+ const v2 = await makeCindy('v2.cindy', {
+ ...goodManifest(),
+ version: '2.0.0',
+ });
+ const first = await manager.update(v2, {
+ expectedInstalledApproval: staleApproval,
+ });
+ expect(first).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+
+ const v3 = await makeCindy('v3.cindy', {
+ ...goodManifest(),
+ version: '3.0.0',
+ });
+ await expectRejection(
+ await manager.update(v3, {
+ expectedInstalledApproval: staleApproval,
+ }),
+ 'state-changed',
+ );
+ expect(manager.list()[0].manifest.version).toBe('2.0.0');
+ });
+
+ it('quarantines an update while the new directory is published but receipt is not committed', async () => {
+ await manager.install(await makeCindy('v1.cindy', goodManifest()));
+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });
+ const originalRename = fs.promises.rename;
+ let releasePublish!: () => void;
+ let publishStarted!: () => void;
+ const publishStartedPromise = new Promise<void>((resolve) => {
+ publishStarted = resolve;
+ });
+ const publishGate = new Promise<void>((resolve) => {
+ releasePublish = resolve;
+ });
+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ if (String(from).includes('.cindy-installing-hello-')) {
+ const result = await originalRename(from, to);
+ publishStarted();
+ await publishGate;
+ return result;
+ }
+ return originalRename(from, to);
+ });
+ try {
+ const updatePromise = manager.update(v2, {
+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),
+ });
+ await publishStartedPromise;
+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
+ releasePublish();
+ expect('ghost' in (await updatePromise)).toBe(true);
+ } finally {
+ releasePublish();
+ renameSpy.mockRestore();
+ }
+ });
+
+ it('keeps a committed update quarantined until its durable journal is cleared', async () => {
+ await manager.install(await makeCindy('v1.cindy', goodManifest()));
+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });
+ const store = (
+ manager as unknown as {
+ receiptStore: { clearPendingMutation(id: string): Promise<void> };
+ }
+ ).receiptStore;
+ const clearSpy = vi
+ .spyOn(store, 'clearPendingMutation')
+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));
+ try {
+ const result = await manager.update(v2, {
+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),
+ });
+ expect('ghost' in result).toBe(true);
+ if (!('ghost' in result)) throw new Error('expected committed update projection');
+ expect(result.ghost).toMatchObject({
+ manifest: { version: '2.0.0' },
+ approval: { state: 'invalid' },
+ enabled: false,
+ });
+ expect(manager.list()[0]).toMatchObject({
+ manifest: { version: '2.0.0' },
+ approval: { state: 'invalid' },
+ enabled: false,
+ });
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ ).toBe(true);
+ } finally {
+ clearSpy.mockRestore();
+ }
+
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
+ expect(recovered.list()[0]).toMatchObject({
+ manifest: { version: '2.0.0' },
+ approval: { state: 'approved' },
+ });
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ ).toBe(false);
+ });
+
+ it('removes the receipt and approved skill snapshots on uninstall', async () => {
+ const manifest = {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],
+ },
+ };
+ const cindy = await makeCindy('skill.cindy', manifest, {
+ 'skills/demo/SKILL.md':
+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ });
+ await manager.install(cindy);
+ const listed = manager.list()[0];
+ expect(listed.approvedSkillRoot).toBeTruthy();
+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(true);
+
+ await manager.uninstall('skilled');
+ expect(fs.existsSync(receiptPath('skilled'))).toBe(false);
+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(false);
+ });
+
+ it('keeps an uninstall journal when receipt cleanup fails after content removal', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest()));
+ await fs.promises.rm(receiptPath());
+ await fs.promises.mkdir(receiptPath());
+ await fs.promises.writeFile(path.join(receiptPath(), 'blocked'), 'x');
+
+ const result = await manager.uninstall('hello');
+
+ expect(result).toEqual({ ok: true });
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ expect(manager.list()).toEqual([]);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(
+ true,
+ );
+ await fs.promises.rm(receiptPath(), { recursive: true, force: true });
+ const recovered = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ });
+ expect(recovered.list()).toEqual([]);
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),
+ ).toBe(false);
+ });
+
+ it('keeps disabling possible when the approved skill snapshot is gone, and rebuilds it on enable', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // 外部把快照删掉:停用是安全方向,必须仍然成功,不能把插件卡在既不能用也不能关。
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'approved' },
+ });
+
+ // 重新启用时从当前安装目录重建快照,不需要用户重新走一次确认。
+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });
+ const healed = manager.list()[0];
+ expect(healed.enabled).toBe(true);
+ expect(healed.approvedSkillRoot).toBe(snapshotRoot);
+ expect(
+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),
+ ).toContain('Approved instructions');
+ });
+
+ it('refuses to rebuild an enable-time snapshot from install bytes that drifted from the approved manifest', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // 安装目录里的 SKILL.md 与批准 manifest 声明的 description 不再一致,快照也没了:
+ // 停用照样成功(安全方向),但重建快照必须拒——否则启用就等于批准一份用户
+ // 没看过的技能指令。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Silently widened skill\n---\n\nTampered instructions\n',
+ );
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('prunes skill snapshots left behind by superseded approval revisions', async () => {
+ await manager.install(await makeCindy('skill-v1.cindy', skillManifest(), skillFiles()));
+ const firstSnapshot = manager.list()[0].approvedSkillRoot!;
+ const snapshotParent = path.dirname(firstSnapshot);
+
+ await updateGhost(
+ await makeCindy(
+ 'skill-v2.cindy',
+ { ...skillManifest(), version: '2.0.0' },
+ skillFiles(),
+ ),
+ 'skilled',
+ );
+ const secondSnapshot = manager.list()[0].approvedSkillRoot!;
+
+ expect(secondSnapshot).not.toBe(firstSnapshot);
+ expect(await fs.promises.readdir(snapshotParent)).toEqual([
+ path.basename(secondSnapshot),
+ ]);
+ });
+
+ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');
+ // 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。
+ const external = path.join(workDir, 'external-data');
+ await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });
+ await fs.promises.writeFile(path.join(external, 'stale-revision', 'sentinel.txt'), 'keep');
+ // 把 `<id>` 父段整个换成指向外部目录的 junction(同权限进程可做到)。
+ await fs.promises.rm(idDir, { recursive: true, force: true });
+ try {
+ await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return; // 环境建不了链接则跳过;判定逻辑平台同源。
+ }
+
+ // 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把
+ // 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的
+ // "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。
+ await manager.setEnabled('skilled', false);
+ expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);
+ // 外部目录里也不应多出任何被"发布"进去的快照字节。
+ expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);
+ });
+
+ it('holds the install-time SKILL.md size ceiling when rebuilding from mutable install bytes', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ const installedSkillMd = path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md');
+ // 快照缺失时取字节的来源是可变安装目录。这里塞的 SKILL.md frontmatter 与批准
+ // manifest 完全一致(躲过一致性校验),只是正文超过装入侧上限 —— 重建必须照样拒,
+ // 否则启用这条路会批准一份装入/更新永远不会接受的超大技能指令,而且要先整份
+ // 读进内存。
+ await fs.promises.writeFile(
+ installedSkillMd,
+ `---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n${'padding '.repeat(
+ GHOST_SKILL_MD_MAX_BYTES / 4,
+ )}`,
+ );
+ expect((await fs.promises.lstat(installedSkillMd)).size).toBeGreaterThan(
+ GHOST_SKILL_MD_MAX_BYTES,
+ );
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('refuses to rebuild a snapshot when only the SKILL.md body drifted', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,
+ // 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',
+ );
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('refuses to rebuild a snapshot when a helper file was added to the skill directory', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),
+ '#!/bin/sh\necho injected\n',
+ );
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('refuses to follow a link planted inside the skill directory when rebuilding', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ const outside = path.join(workDir, 'outside-skill');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'bytes from outside the skill dir');
+ // Windows junction 不需要管理员权限即可创建,是本平台成本最低的一条"把技能目录
+ // 之外的字节拉进批准快照"的路子。判据不能建立在 Dirent 类型位的实现细节上,
+ // 所以这条用例把行为钉住:planted link 一律拒,快照不落地。
+ try {
+ await fs.promises.symlink(
+ outside,
+ path.join(rootDir, 'skilled', 'skills', 'demo', 'linked'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ // 状态根里不该出现任何来自技能目录之外的字节(含崩溃残留的 .tmp)。
+ const stateRoot = manager.approvalStateRoot();
+ const leaked: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const child = path.join(dir, entry.name);
+ if (entry.isDirectory()) walk(child);
+ else if (entry.name === 'leak.txt') leaked.push(child);
+ }
+ };
+ if (fs.existsSync(stateRoot)) walk(stateRoot);
+ expect(leaked).toEqual([]);
+ });
+
+ it('rejects bytes swapped after the hash check but before the snapshot copy finishes', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // 先停用、再删快照:停用本身会把快照重建回来(字节没动、校验放行),顺序颠倒
+ // 会让后面的启用走"快照已存在"的早退路径,根本不经过复制。
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+
+ // 模拟同权限本机进程抢在复制这一刻换掉源字节:复制动作落到 temp 的是被改写的
+ // 内容,而源目录事后看起来仍然"没问题"。所以校验必须落在**已经复制到 temp 的
+ // 那份字节**上;若校验读的是源目录,这里就会放行一份没人确认过的技能指令。
+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';
+ let swapped = 0;
+ const spy = vi
+ .spyOn(fs.promises, 'copyFile')
+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {
+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {
+ swapped += 1;
+ await fs.promises.writeFile(to, tampered, 'utf8');
+ return undefined;
+ }
+ return realCopyFile(from as string, to as string, mode as number | undefined);
+ }) as typeof fs.promises.copyFile);
+ try {
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(swapped).toBe(1); // 确认这一轮真的走到了复制
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('applies the SKILL.md size ceiling to the bytes that actually landed in the snapshot', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+
+ // 源目录看起来一切正常(预检放行),复制这一刻落到 temp 的却是超大文件。上限必须
+ // 作用在这份字节上,而不是只作用在预检读到的那份 —— 预检不是安全边界。
+ let swapped = 0;
+ const spy = vi
+ .spyOn(fs.promises, 'copyFile')
+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {
+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {
+ swapped += 1;
+ await fs.promises.writeFile(to, 'x'.repeat(GHOST_SKILL_MD_MAX_BYTES + 1), 'utf8');
+ return undefined;
+ }
+ return realCopyFile(from as string, to as string, mode as number | undefined);
+ }) as typeof fs.promises.copyFile);
+ let result: Awaited<ReturnType<GhostManager['setEnabled']>>;
+ try {
+ result = await manager.setEnabled('skilled', true);
+ } finally {
+ spy.mockRestore();
+ }
+ await expectRejection(result, 'io');
+ // 断言到 reason 才能区分校验顺序:上限先跑报"exceeds N bytes",指纹先跑报
+ // "no longer matches..."。只比 code 的话两种顺序都是 io,用例就退化成
+ // 行为钉住、测不出重排。
+ expect((result as { rejection: { reason: string } }).rejection.reason).toMatch(
+ /exceeds \d+ bytes/,
+ );
+ expect(swapped).toBe(1);
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('keeps an install unusable when a stale approval cannot be revoked', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest()));
+ // 撤销失败(状态根不可写等,与写批准失败同一成因)不得退回"继续拿旧批准跑":
+ // removeInstallApproval 的契约是返回后一定不再被授权运行。
+ const spy = vi
+ .spyOn(fs.promises, 'rm')
+ .mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
+ try {
+ await manager.removeInstallApproval('hello');
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');
+ });
+
+ it('does not trust an already-present snapshot whose bytes were rewritten in place', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ const snapshotSkillMd = path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md');
+ // 快照就位后被就地改写(状态根没有写保护)。主 Agent 是顺着共享链接持续读它的,
+ // 所以"快照已存在"不能当成"仍是被批准的那份字节"直接早退信任。
+ await fs.promises.writeFile(
+ snapshotSkillMd,
+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',
+ );
+
+ // 安装目录里的字节没动过 → 删掉坏快照后能按批准字节重建,自愈。
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });
+ expect(await fs.promises.readFile(snapshotSkillMd, 'utf8')).toContain('Approved instructions');
});
- it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {
- const zip = new JSZip();
- zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));
- zip.file('hello-pack/assets/a.txt', 'a');
- const out = path.join(workDir, 'wrapped.cindy');
- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));
+ it('refuses to keep a rewritten snapshot when the installed bytes drifted too', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';
+ // 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。
+ await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);
+ await fs.promises.writeFile(
+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ tampered,
+ );
- const result = await manager.install(out);
- expect('ghost' in result).toBe(true);
- // 包裹层被剥掉:内容直接落在 <root>/hello/ 下
- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
});
- it('源文件不存在 → source-not-found', async () => {
- await expectRejection(await manager.install(path.join(workDir, 'nope.cindy')), 'source-not-found');
+ it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // 字节指纹校验不能把合法的自愈场景一起堵死:外部清理误删快照、内容没动过。
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(true);
+ expect(
+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),
+ ).toContain('Approved instructions');
});
- it('不是 zip 的文件 → file-invalid', async () => {
- const bad = path.join(workDir, 'bad.cindy');
- await fs.promises.writeFile(bad, 'this is not a zip');
- await expectRejection(await manager.install(bad), 'file-invalid');
+ it('bundled unchanged approval repairs a deleted skill snapshot without toggling enabled state', async () => {
+ const manifest = skillManifest();
+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));
+ const listed = manager.list()[0];
+ const source = await writeBundledSource(listed.manifest, skillFiles());
+ const snapshotRoot = listed.approvedSkillRoot!;
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+
+ expect(
+ await manager.approveTrustedBundledInstall(listed.manifest, listed.enabled, source),
+ ).toBe(true);
+ expect(manager.list()[0].enabled).toBe(listed.enabled);
+ const repairedSnapshotRoot = manager.list()[0].approvedSkillRoot!;
+ expect(
+ await fs.promises.readFile(
+ path.join(repairedSnapshotRoot, 'skills', 'demo', 'SKILL.md'),
+ 'utf8',
+ ),
+ ).toContain('Approved instructions');
});
- it('缺 ghost.json → file-invalid', async () => {
- const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });
- await expectRejection(await manager.install(cindy), 'file-invalid');
+ it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const receipt = JSON.parse(
+ await fs.promises.readFile(receiptPath('skilled'), 'utf8'),
+ ) as Record<string, unknown>;
+ // 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。
+ delete receipt.skillContentSha256;
+ await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));
+
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
});
- it('ghost.json 不是合法 JSON → file-invalid', async () => {
- const zip = new JSZip();
- zip.file('ghost.json', '{ not json');
- const out = path.join(workDir, 'badjson.cindy');
- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));
- await expectRejection(await manager.install(out), 'file-invalid');
+ 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('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {
- const cindy = await makeCindy('decl.cindy', {
- schemaVersion: 1,
- id: 'legacy',
- name: '老声明型',
- version: '1.0.0',
- kind: 'declaration',
- panel: { title: '静态面板', body: '一段文字' },
+ 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;
+
+ // 随包对账在换入新种子字节后写批准失败时走的收敛动作:撤掉陈旧批准。
+ // 撤掉之后插件必须彻底不可运行,而不是继续拿旧批准跑新代码。
+ await manager.removeInstallApproval('hello');
+
+ expect(fs.existsSync(receiptPath())).toBe(false);
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'legacy-unapproved' },
+ });
+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');
+
+ // 下一轮启动对账重新补批准即自愈,不需要用户介入。
+ expect(
+ await manager.approveTrustedBundledInstall(
+ approvedManifest,
+ true,
+ await writeBundledSource(approvedManifest),
+ ),
+ ).toBe(true);
+ expect(manager.list()[0]).toMatchObject({
+ enabled: true,
+ approval: { state: 'approved' },
});
- await expectRejection(await manager.install(cindy), 'file-invalid');
});
- it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {
- const manifest = {
- ...goodManifest(),
- slots: ['node'],
- tools: undefined,
- node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },
+ it('uses the immutable bundled source directory when minting the approval receipt', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const approvedManifest = manager.list()[0].manifest;
+ const sourceDir = path.join(workDir, 'bundled-seeds', approvedManifest.id);
+ trustedBundledIds.add(approvedManifest.id);
+ await fs.promises.mkdir(sourceDir, { recursive: true });
+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(approvedManifest));
+ await fs.promises.writeFile(path.join(sourceDir, 'main.js'), 'immutable bundled bytes');
+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'mutable bytes');
+
+ const unsafeCall = manager.approveTrustedBundledInstall as unknown as (
+ manifest: InstalledGhost['manifest'],
+ markerEnabled: boolean,
+ ) => Promise<boolean>;
+ await expect(unsafeCall.call(manager, approvedManifest, true)).rejects.toThrow(
+ /verified bundled source directory/,
+ );
+ await expect(
+ manager.approveTrustedBundledInstall(approvedManifest, true, {
+ sourceDir: path.join(rootDir, approvedManifest.id),
+ }),
+ ).rejects.toThrow(/mutable installed directory/);
+ const arbitrarySourceDir = path.join(workDir, 'arbitrary-source', approvedManifest.id);
+ await fs.promises.mkdir(arbitrarySourceDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(arbitrarySourceDir, 'ghost.json'),
+ JSON.stringify(approvedManifest),
+ );
+ await expect(
+ manager.approveTrustedBundledInstall(approvedManifest, true, {
+ sourceDir: arbitrarySourceDir,
+ }),
+ ).rejects.toThrow(/trusted seed roster/);
+
+ expect(
+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir }),
+ ).toBe(true);
+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256?: string;
};
- const cindy = await makeCindy('missing-node.cindy', manifest);
- expect(await manager.inspect(cindy)).toMatchObject({
- rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },
+ const sourcePackageSha256 = receipt.packageSha256;
+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'different mutable bytes');
+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });
+ const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {
+ packageSha256?: string;
+ };
+ expect(stableReceipt.packageSha256).toBe(sourcePackageSha256);
+ });
+
+ it('publishes bundled replacements through the pending journal and commits on receipt write', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest()));
+ const approvedManifest = manager.list()[0].manifest;
+ const { sourceDir } = await writeBundledSource(approvedManifest, {
+ 'main.js': 'immutable replacement bytes',
});
- await expectRejection(await manager.install(cindy), 'file-invalid');
+ const stateRoot = manager.approvalStateRoot();
+ const pendingPath = path.join(stateRoot, '.pending-hello.json');
+
+ await manager.runExclusiveMutation(async (mutation) => {
+ expect(await mutation.removeInstallApproval('hello')).toBe(true);
+ await mutation.publishTrustedBundledSeed('hello', sourceDir, { disabled: false });
+ expect(fs.existsSync(pendingPath)).toBe(true);
+ expect(
+ (await fs.promises.readdir(rootDir)).some((name) =>
+ name.startsWith('.cindy-updating-hello-'),
+ ),
+ ).toBe(true);
+ await mutation.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });
+ });
+
+ expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'main.js'), 'utf8')).toBe(
+ 'immutable replacement bytes',
+ );
+ expect(fs.existsSync(pendingPath)).toBe(false);
+ expect(
+ (await fs.promises.readdir(rootDir)).some((name) =>
+ name.startsWith('.cindy-updating-hello-'),
+ ),
+ ).toBe(false);
+ expect(manager.list()[0].approval.state).toBe('approved');
});
- it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(
- '包不能自带主机保留文件 %s',
- async (reservedFile) => {
- const cindy = await makeCindy('reserved.cindy', goodManifest(), {
- [reservedFile]: '{}',
- });
- expect(await manager.inspect(cindy)).toMatchObject({
- rejection: {
- code: 'file-invalid',
- reason: expect.stringContaining('主机保留文件'),
- },
- });
- await expectRejection(await manager.install(cindy), 'file-invalid');
- },
- );
+ it('keeps a receipt-pinned disable when the .disabled mirror was lost, and rewrites the mirror', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const { manifest: approvedManifest } = JSON.parse(
+ await fs.promises.readFile(receiptPath(), 'utf8'),
+ ) as { manifest: InstalledGhost['manifest'] };
+ const source = await writeBundledSource(approvedManifest);
+ // 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);
+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);
- it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {
- const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });
- await expectRejection(await manager.install(cindy), 'file-invalid');
- expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装
- expect(onChanged).not.toHaveBeenCalled();
+ // 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。
+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+
+ // 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式
+ // 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(false);
+ expect(manager.list()[0].enabled).toBe(false);
+ // 镜像被补写回去:回滚到旧客户端(只认镜像文件)时仍按停用对待。
+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
});
- // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。
- it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(
- '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',
- async (entryName) => {
- // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字
- // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。
- const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });
- const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {
- [entryName]: evilManifest,
- });
- expect(await manager.inspect(cindy)).toMatchObject({
- rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },
- });
- await expectRejection(await manager.install(cindy), 'file-invalid');
- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
- expect(onChanged).not.toHaveBeenCalled();
- },
- );
+ it('an old-client style .disabled marker still turns a bundled receipt off', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const { manifest: approvedManifest } = JSON.parse(
+ await fs.promises.readFile(receiptPath(), 'utf8'),
+ ) as { manifest: InstalledGhost['manifest'] };
+ const source = await writeBundledSource(approvedManifest);
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);
+
+ // 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——
+ // 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。
+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);
+ expect(manager.list()[0].enabled).toBe(false);
+ });
- it('重复装入同 id → already-installed,原安装不受影响', async () => {
+ it('a bundled update keeps the receipt-pinned disable even when the marker was lost', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
- onChanged.mockClear();
- await expectRejection(await manager.install(await makeCindy('b.cindy', goodManifest())), 'already-installed');
- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
- expect(onChanged).not.toHaveBeenCalled();
+ const { manifest: approvedManifest } = JSON.parse(
+ await fs.promises.readFile(receiptPath(), 'utf8'),
+ ) as { manifest: InstalledGhost['manifest'] };
+ expect(
+ await manager.approveTrustedBundledInstall(
+ approvedManifest,
+ true,
+ await writeBundledSource(approvedManifest),
+ ),
+ ).toBe(true);
+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);
+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+
+ // 随包更新那一轮走的是"建全新 receipt"分支,与稳态分支共用同一条合并规则:
+ // 只堵稳态分支的话,镜像在更新 tick 之前丢失仍会静默重新启用,同一个洞换条路。
+ const bumped = { ...approvedManifest, version: '1.0.1' };
+ expect(
+ await manager.approveTrustedBundledInstall(
+ bumped,
+ true,
+ await writeBundledSource(bumped),
+ ),
+ ).toBe(true);
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ manifest: { version: '1.0.1' },
+ });
+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
});
- it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {
- await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));
- await expectRejection(
- await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),
- 'command-conflict',
+ it('refuses to mint a bundled approval for an id outside the seed roster', async () => {
+ // 该入口不经用户确认就铸出批准;builtin-only 边界必须运行期强制,不能只靠
+ // "唯一调用者是随包对账"这条纪律。
+ const guarded = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ isTrustedBundledId: () => false,
+ });
+ const validated = validateGhostManifest(goodManifest());
+ if (!validated.ok) throw new Error(validated.reason);
+ await expect(
+ guarded.approveTrustedBundledInstall(
+ validated.manifest,
+ true,
+ await writeBundledSource(validated.manifest),
+ ),
+ ).rejects.toThrow(/种子清单/);
+ });
+
+ it('invalidates a receipt whose locale snapshot keys no longer match the manifest', async () => {
+ hostLocale = 'en';
+ const manifest = {
+ ...goodManifest(),
+ locales: { en: 'locales/en.json' },
+ };
+ await manager.install(
+ await makeCindy('localized.cindy', manifest, {
+ 'locales/en.json': JSON.stringify({ name: 'Approved English name' }),
+ }),
);
- expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘
- const ok = await manager.install(await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')));
- expect('ghost' in ok).toBe(true);
- expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);
+ const receipt = JSON.parse(
+ await fs.promises.readFile(receiptPath(), 'utf8'),
+ ) as Record<string, unknown>;
+ receipt.localeResources = {};
+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));
+
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
});
});
@@@ -3719,9 -643,9 +3774,14 @@@ describe('GhostManager · author / icon
const cindy = await makeCindy('icon2.cindy', iconManifest(), { 'assets/icon.png': 'PNGDATA' });
await manager.install(cindy);
await fs.promises.rm(path.join(rootDir, 'hello', 'assets', 'icon.png'));
++ // 受体模型:已批准投影的 icon 来自 receipt 快照(GhostManager.ts:1684),
++ // 装后删盘上 icon 文件不改变 list() 输出——快照即批准时钉下的图标。
++ // main 旧的"删文件/换软链 → 降级为无图标"两个用例前提在受体模型下不再成立
++ // (已批准根本不读盘);活读路径(legacy 未批准)的无泄漏由本文件
++ // 'never reads icon bytes from outside the plugin dir...' 用例覆盖。
const listed = manager.list();
expect(listed).toHaveLength(1);
- expect(listed[0].iconDataUrl).toBeUndefined();
+ expect(listed[0].iconDataUrl).toBe('data:image/png;base64,UE5HREFUQQ==');
expect(listed[0].manifest.author).toBe('Lizi');
});
diff --cc apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 8259e61764,c87d09c4e2..ffc741bc5d
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@@ -14,9 -16,9 +16,12 @@@ import { afterEach, beforeEach, describ
import {
FORGE_GUIDE,
- packGhostDir,
++ // 本测试文件用同名本地包装器(注入 sessionWorkdir / writeScaffold 门参)遮蔽,
++ // 故 raw 函数以别名导入;main 的 packGhostDirToFile 无包装器,直接导入。
+ packGhostDir as packGhostDirRaw,
+ packGhostDirToFile,
- scaffoldGhostDir,
+ scaffoldGhostDir as scaffoldGhostDirRaw,
+ type ForgeScaffoldWriteRequest,
type ForgeScaffoldTemplate,
} from '../forge';
import { GhostManager } from '../GhostManager';
@@@ -108,269 -74,6 +131,277 @@@ async function makeSrcDir(files: Record
}
describe('packGhostDir', () => {
+ it('writes an in-workdir alias output to the canonical source directory', async () => {
+ const sourceTarget = path.join(workDir, 'source-target');
+ const sourceAlias = path.join(workDir, 'source-alias');
+ await fs.promises.mkdir(sourceTarget, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(sourceTarget, 'ghost.json'),
+ JSON.stringify({ ...GOOD_MANIFEST, id: 'inside' }),
+ );
+ await fs.promises.writeFile(path.join(sourceTarget, 'main.js'), 'export default {}');
+ await fs.promises.symlink(
+ sourceTarget,
+ sourceAlias,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ const packed = await packGhostDir(sourceAlias);
+ expect(packed).toMatchObject({ ok: true, cindyPath: path.join(sourceTarget, 'inside-1.0.0.cindy') });
+ await expect(fs.promises.access(path.join(sourceTarget, 'inside-1.0.0.cindy'))).resolves.toBeUndefined();
+ });
+
+ it('rejects a file replaced by a link after classification', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {};',
+ });
+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-file-race-'));
+ const outsideFile = path.join(outsideRoot, 'secret.js');
+ await fs.promises.writeFile(outsideFile, 'outside-secret');
+ const originalLstat = fs.promises.lstat.bind(fs.promises);
+ let swapped = false;
- const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file) => {
- const result = await originalLstat(file);
++ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
++ // 忠实转发 options:readBoundedFileNoFollow 在 Windows 走 lstat(path,{bigint:true}),
++ // 丢掉 options 会返回非 bigint stat、令 sameInode 误判,破坏无关的 ghost.json 读取。
++ const result = await (
++ originalLstat as (p: fs.PathLike, o?: fs.StatOptions) => Promise<fs.Stats & fs.BigIntStats>
++ )(file, options);
+ if (!swapped && path.basename(String(file)) === 'main.js') {
+ swapped = true;
+ await fs.promises.rm(String(file), { force: true });
+ await fs.promises.symlink(
+ outsideFile,
+ String(file),
+ process.platform === 'win32' ? 'file' : undefined,
+ );
+ }
+ return result;
+ });
+ try {
+ const packed = await packGhostDir(dir);
+ expect(packed).toMatchObject({ ok: false, errorCode: 'ENTRY_MISSING' });
+ await expect(fs.promises.access(path.join(dir, 'demo-1.0.0.cindy'))).rejects.toThrow();
+ } finally {
+ lstatSpy.mockRestore();
+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('rejects a child directory replaced by a junction before recursion', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {};',
+ 'assets/readme.txt': 'inside',
+ });
+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-dir-race-'));
+ const outsideDir = path.join(outsideRoot, 'assets');
+ await fs.promises.mkdir(outsideDir, { recursive: true });
+ await fs.promises.writeFile(path.join(outsideDir, 'secret.txt'), 'outside-secret');
+ const assetsDir = path.join(dir, 'assets');
+ const originalLstat = fs.promises.lstat.bind(fs.promises);
+ let swapped = false;
- const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file) => {
- const result = await originalLstat(file);
++ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file: fs.PathLike, options?: fs.StatOptions) => {
++ // 忠实转发 options:readBoundedFileNoFollow 在 Windows 走 lstat(path,{bigint:true}),
++ // 丢掉 options 会返回非 bigint stat、令 sameInode 误判,破坏无关的 ghost.json 读取。
++ const result = await (
++ originalLstat as (p: fs.PathLike, o?: fs.StatOptions) => Promise<fs.Stats & fs.BigIntStats>
++ )(file, options);
+ if (!swapped && path.resolve(String(file)) === path.resolve(assetsDir)) {
+ swapped = true;
+ await fs.promises.rm(assetsDir, { recursive: true, force: true });
+ await fs.promises.symlink(
+ outsideDir,
+ assetsDir,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ }
+ return result;
+ });
+ try {
+ const packed = await packGhostDir(dir);
+ expect(packed).toMatchObject({ ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR' });
+ await expect(fs.promises.access(path.join(dir, 'demo-1.0.0.cindy'))).rejects.toThrow();
+ } finally {
+ lstatSpy.mockRestore();
+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('requires the source to stay inside the current session workdir', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {}',
+ });
+ await expect(packGhostDirRaw(dir)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ });
+ await expect(
+ packGhostDirRaw(dir, { sessionWorkdir: path.join(workDir, 'missing-workdir') }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ });
+
+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-outside-'));
+ try {
+ const outsideDir = path.join(outsideRoot, 'src');
+ await fs.promises.cp(dir, outsideDir, { recursive: true });
+ await expect(packGhostDirRaw(outsideDir, { sessionWorkdir: workDir })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ });
+
+ const alias = path.join(workDir, 'outside-alias');
+ await fs.promises.symlink(outsideDir, alias, 'junction');
+ await expect(packGhostDirRaw(alias, { sessionWorkdir: workDir })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
+ });
+ } finally {
+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('rejects Host-managed roots, descendants, case aliases, and junction aliases', async () => {
+ const managedRoot = path.join(workDir, 'managed');
+ const installedDir = path.join(managedRoot, 'demo');
+ await fs.promises.mkdir(installedDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(installedDir, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ await fs.promises.writeFile(path.join(installedDir, 'main.js'), '// installed');
+
+ await expect(
+ packGhostDir(managedRoot, { forbiddenRootDirs: [managedRoot] }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
+ });
+ await expect(
+ packGhostDir(installedDir, { forbiddenRootDirs: [managedRoot] }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
+ });
+
+ if (process.platform === 'win32') {
+ await expect(
+ packGhostDir(installedDir.toUpperCase(), {
+ forbiddenRootDirs: [managedRoot.toLowerCase()],
+ }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
+ });
+ }
+
+ const alias = path.join(workDir, 'installed-alias');
+ try {
+ await fs.promises.symlink(
+ installedDir,
+ alias,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+ await expect(
+ packGhostDir(alias, { forbiddenRootDirs: [managedRoot] }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
+ });
+ });
+
+ 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),
+ 'main.js': '// authoring source',
+ });
+ const result = await packGhostDir(dir, {
+ forbiddenRootDirs: [path.join(workDir, 'managed')],
+ });
+ expect(result.ok, JSON.stringify(result)).toBe(true);
+ });
+
it('happy path:产物落源码目录(id-version.cindy),且能被装入侧 inspect 认可', async () => {
const dir = await makeSrcDir({
'ghost.json': JSON.stringify(GOOD_MANIFEST),
@@@ -391,37 -94,313 +422,344 @@@
await fs.promises.rm(r.cindyPath, { force: true });
});
+ it('把已校验的 manifest 快照直接用于产物,避免校验 A、打包 B', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {};',
+ });
+ const originalReaddir = fs.promises.readdir.bind(fs.promises);
+ let mutated = false;
+ const readdirSpy = vi.spyOn(fs.promises, 'readdir').mockImplementation(async (directory, options) => {
+ const entries = await originalReaddir(directory, options as never);
+ if (!mutated && path.resolve(String(directory)) === path.resolve(dir)) {
+ mutated = true;
+ await fs.promises.writeFile(
+ path.join(dir, 'ghost.json'),
+ JSON.stringify({ ...GOOD_MANIFEST, id: 'bravo', version: '9.0.0' }),
+ );
+ }
+ return entries as never;
+ });
+ try {
+ const packed = await packGhostDir(dir);
+ expect(packed).toMatchObject({ ok: true, manifest: GOOD_MANIFEST });
+ if (!packed.ok) return;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));
+ const manifest = await zip.file('ghost.json')?.async('string');
+ expect(manifest).toContain('"id":"demo"');
+ expect(manifest).not.toContain('"id":"bravo"');
+ } finally {
+ readdirSpy.mockRestore();
+ }
+ });
+
+ it('iconPng 仅覆盖包内图标与清单快照,不改写插件源码', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ });
+ const iconPng = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ 'base64',
+ );
+
+ const packed = await packGhostDir(dir, { iconPng });
+ expect(packed.ok, JSON.stringify(packed)).toBe(true);
+ if (!packed.ok) return;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));
+ expect(JSON.parse(await zip.file('ghost.json')!.async('string'))).toMatchObject({
+ icon: 'assets/icon.png',
+ });
+ expect(await zip.file('assets/icon.png')!.async('nodebuffer')).toEqual(iconPng);
+
+ expect(JSON.parse(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'))).not.toHaveProperty(
+ 'icon',
+ );
+ await expect(fs.promises.stat(path.join(dir, 'assets/icon.png'))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+
+ const manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts') });
+ const inspected = await manager.inspect(packed.cindyPath);
+ expect('manifest' in inspected, JSON.stringify(inspected)).toBe(true);
+ });
+
+ it('iconPng 超过安装器 512 KiB 上限时在打包期拒绝', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ });
+
+ await expect(packGhostDir(dir, { iconPng: Buffer.alloc(512 * 1024 + 1) })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'TOO_LARGE',
+ });
+ });
+
+ it('已签名源码使用 iconPng 时拒绝 overlay,避免生成验签必失败的包', async () => {
+ const originalIcon = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ 'base64',
+ );
+ const manifest = { ...GOOD_MANIFEST, icon: 'assets/icon.png' };
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// brain',
+ });
+ await fs.promises.mkdir(path.join(dir, 'assets'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'assets/icon.png'), originalIcon);
+
+ const sourceZip = new JSZip();
+ sourceZip.file('ghost.json', JSON.stringify(manifest));
+ sourceZip.file('main.js', '// brain');
+ sourceZip.file('assets/icon.png', originalIcon);
+ const { privateKey } = crypto.generateKeyPairSync('ed25519');
+ const signed = await signGhostPackage(
+ await sourceZip.generateAsync({ type: 'nodebuffer' }),
+ { publisherName: 'Forge Test Publisher', privateKey },
+ );
+ const signedZip = await JSZip.loadAsync(signed);
+ const signatureBytes = await signedZip.file(GHOST_SIGNATURE_FILE)!.async('nodebuffer');
+ await fs.promises.writeFile(path.join(dir, GHOST_SIGNATURE_FILE), signatureBytes);
+
+ await expect(packGhostDir(dir, { iconPng: Buffer.from('replacement') })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: expect.stringContaining('已签名插件不能使用 AI 图标覆盖'),
+ });
+
+ const fallback = await packGhostDir(dir);
+ expect(fallback.ok, JSON.stringify(fallback)).toBe(true);
+ if (!fallback.ok) return;
+ const fallbackZip = await JSZip.loadAsync(await fs.promises.readFile(fallback.cindyPath));
+ expect(await fallbackZip.file('assets/icon.png')!.async('nodebuffer')).toEqual(originalIcon);
+ expect(await fallbackZip.file(GHOST_SIGNATURE_FILE)!.async('nodebuffer')).toEqual(signatureBytes);
+
+ const manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts') });
+ expect(await manager.inspect(fallback.cindyPath)).toMatchObject({
+ trust: { publisherSigned: true },
+ });
+ });
+
+ it('无效清单传 iconPng 仍返回 MANIFEST_INVALID,不被 overlay 改造成其它形状', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': 'null',
+ 'main.js': '// brain',
+ });
+
+ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ });
+ });
+
+ it('icon overlay 后清单超过安装器上限时在打包期拒绝', async () => {
+ // 用未知字段填充到上限附近:validator 会忽略它,但安装器仍必须按实际
+ // ghost.json 字节数限流。overlay 只能写紧凑 JSON,并且写入 zip 前再复核。
+ const emptyExtraBytes = Buffer.byteLength(
+ `${JSON.stringify({ ...GOOD_MANIFEST, extra: '' })}\n`,
+ 'utf8',
+ );
+ const manifest = {
+ ...GOOD_MANIFEST,
+ extra: 'x'.repeat(GHOST_INSTALL_MANIFEST_MAX_BYTES - emptyExtraBytes - 4),
+ };
+ const originalBytes = Buffer.byteLength(`${JSON.stringify(manifest)}\n`, 'utf8');
+ expect(originalBytes).toBeLessThanOrEqual(GHOST_INSTALL_MANIFEST_MAX_BYTES);
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(manifest),
+ 'main.js': '// brain',
+ });
+
+ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: expect.stringContaining('合成后超过安装器'),
+ });
+ });
+
+ it('assets/icon.png 已被目录占用时拒绝 icon overlay', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ });
+ await fs.promises.mkdir(path.join(dir, 'assets/icon.png'), { recursive: true });
+
+ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: expect.stringContaining('目标路径已被源码目录占用'),
+ });
+ });
+
+ it('assets/icon.png 子路径已被目录占用时拒绝 icon overlay', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ 'assets/icon.png/child.txt': 'occupied',
+ });
+
+ await expect(packGhostDir(dir, { iconPng: Buffer.from('png') })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ message: expect.stringContaining('目标路径已被源码目录占用'),
+ });
+ });
+
+ it('打包进 zip 的 ghost.json 是校验时的快照,并发改写不生效(防 TOCTOU)', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ });
+ // 模拟"校验通过后、写入 zip 前"目录被并发改写:保 id/version,偷加权限声明。
+ // 若打包时重读磁盘,包里的 manifest 会与返回值(安装侧审阅比对的依据)分叉。
+ const tampered = JSON.stringify({ ...GOOD_MANIFEST, slots: ['tool', 'network'], network: { allow: ['x.test'] } });
+ const realRead = fs.promises.readFile;
+ let ghostReads = 0;
+ const spy = vi
+ .spyOn(fs.promises, 'readFile')
+ .mockImplementation(((target: unknown, ...rest: unknown[]) => {
+ if (String(target).endsWith('ghost.json')) {
+ ghostReads += 1;
+ if (ghostReads > 1) return Promise.resolve(Buffer.from(tampered));
+ }
+ return (realRead as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.promises.readFile);
+ try {
+ const r = await packGhostDir(dir);
+ expect(r.ok, JSON.stringify(r)).toBe(true);
+ if (!r.ok) return;
+ const zip = await JSZip.loadAsync(await realRead(r.cindyPath));
+ const packedManifest = JSON.parse(await zip.file('ghost.json')!.async('string'));
+ // 包里的 manifest 必须与返回值一致(校验时的快照),不能是改写后的版本。
+ expect(packedManifest.slots).toEqual(GOOD_MANIFEST.slots);
+ expect(packedManifest).not.toHaveProperty('network');
+ await fs.promises.rm(r.cindyPath, { force: true });
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it.skipIf(!canSymlink)('ghost.json 为符号链接 → MANIFEST_INVALID(与市场发现/安装同一把闸)', async () => {
+ // 符号链接:目标是合法清单也不放行——“符号链接一律不穿透”覆盖身份卡本身,
+ // 否则打包输入目录里一根链接就能把目录外的文件读进打包管道。
+ const outside = path.join(workDir, 'outside-ghost.json');
+ await fs.promises.writeFile(outside, JSON.stringify(GOOD_MANIFEST));
+ const linked = path.join(workDir, 'src-linked');
+ await fs.promises.mkdir(linked, { recursive: true });
+ await fs.promises.symlink(outside, path.join(linked, 'ghost.json'));
+ await fs.promises.writeFile(path.join(linked, 'main.js'), '// brain');
+ expect(await packGhostDir(linked)).toMatchObject({
+ ok: false,
+ errorCode: 'MANIFEST_INVALID',
+ });
+ });
+
+ it('ghost.json 超限 → MANIFEST_INVALID(与市场发现/安装同一把闸)', async () => {
+ // 超限:JSON 本身合法(合法清单 + 尾随空白撑体积),必须在读取层按大小拒,
+ // 不能等到 JSON.parse/validate——那时数 GB 的文件已经进内存了。
+ const big = path.join(workDir, 'src-big');
+ await fs.promises.mkdir(big, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(big, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST) + ' '.repeat(600 * 1024),
+ );
+ await fs.promises.writeFile(path.join(big, 'main.js'), '// brain');
+ const r = await packGhostDir(big);
+ expect(r).toMatchObject({ ok: false, errorCode: 'MANIFEST_INVALID' });
+ if (!r.ok) expect(r.message).toContain('不是普通文件或超过');
+ });
+
+ it('zip 阶段逐文件走剩余预算限量闸:walk 之后被撑大的文件结构化拒绝', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ });
+ // 33MiB 零填充:超总预算(32MiB),但压缩后极小——旧实现无界 readFile 后
+ // 整包压缩体积检查照样通过,超大字节已经进过内存。
+ await fs.promises.writeFile(path.join(dir, 'blob.bin'), Buffer.alloc(33 * 1024 * 1024));
+ // 模拟"walk 预算预估时文件还小,zip 读取时已被并发撑大":walk 的 stat 看
+ // 到 10 字节。句柄侧 handle.stat 不受此 spy 影响,读到真实大小。
+ const realStat = fs.promises.stat;
+ const spy = vi.spyOn(fs.promises, 'stat').mockImplementation((async (
+ target: Parameters<typeof fs.promises.stat>[0],
+ ...rest: unknown[]
+ ) => {
+ const st = await (realStat as (...a: unknown[]) => Promise<fs.Stats>)(target, ...rest);
+ if (String(target).endsWith('blob.bin')) {
+ return Object.assign(Object.create(Object.getPrototypeOf(st)), st, { size: 10 });
+ }
+ return st;
+ }) as typeof fs.promises.stat);
+ try {
+ const r = await packGhostDir(dir);
+ expect(r).toMatchObject({ ok: false, errorCode: 'TOO_LARGE' });
+ if (!r.ok) expect(r.message).toContain('打包期间被并发改动或超出剩余体积预算');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('打包器不自我参照:realpath 与调用方给定的规范根不一致 → 拒绝', async () => {
+ // 只靠"自己 realpath 一次、再拿它当 containWithin 锚点"是自我参照:目录在
+ // 调用方校验之后、这里解析之前被换成指向外部的链接时,锚点就是那个外部目录,
+ // 包含性判定全部通过,外部 payload 会被打包。锚点必须由上游给。
+ const outside = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// outside payload',
+ 'secret.txt': 'EXFILTRATED',
+ });
+ const staged = path.join(workDir, 'staged');
+ await fs.promises.mkdir(staged, { recursive: true });
+ const pluginDir = path.join(staged, 'alpha');
+ await fs.promises.mkdir(pluginDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(pluginDir, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ await fs.promises.writeFile(path.join(pluginDir, 'main.js'), '// brain');
+ // 调用方(安装管道)校验时拿到的规范根。
+ const expectedRealDir = await fs.promises.realpath(pluginDir);
+ // 校验之后被换成指向外部目录的链接(外部目录留着同样的 ghost.json)。
+ await fs.promises.rm(pluginDir, { recursive: true, force: true });
+ await fs.promises.symlink(
+ await fs.promises.realpath(outside),
+ pluginDir,
+ directoryLinkType,
+ );
+
+ const dest = path.join(workDir, 'out.cindy');
+ const r = await packGhostDirToFile(pluginDir, dest, expectedRealDir);
+ expect(r).toMatchObject({ ok: false, errorCode: 'MANIFEST_INVALID' });
+ if (!r.ok) expect(r.message).toContain('打包前被替换');
+ // 外部 payload 一个字节都没进包(产物根本没生成)。
+ expect(fs.existsSync(dest)).toBe(false);
+ });
+
+ it('规范根一致时正常打包(锚点校验不误伤)', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ });
+ const dest = path.join(workDir, 'ok.cindy');
+ const realDir = await fs.promises.realpath(dir);
+ const r = await packGhostDirToFile(realDir, dest, realDir);
+ expect(r.ok, JSON.stringify(r)).toBe(true);
+ expect(fs.existsSync(dest)).toBe(true);
+ });
+
+ it('结构守卫:forge.ts 与 ghostLocaleFiles.ts 不允许出现按路径的 readFile', async () => {
+ // 打包管道触及的都是用户可写目录,所有读取必须走 readBoundedFileNoFollow
+ // 系列;任何一处退回按路径 readFile 都会重开"检查与读取两次打开"的窗口。
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ for (const rel of ['../forge.ts', '../ghostLocaleFiles.ts']) {
+ const source = await fs.promises.readFile(path.join(here, rel), 'utf8');
+ expect(source, rel).not.toMatch(/fs\.promises\.readFile\(/);
+ expect(source, rel).not.toMatch(/readFileSync\(/);
+ expect(source, rel).toMatch(/readBoundedFileNoFollow/);
+ }
+ });
+
it('打包跳过开发残留:.git / node_modules / 隐藏文件 / 旧 .cindy 不进包', async () => {
const dir = await makeSrcDir({
'ghost.json': JSON.stringify(GOOD_MANIFEST),
diff --cc apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
index 3497f6ac94,0000000000..d22c5eddd9
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
@@@ -1,87 -1,0 +1,98 @@@
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+/**
+ * 源码契约测试:所有会改写插件世界(内容根/状态根/运行时)的 IPC 写路径,
+ * handler 体内必须持 GhostMutationCoordinator 租约。
+ *
+ * 背景:GhostManager 与 ReceiptStore 的根路径都是调用时现解析的
+ * (ownerScopedUserDataPath),账号切换边界只等待 coordinator
+ * (bootstrap-electron 的 waitForGhostMutations)。写路径不持租约,异步窗口
+ * (inspect/parse/hash)里切号落定,后半段写入就会漏进新 owner 的命名空间 ——
+ * A 发起的安装落进 B、A 的内容目录配上 B 的 receipt。第 7 轮 review 实锤了
+ * 本地 install/update/set-enabled 三条正是这么漏的(市场路径一直有租约)。
+ *
+ * index.ts 拉起整张 main 进程单例图,handler 无法脱离 electron 直测,所以用
+ * 源码扫描钉契约:每个列出的 handler 块里必须出现 beginGhostMutation(取租约)
+ * 与 captureGhostMutationOwner(入口同步捕获 owner,防"用切换后的 owner 取租约
+ * 照样通过"——租约要核对的是发起时刻的 owner)。新增写路径 handler 时把名字加进
+ * 清单;想移除租约必须先改掉 owner 动态解析这个前提。
+ */
+
+const MUTATING_GHOST_CHANNELS = [
+ 'ghosts:install',
+ 'ghosts:update',
+ 'ghosts:set-enabled',
+] as const;
+
+function handlerBlock(source: string, channel: string): string {
+ const start = source.indexOf(`ipcMain.handle('${channel}'`);
+ expect(start, `handler for ${channel} not found`).toBeGreaterThan(-1);
+ // handler 以两空格缩进的 `});` 收尾(仓库排版惯例);取到那里足够覆盖整个闭包。
+ const end = source.indexOf('\n });', start);
+ expect(end, `handler block for ${channel} has no terminator`).toBeGreaterThan(start);
+ return source.slice(start, end);
+}
+
+describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {
+ const source = fs.readFileSync(
+ path.join(__dirname, '..', 'index.ts'),
+ 'utf8',
+ );
+
+ for (const channel of MUTATING_GHOST_CHANNELS) {
+ it(`${channel} 持租约且入口同步捕获 owner`, () => {
+ const block = handlerBlock(source, channel);
+ expect(block, `${channel} 缺 beginGhostMutation`).toContain('beginGhostMutation(');
+ expect(block, `${channel} 缺 captureGhostMutationOwner`).toContain(
+ 'captureGhostMutationOwner()',
+ );
+ });
+ }
+
+ it('ghosts:reapprove-installed 持租约,owner 以 inspect 时点的一次性票据为准(更强于 handler 内 capture)', () => {
+ // 第 8 轮 P0-2:owner 在 confirm 入口才 capture 绑不住"读事实那一刻"——确认卡
+ // 停留期间切号,A 看的确认可以给 B 的同 id 目录铸批准。现在 inspect 发一次性
+ // 票据(钉 owner + id + manifestSha256),confirm 原子消费并以**票据里的 owner**
+ // 起租约:generation 不等直接拒。handler 内不该再出现 captureGhostMutationOwner
+ // (那会退化回"用确认时刻的 owner",正是要消掉的形态)。
+ const block = handlerBlock(source, 'ghosts:reapprove-installed');
+ expect(block).toContain('reapproveTickets.consume(');
+ expect(block).toContain('beginGhostMutation(ticket.owner)');
+ expect(block).not.toContain('captureGhostMutationOwner()');
+ // inspect 侧必须在读事实之前捕获 owner 并发票。
+ const inspectBlock = handlerBlock(source, 'ghosts:reapprove-inspect');
+ expect(inspectBlock).toContain('captureGhostMutationOwner()');
+ expect(inspectBlock).toContain('reapproveTickets.issue(');
+ });
+
+ it('ghosts:uninstall 经 uninstallGhostAndCleanup 持租约(入口同步取,无异步窗口故无需 capture)', () => {
+ const block = handlerBlock(source, 'ghosts:uninstall');
+ expect(block).toContain('uninstallGhostAndCleanup(');
- const start = source.indexOf('export async function uninstallGhostAndCleanup');
++ // main 的 per-ghost 屏障重构后,外层委托 withGhostInstallLock,实际清理与租约在
++ // ...Locked 内(lock 内取租约,包住整段清理)。契约钉在真正干活的 Locked 函数上。
++ const outerStart = source.indexOf('export async function uninstallGhostAndCleanup');
++ expect(outerStart).toBeGreaterThan(-1);
++ const outer = source.slice(outerStart, source.indexOf('\n}', outerStart));
++ expect(outer).toContain('withGhostInstallLock(');
++ const start = source.indexOf('async function uninstallGhostAndCleanupLocked');
+ expect(start).toBeGreaterThan(-1);
+ const fn = source.slice(start, source.indexOf('\n}', start));
+ expect(fn).toContain('beginGhostMutation(');
+ });
+
+ it('市场装入/更新持租约(installOrUpdateMarketGhostPackage)', () => {
- const start = source.indexOf('export async function installOrUpdateMarketGhostPackage');
++ // 同上:外层委托 withGhostInstallLock,owner 捕获 + 起租约在 ...Locked 内。
++ const outerStart = source.indexOf('export async function installOrUpdateMarketGhostPackage');
++ expect(outerStart).toBeGreaterThan(-1);
++ const outer = source.slice(outerStart, source.indexOf('\n}', outerStart));
++ expect(outer).toContain('withGhostInstallLock(');
++ const start = source.indexOf('async function installOrUpdateMarketGhostPackageLocked');
+ expect(start).toBeGreaterThan(-1);
+ const block = source.slice(start, source.indexOf('\n}', start));
+ expect(block).toContain('captureGhostMutationOwner()');
+ expect(block).toContain('beginGhostMutation(');
+ });
+});
diff --cc apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts
index 0000000000,38abeddcda..f7bd5e29d4
mode 000000,100644..100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts
@@@ -1,0 -1,253 +1,254 @@@
+ import { describe, expect, it, vi } from 'vitest';
+
+ import type { GhostNetworkNeeds, InstalledGhost } from '../../../shared/ghost.js';
+ import { GhostNetworkSlot, type NetworkSlotDeps } from '../networkSlot.js';
+
+ const URL = 'https://service-a.x.test/whoami';
+ const INPUT = {
+ membershipId: 'membership-1',
+ audience: 'org-example:plugin-a',
+ allowedHosts: ['service-a.x.test'],
+ };
+ const TOKEN_INPUT = { membershipId: INPUT.membershipId, audience: INPUT.audience };
+
+ function ghost(
+ hosts: string[] = ['service-a.x.test'],
+ injectHosts: string[] = ['service-a.x.test'],
+ ): InstalledGhost {
+ const network: GhostNetworkNeeds = {
+ hosts,
+ secrets: [
+ {
+ key: 'cindy_identity',
+ label: 'Cindy Enterprise Identity',
+ source: 'oidc-token',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: injectHosts,
+ },
+ },
+ ],
+ };
+ return {
+ manifest: {
+ schemaVersion: 2,
+ id: 'plugin-a',
+ name: 'Plugin A',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool', 'network'],
+ tools: [{ name: 'whoami_a', description: 'Show identity' }],
+ network,
+ },
+ dir: '/fake/plugin-a',
+ enabled: true,
++ approval: { state: 'approved', revision: 'rev-a' },
+ };
+ }
+
+ function response(status = 200): Response {
+ return new Response(JSON.stringify({ service: 'a', ok: status === 200 }), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+
+ function makeSlot(overrides: Partial<NetworkSlotDeps> = {}) {
+ const fetchImpl = vi.fn<NetworkSlotDeps['fetchImpl']>(async () => response());
+ const resolve = vi.fn(() => INPUT);
+ const getToken = vi.fn(async () => 'connection.jwt.value');
+ const invalidate = vi.fn();
+ const deps: NetworkSlotDeps = {
+ getGhost: () => ghost(),
+ readSecret: () => null,
+ getLoginEmail: () => null,
+ fetchImpl,
+ readGhostMedia: async () => null,
+ takeDirDeposit: () => null,
+ writeSaveDeposit: async () => null,
+ saveGhostMedia: async () => ({ url: '', hash: '', ext: '' }),
+ isSupportedMediaMime: () => false,
+ connectionTokens: { resolve, getToken, invalidate },
+ ...overrides,
+ };
+ return {
+ slot: new GhostNetworkSlot(deps),
+ fetchImpl,
+ resolve,
+ getToken,
+ invalidate,
+ };
+ }
+
+ describe('networkSlot Connection identity', () => {
+ it('replaces a plugin-supplied Authorization header and never returns the token', async () => {
+ const h = makeSlot();
+ const result = await h.slot.handleFetchRequest('plugin-a', {
+ url: URL,
+ headers: { Authorization: 'Bearer forged-by-plugin' },
+ });
+
+ expect(result.ok).toBe(true);
+ expect(h.getToken).toHaveBeenCalledWith(TOKEN_INPUT);
+ expect(h.fetchImpl.mock.calls[0]?.[1].headers).toMatchObject({
+ Authorization: 'Bearer connection.jwt.value',
+ });
+ expect(JSON.stringify(result)).not.toContain('connection.jwt.value');
+ expect(JSON.stringify(result)).not.toContain('forged-by-plugin');
+ });
+
+ it('fails closed when the audience resolver does not authorize the plugin', async () => {
+ const h = makeSlot({
+ connectionTokens: {
+ resolve: () => null,
+ getToken: vi.fn(async () => {
+ throw new Error('must not issue');
+ }),
+ invalidate: vi.fn(),
+ },
+ });
+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(result.ok).toBe(false);
+ expect(h.fetchImpl).not.toHaveBeenCalled();
+ expect(JSON.stringify(result)).not.toContain('org-example');
+ });
+
+ it('fails closed before issuance when the target host is absent from the manifest', async () => {
+ const h = makeSlot({
+ connectionTokens: {
+ resolve: () => ({ ...INPUT, allowedHosts: ['other.x.test'] }),
+ getToken: vi.fn(async () => {
+ throw new Error('must not issue');
+ }),
+ invalidate: vi.fn(),
+ },
+ });
+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(result.ok).toBe(false);
+ expect(h.fetchImpl).not.toHaveBeenCalled();
+ expect(JSON.stringify(result)).not.toContain(INPUT.audience);
+ });
+
+ it('blocks a redirect before the second request when its host is not in the manifest', async () => {
+ const h = makeSlot({
+ getGhost: () =>
+ ghost(
+ ['service-a.x.test', 'service-b.x.test'],
+ ['service-a.x.test', 'service-b.x.test'],
+ ),
+ });
+ h.fetchImpl.mockResolvedValueOnce(
+ new Response(null, {
+ status: 302,
+ headers: { location: 'https://service-b.x.test/whoami' },
+ }),
+ );
+
+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(result.ok).toBe(false);
+ expect(h.fetchImpl).toHaveBeenCalledTimes(1);
+ expect(h.getToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('invalidates, reissues, and replays exactly once after a 401', async () => {
+ const h = makeSlot();
+ h.fetchImpl.mockResolvedValueOnce(response(401)).mockResolvedValueOnce(response(200));
+ h.getToken.mockResolvedValueOnce('connection.jwt.1').mockResolvedValueOnce('connection.jwt.2');
+
+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(result.ok).toBe(true);
+ expect(h.fetchImpl).toHaveBeenCalledTimes(2);
+ expect(h.getToken).toHaveBeenCalledTimes(2);
+ expect(h.invalidate).toHaveBeenCalledTimes(1);
+ expect(h.invalidate).toHaveBeenCalledWith(TOKEN_INPUT);
+ expect(h.fetchImpl.mock.calls.map((call) => call[1].headers.Authorization)).toEqual([
+ 'Bearer connection.jwt.1',
+ 'Bearer connection.jwt.2',
+ ]);
+ });
+
+ it('invalidates but does not replay a non-idempotent request after a 401', async () => {
+ const h = makeSlot();
+ h.fetchImpl.mockResolvedValue(response(401));
+
+ const result = await h.slot.handleFetchRequest('plugin-a', {
+ url: URL,
+ method: 'POST',
+ body: '{"action":"create"}',
+ });
+
+ expect(result).toMatchObject({ ok: true, status: 401 });
+ expect(h.fetchImpl).toHaveBeenCalledTimes(1);
+ expect(h.getToken).toHaveBeenCalledTimes(1);
+ expect(h.invalidate).toHaveBeenCalledTimes(1);
+ expect(h.invalidate).toHaveBeenCalledWith(TOKEN_INPUT);
+ });
+
+ it.each([301, 302, 303])(
+ 'does not replay an original POST after a %s redirect downgrades it to GET before a 401',
+ async (redirectStatus) => {
+ const h = makeSlot();
+ h.fetchImpl
+ .mockResolvedValueOnce(
+ new Response(null, {
+ status: redirectStatus,
+ headers: { location: 'https://service-a.x.test/after-redirect' },
+ }),
+ )
+ .mockResolvedValueOnce(response(401));
+
+ const result = await h.slot.handleFetchRequest('plugin-a', {
+ url: URL,
+ method: 'POST',
+ body: '{"action":"create"}',
+ });
+
+ expect(result).toMatchObject({ ok: true, status: 401 });
+ expect(h.fetchImpl).toHaveBeenCalledTimes(2);
+ expect(h.fetchImpl.mock.calls.map((call) => call[1].method)).toEqual(['POST', 'GET']);
+ expect(h.getToken).toHaveBeenCalledTimes(2);
+ expect(h.invalidate).toHaveBeenCalledTimes(1);
+ expect(h.invalidate).toHaveBeenCalledWith(TOKEN_INPUT);
+ },
+ );
+
+ it('does not retry 403 and never retries a second 401', async () => {
+ const forbidden = makeSlot();
+ forbidden.fetchImpl.mockResolvedValue(response(403));
+ const forbiddenResult = await forbidden.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(forbiddenResult).toMatchObject({ ok: true, status: 403 });
+ expect(forbidden.fetchImpl).toHaveBeenCalledTimes(1);
+ expect(forbidden.invalidate).not.toHaveBeenCalled();
+
+ const unauthorized = makeSlot();
+ unauthorized.fetchImpl.mockResolvedValue(response(401));
+ const unauthorizedResult = await unauthorized.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(unauthorizedResult).toMatchObject({ ok: true, status: 401 });
+ expect(unauthorized.fetchImpl).toHaveBeenCalledTimes(2);
+ expect(unauthorized.invalidate).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels before fetch when the active Membership changes after issuance', async () => {
+ const h = makeSlot();
+ h.resolve
+ .mockReturnValueOnce(INPUT)
+ .mockReturnValueOnce({ ...INPUT, membershipId: 'membership-2' });
+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(result.ok).toBe(false);
+ expect(h.fetchImpl).not.toHaveBeenCalled();
+ expect(JSON.stringify(result)).not.toContain('connection.jwt.value');
+ });
+
+ it('cancels before fetch when the manifest no longer authorizes the injected hostname', async () => {
+ const h = makeSlot();
+ h.resolve
+ .mockReturnValueOnce(INPUT)
+ .mockReturnValueOnce({ ...INPUT, allowedHosts: ['other.x.test'] });
+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });
+ expect(result.ok).toBe(false);
+ expect(h.fetchImpl).not.toHaveBeenCalled();
+ expect(JSON.stringify(result)).not.toContain('connection.jwt.value');
+ });
+ });
diff --cc apps/desktop/src/main/cindy-brain/forge.ts
index 72b80b7720,885271eba9..d176039e1c
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@@ -27,233 -26,19 +27,51 @@@ import
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
- import {
- classifyGhostDirEntry,
- resolveGhostContentPath,
- } from './ghostContentTree.js';
+ import { GHOST_MANIFEST_MAX_BYTES, readBoundedFileNoFollow } from '../utils/readBoundedFile.js';
+ import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
+ import { GHOST_SIGNATURE_FILE } from './ghostSignature.js';
+import { isPathInsideDir } from './dirDeposit.js';
import { checkSkillMdConsistency } from './skillSlot.js';
- /** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */
- const MAX_BASIC_FILES = 256;
- const MAX_NODE_FILES = 2_048;
- const MAX_BASIC_TOTAL_BYTES = 32 * 1024 * 1024;
- const MAX_NODE_TOTAL_BYTES = 256 * 1024 * 1024;
- const MAX_BASIC_CINDY_BYTES = 8 * 1024 * 1024;
- const MAX_NODE_CINDY_BYTES = 128 * 1024 * 1024;
-
- class ForgeSourceChangedError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'ForgeSourceChangedError';
- }
- }
-
- class ForgeSizeLimitError extends Error {
- constructor(message: string) {
- super(message);
- this.name = 'ForgeSizeLimitError';
- }
- }
-
- function sameForgeFileIdentity(expected: fs.Stats, current: fs.Stats): boolean {
- if (!current.isFile() || expected.size !== current.size || expected.mtimeMs !== current.mtimeMs) {
- return false;
- }
- // Some Windows filesystems report zero dev/ino. Size + mtime is the portable
- // fallback there; when identity is available, replacement through a swapped
- // ancestor must also match the original object.
- return (expected.dev === 0 && expected.ino === 0) ||
- (expected.dev === current.dev && expected.ino === current.ino);
- }
-
- function sameForgeDirectoryIdentity(expected: fs.Stats, current: fs.Stats): boolean {
- if (!current.isDirectory()) return false;
- return (expected.dev === 0 && expected.ino === 0) ||
- (expected.dev === current.dev && expected.ino === current.ino);
- }
++/**
++ * `fs.promises.realpath` 没有 native 变体,promisify 一次(scaffold/pack 的受管根
++ * 与 workdir 门都靠它拿到规范路径再比对)。
++ */
++const realpathNative = promisify(fs.realpath.native);
+
+function sameForgeCanonicalPath(left: string, right: string): boolean {
+ const fold = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value);
+ return fold(path.resolve(left)) === fold(path.resolve(right));
+}
+
- async function readForgeFileStable(
- absPath: string,
- sourceRoot: string,
- expectedFromWalk?: fs.Stats,
- maxBytes?: number,
- ): Promise<Buffer> {
- const realBeforeOpen = await realpathNative(absPath);
- if (!isPathInsideDir(sourceRoot, realBeforeOpen)) {
- throw new ForgeSourceChangedError('Forge source entry escaped the validated source root');
- }
- const pathStat = await fs.promises.lstat(absPath);
- if (!pathStat.isFile() || pathStat.isSymbolicLink()) {
- throw new ForgeSourceChangedError('Forge source entry changed after classification');
- }
- if (expectedFromWalk && !sameForgeFileIdentity(expectedFromWalk, pathStat)) {
- throw new ForgeSourceChangedError('Forge source file changed after classification');
- }
-
- const noFollow = fs.constants.O_NOFOLLOW ?? 0;
- let handle: Awaited<ReturnType<typeof fs.promises.open>>;
- try {
- handle = await fs.promises.open(absPath, fs.constants.O_RDONLY | noFollow);
- } catch (error) {
- const code = (error as NodeJS.ErrnoException).code;
- if (code === 'ELOOP' || code === 'ENOENT' || code === 'EISDIR' || code === 'ENOTDIR') {
- throw new ForgeSourceChangedError('Forge source entry changed before open');
- }
- throw error;
- }
- try {
- const opened = await handle.stat();
- if (!sameForgeFileIdentity(pathStat, opened)) {
- throw new ForgeSourceChangedError('Forge source file identity changed before read');
- }
- if (opened.nlink !== 1) {
- throw new ForgeSourceChangedError('Forge source file has aliases outside the validated tree');
- }
- if (maxBytes !== undefined && opened.size > maxBytes) {
- throw new ForgeSizeLimitError(`Forge source file exceeds the remaining size limit: ${absPath}`);
- }
- const bytes = Buffer.allocUnsafe(opened.size);
- let offset = 0;
- while (offset < bytes.byteLength) {
- const { bytesRead } = await handle.read(
- bytes,
- offset,
- bytes.byteLength - offset,
- null,
- );
- if (bytesRead === 0) break;
- offset += bytesRead;
- }
- if (offset !== bytes.byteLength) {
- throw new ForgeSourceChangedError('Forge source file shrank while being read');
- }
- const after = await handle.stat();
- if (!sameForgeFileIdentity(pathStat, after)) {
- throw new ForgeSourceChangedError('Forge source file changed while being read');
- }
- const realAfterRead = await realpathNative(absPath);
- if (!sameForgeCanonicalPath(realBeforeOpen, realAfterRead) ||
- !isPathInsideDir(sourceRoot, realAfterRead)) {
- throw new ForgeSourceChangedError('Forge source entry changed during read');
- }
- return bytes;
- } finally {
- await handle.close().catch(() => undefined);
- }
- }
-
- async function readForgeDirectoryEntriesStable(
- absPath: string,
- sourceRoot: string,
- ): Promise<fs.Dirent[]> {
- const before = await fs.promises.lstat(absPath);
- if (!before.isDirectory() || before.isSymbolicLink()) {
- throw new ForgeSourceChangedError('Forge source directory changed after classification');
- }
- const realBefore = await realpathNative(absPath);
- if (!isPathInsideDir(sourceRoot, realBefore)) {
- throw new ForgeSourceChangedError('Forge source directory escaped the validated source root');
- }
- const entries = await fs.promises.readdir(absPath, { withFileTypes: true });
- const after = await fs.promises.lstat(absPath);
- const realAfter = await realpathNative(absPath);
- if (!sameForgeDirectoryIdentity(before, after) ||
- !sameForgeCanonicalPath(realBefore, realAfter) ||
- !isPathInsideDir(sourceRoot, realAfter)) {
- throw new ForgeSourceChangedError('Forge source directory changed while being read');
- }
- return entries;
- }
-
- async function writeForgeFileStable(
- absPath: string,
- parentDir: string,
- bytes: Uint8Array,
- ): Promise<void> {
- const expectedParent = await fs.promises.lstat(parentDir);
- if (!expectedParent.isDirectory() || expectedParent.isSymbolicLink()) {
- throw new ForgeSourceChangedError('Forge output parent is not a regular directory');
- }
- const expectedParentReal = await realpathNative(parentDir);
- if (!sameForgeCanonicalPath(expectedParentReal, parentDir)) {
- throw new ForgeSourceChangedError('Forge output parent changed before write');
- }
-
- let expectedTarget: fs.Stats | null = null;
- try {
- expectedTarget = await fs.promises.lstat(absPath);
- if (!expectedTarget.isFile() || expectedTarget.isSymbolicLink()) {
- throw new ForgeSourceChangedError('Forge output path is not a regular file');
- }
- if (expectedTarget.nlink !== 1) {
- throw new ForgeSourceChangedError('Forge output path has aliases outside the validated tree');
- }
- } catch (error) {
- if (!isMissingFsError(error)) throw error;
- }
-
- let handle: Awaited<ReturnType<typeof fs.promises.open>>;
- const createdTarget = expectedTarget === null;
- try {
- handle = await fs.promises.open(absPath, expectedTarget ? 'r+' : 'wx');
- } catch (error) {
- if (!expectedTarget && isMissingFsError(error)) {
- throw new ForgeSourceChangedError('Forge output disappeared before write');
- }
- throw error;
- }
- try {
- const openedTarget = await handle.stat();
- const currentParent = await fs.promises.lstat(parentDir);
- const currentParentReal = await realpathNative(parentDir);
- if (!sameForgeDirectoryIdentity(expectedParent, currentParent) ||
- !sameForgeCanonicalPath(expectedParentReal, currentParentReal) ||
- !sameForgeCanonicalPath(currentParentReal, parentDir)) {
- throw new ForgeSourceChangedError('Forge output parent changed before bytes were written');
- }
- const currentTarget = await fs.promises.lstat(absPath);
- if (!currentTarget.isFile() || currentTarget.isSymbolicLink() ||
- currentTarget.nlink !== 1 ||
- !sameForgeFileIdentity(openedTarget, currentTarget) ||
- (expectedTarget && !sameForgeFileIdentity(expectedTarget, openedTarget))) {
- throw new ForgeSourceChangedError('Forge output path changed before bytes were written');
- }
- await handle.truncate(0);
- await handle.writeFile(bytes);
- const afterParent = await fs.promises.lstat(parentDir);
- const afterParentReal = await realpathNative(parentDir);
- if (!sameForgeDirectoryIdentity(expectedParent, afterParent) ||
- !sameForgeCanonicalPath(expectedParentReal, afterParentReal)) {
- throw new ForgeSourceChangedError('Forge output parent changed while writing');
- }
- } catch (error) {
- if (createdTarget) {
- try {
- const currentTarget = await fs.promises.lstat(absPath);
- const openedTarget = await handle.stat();
- if (sameForgeFileIdentity(currentTarget, openedTarget)) {
- await fs.promises.unlink(absPath);
- }
- } catch {
- // Best-effort cleanup only; never turn a boundary rejection into a write.
- }
++/**
++ * 解析已存在祖先的真身、保留尚不存在的尾段,让受管根在首次落盘前就可比对。
++ */
++async function resolveThroughExistingAncestor(inputPath: string): Promise<string> {
++ let cursor = path.resolve(inputPath);
++ const tail: string[] = [];
++ while (true) {
++ try {
++ const real = await realpathNative(cursor);
++ return path.join(real, ...tail);
++ } catch (error) {
++ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
++ const parent = path.dirname(cursor);
++ if (parent === cursor) return path.resolve(inputPath);
++ tail.unshift(path.basename(cursor));
++ cursor = parent;
+ }
- throw error;
- } finally {
- await handle.close().catch(() => undefined);
+ }
+}
+
- function isMissingFsError(error: unknown): boolean {
- return (error as NodeJS.ErrnoException).code === 'ENOENT';
- }
+ /** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */
+ const MAX_BASIC_FILES = 256;
+ const MAX_NODE_FILES = 2_048;
+ const MAX_BASIC_TOTAL_BYTES = 32 * 1024 * 1024;
+ const MAX_NODE_TOTAL_BYTES = 256 * 1024 * 1024;
+ const MAX_BASIC_CINDY_BYTES = 8 * 1024 * 1024;
+ const MAX_NODE_CINDY_BYTES = 128 * 1024 * 1024;
+ const FORGE_AI_ICON_PATH = 'assets/icon.png';
/** 打包时跳过的目录/文件(源码目录里的开发残留,不属于意识本体)。 */
function shouldSkip(name: string): boolean {
@@@ -267,16 -52,7 +85,15 @@@ export type ForgePackResult
| { ok: true; cindyPath: string; manifest: GhostManifest }
| {
ok: false;
- errorCode: 'DIR_NOT_FOUND' | 'MANIFEST_INVALID' | 'ENTRY_MISSING' | 'TOO_LARGE' | 'INTERNAL';
+ errorCode:
+ | 'DIR_NOT_FOUND'
- | 'SOURCE_OUTSIDE_WORKDIR'
- | 'WORKDIR_NOT_LOCAL'
- | 'WORKDIR_READ_ONLY'
- | 'SOURCE_IS_INSTALLED_PLUGIN'
+ | 'MANIFEST_INVALID'
+ | 'ENTRY_MISSING'
+ | 'TOO_LARGE'
- | 'INTERNAL';
++ | 'INTERNAL'
++ // Forge 打包出口的会话 workdir 门 + 受管根禁区(C-4 + #7)。
++ | 'SOURCE_OUTSIDE_WORKDIR'
++ | 'SOURCE_IS_INSTALLED_PLUGIN';
message: string;
};
@@@ -311,25 -87,6 +128,29 @@@ interface ForgeScaffoldInput
description?: string;
}
++/**
++ * scaffold 落盘能力(C-4):实际写盘委托给隔离的稳定父目录写入器(main 侧
++ * forgeScaffoldCapability/worker),forge.ts 只做校验与内容生成,不直接碰盘。
++ */
+export interface ForgeScaffoldWriteRequest {
+ parentDir: string;
+ targetName: string;
+ expectedParent: {
+ realPath: string;
+ dev: number;
+ ino: number;
+ };
+ files: Array<{ path: string; base64: string }>;
+}
+
+export type ForgeScaffoldWriteResult =
+ | { ok: true }
+ | { ok: false; errorCode: 'TARGET_EXISTS' | 'INTERNAL'; message: string };
+
+export type ForgeScaffoldWriter = (
+ request: ForgeScaffoldWriteRequest,
+) => Promise<ForgeScaffoldWriteResult>;
+
/** 生成插件清单;先走正式校验,再允许任何文件落盘。 */
function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {
const common = {
@@@ -681,169 -423,130 +491,129 @@@ export async function scaffoldGhostDir
const resolved = path.resolve(input.dir);
const workdir = options?.sessionWorkdir;
if (!workdir) {
- return {
- ok: false,
- errorCode: 'INVALID_INPUT',
- message: '没有会话工作目录,无法确定骨架输出位置',
- };
+ return { ok: false, errorCode: 'INVALID_INPUT', message: '没有会话工作目录,无法确定骨架输出位置' };
}
-- // 字面 startsWith 不设防软链:工作目录里若有 out -> /tmp/out 之类的
-- // 软链祖先,字面在内、实际在外。两边都按 realpath 对账——目标还不存在,
-- // 就取「已存在的最深祖先」的真身再拼回剩余段。
++ // 字面 startsWith 不设防软链:工作目录里若有 out -> /tmp/out 之类的软链祖先,
++ // 字面在内、实际在外。两边都按 realpath 对账——目标还不存在,就取「已存在的最深
++ // 祖先」的真身再拼回剩余段(与打包侧受管根解析共用 resolveThroughExistingAncestor)。
let realWorkdir: string;
try {
- realWorkdir = await fs.promises.realpath(path.resolve(workdir));
+ realWorkdir = await realpathNative(path.resolve(workdir));
} catch {
- return {
- ok: false,
- errorCode: 'INVALID_INPUT',
- message: '会话工作目录不存在,无法确定骨架输出位置',
- };
+ return { ok: false, errorCode: 'INVALID_INPUT', message: '会话工作目录不存在,无法确定骨架输出位置' };
}
- // 「已存在的最深祖先取真身再拼回剩余段」与打包侧受管根解析共用同一个 helper ——
- // 这段 walk 原来在这里手写了一份,同一判定两份实现正是这条链路反复出问题的形态。
- let realAncestor = resolved;
- const pendingSegments: string[] = [];
- for (;;) {
- try {
- realAncestor = await fs.promises.realpath(realAncestor);
- break;
- } catch (err) {
- if (!hasFsErrorCode(err, 'ENOENT')) {
- return {
- ok: false,
- errorCode: 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
- };
- }
- const parent = path.dirname(realAncestor);
- if (parent === realAncestor) break; // 到根了,根一定存在,防御性兜底
- pendingSegments.unshift(path.basename(realAncestor));
- realAncestor = parent;
- }
+ let realTarget: string;
+ try {
+ realTarget = await resolveThroughExistingAncestor(resolved);
+ } catch (err) {
- return {
- ok: false,
- errorCode: 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
- };
++ return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
}
- const realTarget = path.join(realAncestor, ...pendingSegments);
if (!realTarget.startsWith(`${realWorkdir}${path.sep}`) && realTarget !== realWorkdir) {
return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 必须在当前会话工作目录内' };
}
+ for (const forbiddenRoot of options?.forbiddenRootDirs ?? []) {
+ let resolvedForbiddenRoot: string;
+ try {
+ resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
+ } catch (err) {
- return {
- ok: false,
- errorCode: 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
- };
++ return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
+ }
- // 与打包侧同形的双向判定。祖先方向这一半在这里是 defense-in-depth 而不是修洞:
- // 骨架目标若是受管根的祖先,该目录必然已存在,最终 rename 会以 TARGET_EXISTS 拒掉。
- // 仍然写出来,是为了不让"上游守卫够不够用"依赖读者去推断下游 rename 的语义 ——
- // 判定散落且各自只覆盖一半,正是这条链路反复出问题的成因。
++ // 与打包侧同形的双向判定:骨架目标既不能落进受管根(已装插件 / 状态根 / seed 根),
++ // 也不能是它们的祖先。祖先方向此处是纵深防御(该目录必已存在,最终 rename 会
++ // TARGET_EXISTS 拒掉),但判定不散落、两半都覆盖,才不会靠读者去推断下游语义。
+ if (
+ isPathInsideDir(resolvedForbiddenRoot, realTarget) ||
+ isPathInsideDir(realTarget, resolvedForbiddenRoot)
+ ) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message:
+ 'dir 不能落在已安装插件目录或 Host 管理的状态目录内,也不能是它们的上级目录;请在工作目录里换一个独立的作者目录',
+ };
+ }
+ }
+ const targetDir = path.resolve(input.dir);
const files = scaffoldFiles(input);
-- // 显式收窄而非 as 断言:manifest 恒为 JSON 字符串,二进制项(占位图标)另存;
-- // 未来若误把 manifest 写成 Buffer,这里在编译/测试期就报,而不是运行期 parse 炸。
const manifestRaw = files[GHOST_MANIFEST_FILE];
if (typeof manifestRaw !== 'string') {
return { ok: false, errorCode: 'INTERNAL', message: 'scaffold manifest 必须是 JSON 字符串' };
}
const validation = validateGhostManifest(JSON.parse(manifestRaw));
if (!validation.ok) {
-- return {
-- ok: false,
-- errorCode: 'INVALID_INPUT',
-- message: `插件信息不合格:${validation.reason}`,
-- };
++ return { ok: false, errorCode: 'INVALID_INPUT', message: `插件信息不合格:${validation.reason}` };
}
- const targetDir = path.resolve(input.dir);
try {
await fs.promises.lstat(targetDir);
-- return {
-- ok: false,
-- errorCode: 'TARGET_EXISTS',
-- message: `目标已经存在,不会覆盖:${targetDir}`,
-- };
++ return { ok: false, errorCode: 'TARGET_EXISTS', message: `目标已经存在,不会覆盖:${targetDir}` };
} catch (err) {
if (!hasFsErrorCode(err, 'ENOENT')) {
-- return {
-- ok: false,
-- errorCode: 'INTERNAL',
-- message: err instanceof Error ? err.message : String(err),
-- };
++ return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
}
}
const parentDir = path.dirname(targetDir);
- let stagingDir: string | null = null;
+ let parentStat: fs.Stats;
+ let parentRealPath: string;
try {
- await fs.promises.mkdir(parentDir, { recursive: true });
- stagingDir = await fs.promises.mkdtemp(
- path.join(parentDir, `.${path.basename(targetDir)}-scaffold-`),
- );
- for (const [rel, content] of Object.entries(files)) {
- const abs = path.join(stagingDir, rel);
- await fs.promises.mkdir(path.dirname(abs), { recursive: true });
- await fs.promises.writeFile(abs, content, { encoding: 'utf8', flag: 'wx' });
+ parentStat = await fs.promises.lstat(parentDir);
+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
- return {
- ok: false,
- errorCode: 'INVALID_INPUT',
- message: 'dir 的父目录必须是工作目录内已存在的普通目录',
- };
++ return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 的父目录必须是工作目录内已存在的普通目录' };
}
- try {
- await fs.promises.rename(stagingDir, targetDir);
- stagingDir = null;
- } catch (err) {
- if (hasFsErrorCode(err, 'EEXIST') || hasFsErrorCode(err, 'ENOTEMPTY')) {
- return {
- ok: false,
- errorCode: 'TARGET_EXISTS',
- message: `目标已经存在,不会覆盖:${targetDir}`,
- };
- }
- throw err;
+ parentRealPath = await realpathNative(parentDir);
+ if (
+ !sameForgeCanonicalPath(parentRealPath, parentDir) ||
+ !isPathInsideDir(realWorkdir, parentRealPath)
+ ) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: 'dir 的父目录必须是工作目录内已存在且没有链接祖先的普通目录',
+ };
}
- return {
- ok: true,
- dir: targetDir,
- template,
- files: Object.keys(files).sort(),
- nextSteps: [
- '按需要修改 ghost.json、main.js 和 worker 源码。',
- '调用 ghost_forge_pack 打包并让用户确认安装。',
- 'Node 模板不允许在安装或首次运行时执行 npm install、npx 或 postinstall。',
- ],
- };
} catch (err) {
+ if (hasFsErrorCode(err, 'ENOENT')) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message: 'dir 的父目录必须先创建,并且必须位于当前工作目录内',
+ };
+ }
- return {
- ok: false,
- errorCode: 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
- };
++ return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };
+ }
+
++ // 实际落盘委托给隔离的稳定父目录写入器(C-4):forge.ts 只生成内容,不直接写盘。
+ if (!options?.writeScaffold) {
return {
ok: false,
errorCode: 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
+ message: 'Forge scaffold stable-directory capability is unavailable',
};
- } finally {
- if (stagingDir) {
- await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
- }
}
+ const writeResult = await options.writeScaffold({
+ parentDir,
+ targetName: path.basename(targetDir),
- expectedParent: {
- realPath: parentRealPath,
- dev: parentStat.dev,
- ino: parentStat.ino,
- },
++ expectedParent: { realPath: parentRealPath, dev: parentStat.dev, ino: parentStat.ino },
+ files: Object.entries(files).map(([rel, content]) => ({
+ path: rel,
+ base64: (typeof content === 'string' ? Buffer.from(content, 'utf8') : content).toString('base64'),
+ })),
+ });
+ if (!writeResult.ok) {
- return {
- ok: false,
- errorCode: writeResult.errorCode,
- message: writeResult.message,
- };
++ return { ok: false, errorCode: writeResult.errorCode, message: writeResult.message };
+ }
+ return {
+ ok: true,
+ dir: targetDir,
+ template,
+ files: Object.keys(files).sort(),
+ nextSteps: [
+ '按需要修改 ghost.json、main.js 和 worker 源码。',
+ '调用 ghost_forge_pack 打包并让用户确认安装。',
+ 'Node 模板不允许在安装或首次运行时执行 npm install、npx 或 postinstall。',
+ ],
+ };
}
/**
@@@ -1071,16 -725,16 +792,25 @@@ async function buildGhostPackage
}
// 4) 收集文件(递归,跳过开发残留),数量/体积设限。
- const files: Array<{ rel: string; bytes: Buffer }> = [];
++ // 分类一律走 lstat(不信 readdir Dirent 的类型位——libuv 对 junction 的类型位
++ // 跨平台不稳),按我们分支的加固语义处理:
++ // - 目录:进递归前按 realpath 复核仍在规范源码根内。目录可能在"分类"与
++ // "递归"之间被换成指向根外/受管根的 junction(TOCTOU);realpath 越界即拒
++ // (SOURCE_OUTSIDE_WORKDIR),避免把根外字节递归卷进 .cindy。
++ // - 符号链接:清单声明的入口是链接 → ENTRY_MISSING(装入侧会缺入口 404,
++ // 打包期就拦);非声明的链接 → 跳过,不穿透、不把目标字节打进包。
++ // - 普通文件:收集(字节读取仍在下面按 realDir containWithin 现读)。
+ const files: Array<{ rel: string; abs: string }> = [];
let totalBytes = 0;
const maxFiles = manifest.node ? MAX_NODE_FILES : MAX_BASIC_FILES;
const maxTotalBytes = manifest.node ? MAX_NODE_TOTAL_BYTES : MAX_BASIC_TOTAL_BYTES;
const seenPackPaths = new Set<string>();
- const walk = async (cur: string, relBase: string): Promise<ForgePackResult | null> => {
- const boundaryBeforeRead = await ensureSourceBoundary();
- if (boundaryBeforeRead) return boundaryBeforeRead;
- const entries = await readForgeDirectoryEntriesStable(cur, sourceDir);
++ const requiredPackPaths = new Set(mustExist.map((entry) => entry.toLowerCase()));
+ const walk = async (
+ cur: string,
+ relBase: string,
+ ): Promise<Exclude<ForgePackResult, { ok: true }> | null> => {
+ const entries = await fs.promises.readdir(cur, { withFileTypes: true });
for (const e of entries) {
if (shouldSkip(e.name)) continue;
const abs = path.join(cur, e.name);
@@@ -1094,38 -748,21 +824,50 @@@
};
}
seenPackPaths.add(foldedRel);
- // 类型判定走 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 (kind === 'file') {
- if (files.length >= maxFiles) {
- return { ok: false, errorCode: 'TOO_LARGE', message: `文件过多(上限 ${maxFiles} 个)` };
- if (e.isDirectory()) {
++ let st: fs.Stats;
++ try {
++ st = await fs.promises.lstat(abs);
++ } catch {
++ // 分类时条目已消失(并发删除):声明入口 → ENTRY_MISSING,其它跳过。
++ if (requiredPackPaths.has(foldedRel)) {
++ return { ok: false, errorCode: 'ENTRY_MISSING', message: `清单声明的文件不存在:${rel}` };
+ }
- const validatedSnapshot = validatedFileSnapshots.get(foldedRel);
- if (validatedSnapshot && validatedSnapshot.rel !== rel) {
++ continue;
++ }
++ if (st.isSymbolicLink()) {
++ if (requiredPackPaths.has(foldedRel)) {
+ return {
+ ok: false,
- errorCode: 'MANIFEST_INVALID',
- message: `manifest 声明路径大小写不一致:${validatedSnapshot.rel} / ${rel}`,
++ errorCode: 'ENTRY_MISSING',
++ message: `清单声明的文件是链接,不可打包:${rel}`,
+ };
+ }
- const bytes = validatedSnapshot?.bytes ??
- await readForgeFileStable(abs, sourceDir, undefined, maxTotalBytes - totalBytes);
- if (bytes.byteLength > maxTotalBytes - totalBytes) {
++ continue;
++ }
++ if (st.isDirectory()) {
++ // 进递归前按 realpath 复核:分类与递归之间目录可能被换成指向根外的
++ // junction。realpath 越出规范源码根即拒,不把根外字节卷进包。
++ let realCur: string;
++ try {
++ realCur = await realpathNative(abs);
++ } catch {
++ continue;
++ }
++ if (!isPathInsideDir(realDir, realCur)) {
+ return {
+ ok: false,
- errorCode: 'TOO_LARGE',
- message: `总体积超上限(${maxTotalBytes} 字节)`,
++ errorCode: 'SOURCE_OUTSIDE_WORKDIR',
++ message: `源码子目录在打包期被替换为指向根外的链接:${rel}`,
+ };
+ }
- files.push({ rel, bytes });
- totalBytes += bytes.byteLength;
+ const bad = await walk(abs, rel);
+ if (bad) return bad;
- } else if (e.isSymbolicLink()) {
- // 符号链接一律不穿透。此前是静默跳过——OneDrive 未水合占位文件、
- // 仓库里提交的链接都会被悄悄丢出包外,校验说"在场"、包里却没有,
- // 运行期才 404。改为结构化拒绝,错误可见。
- return {
- ok: false,
- errorCode: 'MANIFEST_INVALID',
- message: `源码目录含符号链接条目,不允许打包:${rel}`,
- };
- } else if (e.isFile()) {
++ } else if (st.isFile()) {
+ files.push({ rel, abs });
++ // 体积预算用 stat(而非 lstat.size):这是"walk 期预估"值,真正的
++ // 权威边界在下面 zip 步按剩余预算 containWithin 现读时强制(文件可能在
++ // walk 与读取之间被并发撑大)。分类归 lstat,预算归 stat,各司其职。
+ totalBytes += (await fs.promises.stat(abs)).size;
if (files.length > maxFiles) {
return { ok: false, errorCode: 'TOO_LARGE', message: `文件过多(上限 ${maxFiles} 个)` };
}
@@@ -1136,12 -773,6 +878,9 @@@
message: `总体积超上限(${maxTotalBytes} 字节)`,
};
}
+ } else if (requiredPackPaths.has(foldedRel)) {
- return {
- ok: false,
- errorCode: 'ENTRY_MISSING',
- message: `清单声明的文件不存在或不是普通文件(链接不可打包):${rel}`,
- };
++ // 声明入口是块/字符设备、FIFO 等非常规条目 → 视为缺失。
++ return { ok: false, errorCode: 'ENTRY_MISSING', message: `清单声明的文件不是普通文件:${rel}` };
}
}
return null;
@@@ -1177,26 -878,42 +986,83 @@@
message: `压缩包体积超上限(${maxCindyBytes} 字节)`,
};
}
- const boundaryBeforeWrite = await ensureSourceBoundary();
- if (boundaryBeforeWrite) return boundaryBeforeWrite;
- const cindyPath = path.join(sourceDir, `${manifest.id}-${manifest.version}.cindy`);
- await writeForgeFileStable(cindyPath, sourceDir, buf);
- return { ok: true, cindyPath, manifest };
+ return {
+ ok: true,
+ buf,
+ manifest,
+ manifestRaw: (manifestRaw ?? {}) as Record<string, unknown>,
+ };
} catch (err) {
- if (err instanceof ForgeSourceChangedError) {
- return {
- ok: false,
- errorCode: 'SOURCE_OUTSIDE_WORKDIR',
- message: err.message,
- };
- }
- if (err instanceof ForgeSizeLimitError) {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
+ }
+
+ /**
+ * 校验 + 打包一个意识源码目录。产物写到源码目录自身(<id>-<version>.cindy,
+ * 同名覆盖——同 id 同版本重打包语义上就是同一个包),用户在自己的意识目录里
+ * 就能拿到成品;出错返回结构化分类,agent 按 message 修源码即可,不抛异常。
+ */
+ export async function packGhostDir(
+ dir: string,
- options?: { iconPng?: Buffer },
++ options?: { sessionWorkdir?: string | null; forbiddenRootDirs?: readonly string[]; iconPng?: Buffer },
+ ): Promise<ForgePackResult> {
- const built = await buildGhostPackage(dir, undefined, options);
++ // Forge 打包出口专属安全门(C-4 + #7):source 必须在会话 workdir 内、且不得是受管根
++ //(已装插件 / 批准状态根 / seed 根,双向判定)。算出的 realSourceDir 作为
++ // buildGhostPackage 的 expectedRealDir 上游锚点——正是它要求"由上游校验后传入"的那份。
++ const workdir = options?.sessionWorkdir;
++ if (!workdir) {
++ return { ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR', message: 'Forge pack requires an active session workdir' };
++ }
++ let realWorkdir: string;
++ try {
++ realWorkdir = await realpathNative(path.resolve(workdir));
++ } catch {
++ return { ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR', message: 'The current session workdir does not exist' };
++ }
++ let realSourceDir: string;
++ try {
++ realSourceDir = await realpathNative(dir);
++ } catch {
++ return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `目录不存在:${dir}` };
++ }
++ if (!isPathInsideDir(realWorkdir, realSourceDir)) {
++ return { ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR', message: 'Forge source must be inside the current session workdir' };
++ }
++ for (const forbiddenRoot of options?.forbiddenRootDirs ?? []) {
++ const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
++ // 双向:源目录落在受管根内要拒(拿已安装插件当源码),源目录是受管根祖先也要拒
++ //(递归打包会走进 cindy-brain / ghost-install-state / seed 根,把已装字节、批准
++ // receipt、技能快照打进 .cindy)。
++ if (
++ isPathInsideDir(resolvedForbiddenRoot, realSourceDir) ||
++ isPathInsideDir(realSourceDir, resolvedForbiddenRoot)
++ ) {
+ return {
+ ok: false,
- errorCode: 'TOO_LARGE',
- message: err.message,
++ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
++ message:
++ 'Forge source must not be an installed Plugin or a Host-managed state directory; copy the source into the current session workdir first',
+ };
+ }
++ }
++ const built = await buildGhostPackage(dir, realSourceDir, options ? { iconPng: options.iconPng } : undefined);
+ if (!built.ok) return built;
+ const authoringIssue = firstGhostAuthoringIssue(built.manifestRaw);
+ if (authoringIssue) {
+ return { ok: false, errorCode: 'MANIFEST_INVALID', message: authoringIssue };
+ }
+ // 产物跟源码住一起(2026-07 Lizi 定案:拿取直观);文件收集在写盘之前完成
+ // + shouldSkip 跳过 *.cindy,自身产物不会进包;同名覆盖。
- const cindyPath = path.join(dir, `${built.manifest.id}-${built.manifest.version}.cindy`);
++ // 落地到**规范源码目录**(realpath 产物)而非可能是符号链接/别名的入参 `dir`:
++ // 产物必须写进真实目录,别名只是通往它的一条路径。
++ const cindyPath = path.join(realSourceDir, `${built.manifest.id}-${built.manifest.version}.cindy`);
+ try {
+ await fs.promises.writeFile(cindyPath, built.buf);
+ } catch (err) {
return {
ok: false,
errorCode: 'INTERNAL',
@@@ -3270,20 -3236,50 +3385,56 @@@ if (r.ok && r.confirmed)
## 7. 打包与测试
+ ### 7.1 打包前轻量确认图标
+
+ 准备调用 \`ghost_forge_pack\` 前检查一次图标。如果清单没有 \`icon\`,或者本次用了
+ \`ghost_forge_scaffold\` 且没有明确替换它生成的占位图,就视为图标尚未配置。此时只
+ **轻提醒一次**,不要把图标变成验收门槛,也不要擅自开始耗时的图片生成。提示与选项
+ 使用用户当前对话语言:
+
+ - **使用 AI 生成(推荐)**:仅在用户选择后,调用当前可用的图片生成能力;它与当前
+ 聊天模型解耦,不要因为用户正在使用 GLM、Claude 等文本模型而切换聊天模型。把插件
+ 展示名与一句话用途填入下面模板后原样注入,不要临场追加文字、品牌或复杂场景:
+
+ \`\`\`text
+ Create a polished square app icon for a Cindy plugin named "{{name}}". Purpose: {{one-sentence purpose}}. Show one clear, original visual metaphor for that purpose. Use a clean geometric composition, a restrained natural color palette, high contrast, and a centered subject with generous safe padding so it remains readable at 32–48 px. Use one symbol only on a simple solid or transparent background. No text, letters, numbers, UI mockups, scenes, baked-in rounded corners, trademarks, copied brand shapes, watermarks, heavy gradients, inner shadows, or photorealism. Output a 1024×1024 PNG.
+ \`\`\`
+
+ 只尝试一次。图片能力不可用、超时或失败时不要重试,直接调用
+ \`ghost_forge_pack({ dir })\`,保留占位图/宿主默认图标继续打包,不让图标阻塞用户。
+ 生成成功后,从图片工具结果的 \`xdt_image_url\` 取单张地址;如果结果只有
+ \`xdt_image_urls\`,取数组第一项(例如 \`const selectedImageUrl = result.xdt_image_url ?? result.xdt_image_urls?.[0]\`)。
+ 仅当它是 \`cindy-media://\` 地址时,才把它原样交给
+ \`ghost_forge_pack({ dir, icon_source: selectedImageUrl })\`;主机会转成 1024×1024 PNG 并
+ 嵌入安装包。icon_source 处理失败时 pack 也会自动回退默认图标,不要再发起第二次生成。
+ 如果源码根目录已有 \`cindy-signatures.json\`,pack 会保留原图标和原签名,不做 AI
+ 图标覆盖;任何文件变更都必须交给发布流水线重新签名,不能静默降级信任等级。
+ - **上传图片**:让用户提供图片,保存到 \`assets/icon.png\`,并同步把
+ \`ghost.json\` 的 \`icon\` 字段设为 \`assets/icon.png\` 后继续;不要要求用户先把图片
+ 处理成圆角,宿主负责最终显示形态。
+ - **使用默认图标(跳过)**:立即继续打包;scaffold 项目保留占位图,未使用 scaffold
+ 的项目可以省略 \`icon\`,由宿主显示默认图标。跳过与使用默认是同一个选择。
+
+ 如果插件明确对应现有品牌或服务(如 X/Twitter、Notion),不要用 AI 仿制商标。将推荐
+ 项改为“使用官方品牌图标”,只从品牌官网、官方开发者文档或官方媒体资源中查询并设置;
+ 来源不可靠或获取失败时同样回退上传/默认,不延长创建流程。
+
+ ### 7.2 打包、安装与验证
+
1. 新插件先调 \`ghost_forge_scaffold\` 生成骨架,或把已有源码放在用户工作目录下的
- 一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件;
+ 一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件,
+ 其父目录必须是工作目录内已存在的普通目录;也不能落在已安装插件目录或 Host 状态目录内(会被拒,理由同下一条);
- 2. **Forge 源码必须是当前会话工作目录里的独立作者目录**。已安装插件目录以及
++ **Forge 源码必须是当前会话工作目录里的独立作者目录**。已安装插件目录以及
+ Host 管理的状态目录都不是源码区,禁止直接修改、打包或用路径别名绕过;若要继续
- 开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;
- 3. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;
++ 开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;
+ 2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;
产物落在源码目录里(\`<id>-<version>.cindy\`,同版本覆盖,下次打包自动跳过);
- 若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,
- 按上一步迁出源码后再打包;
- 4. **告知用户去点弹窗**(装入默认沉睡,提醒用户勾"立即开启"或到主界面侧边栏「插件」中唤醒);
- 5. 改代码后重新 pack:同 id 会弹"更新 vX → vY",唤醒状态与面板位置自动保留
++ 若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,
++ 按上一步迁出源码后再打包;也可能返回 \`SOURCE_OUTSIDE_WORKDIR\`(源码不在会话工作目录内);
+ 3. **告知用户去点弹窗**(装入默认沉睡,提醒用户勾"立即开启"或到主界面侧边栏「插件」中唤醒);
+ 4. 改代码后重新 pack:同 id 会弹"更新 vX → vY",唤醒状态与面板位置自动保留
(记得 bump ghost.json 的 version);
- 6. 验证:让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
+ 5. 验证:让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
## 8. 发布签名与审核
diff --cc apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
index 1b271ed45e,83beb107e6..1442beb598
--- a/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
@@@ -6,7 -6,7 +6,8 @@@ import
validateGhostManifestLocaleResource,
type GhostManifest,
} from '../../shared/ghost.js';
+import { classifyGhostDirEntrySync } from './ghostContentTree.js';
+ import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
export type GhostLocaleDirectoryValidation = { ok: true } | { ok: false; reason: string };
diff --cc apps/desktop/src/main/cindy-brain/index.ts
index 92ab1ab35a,2666f8033a..ac56eedbb0
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@@ -11,16 -11,18 +11,21 @@@ import
GHOST_CARD_HEIGHT_DEFAULT,
GHOST_CARD_HEIGHT_MAX,
GHOST_CARD_HEIGHT_MIN,
+ GHOST_INSTALL_MANIFEST_MAX_BYTES,
+ GHOST_MANIFEST_FILE,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
+ isGhostInstallApprovalToken,
+ ghostPermissionBaselineKey,
+ unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
isCindyAccountGhostId,
isOfficialGhostId,
+ ghostPermissionItems,
+ ghostPermissionProjectionFingerprint,
isValidGhostId,
layoutWithGhostPanel,
+ validateGhostManifest,
type GhostHostNoticeKey,
type GhostImageAspectRatio,
type GhostManifest,
@@@ -39,15 -44,11 +47,17 @@@ import
type ActiveAppSession,
} from '../appSessionState.js';
import { getLayoutStore } from '../layout/index.js';
-import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';
+import {
+ GhostManager,
+ type GhostExclusiveMutation,
+ type InstallRejection,
+ type UninstallRejection,
+} from './GhostManager.js';
import { exportGhostPackage } from './exportGhostPackage.js';
import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';
+import { createOneShotTicketStore } from './oneShotTickets.js';
+ import { withGhostInstallLock } from './ghostInstallLock.js';
+ import { GhostPackagePermissionReviewRequiredError } from './packagePermissionReview.js';
import {
clearBuiltinTombstone,
listEligibleBuiltinCommands,
@@@ -107,13 -101,20 +118,21 @@@ import { handleGhostSecretsRequest } fr
import { handleGhostOauthRequest } from './runtime/ghostOauthEndpoint.js';
import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoint.js';
import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccounts.js';
+import { cancelActiveGhostOauthFlow } from './ghostOauthFlow.js';
+ import {
+ appendReadyGhostOauthReauthSuggest,
+ findGhostOauthReauthSuggest,
+ } from './ghostOauthScopeStaleness.js';
import { mapGhostOauthConnectError } from './ghostOauthSetupError.js';
import { reclaimLoopbackPort } from './portReclaim.js';
import { GhostConnectionManager } from './ghostConnections.js';
import { getResolvedMainLocale, t } from '../i18n.js';
-import { reconcileGhostSkillLinks } from './skillSlot.js';
+import { reconcileGhostSkillLinks, removeGhostSkillLinksForRoots } from './skillSlot.js';
- import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+ import {
+ assertTrustedAppRendererEvent,
+ isTrustedAppRendererEvent,
+ isTrustedAppRendererWindow,
+ } from '../security/trustedAppRenderer.js';
import {
FILO_GOOGLE_GHOST_ID,
FILO_GOOGLE_SECRET_KEY,
@@@ -624,17 -677,33 +746,41 @@@ function availableGhosts(): InstalledGh
);
}
+ function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {
+ try {
+ const suggest = getGhostOauthReauthSuggest(withRuntimeFiloGoogleClient(ghost.manifest));
+ return {
+ ...ghost,
+ ...(suggest
+ ? {
+ oauthScopeStale: {
+ secretKey: suggest.secretKey,
+ missingScopeCount: suggest.missingScopeCount,
+ },
+ }
+ : {}),
+ };
+ } catch (error) {
+ // 详情页角标是提示面,保险库异常不能让插件清单整体消失。
+ log.warn('ghost oauth scope stale projection omitted', {
+ ghostId: ghost.manifest.id,
+ errorType: error instanceof Error ? error.name : typeof error,
+ });
+ return ghost;
+ }
+ }
+
function findAvailableGhost(id: string): InstalledGhost | null {
- if (!isGhostAvailableForActiveSession(id)) return null;
- return getGhostManager().list().find((ghost) => ghost.manifest.id === id) ?? null;
+ return availableGhosts().find((ghost) => ghost.manifest.id === id) ?? null;
+}
+
+/** Runtime-authorized lookup for integrations outside this module. */
+export function findAvailableGhostForAuthorization(id: string): InstalledGhost | null {
+ return findAvailableGhost(id);
+}
+
+export function listAvailableGhostsForAuthorization(): InstalledGhost[] {
+ return availableGhosts();
}
function requireGhostAvailableForActiveSession(id: string): void {
@@@ -3061,9 -3406,15 +3698,16 @@@ async function installAndDockLocked
: {}),
});
if ('rejection' in result) throwInstallError(result.rejection);
- // Builtin tombstone clearing is part of GhostManager's durable install
- // journal. A transient state write failure keeps the marker for startup
- // recovery without turning an already committed install into a false error.
+ // 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。
+ // 宁可装完即报错让上层看见,也不要留下"以为串行、其实没有"的假象。
+ if (result.ghost.manifest.id !== opts.ghostId) {
+ throw new Error(
+ `装入包的 ghostId(${result.ghost.manifest.id})与加锁使用的 id(${opts.ghostId})不一致`,
+ );
+ }
- // 用户手动重装同 id 的内置意识 = 重新跟随包内版本(清墓碑,播种恢复对账)。
- clearBuiltinTombstone(brainRootDir(), result.ghost.manifest.id, log);
++ // 内置墓碑清除已并入 GhostManager 的 durable install journal(marker.clearBuiltinTombstone
++ // + 提交时清除 + 崩溃恢复补清),此处不再直接调用:瞬时状态写失败会保留 marker 交由
++ // 启动恢复,而不是把已提交的安装误报成错误。
// 声明了面板的意识装入后立即停进布局树(树上已有 = 重装,原位复活不动树)。
// 顺序刻意:manager.install 内已广播 ghosts:changed(renderer 先注册面板),
// 这里再 setLayout 触发 layout:changed(pane 出现时面板组件必然已就位,规则 7)。
@@@ -3091,13 -3442,39 +3735,42 @@@ export async function installOrUpdateMa
expected: {
ghostId: string;
version: string;
++ /** receipt 模型并发护栏:更新分支比对 receipt 派生 token(与 main 硬化叠加,决策 A)。 */
+ expectedInstalledApproval?: string;
/**
- * 用户在确认卡上审阅过的市场清单(服务端 release.manifest)。下载包的清单必须与
- * 它在**权限投影与指令**上逐项一致 —— 权限 diff 是拿它算的,不绑定的话服务端记录
- * 与包内 ghost.json 不一致时,用户看到 A 权限、批准并运行的却是 B 权限。
+ * 装入确认框实际展示给用户的那份 manifest(来源方给的)。给了就逐项比对:
+ * 包里多出来的权限会暂停落位并交由上层复核。两条市场路径都必须给;
+ * 本地 `.cindy` 装入不经此出口,确认框读的就是包本身,没有这层漂移。
*/
- expectedManifest?: GhostManifest;
+ reviewedManifest?: GhostManifest;
+ /**
+ * 经市场账本摘要认证的旧版已安装清单。历史详情投影漏掉、但用户此前
- * 已批准的权限可继续作为基线;未被该基线覆盖的真实包权限仍走复核。
++ * 已批准的权限可继续作为基线;未被该基线覆盖的真实包权限仍走复核。
+ */
+ previouslyInstalledManifest?: GhostManifest;
+ /** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */
+ approvedPackageSha256?: string;
+ reviewedBaseline?: string;
+ },
+ ): Promise<InstalledGhost> {
+ // 卡点:按 ghostId 上锁,覆盖 inspect → 落位整段。服务端与自定义两条市场路径
+ // 都经此出口,调用方漏取锁也被兜住;调用方已持有时按可重入 no-op(它们会把
+ // 复核与账本写入一起纳入同一把锁,范围比这里更大)。
+ return withGhostInstallLock(expected.ghostId, () =>
+ installOrUpdateMarketGhostPackageLocked(cindyFilePath, expected),
+ );
+ }
+
+ async function installOrUpdateMarketGhostPackageLocked(
+ cindyFilePath: string,
+ expected: {
+ ghostId: string;
+ version: string;
++ expectedInstalledApproval?: string;
+ reviewedManifest?: GhostManifest;
+ previouslyInstalledManifest?: GhostManifest;
+ approvedPackageSha256?: string;
+ reviewedBaseline?: string;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@@ -3116,26 -3493,60 +3789,62 @@@
);
}
requireGhostAvailableForActiveSession(expected.ghostId);
- rejectUnauthorizedTokenBroker(inspected.manifest);
- if (expected.expectedManifest) {
- // 权限投影 + 指令逐项比对,而不是整卡 deep-equal:服务端清单允许存在展示性
- // 差异(字段顺序/补充元数据),但用户批准的权限内容必须就是包里的那份。
- // 指纹覆盖 key + kind + labelArgs + detail/detailKey/detailArgs —— 只比 key
- // 会漏掉同 key 下的安全语义字段(preview 的 hosts、OAuth scopes、node secret
- // 绑定方式、工具描述都在这些字段里),用户看 A、receipt 钉 B。
- const sameProjection =
- ghostPermissionProjectionFingerprint(expected.expectedManifest) ===
- ghostPermissionProjectionFingerprint(inspected.manifest) &&
- (expected.expectedManifest.command ?? null) === (inspected.manifest.command ?? null);
- if (!sameProjection) {
+ /**
+ * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。
+ *
+ * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,
+ * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。
+ * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`
+ * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是
+ * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着
+ * 它装进来,用户**从没审过就多出一个常驻能力面**。
+ *
+ * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包
- * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。
++ * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。
+ * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。
++ * (token broker 授权校验由下方 rejectUnauthorizedTokenBroker(canonicalManifest) 统一执行,
++ * 原 receipt 分支在此处的硬中止已被本可恢复复核取代,见约束文档 §11 整合任务①。)
+ */
+ const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
+ if (expected.reviewedManifest) {
+ const installedBaseline = installed
+ ? ghostPermissionBaselineKey(installed.manifest)
+ : null;
+ // 真实包复核的批准必须始终绑定当时那份包与已装权限面,不能只在
+ // 当前仍存在来源清单差异时才校验。否则两次请求间包字节发生变化、
+ // 新包恰好不再多权限时,会绕过旧批准的 SHA/基线绑定直接落位。
+ if (
+ expected.approvedPackageSha256 !== undefined &&
+ (expected.approvedPackageSha256 !== inspected.packageSha256 ||
+ (expected.reviewedBaseline ?? null) !== installedBaseline)
+ ) {
throwIpcError(
- 'GHOST_FILE_INVALID',
- '下载包的权限声明与确认时审阅的市场清单不一致,已中止安装',
+ 'PRECONDITION_FAILED',
+ 'Downloaded Plugin package changed after permission review',
);
}
+ const added = unreviewedGhostPermissionItems(
+ expected.reviewedManifest,
+ expected.previouslyInstalledManifest,
+ inspected.canonicalManifest,
+ );
+ if (added.length > 0) {
+ const review: PluginMarketPackageReview = {
+ manifest: inspected.manifest,
+ packageSha256: inspected.packageSha256,
+ installedBaseline,
+ };
+ if (expected.approvedPackageSha256 === undefined) {
+ log.warn('market package declares unreviewed permissions', {
+ ghostId: expected.ghostId,
+ keys: added.map((item) => item.key),
+ });
+ throw new GhostPackagePermissionReviewRequiredError(review);
+ }
+ }
}
+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest);
- const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
// Node 高风险条目由 renderer 装入确认卡权限清单如实展示;
// 2026-07-24 Lizi 定案:不再有 Main 侧原生二次确认弹窗(PR #333,本处为其
// 漏删的市场安装路径调用点,一并对齐)。
@@@ -3163,15 -3577,9 +3875,17 @@@
getGhostErrandSlot().clearGhost(expected.ghostId);
let result: Awaited<ReturnType<typeof manager.update>>;
try {
- // 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。
++ // 与首装分支同一口径:钉住 inspect 时校验过的包字节。receipt 模型下更新必须
++ // 绑定 receipt token(决策 A:与 main 的 sha 钉扎叠加),否则并发批准变更绕不过去。
+ if (!expected.expectedInstalledApproval) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state was not bound to the market update',
+ );
+ }
result = await manager.update(cindyFilePath, {
expectedPackageSha256: inspected.packageSha256,
+ expectedInstalledApproval: expected.expectedInstalledApproval,
});
} catch (error) {
spawnIfResident(installed);
@@@ -4223,18 -4714,15 +5025,21 @@@ export function registerGhostIpc(): voi
rejectUnauthorizedTokenBroker(probe.manifest);
// Node 高风险提示在 renderer 装入确认卡的权限清单里如实展示;
// 2026-07-24 Lizi 定案:不再追加 Main 原生二次确认弹窗。
- const enable = installOpts.enable === true;
+ const enable = installOpts?.enable === true;
- // 锁由 installAndDock 按 ghostId 自动获取(卡点);这里传 id 即可。
- return {
- ghost: await installAndDock(manager, lizFilePath, {
- ghostId: probe.manifest.id,
- enable,
- expectedPackageSha256,
- }),
- };
++ // owner 租约在锁外整段持有(防中途 owner 切换把落位写进新 owner);按 ghostId 的
++ // 互斥锁由 installAndDock 自动获取(卡点),这里传 id 即可。二者语义不同,叠加保留。
+ const releaseMutation = beginGhostMutation(mutationOwner);
+ try {
+ return {
+ ghost: await installAndDock(manager, lizFilePath, {
++ ghostId: probe.manifest.id,
+ enable,
- expectedPackageSha256: installOpts.expectedPackageSha256,
++ expectedPackageSha256,
+ }),
+ };
+ } finally {
+ releaseMutation();
+ }
});
// 原位更新(同 id 换版):先熄灯沙箱(新代码由下一次派活/面板重挂拉起),
@@@ -4274,11 -4748,10 +5079,13 @@@
}
rejectReservedGhostId(inspected.manifest.id);
rejectUnauthorizedTokenBroker(inspected.manifest);
- const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
- // 从熄灯到换版收尾整段持租约:熄灯之后的每一步都在改"当前 owner"的插件世界,
- // 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。
- // 与市场装入/本地装入/卸载共用按 ghostId 的互斥:换目录期间同 id 的其它
- // 装入/卸载不得插入(否则并发装入会与本次 rename 竞争、留下不一致态)。
- return withGhostInstallLock(inspected.manifest.id, async () => {
- const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
++ // 从熄灯到换版收尾整段持 owner 租约:熄灯之后每一步都在改"当前 owner"的插件世界,
++ // 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。租约在锁外,
++ // 与市场/本地装入/卸载共用的按 ghostId 互斥叠加(二者语义不同,决策 A 都保留)。
+ const releaseMutation = beginGhostMutation(mutationOwner);
+ try {
++ return await withGhostInstallLock(inspected.manifest.id, async () => {
++ const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
runtime.stop(inspected.manifest.id);
getGhostNodeRuntimeBroker().stop(inspected.manifest.id);
getGhostAgentSlot().clearGhost(inspected.manifest.id);
@@@ -4315,9 -4779,7 +5122,10 @@@
}
spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火
return { ghost: result.ghost };
- });
++ });
+ } finally {
+ releaseMutation();
+ }
});
// 设置页「装入意识…」第一步:系统文件选择框(按 .cindy 过滤),只选不装。
@@@ -4611,31 -4941,29 +5417,41 @@@
if (typeof enabled !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'enabled must be a boolean');
}
- if (!enabled) {
- runtime.stop(id); // 沉睡立即熄灯
- getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭
- getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)
- }
- const result = await manager.setEnabled(id, enabled);
- if ('rejection' in result) throwUninstallError(result.rejection);
- if (enabled) {
- runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起
- const ghost = findAvailableGhost(id);
- if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
- resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来
- } else {
- // 未读停止投影(记录保留):沉睡的意识没法把面板里的内容给你看,留一颗点
- // 只是噪声;但用户是"先别烦我"不是"这条我读过了",唤醒要能找回来。
- //
- // **必须在 setEnabled 成功之后**:写 `.disabled` 可能失败(目录只读 / IO
- // 错误),那时插件仍是启用态,可提前熄灭的话未读点就被错误清掉、且不会自愈
- // (要等插件再次上报或重启)。熄灯类操作(runtime/node/订阅)放在前面是既有
- // 行为且幂等,唯独这条会留下用户可见的错状态(copilot + codex review)。
- suspendGhostUnreadProjection(id);
+ // 同 install/update 的 owner 租约:setEnabled 先 await pathExists(旧 owner 的
+ // 安装目录)再动态写 receipt —— 不持租约,这个异步窗口里切号落定会拿 A 的镜像
+ // 状态改 B 的 receipt(启停同时落在两个 owner 的两半)。
+ const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ try {
+ if (!enabled) {
+ runtime.stop(id); // 沉睡立即熄灯
+ getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭
+ getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)
+ // 与更新/撤销路径同款:agent 工具授权与 errand 节流/在途记录不跨停用存活,
+ // 重新启用后从干净状态开始。
+ getGhostAgentSlot().clearGhost(id);
+ getGhostErrandSlot().clearGhost(id);
+ }
+ const result = await manager.setEnabled(id, enabled);
+ if ('rejection' in result) throwUninstallError(result.rejection);
+ if (enabled) {
+ runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起
+ const ghost = findAvailableGhost(id);
+ if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
++ resumeGhostUnreadProjection(id); // 沉睡期间保留的那颗点回来(#1421)
++ } else {
++ // 未读停止投影(记录保留):沉睡的意识没法把面板里的内容给你看,留一颗点
++ // 只是噪声;但用户是"先别烦我"不是"这条我读过了",唤醒要能找回来。
++ //
++ // **必须在 setEnabled 成功之后**:写 `.disabled` 可能失败(目录只读 / IO
++ // 错误),那时插件仍是启用态,可提前熄灭的话未读点就被错误清掉、且不会自愈
++ // (要等插件再次上报或重启)。熄灯类操作(runtime/node/订阅)放在前面是既有
++ // 行为且幂等,唯独这条会留下用户可见的错状态(copilot + codex review)。
++ suspendGhostUnreadProjection(id);
+ }
+ return { ok: true };
+ } finally {
+ releaseMutation();
}
- return { ok: true };
});
// 运行时状态快照(面板错误接管态的首帧数据源;广播只覆盖后续变化)。
diff --cc apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index 195b1b3e01,8a0df18cfd..cf34ab01cd
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@@ -21,16 -24,48 +24,56 @@@ import type
const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'ghost-workdir-gate-'));
const prefsFile = () => path.join(tmpUserData, 'ghost-workdir-prefs.json');
+ const outsideDir = path.join(tmpUserData, 'outside');
const logWarnMock = vi.fn();
+ const logInfoMock = vi.fn();
const grantAttachmentsMock = vi.fn();
+const { packGhostDirMock } = vi.hoisted(() => ({ packGhostDirMock: vi.fn() }));
+const releaseMutationMock = vi.fn();
+const captureMutationOwnerMock = vi.fn(() => ({
+ mode: 'local' as const,
+ dataOwnerId: 'test',
+ generation: 0,
+}));
+const acquireMutationLeaseMock = vi.fn(() => releaseMutationMock);
+ const confirmRequestMock = vi.fn(async () => ({ confirmed: true, allowDirs: false }));
+ const classifyLocalAttachmentPathMock = vi.fn();
+ const resolveGhostAttachmentUrlMock = vi.fn();
+ type TestLedgerRef = {
+ hash: string;
+ refKind: string;
+ refId: string;
+ originKind?: 'user' | 'tool';
+ };
+ const ledgerRefs: TestLedgerRef[] = [];
+ const ledgerHasRefMock = vi.fn(async (params: TestLedgerRef) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refKind === params.refKind &&
+ ref.refId === params.refId &&
+ (params.originKind === undefined || ref.originKind === params.originKind),
+ ),
+ );
+ const ledgerHasGhostToolGrantMock = vi.fn(
+ async (params: { hash: string; ghostId: string }) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refId === params.ghostId &&
+ ref.originKind === 'tool' &&
+ (ref.refKind === 'ghost-tool-grant' || ref.refKind === 'ghost-grant'),
+ ),
+ );
+ const ledgerAddRefMock = vi.fn(async (params: TestLedgerRef) => {
+ ledgerRefs.push({ ...params });
+ return `ref-${ledgerRefs.length}`;
+ });
+ const dirDepositMock = vi.fn(() => ({ ok: true, receipt: { token: 'dir-ticket' } }));
+ const saveDepositMock = vi.fn(() => ({ ok: true, receipt: { token: 'save-ticket' } }));
+ const liveGrantStateMock = vi.fn();
+ const alsSessionContextMock = vi.fn();
+ const resolvedAttachmentOrigins: Array<'user' | 'tool' | undefined> = [];
vi.mock('electron', () => ({ app: { getPath: () => tmpUserData } }));
vi.mock('../../appSessionState.js', () => ({
@@@ -48,23 -83,24 +91,29 @@@ vi.mock('@cindy/mcps', () => ({ getLizi
const WORKDIR = '/proj/alpha';
const listMock = vi.fn<() => unknown[]>(() => []);
const dispatchMock = vi.fn(async () => ({ ok: true as const, result: 'done' }));
- const setupAssessmentMock = vi.fn((_ghostId: string) => ({
- state: 'ready' as const,
- revision: 0,
- groups: [],
- }));
+ const setupAssessmentMock = vi.fn((_ghostId: string) => {
+ void _ghostId;
+ return {
+ state: 'ready' as const,
+ revision: 0,
+ groups: [],
+ };
+ });
const ensureReadyMock = vi.fn(
- async (_request: GhostSetupEnsureRequest): Promise<GhostSetupEnsureResult> => ({
- ok: true as const,
- assessment: { state: 'ready' as const, revision: 0, groups: [] },
- }),
+ async (_request: GhostSetupEnsureRequest): Promise<GhostSetupEnsureResult> => {
+ void _request;
+ return {
+ ok: true as const,
+ assessment: { state: 'ready' as const, revision: 0, groups: [] },
+ };
+ },
);
-const sessionSnapshotMock = vi.fn(async () => ({
+const sessionSnapshotMock = vi.fn(async (): Promise<{
+ workingDir: string;
+ permissionMode: string;
+ planModeEnabled: boolean;
+ remoteHostId: string | null;
+}> => ({
workingDir: WORKDIR,
permissionMode: 'auto',
planModeEnabled: false,
@@@ -96,19 -126,19 +145,23 @@@ vi.mock('../../cindy-brain/attachmentGr
MAX_GRANT_ONLY_ATTACHMENTS: 32,
}));
vi.mock('../../cindy-brain/dirDeposit.js', () => ({
- collectDirFiles: vi.fn(),
- getDirDepositVault: vi.fn(),
- getSaveDepositVault: vi.fn(),
+ collectDirFiles: () => ({ ok: true, files: [], totalBytes: 0 }),
+ getDirDepositVault: () => ({ deposit: dirDepositMock }),
+ getSaveDepositVault: () => ({ deposit: saveDepositMock }),
isPathInsideDir: () => false,
}));
- vi.mock('../../cindy-brain/ghostGrantConfirmBridge.js', () => ({ getGhostGrantConfirmBridge: vi.fn() }));
- vi.mock('../../cindy-brain/ghostLocalPathGrant.js', () => ({ classifyLocalAttachmentPath: vi.fn() }));
+ vi.mock('../../cindy-brain/ghostGrantConfirmBridge.js', () => ({
+ getGhostGrantConfirmBridge: () => ({ request: confirmRequestMock }),
+ }));
+ vi.mock('../../cindy-brain/ghostLocalPathGrant.js', () => ({
+ classifyLocalAttachmentPath: classifyLocalAttachmentPathMock,
+ }));
vi.mock('../../cindy-brain/cardService.js', () => ({ withCardToken: (r: unknown) => r }));
-vi.mock('../../cindy-brain/forge.js', () => ({ FORGE_GUIDE: 'guide', packGhostDir: vi.fn() }));
+vi.mock('../../cindy-brain/forge.js', () => ({
+ FORGE_GUIDE: 'guide',
+ packGhostDir: packGhostDirMock,
+ scaffoldGhostDir: vi.fn(),
+}));
vi.mock('../../cindy-brain/openFileInstall.js', () => ({ handleIncomingCindyFile: vi.fn() }));
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionFsSnapshot: sessionSnapshotMock,
@@@ -165,10 -214,91 +237,94 @@@ beforeEach(() =>
assessment: { state: 'ready', revision: 0, groups: [] },
});
grantAttachmentsMock.mockReset();
+ grantAttachmentsMock.mockImplementation(
+ async (
+ deps: {
+ resolveImageUrl: (url: string) => Promise<{
+ absPath: string;
+ originKind?: 'user' | 'tool';
+ buffer?: Uint8Array;
+ }>;
+ addRef: (params: TestLedgerRef) => Promise<string>;
+ },
+ params: { urls: string[]; ghostId: string; maxCount?: number },
+ ) => {
+ if (params.urls.length > (params.maxCount ?? 4)) {
+ return { ok: false, message: `附件过多(单次上限 ${params.maxCount ?? 4} 张)` };
+ }
+ const hashes: string[] = [];
+ for (const url of params.urls) {
+ const resolved = await deps.resolveImageUrl(url);
+ resolvedAttachmentOrigins.push(resolved.originKind);
+ const buffer = resolved.buffer ?? (await fs.promises.readFile(resolved.absPath));
+ const hash = createHash('sha256').update(buffer).digest('hex');
+ const originKind = resolved.originKind ?? 'user';
+ await deps.addRef({
+ hash,
+ refKind: originKind === 'user' ? 'ghost-grant' : 'ghost-tool-grant',
+ refId: params.ghostId,
+ originKind,
+ });
+ hashes.push(hash);
+ }
+ return { ok: true, hashes };
+ },
+ );
+ resolvedAttachmentOrigins.length = 0;
+ confirmRequestMock.mockReset();
+ confirmRequestMock.mockResolvedValue({ confirmed: true, allowDirs: false });
+ classifyLocalAttachmentPathMock.mockReset();
+ classifyLocalAttachmentPathMock.mockImplementation((url: string) => {
+ const stat = fs.statSync(url);
+ return {
+ kind: 'outside-workdir',
+ absPath: url,
+ mimeType: 'image/png',
+ size: stat.size,
+ name: path.basename(url),
+ };
+ });
+ resolveGhostAttachmentUrlMock.mockReset();
+ resolveGhostAttachmentUrlMock.mockImplementation(() => {
+ throw new Error('not a managed media URL');
+ });
+ ledgerHasRefMock.mockReset();
+ ledgerHasRefMock.mockImplementation(async (params: TestLedgerRef) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refKind === params.refKind &&
+ ref.refId === params.refId &&
+ (params.originKind === undefined || ref.originKind === params.originKind),
+ ),
+ );
+ ledgerHasGhostToolGrantMock.mockReset();
+ ledgerHasGhostToolGrantMock.mockImplementation(
+ async (params: { hash: string; ghostId: string }) =>
+ ledgerRefs.some(
+ (ref) =>
+ ref.hash === params.hash &&
+ ref.refId === params.ghostId &&
+ ref.originKind === 'tool' &&
+ (ref.refKind === 'ghost-tool-grant' || ref.refKind === 'ghost-grant'),
+ ),
+ );
+ ledgerAddRefMock.mockReset();
+ ledgerAddRefMock.mockImplementation(async (params: TestLedgerRef) => {
+ ledgerRefs.push({ ...params });
+ return `ref-${ledgerRefs.length}`;
+ });
+ ledgerRefs.length = 0;
+ dirDepositMock.mockClear();
+ saveDepositMock.mockClear();
+ liveGrantStateMock.mockReset();
+ liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null });
+ alsSessionContextMock.mockReset();
logWarnMock.mockClear();
+ logInfoMock.mockClear();
+ releaseMutationMock.mockClear();
+ captureMutationOwnerMock.mockClear();
+ acquireMutationLeaseMock.mockClear();
sessionSnapshotMock.mockReset();
sessionSnapshotMock.mockResolvedValue({
workingDir: WORKDIR,
diff --cc apps/desktop/src/main/mcp-integrations/ghost.ts
index 27f1d3baa4,4964c2a75b..1747603359
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@@ -55,15 -60,10 +60,14 @@@ import { drainGhostCallMedia } from '..
import {
getGhostCardService,
getGhostManager,
- ghostForgeForbiddenRootDirs,
getGhostPipeDispatcher,
getGhostSetupAssessment,
- acquireGhostMutationLeaseForMcp,
++ ghostForgeForbiddenRootDirs,
+ captureGhostMutationOwnerForMcp,
- findAvailableGhostForAuthorization,
- listAvailableGhostsForAuthorization,
++ acquireGhostMutationLeaseForMcp,
isGhostAvailableForActiveSession,
} from '../cindy-brain/index.js';
++import { writeForgeScaffoldWithStableParent } from '../cindy-brain/forgeScaffoldCapability.js';
import { getGhostSetupCoordinator } from '../cindy-brain/ghostSetupCoordinator.js';
import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';
@@@ -152,63 -182,11 +186,65 @@@ async function buildGhostSessionContext
);
}
++/* ────────────────────────────────────────────────────────────────────────
++ * Forge C-4 门:Forge 做的是**本机文件写**,裸 MCP workingDir 只是标签,不能
++ * 直接交给 fs。权威 session 行决定它是否本机、是否当前可写(远程/只读/plan 一律
++ * fail closed)。owner lease 在首个 await 前捕获、持到 scaffold/pack + 装入确认
++ * 转交结束,账号 teardown 会等它释放。
++ * ──────────────────────────────────────────────────────────────────────── */
++
+type ForgeSessionFsGate =
+ | { ok: true; workingDir: string }
+ | {
+ ok: false;
+ errorCode: 'WORKDIR_NOT_LOCAL' | 'WORKDIR_READ_ONLY';
+ message: string;
+ };
+
+async function withForgeOwnerLease<T>(operation: () => Promise<T>): Promise<T> {
+ const owner = captureGhostMutationOwnerForMcp();
+ const release = acquireGhostMutationLeaseForMcp(owner);
+ try {
+ return await operation();
+ } finally {
+ release();
+ }
+}
+
- /**
- * Forge performs Host-side local filesystem writes. A raw MCP workingDir is
- * only a label; the authoritative session row decides whether it is local and
- * whether writes are currently allowed. Keep this gate next to the session
- * snapshot builder so scaffold/pack cannot silently drift into independent
- * caller-supplied path checks.
- */
+async function getForgeSessionFsGate(
+ sessionContext: LiziMcpSessionContext | undefined,
+): Promise<ForgeSessionFsGate> {
+ const sessionId = sessionContext?.sessionId ?? null;
+ if (!sessionId) {
+ return {
+ ok: false,
+ errorCode: 'WORKDIR_NOT_LOCAL',
+ message: 'Forge requires an authoritative local session workdir',
+ };
+ }
+ const snapshot = await getSessionFsSnapshot(sessionId);
+ if (!snapshot?.workingDir || snapshot.remoteHostId) {
+ return {
+ ok: false,
+ errorCode: 'WORKDIR_NOT_LOCAL',
+ message: 'Forge cannot use a remote or unverified session workdir on the local host',
+ };
+ }
+ if (workdirWriteVerdict(snapshot.permissionMode, snapshot.planModeEnabled) === 'deny') {
+ return {
+ ok: false,
+ errorCode: 'WORKDIR_READ_ONLY',
+ message: 'Forge is disabled while the current session workdir is read-only or in plan mode',
+ };
+ }
+ return { ok: true, workingDir: snapshot.workingDir };
+}
+
/** 意识显示名(确认卡标题用;查不到回落 id)。 */
function ghostDisplayName(ghostId: string): string {
- const g = findAvailableGhostForAuthorization(ghostId);
+ const g = getGhostManager()
+ .list()
+ .find((x) => x.manifest.id === ghostId);
return g?.manifest.name ?? ghostId;
}
@@@ -1133,46 -1376,66 +1434,83 @@@ export function getCindyGhostsMcpDeps
return FORGE_GUIDE;
},
async forgeScaffold(request): Promise<CindyForgeScaffoldResult> {
- const sessionWorkdir = resolveSessionContext()?.workingDir ?? null;
- const result = await scaffoldGhostDir(request, { sessionWorkdir });
- if (result.ok) {
- log.info('ghost forge scaffold created', {
- dir: result.dir,
- template: result.template,
- files: result.files,
++ // C-4:owner lease 在首个 await 前捕获并持到副作用结束;workingDir 取权威
++ // session snapshot(远程/只读/plan fail closed),不用裸 MCP workingDir。
+ return withForgeOwnerLease(async () => {
+ const gate = await getForgeSessionFsGate(resolveSessionContext());
+ if (!gate.ok) return gate;
+ const result = await scaffoldGhostDir(request, {
+ sessionWorkdir: gate.workingDir,
+ forbiddenRootDirs: ghostForgeForbiddenRootDirs(),
+ writeScaffold: writeForgeScaffoldWithStableParent,
});
- }
- return result;
+ if (result.ok) {
+ log.info('ghost forge scaffold created', {
+ dir: result.dir,
+ template: result.template,
+ files: result.files,
+ });
+ }
+ return result;
+ });
},
- async forgePack({ dir }): Promise<CindyForgePackResult> {
+ async forgePack({ dir, iconSource }): Promise<CindyForgePackResult> {
- let iconPng: Buffer | undefined;
- let iconNote = '';
- if (iconSource !== undefined) {
- try {
- const resolved = blobStore.resolveSafe(iconSource);
- if (!resolved.mimeType.startsWith('image/')) {
- throw new Error('icon_source 不是图片');
- }
- const stat = await fs.promises.stat(resolved.absPath);
- if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_FORGE_ICON_SOURCE_BYTES) {
- throw new Error(`icon_source 体积必须在 1–${MAX_FORGE_ICON_SOURCE_BYTES} 字节之间`);
+ return withForgeOwnerLease(async () => {
+ const gate = await getForgeSessionFsGate(resolveSessionContext());
+ if (!gate.ok) return gate;
- const packed = await packGhostDir(dir, {
++ let iconPng: Buffer | undefined;
++ let iconNote = '';
++ if (iconSource !== undefined) {
++ try {
++ const resolved = blobStore.resolveSafe(iconSource);
++ if (!resolved.mimeType.startsWith('image/')) {
++ throw new Error('icon_source 不是图片');
++ }
++ const stat = await fs.promises.stat(resolved.absPath);
++ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_FORGE_ICON_SOURCE_BYTES) {
++ throw new Error(`icon_source 体积必须在 1–${MAX_FORGE_ICON_SOURCE_BYTES} 字节之间`);
++ }
++ iconPng = await convertForgeIconToPng(resolved.absPath);
++ iconNote = 'AI 图标已嵌入安装包。';
++ } catch (err) {
++ iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';
++ log.warn('ghost forge icon fallback', {
++ dir,
++ error: err instanceof Error ? err.message : String(err),
++ });
+ }
- iconPng = await convertForgeIconToPng(resolved.absPath);
- iconNote = 'AI 图标已嵌入安装包。';
- } catch (err) {
- iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';
- log.warn('ghost forge icon fallback', {
- dir,
- error: err instanceof Error ? err.message : String(err),
- });
+ }
- }
+
- let packed = await packGhostDir(dir, iconPng ? { iconPng } : undefined);
- // icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码
- // 本身也不合法,则返回原本就会出现的结构化错误。
- if (!packed.ok && iconPng) {
- const fallbackPacked = await packGhostDir(dir);
- if (fallbackPacked.ok) {
- packed = fallbackPacked;
- iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';
- } else {
- return fallbackPacked;
++ const packOptions = {
+ sessionWorkdir: gate.workingDir,
+ forbiddenRootDirs: ghostForgeForbiddenRootDirs(),
- });
++ };
++ let packed = await packGhostDir(dir, iconPng ? { ...packOptions, iconPng } : packOptions);
++ // icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码
++ // 本身也不合法,则返回原本就会出现的结构化错误。
++ if (!packed.ok && iconPng) {
++ const fallbackPacked = await packGhostDir(dir, packOptions);
++ if (fallbackPacked.ok) {
++ packed = fallbackPacked;
++ iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';
++ } else {
++ return fallbackPacked;
++ }
+ }
- }
- if (!packed.ok) return packed;
- // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
- // 自动转"更新 vX → vY"),用户点头才真装。
- await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge');
- log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });
- return {
- ok: true,
- cindyPath: packed.cindyPath,
- id: packed.manifest.id,
- name: packed.manifest.name,
- version: packed.manifest.version,
- note: `${iconNote}已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。`,
- };
+ if (!packed.ok) return packed;
+ // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
- // 自动转"更新 vX → vY"),用户点头才真装。
++ // 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。
+ await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge');
+ log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });
+ return {
+ ok: true,
+ cindyPath: packed.cindyPath,
+ id: packed.manifest.id,
+ name: packed.manifest.name,
+ version: packed.manifest.version,
- note: '已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。',
++ note: `${iconNote}已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。`,
+ };
+ });
},
logger: log,
};
diff --cc apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 639c803614,355c23aa34..7364e6b761
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@@ -76,9 -67,16 +80,18 @@@ import type { PluginMarketApi } from '.
const roots: string[] = [];
const PLUGIN_ID = `c${'a'.repeat(24)}`;
+const APPROVED_INSTALL_TOKEN =
+ 'approved:00000000-0000-4000-8000-000000000001';
+ /** 手动可控 deferred,用于精确编排"安装在飞行中"的交错。 */
+ function deferred(): { promise: Promise<void>; resolve: () => void } {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+ }
+
afterEach(() => {
runtime.ghosts = [];
runtime.install.mockReset();
@@@ -451,9 -680,7 +695,9 @@@ describe('PluginMarketService migratio
{
ghostId: item.ghostId,
version: item.currentRelease.version,
- // 权限绑定:用户确认的服务端清单必须随包传给装入侧比对(P0:服务端记录与
- // 包内 ghost.json 不一致时,不能让"看到 A 权限、批准 B 权限"发生)。
- expectedManifest: expect.objectContaining({ id: item.ghostId }),
++ // 权限绑定:用户确认的服务端清单(main 命名 reviewedManifest)必须随包传给装入侧
++ // 比对(P0:服务端记录与包内 ghost.json 不一致时,不能让"看到 A 权限、批准 B 权限"发生)。
+ reviewedManifest: expect.objectContaining({ id: item.ghostId }),
},
);
expect(snapshot.items[0]).toMatchObject({
diff --cc apps/desktop/src/main/plugin-market/registerIpc.ts
index cf758fe251,f46edc7c36..95dbb4ead1
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@@ -1,7 -3,7 +3,7 @@@ import os from 'node:os'
import { ipcMain } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
- import { isGhostInstallApprovalToken } from '../../shared/ghost.js';
-import type { GhostManifest } from '../../shared/ghost.js';
++import { isGhostInstallApprovalToken, type GhostManifest } from '../../shared/ghost.js';
import { setGhostUninstallLedgerPreparer } from '../cindy-brain/index.js';
import { createLogger } from '../logger.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
@@@ -59,29 -77,38 +77,52 @@@ export function registerPluginMarketIpc
typeof options === 'object' && options !== null
? (options as {
expectedReleaseId?: unknown;
+ expectedInstalledApproval?: unknown;
+ expectedManifest?: unknown;
allowPermissionExpansion?: unknown;
+ reviewedBaseline?: unknown;
+ approvedPackageSha256?: unknown;
})
: null;
const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');
+ const expectedInstalledApproval = obj?.expectedInstalledApproval;
+ if (
+ expectedInstalledApproval !== undefined &&
+ !isGhostInstallApprovalToken(expectedInstalledApproval)
+ ) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'expectedInstalledApproval must come from ghosts:list',
+ );
+ }
+ const expectedManifest =
+ obj?.expectedManifest === undefined || obj?.expectedManifest === null
+ ? undefined
+ : requireObject(obj.expectedManifest);
const allowPermissionExpansion = obj?.allowPermissionExpansion === true;
+ // 扩权批准的审阅基线:只收字符串,野值按缺席处理(缺席 = 保持旧行为)。
+ const reviewedBaseline =
+ typeof obj?.reviewedBaseline === 'string' ? obj.reviewedBaseline : undefined;
+ const approvedPackageSha256 =
+ typeof obj?.approvedPackageSha256 === 'string'
+ ? obj.approvedPackageSha256
+ : undefined;
+ if (
+ approvedPackageSha256 !== undefined &&
+ !/^[a-f0-9]{64}$/.test(approvedPackageSha256)
+ ) {
+ throwIpcError('INVALID_PARAMS', 'approvedPackageSha256 is invalid');
+ }
return invokePluginMarket(() =>
service().install(requireString(pluginId, 'pluginId'), {
expectedReleaseId,
+ ...(expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval }
+ : {}),
+ ...(expectedManifest ? { expectedManifest: expectedManifest as unknown as GhostManifest } : {}),
allowPermissionExpansion,
+ ...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),
+ ...(approvedPackageSha256 !== undefined ? { approvedPackageSha256 } : {}),
}),
);
},
diff --cc apps/desktop/src/main/plugin-market/service.ts
index 3218d1812b,a88bb60644..d3a0cd82fc
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@@ -7,13 -7,14 +7,15 @@@ import
type VisiblePluginDetail,
type VisiblePluginSummary,
} from '@cindy/plugin-protocol';
- import { app, type WebContents } from 'electron';
+ import { app, dialog } from 'electron';
import {
- diffInstalledGhostPermissionItems,
+ diffGhostPermissionItems,
+ ghostInstallApprovalToken,
+ ghostPermissionBaselineKey,
isOfficialGhostId,
validateGhostManifest,
+ type GhostManifest,
type InstalledGhost,
} from '../../shared/ghost.js';
import type {
@@@ -197,54 -353,68 +354,88 @@@ export class PluginMarketService
requireSameMarketOwner(owner);
const ledger = this.ledgerForOwner(owner);
+ // ghostId 冲突判定跨服务端与自定义市场合并计算(全局唯一、先装先得)。
+ // 必须**先于** applyDefaultInstalls 算出来:默认安装会真的下载并启用插件,
+ // 若只按服务端目录判重,与自定义来源同 ghostId 的默认项会被静默抢占所有权,
+ // 而列表随后又把它标成 conflict —— 既定事实已经发生。
+ const duplicateGhostIds = combinedDuplicateGhostIds(plugins, customEntries);
await this.adoptLegacyInstallations(plugins, ledger, owner);
+ await this.migrateMarketManifestDigests(plugins, ledger, owner);
await this.reconcileRemovedInstallations(ledger, owner);
- await this.applyDefaultInstalls(plugins, owner, ledger);
+ // 自定义目录不完整(某来源暂时不可读)时跳过全部默认安装:此刻的合并冲突
+ // 集合缺了坏来源声明的 ghostId,自动安装会在它恢复前抢占所有权。
+ if (customComplete) {
+ await this.applyDefaultInstalls(plugins, owner, ledger, duplicateGhostIds);
+ } else {
+ log.warn('skipping default installs: custom marketplace catalog is incomplete');
+ }
requireSameMarketOwner(owner);
- return { items: this.toItems(plugins, ledger), unavailableReason: null };
+ const local = this.localInstallSnapshot(ledger);
+ const serverItems = plugins.map((plugin) =>
+ this.toItem(plugin, duplicateGhostIds, local),
+ );
+ const items = [...serverItems, ...this.projectCustomItems(customEntries, duplicateGhostIds, local)];
+ // 聚合完成、返回 Renderer 前最后校验:账号在任一 await 间隙漂移则拒绝,
+ // 不把按旧账号解析的自定义项/账本状态发给当前会话。
+ requireSameMarketOwner(owner);
+ return {
+ items,
+ unavailableReason: null,
+ customSourceNames,
+ };
}
+ /**
+ * detail 响应必须与请求身份一致:后续下载、安装、ledger 全都信 detail 的自报
+ * 字段,不绑定的话异常/恶意服务端响应可以把 A 的确认导向 B 的内容,并绕过
+ * 调用方基于目录 summary 做过的可见性与 ghostId 冲突判断。
+ */
+ private requireDetailIdentity(
+ detail: { id: string; ghostId: string },
+ expected: { pluginId: string; ghostId?: string },
+ ): void {
+ if (
+ detail.id !== expected.pluginId ||
+ (expected.ghostId !== undefined && detail.ghostId !== expected.ghostId)
+ ) {
+ throwIpcError('GHOST_FILE_INVALID', 'Market detail response does not match the requested Plugin');
+ }
+ }
+
async detail(pluginId: string): Promise<PluginMarketDetail> {
+ // 自定义市场插件走本地发现,不要求服务端可用,也不受 CUID 形状约束。
+ const customRef = parseCustomMarketPluginId(pluginId);
+ if (customRef) return this.customDetail(customRef);
if (!isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
}
this.requireConfigured();
- const owner = captureMarketOwner();
- const plugin = await this.api.detail(pluginId);
- requireSameMarketOwner(owner);
- this.requireDetailIdentity(plugin, { pluginId });
- if (owner.mode === 'local' && plugin.scope !== 'public') {
- throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');
- }
- const compatible = validateGhostManifest(plugin.currentRelease.manifest);
- if (!compatible.ok) {
- throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
- }
- return {
- ...this.toItem(
- plugin,
- NO_DUPLICATE_GHOST_IDS,
- this.localInstallSnapshot(this.ledgerForOwner(owner)),
- ),
- manifest: compatible.manifest,
- };
+ return this.runForOwner(async (owner) => {
+ const plugin = await this.api.detail(pluginId);
+ requireSameMarketOwner(owner);
++ // 详情响应必须与请求的 pluginId 绑定:server 换身份会让用户审阅到别的插件
++ // (receipt 分支保留的安全绑定,与 main 的跨来源去重叠加)。
++ this.requireDetailIdentity(plugin, { pluginId });
+ if (owner.mode === 'local' && plugin.scope !== 'public') {
+ throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');
+ }
+ const compatible = validateGhostManifest(plugin.currentRelease.manifest);
+ if (!compatible.ok) {
+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
+ }
+ // 详情必须与列表同口径:传空重复集合会把列表标为 conflict 并禁用的项
+ // 在详情页恢复成可安装,给出一条绕过冲突闸的入口。
+ const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);
+ requireSameMarketOwner(owner);
+ return {
+ ...this.toItem(
+ plugin,
+ duplicates,
+ this.localInstallSnapshot(this.ledgerForOwner(owner)),
+ ),
+ manifest: compatible.manifest,
+ };
+ });
}
async install(
@@@ -294,9 -478,16 +502,17 @@@
ghost: await this.installDetail(
plugin,
{
- expectedInstalled: existing,
+ expectedInstalled: Boolean(existing),
+ expectedInstalledApproval: options.expectedInstalledApproval,
allowPermissionExpansion: options.allowPermissionExpansion === true,
+ ...(options.reviewedBaseline !== undefined
+ ? { reviewedBaseline: options.reviewedBaseline }
+ : {}),
+ ...(options.approvedPackageSha256 !== undefined
+ ? { approvedPackageSha256: options.approvedPackageSha256 }
+ : {}),
+ // 下载可能持续数分钟,提交副作用前按当前事实再算一次。
+ recheckOwnership: assertOwnership,
},
owner,
ledger,
@@@ -368,9 -1090,17 +1115,19 @@@
plugin: VisiblePluginDetail,
options: {
allowPermissionExpansion?: boolean;
++ /** receipt 模型的并发护栏:比对 receipt 派生 token,状态变更即拒(与 main 硬化叠加)。 */
+ expectedInstalledApproval?: string;
+ /** 扩权批准所依据的已装权限指纹;安装锁内复核,详见 install() 的说明。 */
+ reviewedBaseline?: string;
+ /** 用户确认过的真实下载包 SHA。 */
+ approvedPackageSha256?: string;
/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
+ /**
+ * 提交副作用前的所有权复核。下载可能持续数分钟,期间另一窗口可经独立的
+ * market-sources 互斥键添加声明同一 ghostId 的来源,入口处那次判定已过期。
+ */
+ recheckOwnership?: () => Promise<void>;
} = { expectedInstalled: false },
owner = captureMarketOwner(),
ledger = this.ledgerForOwner(owner),
@@@ -386,16 -1116,6 +1143,21 @@@
if (existing && (!currentRecord?.installed || currentRecord.pluginId !== plugin.id)) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
++ // 受体并发护栏(TOCTOU):仅当调用方**显式**带来了确认时捕获的批准令牌才核对。
++ // 令牌是更新/恢复入口在渲染确认框那一刻钉下的当前受体;它对不上 = 确认往返
++ // 窗口里批准被换过,拒绝用旧同意批新包。自动播种/迁移/首装(不带令牌)不受此闸,
++ // 各自的 expectedInstalled / 所有权 / reviewedBaseline 门负责它们的关切。
+ if (
+ existing &&
++ options.expectedInstalledApproval !== undefined &&
+ ghostInstallApprovalToken(existing.approval) !==
+ options.expectedInstalledApproval
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state changed after permission review',
+ );
+ }
const compatible = validateGhostManifest(plugin.currentRelease.manifest);
if (!compatible.ok) {
@@@ -440,47 -1170,66 +1212,95 @@@
'Plugin was uninstalled while the update was downloading',
);
}
++ // 同锁外那道:仅当确认时捕获过批准令牌才做锁内权威复核(TOCTOU)。
++ // 未带令牌的更新(如相对 legacy 安装的原位更新)不受此闸,由 reviewedBaseline
++ // 复核扩权、由 stillInstalled 存在性挡"下载期间被卸载"。
+ if (
++ options.expectedInstalledApproval !== undefined &&
+ ghostInstallApprovalToken(stillInstalled.approval) !==
- options.expectedInstalledApproval
++ options.expectedInstalledApproval
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state changed while the update was downloading',
+ );
+ }
+ } else if (
+ getGhostManager()
+ .list()
+ .some((ghost) => ghost.manifest.id === plugin.ghostId)
+ ) {
+ // 用户确认的是首装;下载期间出现同 id 安装时,不能静默把它升级为
+ // “更新现有插件”。即使 Renderer 恰好带了一个可匹配 token,也必须
+ // 刷新详情并按更新流程重新审阅。
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin was installed while the package was downloading',
+ );
}
- // 市场首装一律装完即开(2026-07-26 定案,见 installOrUpdateMarketGhostPackage);
- // 已装过则走原位更新,唤醒/沉睡状态延续当前值。
- const ghost = await installOrUpdateMarketGhostPackage(tempPath, {
- ghostId: plugin.ghostId,
- version: plugin.currentRelease.version,
- // 用户在确认卡上审阅的权限 diff 是拿服务端 release.manifest 算的;把它一并
- // 传下去,由装入侧比对下载包清单的权限投影与指令 —— 服务端记录与包内
- // ghost.json 不一致时中止,不让"看到 A 权限、批准 B 权限"发生。
- expectedManifest: compatible.manifest,
- ...(options.expectedInstalledApproval
- ? { expectedInstalledApproval: options.expectedInstalledApproval }
- : {}),
- });
- // Once the package directory is committed, finish provenance against the
- // owner captured at operation start even if the active session changes.
- // The bound ledger prevents this write from leaking into the new owner.
- await this.withCapturedLedgerMutation(ledger, () => {
- ledger.upsertInstallation(recordFrom(plugin, 'market'));
- });
+ // 复核 + 落位 + 溯源写入在同一对锁内完成:
+ // - SOURCE_MUTATION_KEY:`installOrUpdateMarketGhostPackage` 会先 await 包
+ // 检查才开始改动运行时,复核若在锁外做,结论会在这段等待里过期。
+ // - withGhostInstallLock(ghostId):与本地 .cindy 装入/更新/卸载共用同一按 id
+ // 互斥。少了它,本地装入能在包检查窗口里落入同 id 的包,随后被本次安装当作
+ // 更新目标覆盖,而权限差异确认因审阅时目标不存在而没跑过。账本写入也必须在
+ // 锁内:否则本地装入可以插在"落位"与"写溯源"之间,让账本认领一个其实已被
+ // 替换掉的包(账本摘要若未对上当前安装内容,投影时不会认领)。
+ // 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation,不可反向。
+ const ghost = await this.withMutation(SOURCE_MUTATION_KEY, () =>
+ withGhostInstallLock(plugin.ghostId, async () => {
+ // 改动 Ghost 运行时之前的最后一道:跨来源 ghostId 所有权按当前事实重算。
+ await options.recheckOwnership?.();
+ requireSameMarketOwner(owner);
+ // 权限扩权的**权威**判定点:锁内按当前已装 manifest 重算。锁外那次
+ // 只是快速失败;下载窗口期本地装入/更新若换掉了已装包,旧批准在这里
+ // 被基线比对拦下,并发替换绕不过去(落位就在下面几行)。
+ const installedNow = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
+ assertExpansionApproved(installedNow?.manifest ?? null);
+ const currentRecordNow = ledger.installationForGhost(plugin.ghostId);
+ const installedRawManifest = installedNow
+ ? installedGhostRawManifest(installedNow.dir)
+ : null;
+ const previouslyInstalledManifest =
+ installedRawManifest &&
+ currentRecordNow?.installed &&
+ (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&
+ currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
+ ? installedRawManifest
+ : undefined;
+ // 市场首装一律装完即开(2026-07-26 定案,见 installOrUpdateMarketGhostPackage);
+ // 已装过则走原位更新,唤醒/沉睡状态延续当前值。
+ const installed = await installOrUpdateMarketGhostPackage(tempPath, {
+ ghostId: plugin.ghostId,
+ version: plugin.currentRelease.version,
+ // 确认框渲染的就是这份服务端 manifest;包里若多出权限项,出口处先
+ // 暂停落位并返回真实包权限——服务端投影层与客户端清单契约漂移时,
+ // 必须让用户按实际要安装的能力面重新确认。
+ reviewedManifest: compatible.manifest,
+ ...(previouslyInstalledManifest ? { previouslyInstalledManifest } : {}),
+ ...(options.approvedPackageSha256 !== undefined
+ ? {
+ approvedPackageSha256: options.approvedPackageSha256,
+ reviewedBaseline: options.reviewedBaseline,
+ }
+ : {}),
++ // receipt 模型并发护栏与 main 硬化叠加:装入侧锁内再比对 receipt token。
++ ...(options.expectedInstalledApproval
++ ? { expectedInstalledApproval: options.expectedInstalledApproval }
++ : {}),
+ });
+ // Once the package directory is committed, finish provenance against
+ // the owner captured at operation start even if the active session
+ // changes. The bound ledger prevents this write from leaking into the
+ // new owner.
+ await this.withCapturedLedgerMutation(ledger, () => {
+ ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
+ });
+ return installed;
+ }),
+ );
return ghost;
} finally {
await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);
diff --cc apps/desktop/src/preload/preload.ts
index 7563674701,a5f7d309a7..f9d3967586
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@@ -860,16 -952,11 +952,15 @@@ contextBridge.exposeInMainWorld('electr
install: (
lizFilePath: string,
opts: { enable?: boolean; expectedPackageSha256: string },
- ): Promise<{ ghost: unknown }> =>
- ipcRenderer.invoke('ghosts:install', lizFilePath, opts),
+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:install', lizFilePath, opts),
update: (
lizFilePath: string,
- opts: { expectedPackageSha256: string },
- ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),
+ opts: {
+ expectedPackageSha256: string;
+ expectedInstalledApproval: string;
+ },
+ ): Promise<{ ghost: unknown }> =>
+ ipcRenderer.invoke('ghosts:update', lizFilePath, opts),
cindyPrefsSync: (
id: string,
): {
@@@ -900,32 -1002,12 +1006,33 @@@
trust: unknown;
packageSha256: string;
iconDataUrl?: string;
- }> =>
- ipcRenderer.invoke('ghosts:inspect', lizFilePath),
+ }> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),
+ /** 本地包第三条恢复路径:从已装目录读确认卡事实(零副作用)。 */
+ reapproveInspect: (id: string): Promise<{
+ manifest: unknown;
+ trust: unknown;
+ manifestSha256: string;
+ approvalProjectionSha256: string;
+ previouslyEnabled: boolean;
+ inspectTicket: string;
+ }> => ipcRenderer.invoke('ghosts:reapprove-inspect', id),
+ /** 确认卡点过同意后开 receipt;sha + 一次性票据绑定确认时的事实与 owner。 */
+ reapproveInstalled: (
+ id: string,
+ opts: {
+ enable: boolean;
+ expectedManifestSha256: string;
+ expectedApprovalProjectionSha256: string;
+ expectedInstalledApproval: string;
+ inspectTicket: string;
+ },
+ ): Promise<{ ghost: unknown }> =>
+ ipcRenderer.invoke('ghosts:reapprove-installed', id, opts),
uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),
/** 详情页「导出 .cindy」:main 打包安装目录 → 系统保存对话框落盘。 */
- export: (id: string): Promise<{ status: 'saved'; savedPath: string } | { status: 'canceled' }> =>
+ 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),
diff --cc apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
index b7bfcb3065,08f2667248..2b21f10586
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
@@@ -102,8 -105,7 +106,9 @@@ describe('ghostPluginViewModel', () =>
version: '1',
enabled: true,
canUse: true,
+ approvalState: 'approved',
- builtin: false,
++ builtin: false,
+ tabPanel: false,
},
{
id: 'lizi-mivo',
@@@ -112,8 -114,7 +117,9 @@@
version: '1',
enabled: true,
canUse: true,
+ approvalState: 'approved',
- builtin: false,
++ builtin: false,
+ tabPanel: false,
},
{
id: 'slack',
@@@ -122,8 -123,7 +128,9 @@@
version: '1',
enabled: true,
canUse: true,
+ approvalState: 'approved',
- builtin: false,
++ builtin: false,
+ tabPanel: false,
},
] satisfies GhostPluginListItem[];
diff --cc apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
index c4c1ea5157,78d3bcc705..d8eec45e78
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
@@@ -102,62 -95,7 +99,62 @@@ describe('installFlow · 装入确认'
});
});
+describe('installFlow · approved update binding', () => {
+ function installed(
+ approval: InstalledGhost['approval'],
+ ): InstalledGhost {
+ return {
+ manifest: {
+ ...baseManifest,
+ version: '0.9.0',
+ slots: ['card'],
+ node: undefined,
+ },
+ dir: '/brain/node-ghost',
+ enabled: true,
+ approval,
+ };
+ }
+
+ it('passes the reviewed approved revision to Main', async () => {
+ const current = installed({
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ });
+ const { update } = setupWindow(baseManifest, undefined, [current]);
+ const confirm = vi.fn(async (_options: unknown) => true);
+
+ await confirmAndInstallGhost('/tmp/node-update.cindy', deps(confirm));
+
+ expect(update).toHaveBeenCalledWith('/tmp/node-update.cindy', {
+ expectedPackageSha256: 'a'.repeat(64),
+ expectedInstalledApproval:
+ 'approved:00000000-0000-4000-8000-000000000001',
+ });
+ });
+
+ it('treats every target permission as added when no approved baseline exists', async () => {
+ const current = installed({ state: 'legacy-unapproved' });
+ const { update } = setupWindow(baseManifest, undefined, [current]);
+ const confirm = vi.fn(async (_options: unknown) => true);
+
+ await confirmAndInstallGhost('/tmp/legacy-update.cindy', deps(confirm));
+
+ const review = (confirm.mock.calls[0]![0] as {
+ content: { props: { diff: { added: unknown[]; unchanged: unknown[] } } };
+ }).content;
+ expect(review.props.diff.added.length).toBeGreaterThan(0);
+ expect(review.props.diff.unchanged).toEqual([]);
+ expect(update).toHaveBeenCalledWith(
+ '/tmp/legacy-update.cindy',
+ expect.objectContaining({
+ expectedInstalledApproval: 'legacy-unapproved',
+ }),
+ );
+ });
+});
+
- describe('installFlow · tab 型插件「立即开启并打开页签」', () => {
+ describe('installFlow · tab 型插件「立即开启并打开面板」', () => {
const tabManifest = {
schemaVersion: 2 as const,
id: 'tab-demo-a',
diff --cc apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index 494caa8245,016bca4e54..631d363798
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@@ -35,6 -32,6 +34,8 @@@ import { ghostInstallErrorKey } from '.
* 状态,不偷偷点亮也不偷偷熄灯)。
*/
++const installFlowLog = createLogger('ghost-install-flow');
++
interface InstallFlowDeps {
t: TFunction;
/** ui/confirm-dialog-provider 的 confirm(更新确认,无勾选)。 */
diff --cc apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 3a1aa2f000,b467b380cb..386d991052
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@@ -69,11 -78,12 +78,17 @@@ interface GhostPluginDetailViewProps
enabledOverride?: boolean;
onBack: () => void;
onToggle: (enabled: boolean) => void;
+ /** 主动作:面板型「使用」(打开面板)/ 指令型「对话」;纯工具型不渲染主按钮。 */
onUse: () => void;
+ /** 头部更新 CTA:市场有新版本时走市场更新确认流。 */
onUpdate: () => void;
- /** 缺少批准状态时的恢复入口(重新走一次完整权限确认)。 */
- onReapprove: () => void;
- updateLabel?: string;
++ /**
++ * 缺少批准状态时的恢复入口(重新走一次完整权限确认)。可选:仅插件页宿主注入;
++ * 未注入时按钮不出现,门控见下方 `needsReapproval && !detail.builtin && onReapprove`。
++ */
++ onReapprove?: () => void;
+ /** ⋮ 菜单的兜底路径:从本地 .cindy 文件更新。 */
+ onUpdateFromFile: () => void;
/** 市场存在新版本时的目标版本号;设置后头部展示显著的更新按钮。 */
updateVersion?: string;
updateBusy?: boolean;
@@@ -137,8 -147,7 +152,8 @@@ export function GhostPluginDetailView(
onToggle,
onUse,
onUpdate,
+ onReapprove,
- updateLabel,
+ onUpdateFromFile,
updateVersion,
updateBusy = false,
onUninstall,
@@@ -151,10 -160,10 +166,13 @@@
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
const [descriptionOverflows, setDescriptionOverflows] = useState(false);
const descriptionRef = useRef<HTMLParagraphElement>(null);
- // 未批准的安装不可运行:说明现状 + 给恢复入口,不让它看起来只是"被关掉了"。
- const enabled = enabledOverride ?? detail.enabled;
++ // 未批准的安装不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它
++ // 看起来只是"被关掉了"),再喂 main 改版的 primaryAction/primaryEnabled。
+ const needsReapproval = detail.approvalState !== 'approved';
+ const enabled = (enabledOverride ?? detail.enabled) && !needsReapproval;
- const canUse = enabled && detail.canUse;
+ const primaryAction = ghostPrimaryAction(detail);
+ const primaryEnabled =
+ enabled && (primaryAction === 'panel' || (primaryAction === 'command' && detail.canUse));
const cindyCapabilities = detail.cindyCapabilities;
const hasConfiguration =
detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;
@@@ -233,21 -254,8 +263,22 @@@
className="plugin-detail-actions flex shrink-0 flex-nowrap items-center gap-1.5"
style={WINDOW_NO_DRAG_STYLE}
>
- {needsReapproval && !detail.builtin ? (
- {updateVersion ? (
++ {needsReapproval && !detail.builtin && onReapprove ? (
+ <button
+ type="button"
+ onClick={onReapprove}
+ disabled={updateBusy}
+ className={cn(
+ 'inline-flex h-10 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5 text-13 font-medium text-[var(--text-primary)]',
+ 'transition-[background-color,border-color,transform,opacity] duration-150 hover:border-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-wait disabled:opacity-40 disabled:active:scale-100',
+ )}
+ >
+ {t('settings.ghosts.reapproval.action')}
+ </button>
+ ) : updateVersion ? (
+ // 更新提级(设计定稿):有新版本时黑色主 CTA 直达市场更新确认流。
<button
type="button"
onClick={onUpdate}
@@@ -264,27 -274,67 +297,68 @@@
: t('settings.ghosts.market.updateTo', { version: updateVersion })}
</button>
) : null}
+ {primaryAction !== 'manage' ? (
+ <button
+ type="button"
+ onClick={onUse}
+ disabled={!primaryEnabled}
+ title={!enabled ? t('settings.ghosts.detail.useDisabled') : undefined}
+ className={cn(
+ 'plugin-detail-primary-action inline-flex h-10 min-w-[88px] items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3 text-13 font-medium',
+ updateVersion
+ ? 'border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] hover:bg-[var(--surface-hover-soft)]'
+ : 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)] hover:bg-[var(--accent-hover)]',
+ 'transition-[background-color,transform,opacity] duration-150 active:scale-[0.98]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',
+ )}
+ >
+ {primaryAction === 'command' ? (
+ <MessageCircle size={14} aria-hidden="true" />
+ ) : null}
+ {t(
+ primaryAction === 'panel'
+ ? 'settings.ghosts.detail.useAction'
+ : 'settings.ghosts.detail.chatAction',
+ )}
+ </button>
+ ) : null}
+ {/* 启用开关带明确文字(设计定稿):状态一目了然,点文字同样可切换。 */}
<button
type="button"
- onClick={onUse}
- disabled={!canUse}
- title={!enabled ? t('settings.ghosts.detail.useDisabled') : undefined}
+ onClick={() => {
- if (!toggleDisabled) onToggle(!enabled);
++ // 未批准的安装不可切换启用(点了 Main 也会拒);与 updateBusy 同级门控。
++ if (!toggleDisabled && !needsReapproval) onToggle(!enabled);
+ }}
- disabled={toggleDisabled}
++ disabled={toggleDisabled || needsReapproval}
+ aria-pressed={enabled}
+ aria-label={t('settings.ghosts.enableAria', { name: detail.name })}
className={cn(
- 'plugin-detail-primary-action inline-flex h-10 min-w-[88px] items-center justify-center whitespace-nowrap rounded-full px-3 text-13 font-medium',
- 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)]',
- 'transition-[background-color,transform,opacity] duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- 'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',
+ 'flex shrink-0 items-center gap-2 rounded-full py-1 pl-3 pr-1 transition-colors duration-150',
+ 'hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ 'disabled:cursor-not-allowed disabled:opacity-60',
)}
>
- {t('settings.ghosts.detail.useAction')}
+ <span
+ className={cn(
+ 'text-12',
+ enabled ? 'text-[var(--text-secondary)]' : 'text-[var(--text-tertiary)]',
+ )}
+ >
+ {t(
+ enabled
+ ? 'settings.ghosts.detail.enabledLabel'
+ : 'settings.ghosts.detail.disabledLabel',
+ )}
+ </span>
+ <Switch
+ checked={enabled}
- disabled={toggleDisabled}
++ disabled={toggleDisabled || needsReapproval}
+ aria-hidden="true"
+ tabIndex={-1}
+ className="pointer-events-none"
+ />
</button>
- <Switch
- checked={enabled}
- onCheckedChange={onToggle}
- disabled={toggleDisabled || needsReapproval}
- aria-label={t('settings.ghosts.enableAria', { name: detail.name })}
- />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
diff --cc apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index e00fd75f4a,87ba7be792..4281a921e3
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@@ -31,23 -51,20 +51,25 @@@ import
plainTextToTiptapDoc,
saveDraft as saveComposerDraft,
} from '@/lib/composerDraftStore';
- import { patchDraft } from '@/state/newMakerDraft';
+ import { resetDraftWorkspaceTargets } from '@/state/newMakerDraft';
import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';
-import { confirmAndInstallGhost, pickAndUpdateGhost } from '@/cindy-brain/installFlow';
+import {
+ confirmAndInstallGhost,
+ pickAndUpdateGhost,
+ reapproveInstalledGhost,
+} from '@/cindy-brain/installFlow';
import { GhostPermissionList, GhostUpdateReview } from '@/cindy-brain/GhostPermissionList';
import { cn } from '@/lib/utils';
- import { Switch } from '@/components/ui/switch';
+ import { AttentionDot } from '@/components/sidebar/AttentionDot';
+ import { useGhostUnread, useGhostUnreadSummary } from '@/cindy-brain/ghostUnreadStore';
import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
import { resolveSystemLocale } from '../../../shared/locale';
import {
- diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
+ ghostInstallApprovalToken,
ghostPanelKind,
+ ghostPermissionBaselineKey,
ghostPermissionItems,
isOfficialGhostId,
type GhostSetupStatus,
@@@ -77,9 -111,6 +116,10 @@@ import { GhostPluginIcon } from './Ghos
import { MarketPluginDetailView } from './MarketPluginDetailView';
import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker';
import {
++ // 受体模型的两条纯推导:reapprove 路由判定 + 「市场复核目标是否命中已装」。
++ // main 的卡片改版不再走 catalogItems 交织,orderPluginCatalogItems 已无引用故不引入。
+ ghostReapprovalRoute,
+ marketReviewTargetsInstalledGhost,
- orderPluginCatalogItems,
pluginPresentationOrigin,
pluginUpdateForInstalledVersion,
type PluginPresentationOrigin,
@@@ -456,11 -654,59 +663,62 @@@ export function GhostPluginPage()
[t],
);
+ /**
+ * 市场详情与真实下载包权限不一致时,展示 Main 验证后的真实权限并绑定重试。
+ * Renderer 只负责确认;包 SHA 和已装权限基线均由 Main 重新核对。
+ */
+ const installReviewedMarketPackage = useCallback(
+ async (input: {
+ detail: PluginMarketDetail;
+ lease: { pluginId: string };
+ options: PluginMarketInstallOptions;
+ }): Promise<InstalledGhost | null> => {
+ const initial = await window.electronAPI.pluginMarket.install(
+ input.detail.pluginId,
+ input.options,
+ );
+ if (initial.ghost !== undefined) return initial.ghost;
+ if (!isMarketBusyLeaseActive(input.lease)) return null;
+
+ const review = initial.reviewRequired;
+ if (!review) return null;
+ const approved = await confirm({
+ title: t('settings.ghosts.market.installConfirmTitle', {
+ name: input.detail.name,
+ }),
+ description: t('settings.ghosts.market.installConfirmDescription'),
+ content: <GhostPermissionList items={ghostPermissionItems(review.manifest)} />,
+ maxWidth: 520,
+ confirmText: t('settings.ghosts.market.install'),
+ cancelText: t('settings.ghosts.installConfirm.cancel'),
+ autoFocusConfirm: true,
+ });
+ if (!approved || !isMarketBusyLeaseActive(input.lease)) return null;
+
+ const retried = await window.electronAPI.pluginMarket.install(
+ input.detail.pluginId,
+ {
+ ...input.options,
+ allowPermissionExpansion: review.installedBaseline !== null,
+ reviewedBaseline: review.installedBaseline ?? undefined,
+ approvedPackageSha256: review.packageSha256,
+ },
+ );
+ if (retried.ghost !== undefined) return retried.ghost;
+
+ // 同一 release 的真实包不应漂移;再次要求复核说明已装基线在往返窗口内变化。
+ toast.error(t('settings.ghosts.market.errors.stateChanged'));
+ await refreshMarket();
+ return null;
+ },
+ [confirm, isMarketBusyLeaseActive, refreshMarket, t],
+ );
+
// 市场更新流程由列表卡片和详情页共用:先取目标 release 的完整 manifest 做
// 权限 diff,经用户确认后才安装,不做静默升级。
+ //
+ // 同版本的 `installed` 也走这里:缺少批准状态的存量安装靠"用市场包重装同一
+ // release"恢复,此时权限 diff 会把目标包的全部权限当新增项逐条列出。
const handleMarketUpdate = useCallback(
async (ghostId: string) => {
const marketItem = marketByGhostId.get(ghostId);
@@@ -499,11 -734,21 +757,24 @@@
cancelText: t('settings.ghosts.updateConfirm.cancel'),
});
if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;
- const result = await window.electronAPI.pluginMarket.install(marketItem.pluginId, {
- expectedReleaseId: next.releaseId,
- expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),
- allowPermissionExpansion: diff.added.length > 0,
+ const ghost = await installReviewedMarketPackage({
+ detail: next,
+ lease: marketBusyLease,
+ options: {
+ expectedReleaseId: next.releaseId,
++ // 受体模型:更新必须带旧批准令牌,Main 在安装锁内核对当前受体,
++ // 防止确认往返窗口里批准被替换(用旧同意批新包)。
++ expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),
+ ...(next.sourceType !== 'server' ? { expectedManifest: next.manifest } : {}),
+ allowPermissionExpansion: diff.added.length > 0,
+ // 用户看确认框这段时间里已装 manifest 可能被换掉(如从文件更新);
+ // 把审阅基线交给 Main,在安装锁内复核后才放行扩权。
+ ...(installedGhost
+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
+ : {}),
+ },
});
+ if (!ghost) return;
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
toast.success(
t('settings.ghosts.toast.updated', {
@@@ -541,26 -787,32 +813,52 @@@
await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
}, [confirm, confirmWithCheckbox, handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);
+ /**
+ * 缺少批准状态时的恢复入口。市场自有的包重走市场安装确认(重新下载 + 逐项
+ * 权限确认);本地包让用户重新选一次 `.cindy`。两条路都落到同一套权限确认,
+ * 不存在"点一下就悄悄恢复运行"的分支。
+ */
+ const handleReapprove = useCallback(
+ async (ghostId: string) => {
+ // 随包插件不走人工重新确认(入口已隐藏,这里是防御):批准由启动对账自动补。
+ if (ghosts.find((g) => g.manifest.id === ghostId)?.builtin) return;
+ if (ghostReapprovalRoute(marketByGhostId.get(ghostId)) === 'market') {
+ await handleMarketUpdate(ghostId);
+ return;
+ }
+ // 本地包路线:从已装目录读全量权限清单确认后开 receipt,不用用户翻出原始
+ // .cindy 文件;目录读不出时该流程内部自动回退到"重新选包"。
+ await reapproveInstalledGhost(ghostId, { t, confirm, confirmWithCheckbox });
+ },
+ [confirm, confirmWithCheckbox, ghosts, handleMarketUpdate, marketByGhostId, t],
+ );
+
+ const handleUpdateFromFile = useCallback(async () => {
+ if (!selectedDetail) return;
+ await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
+ }, [confirm, confirmWithCheckbox, selectedDetail, t]);
+
+ // 控制器在挂载期借用本页的市场刷新;卸载后批次继续跑,重新进页全量刷新。
+ useEffect(
+ () => setUpdateAllBatchHooks({ refreshMarket: () => refreshMarket() }),
+ [refreshMarket],
+ );
+ const handleUpdateAll = useCallback(() => {
+ const current = getUpdateAllBatchState();
+ // 运行中或还有待确认项的批次:重开弹窗接着处理,不重建批次。
+ if (current.running || (current.rows !== null && !isBatchFinished(current.rows))) {
+ setUpdateDialogOpen(true);
+ return;
+ }
+ // 单项更新持有 market lease 期间不许开新批次:此刻的市场快照还把那个
+ // 插件标成 update-available,批次会把它一并收进去重复装一遍。
+ if (marketBusyLockRef.current !== null) return;
+ startUpdateAllBatch(
+ updatableInstalledItems.flatMap((item) => (item.marketUpdate ? [item.marketUpdate] : [])),
+ );
+ setUpdateDialogOpen(true);
+ }, [updatableInstalledItems]);
+
const handleInstall = useCallback(async () => {
const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
if (!picked || 'canceled' in picked) return;
@@@ -844,19 -1115,27 +1161,34 @@@
autoFocusConfirm: true,
});
if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;
- const result = await window.electronAPI.pluginMarket.install(marketDetail.pluginId, {
- expectedReleaseId: marketDetail.releaseId,
- ...(isUpdate
- ? {
- expectedInstalledApproval: ghostInstallApprovalToken(
- installedGhost!.approval,
- ),
- }
- : {}),
- ...(isUpdate && diff!.added.length > 0
- ? { allowPermissionExpansion: true }
- : {}),
+ const ghost = await installReviewedMarketPackage({
+ detail: marketDetail,
+ lease: marketBusyLease,
+ options: {
+ expectedReleaseId: marketDetail.releaseId,
++ // 受体模型:同版本重装(恢复缺失批准)与升级都属 isUpdate,必须带旧
++ // 批准令牌,Main 在安装锁内核对当前受体后才放行。
++ ...(isUpdate && installedGhost
++ ? {
++ expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),
++ }
++ : {}),
+ ...(marketDetail.sourceType !== 'server'
+ ? { expectedManifest: marketDetail.manifest }
+ : {}),
+ ...(isUpdate && diff!.added.length > 0
+ ? {
+ allowPermissionExpansion: true,
+ // 确认框展示期间已装 manifest 可能被换掉;基线交由 Main 在
+ // 安装锁内复核,不一致就拒绝这次批准而不是沿用旧同意。
+ ...(installedGhost
+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
+ : {}),
+ }
+ : {}),
+ },
});
+ if (!ghost) return;
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
// 市场首装装完即开(2026-07-26 定案),toast 用"已安装";更新路径如实
// 用"已更新"(生效状态未被改变)。
@@@ -908,40 -1230,42 +1283,45 @@@
if (selectedDetail) {
return (
- <GhostPluginDetailView
- ghost={selectedGhost}
- detail={selectedDetail}
- panelStatus={panelStatus}
- enabledOverride={
- selectedGhost
- ? effectiveEnabled(selectedGhost.manifest.id, selectedGhost.enabled)
- : undefined
- }
- onBack={() => setSelectedId(null)}
- onToggle={(enabled) => void handleToggle(selectedDetail.id, enabled, selectedDetail.name)}
- onUse={handleUse}
- onUpdate={() => void handleUpdate()}
- onReapprove={() => void handleReapprove(selectedDetail.id)}
- updateLabel={
- selectedMarketUpdate
- ? t('settings.ghosts.market.update')
- : undefined
- }
- updateVersion={
- selectedMarketUpdate?.version
- }
- 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}
- />
+ <div className="flex h-full min-h-0 w-full">
+ <div className="min-w-0 flex-1">
+ <GhostPluginDetailView
+ ghost={selectedGhost}
+ detail={selectedDetail}
+ panelStatus={panelStatus}
+ enabledOverride={
+ selectedGhost
+ ? effectiveEnabled(selectedGhost.manifest.id, selectedGhost.enabled)
+ : undefined
+ }
+ onBack={() => setSelectedId(null)}
+ onToggle={(enabled) =>
+ void handleToggle(selectedDetail.id, enabled, selectedDetail.name)
+ }
+ onUse={handleUse}
+ onUpdate={() => void handleUpdate()}
+ onUpdateFromFile={() => void handleUpdateFromFile()}
++ // 受体模型的 §5 恢复入口:缺批准的安装在详情页重新确认(市场包重装 /
++ // 本地包读目录权限确认),详情视图据 needsReapproval 门控运行按钮。
++ onReapprove={() => void handleReapprove(selectedDetail.id)}
+ updateVersion={selectedMarketUpdate?.version}
+ updateBusy={
+ (selectedMarketUpdate !== null && marketBusyId !== null) || batchRunning
+ }
+ onUninstall={() => void handleUninstall()}
+ // 官方保留前缀(cindy-/filo-/xd-)的插件走本地装入会被拒,
+ // 导出产物无法重装,不提供导出项。
+ onExport={
+ selectedGhost && !isOfficialGhostId(selectedDetail.id)
+ ? () => void handleExport()
+ : undefined
+ }
+ toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}
+ onIconLoadError={handleMarketIconLoadError}
+ />
+ </div>
+ {panelAside}
+ </div>
);
}
diff --cc apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index 1fa1960b43,0ec7d3d754..df2afc8ad7
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@@ -37,8 -38,21 +38,23 @@@ const commandPlugin: GhostPluginListIte
version: '1.0.0',
enabled: true,
canUse: true,
+ approvalState: 'approved',
+ builtin: false,
+ tabPanel: false,
+ };
+
+ const panelPlugin: GhostPluginListItem = {
+ ...commandPlugin,
+ id: 'signoff-board',
+ name: 'Signoff Board',
+ tabPanel: true,
+ };
+
+ const toolPlugin: GhostPluginListItem = {
+ ...commandPlugin,
+ id: 'pure-tool',
+ name: 'Pure Tool',
+ canUse: false,
};
const marketPlugin: PluginMarketItem = {
diff --cc apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 4fbcdfe55e,4e1e0e15c8..4ba37d163c
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@@ -99,8 -104,7 +104,9 @@@ const detail: GhostPluginDetail =
version: '1.2.3',
enabled: true,
canUse: true,
+ approvalState: 'approved',
+ builtin: false,
+ tabPanel: false,
author: 'XD',
contents: ['code'],
permissions: [],
@@@ -128,6 -132,50 +134,51 @@@ afterEach(() =>
});
describe('Ghost plugin detail sections', () => {
+ it('shows a non-blocking stale OAuth scope badge inside the configuration section', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ render(
+ <GhostPluginDetailView
+ ghost={{
+ manifest: {
+ schemaVersion: 2,
+ id: detail.id,
+ name: detail.name,
+ version: detail.version,
+ kind: 'chip',
+ entry: 'main.js',
+ slots: [],
+ settingsHtml: 'settings.html',
+ },
+ dir: detail.installDir ?? '/tmp/plugin',
+ enabled: true,
++ approval: { state: 'approved', revision: 'rev-1' },
+ oauthScopeStale: { secretKey: 'account', missingScopeCount: 2 },
+ }}
+ detail={{ ...detail, hasSettingsUi: true }}
+ panelStatus="Docked"
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ const badge = screen.getByRole('status');
+ expect(badge.textContent).toContain('newly added permissions');
+ expect(badge.className).toContain('bg-[var(--warning-bg-soft)]');
+ expect(screen.getByTestId('ghost-settings-webview')).toBeTruthy();
+ });
+
it('keeps the detail surface on one centered content grid', () => {
vi.stubGlobal(
'ResizeObserver',
@@@ -147,7 -195,7 +198,8 @@@
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={vi.fn()}
+ onReapprove={vi.fn()}
+ onUpdateFromFile={vi.fn()}
onUninstall={vi.fn()}
toggleDisabled={false}
/>,
@@@ -196,7 -244,7 +248,8 @@@
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={vi.fn()}
+ onReapprove={vi.fn()}
+ onUpdateFromFile={vi.fn()}
onUninstall={vi.fn()}
toggleDisabled={false}
onIconLoadError={onIconLoadError}
@@@ -227,7 -275,7 +280,8 @@@
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={onUpdate}
+ onReapprove={vi.fn()}
+ onUpdateFromFile={vi.fn()}
updateVersion={detail.version}
onUninstall={vi.fn()}
toggleDisabled={false}
@@@ -243,56 -291,6 +297,62 @@@
expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
});
+ it.each([
+ ['legacy-unapproved', 'settings.ghosts.reapproval.bodyLegacy'],
+ ['invalid', 'settings.ghosts.reapproval.bodyInvalid'],
+ ] as const)('explains the %s approval state and routes to a fresh review', (approvalState, bodyKey) => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onReapprove = vi.fn();
+ const onUpdate = vi.fn();
+ const onToggle = vi.fn();
+ render(
+ <GhostPluginDetailView
+ ghost={null}
+ detail={{ ...detail, approvalState }}
+ panelStatus="Docked"
+ onBack={vi.fn()}
+ onToggle={onToggle}
+ onUse={vi.fn()}
+ onUpdate={onUpdate}
+ onReapprove={onReapprove}
++ onUpdateFromFile={vi.fn()}
+ updateVersion="1.2.4"
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+
+ expect(screen.getByText('settings.ghosts.reapproval.noticeTitle')).toBeTruthy();
+ expect(screen.getByText(bodyKey)).toBeTruthy();
+ // 缺批准时"使用"与"更新"都不该顶在最前面,主动作是重新确认。
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
++ // detail fixture 是指令型插件(canUse:true / tabPanel:false → 'command'),主动作按钮
++ // 标 chatAction;缺批准时 primaryEnabled=false → 禁用。
+ expect(
- (screen.getByRole('button', { name: 'settings.ghosts.detail.useAction' }) as HTMLButtonElement)
++ (screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+
- const toggle = screen.getByRole('switch') as HTMLButtonElement;
++ // 启用开关(改版为带 aria-pressed 的按钮,非原生 switch)缺批准时禁用,点了不触发 onToggle。
++ const toggle = screen.getByRole('button', {
++ name: 'settings.ghosts.enableAria',
++ }) as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ fireEvent.click(toggle);
+ expect(onToggle).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.reapproval.action' }));
+ expect(onReapprove).toHaveBeenCalledTimes(1);
+ expect(onUpdate).not.toHaveBeenCalled();
+ });
+
it('disables every market update entry while an update is busy', async () => {
vi.stubGlobal(
'ResizeObserver',
@@@ -313,8 -311,7 +373,8 @@@
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={onUpdate}
+ onReapprove={vi.fn()}
- updateLabel="Update from market"
+ onUpdateFromFile={vi.fn()}
updateVersion="1.2.4"
updateBusy
onUninstall={vi.fn()}
@@@ -354,8 -434,8 +497,9 @@@
onToggle: vi.fn(),
onUse: vi.fn(),
onUpdate: vi.fn(),
+ onUpdateFromFile: vi.fn(),
onUninstall: vi.fn(),
+ onReapprove: vi.fn(),
toggleDisabled: false,
};
diff --cc apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
index a579447a7b,9482c62fb4..472d8bda14
--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
@@@ -31,54 -31,9 +33,54 @@@ function marketItem
};
}
+describe('marketReviewTargetsInstalledGhost', () => {
+ it('always allows a pending release', () => {
+ expect(
+ marketReviewTargetsInstalledGhost(marketItem('p', 'g', 'update-available'), 'approved'),
+ ).toBe(true);
+ });
+
+ it('allows re-reviewing the current release when the install carries no approval', () => {
+ const installed = marketItem('p', 'g', 'installed');
+ expect(marketReviewTargetsInstalledGhost(installed, 'legacy-unapproved')).toBe(true);
+ expect(marketReviewTargetsInstalledGhost(installed, 'invalid')).toBe(true);
+ });
+
+ it('has nothing to review for an approved install at the current release', () => {
+ expect(marketReviewTargetsInstalledGhost(marketItem('p', 'g', 'installed'), 'approved')).toBe(
+ false,
+ );
+ });
+
+ it('refuses when the local install is gone or the market record is unusable', () => {
+ expect(marketReviewTargetsInstalledGhost(marketItem('p', 'g', 'installed'), undefined)).toBe(
+ false,
+ );
+ expect(marketReviewTargetsInstalledGhost(marketItem('p', 'g', 'conflict'), 'invalid')).toBe(
+ false,
+ );
+ expect(marketReviewTargetsInstalledGhost(null, 'legacy-unapproved')).toBe(false);
+ });
+});
+
+describe('ghostReapprovalRoute', () => {
+ it('replays the market confirmation for market-owned installs', () => {
+ expect(ghostReapprovalRoute(marketItem('p', 'g', 'installed'))).toBe('market');
+ expect(ghostReapprovalRoute(marketItem('p', 'g', 'update-available'))).toBe('market');
+ });
+
+ it('asks for a local package when the market cannot supply the bytes', () => {
+ expect(ghostReapprovalRoute(null)).toBe('local-package');
+ expect(ghostReapprovalRoute(undefined)).toBe('local-package');
+ // conflict = 同 id 归属不清,不能拿市场包顶上去当恢复来源。
+ expect(ghostReapprovalRoute(marketItem('p', 'g', 'conflict'))).toBe('local-package');
+ expect(ghostReapprovalRoute(marketItem('p', 'g', 'not-installed'))).toBe('local-package');
+ });
+});
+
describe('pluginPresentationOrigin', () => {
it('maps public plugins independently of their default-install policy', () => {
- expect(pluginPresentationOrigin({ scope: 'public' })).toBe('public');
+ expect(pluginPresentationOrigin({ scope: 'public', sourceType: 'server' })).toBe('public');
});
it('maps organization plugins to their organization source', () => {
diff --cc apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index 44659c2359,d51d3e536b..32186c702e
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@@ -24,13 -23,8 +24,15 @@@ export interface GhostPluginListItem
version: string;
enabled: boolean;
canUse: boolean;
+ /**
+ * Host 是否持有一次明确的安装/更新确认。非 `approved` 的安装不可运行,列表与
+ * 详情都必须如实说明并给出重新确认入口,而不是让它看起来只是"被关掉了"。
+ */
+ approvalState: GhostInstallApproval['state'];
+ /** 随包内置插件(main 按种子清单投影)。批准态异常时文案与恢复入口都不同。 */
+ builtin: boolean;
+ /** 声明了插件页内独占面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */
+ tabPanel: boolean;
trust?: GhostTrustInfo;
iconDataUrl?: string;
}
@@@ -173,8 -184,7 +192,9 @@@ export function toGhostPluginListItem
version: manifest.version,
enabled: ghost.enabled,
canUse: Boolean(manifest.command),
+ approvalState: ghost.approval.state,
+ builtin: ghost.builtin === true,
+ tabPanel: manifest.panel?.position === 'tab',
trust: ghost.trust ?? {
level: 'unverified',
publisherSigned: false,
diff --cc apps/desktop/src/renderer/i18n/locales/en/common.json
index de256655e6,a0e321332a..9140c72080
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@@ -2926,17 -3220,66 +3220,75 @@@
"noPermissions": "This plugin declares no additional capabilities.",
"installConfirmTitle": "Install “{{name}}”?",
"installConfirmDescription": "The package will be verified for integrity and manifest compatibility. The plugin is enabled automatically after install; you can disable it or adjust its setup anytime.",
- "updateConfirmDescription": "The package will be verified for integrity and manifest compatibility, then replace the installed version. Its current enabled state stays unchanged."
+ "customInstallConfirmDescription": "This plugin comes from a custom marketplace and has not been verified for integrity by the server; its manifest will be validated before install. The plugin is enabled automatically after install; you can disable it or adjust its setup anytime.",
+ "updateConfirmDescription": "The package will be verified for integrity and manifest compatibility, then replace the installed version. Its current enabled state stays unchanged.",
+ "sources": {
+ "addMarketplace": "Add Plugin Marketplace…",
+ "dialogTitle": "Add Plugin Marketplace",
+ "dialogDescription": "Add a plugin marketplace from a GitHub repository, Git URL, or local folder.",
+ "learnMore": "Learn more",
+ "sourceLabel": "Source",
+ "sourcePlaceholder": "openai/plugins or [email protected]:org/repo.git",
+ "refLabel": "Git Ref",
+ "refPlaceholder": "Main branch",
+ "sparseLabel": "Sparse Paths",
+ "sparsePlaceholder": "One path per line, e.g. plugins/codex",
+ "gitUnavailable": "Git is not installed or is older than 2.25. Git sources are unavailable; local folder sources still work.",
+ "listTitle": "Added Marketplaces",
+ "pluginCount": "{{count}} plugins",
+ "sourceError": "Unavailable",
+ "localBadge": "Local",
+ "defaultRef": "Default branch",
+ "neverSynced": "Never synced",
+ "refresh": "Refresh",
+ "remove": "Remove",
+ "removeConfirmTitle": "Remove marketplace \"{{name}}\"?",
+ "removeConfirmDescription": "Plugins from this marketplace will no longer be listed. Installed plugins are kept.",
+ "close": "Close",
+ "add": "Add Marketplace",
+ "errors": {
+ "invalidSource": "Invalid source. Use a GitHub owner/repo, a Git URL, or a local folder path.",
+ "gitUnavailable": "Git is not installed or is older than 2.25, so Git sources cannot be added.",
+ "cloneAuthFailed": "Cannot access this repository. For private repositories, configure Git authentication on this machine first (credential helper or SSH key).",
+ "credentialsNotAllowed": "The source URL cannot contain a username or password. Use system Git authentication instead (credential helper or SSH key).",
+ "cloneFailed": "Failed to clone the repository. Check your network or proxy settings and try again.",
+ "refNotFound": "The specified Git ref was not found. Check the branch or tag name.",
+ "manifestMissing": "No supported marketplace.json manifest was found in this source.",
+ "duplicate": "This marketplace has already been added.",
+ "notFound": "This marketplace does not exist or has been removed."
+ },
+ "guide": {
+ "title": "Custom Plugin Marketplace Guide",
+ "intro": "A plugin marketplace is a Git repository or local folder with a manifest file, used to distribute a set of Cindy plugins.",
+ "structureTitle": "Directory Structure",
+ "structureBody": "A marketplace needs one manifest file plus one directory per plugin. Every plugin directory must contain a valid ghost.json (the plugin identity card).",
+ "structureLabelManifest": "manifest",
+ "structureLabelGhostCard": "Plugin card",
+ "structureLabelEntry": "Plugin entry",
+ "structureNote": "The manifest can live in one of these locations:",
+ "manifestTitle": "Manifest Format",
+ "manifestBody": "name is the unique identity of the marketplace (you manage it by this name after adding). Each source in the plugins array points to a plugin directory inside the repository as a relative path; the object form {\"source\": \"local\", \"path\": \"…\"} is also supported.",
+ "sourceTitle": "Source Formats",
+ "sourceBody": "Accepted sources: GitHub shorthand owner/repo, full Git URLs (https / ssh / git@), and local folder paths (~ supported). Git ref accepts a branch, tag, or commit; leave empty for the default branch. Sparse paths (one per line) check out only the listed subdirectories — useful for large repositories.",
+ "authTitle": "Private Repositories",
+ "authBody": "Authentication relies entirely on your system Git configuration — Cindy never stores Git credentials. SSH: a working key must be configured on this machine; if the organization enforces SAML SSO, authorize the key for that organization via Configure SSO in your GitHub SSH key settings. HTTPS: use a Personal Access Token stored by the system credential helper.",
+ "rulesTitle": "Install Rules",
+ "rulesBody": "Plugin ids are globally unique, first come first served — conflicts with installed plugins are called out explicitly. Plugins using officially reserved prefixes like cindy- cannot be installed from custom marketplaces. Before install, every permission the plugin declares is shown for review; confirming completes the install and enables the plugin.",
+ "copy": "Copy guide",
+ "copied": "Guide copied to clipboard.",
+ "copyFailed": "Copy failed. Please try again."
+ }
+ }
},
+ "reapproval": {
+ "badge": "Permission review needed",
+ "action": "Review Permissions",
+ "actionAria": "Review permissions for plugin {{name}}",
+ "noticeTitle": "Permission review needed",
+ "bodyLegacy": "Cindy has no record of a permission review for this plugin, so it stays disabled. Choose Review Permissions to go through what it asks for and confirm it again.",
+ "bodyInvalid": "The permission review record for this plugin is damaged, so it stays disabled. Choose Review Permissions to go through what it asks for and confirm it again.",
+ "bodyBuiltinRestart": "Something went wrong with this built-in plugin's approval record. Restart Cindy to recover automatically — no other action needed."
+ },
"install": "Install Plugin…",
"empty": "No plugins installed yet",
"emptyHint": "Install from the market, or import a .cindy file from the menu above",
diff --cc apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8069cae696,698e8f6c80..cf38555cea
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@@ -2925,17 -3219,66 +3219,75 @@@
"noPermissions": "このプラグインは追加機能を宣言していません。",
"installConfirmTitle": "「{{name}}」をインストールしますか?",
"installConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してからインストールします。インストール完了後は自動的に有効になり、いつでも無効化や設定の変更ができます。",
- "updateConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してから、既存のバージョンを置き換えます。現在の有効/無効の状態は変わりません。"
+ "customInstallConfirmDescription": "カスタムマーケット由来のプラグインのため、サーバーによる整合性検証は行われません。インストール前にマニフェストを検証します。インストール後は自動で有効になり、プラグインページでいつでも無効化・設定変更ができます。",
+ "updateConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してから、既存のバージョンを置き換えます。現在の有効/無効の状態は変わりません。",
+ "sources": {
+ "addMarketplace": "プラグインマーケットを追加…",
+ "dialogTitle": "プラグインマーケットを追加",
+ "dialogDescription": "GitHub リポジトリ、Git URL、またはローカルフォルダーからプラグインマーケットを追加します。",
+ "learnMore": "詳しく見る",
+ "sourceLabel": "ソース",
+ "sourcePlaceholder": "openai/plugins または [email protected]:org/repo.git",
+ "refLabel": "Git 参照",
+ "refPlaceholder": "メインブランチ",
+ "sparseLabel": "スパースパス",
+ "sparsePlaceholder": "1 行に 1 パス(例: plugins/codex)",
+ "gitUnavailable": "Git がインストールされていないか、バージョンが 2.25 未満です。Git ソースは利用できません。ローカルフォルダーのソースは引き続き利用できます。",
+ "listTitle": "追加済みのマーケット",
+ "pluginCount": "{{count}} 個のプラグイン",
+ "sourceError": "読み込み失敗",
+ "localBadge": "ローカル",
+ "defaultRef": "デフォルトブランチ",
+ "neverSynced": "未同期",
+ "refresh": "更新",
+ "remove": "削除",
+ "removeConfirmTitle": "マーケット「{{name}}」を削除しますか?",
+ "removeConfirmDescription": "削除すると、このマーケットのプラグインは表示されなくなります。インストール済みのプラグインは保持されます。",
+ "close": "閉じる",
+ "add": "マーケットを追加",
+ "errors": {
+ "invalidSource": "ソースの形式が無効です。GitHub の owner/repo、Git URL、またはローカルフォルダーのパスを指定してください。",
+ "gitUnavailable": "Git がインストールされていないか、バージョンが 2.25 未満のため、Git ソースを追加できません。",
+ "cloneAuthFailed": "このリポジトリにアクセスできません。プライベートリポジトリの場合は、先にシステムで Git 認証(credential helper または SSH key)を設定してください。",
+ "credentialsNotAllowed": "ソースの URL にユーザー名やパスワードを含めることはできません。システムの Git 認証(credential helper または SSH key)を使用してください。",
+ "cloneFailed": "リポジトリのクローンに失敗しました。ネットワークまたはプロキシ設定を確認してから再試行してください。",
+ "refNotFound": "指定された Git 参照が見つかりません。ブランチ名またはタグ名を確認してください。",
+ "manifestMissing": "このソースに対応する marketplace.json マニフェストが見つかりません。",
+ "duplicate": "このマーケットはすでに追加されています。",
+ "notFound": "このマーケットは存在しないか、すでに削除されています。"
+ },
+ "guide": {
+ "title": "カスタムプラグインマーケットガイド",
+ "intro": "プラグインマーケットとは、マニフェストファイルを持つ Git リポジトリまたはローカルフォルダーで、Cindy プラグインのセットを配布するためのものです。",
+ "structureTitle": "ディレクトリ構造",
+ "structureBody": "マーケットには 1 つのマニフェストファイルと、プラグインごとのディレクトリが必要です。各プラグインディレクトリには有効な ghost.json(プラグインの身分証)が必要です。",
+ "structureLabelManifest": "マニフェスト",
+ "structureLabelGhostCard": "プラグインカード",
+ "structureLabelEntry": "プラグインのエントリー",
+ "structureNote": "マニフェストは次のいずれかに配置できます:",
+ "manifestTitle": "マニフェスト形式",
+ "manifestBody": "name はマーケットの一意の識別子です(追加後はこの名前で管理します)。plugins 配列の source はリポジトリ内のプラグインディレクトリを相対パスで指します。{\"source\": \"local\", \"path\": \"…\"} のオブジェクト形式も利用できます。",
+ "sourceTitle": "ソース形式",
+ "sourceBody": "GitHub 省略形 owner/repo、完全な Git URL(https / ssh / git@)、ローカルフォルダーパス(~ 可)を指定できます。Git 参照にはブランチ、タグ、commit を指定でき、空ならデフォルトブランチです。スパースパスは 1 行に 1 つ指定し、リポジトリの一部のサブディレクトリだけをチェックアウトします(大きなリポジトリ向け)。",
+ "authTitle": "プライベートリポジトリ",
+ "authBody": "認証はすべてシステムの Git 設定に依存し、Cindy は Git の認証情報を一切保存しません。SSH の場合: 利用可能な key がマシンに設定されている必要があります。組織が SAML SSO を強制している場合は、GitHub の SSH key 設定で Configure SSO からその組織に key を承認してください。HTTPS の場合: Personal Access Token を使用し、システムの credential helper に保存します。",
+ "rulesTitle": "インストールルール",
+ "rulesBody": "プラグイン id はグローバルに一意で先着順です。インストール済みプラグインとの競合は明示されます。cindy- などの公式予約プレフィックスを使うプラグインはカスタムマーケットからインストールできません。インストール前にプラグインが宣言する権限をすべて表示し、確認するとインストールが完了して自動的に有効になります。",
+ "copy": "ガイドをコピー",
+ "copied": "ガイドをクリップボードにコピーしました。",
+ "copyFailed": "コピーに失敗しました。もう一度お試しください。"
+ }
+ }
},
+ "reapproval": {
+ "badge": "権限の再確認が必要",
+ "action": "権限を再確認",
+ "actionAria": "プラグイン「{{name}}」の権限を再確認",
+ "noticeTitle": "権限の再確認が必要",
+ "bodyLegacy": "このプラグインの権限確認の記録が Cindy にないため、無効のままにしています。「権限を再確認」から要求される権限を確認し、あらためて許可してください。",
+ "bodyInvalid": "このプラグインの権限確認の記録が壊れているため、無効のままにしています。「権限を再確認」から要求される権限を確認し、あらためて許可してください。",
+ "bodyBuiltinRestart": "この内蔵プラグインの承認記録に問題が発生しました。Cindy を再起動すると自動的に復元されます。他の操作は不要です。"
+ },
"install": "プラグインをインストール…",
"empty": "まだプラグインがインストールされていません",
"emptyHint": "マーケットからインストールするか、上のメニューから .cindy ファイルを読み込めます",
diff --cc apps/desktop/src/renderer/i18n/locales/ko/common.json
index bf12047d46,c9c80ea855..3d7181eb3c
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@@ -2925,17 -3219,66 +3219,75 @@@
"noPermissions": "이 플러그인은 추가 기능을 선언하지 않았습니다.",
"installConfirmTitle": "‘{{name}}’을(를) 설치할까요?",
"installConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 설치합니다. 설치가 완료되면 자동으로 활성화되며, 언제든지 비활성화하거나 설정을 변경할 수 있습니다.",
- "updateConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 기존 버전을 교체합니다. 현재 활성화 상태는 그대로 유지됩니다."
+ "customInstallConfirmDescription": "사용자 지정 마켓의 플러그인으로 서버 무결성 검증을 거치지 않았으며, 설치 전에 매니페스트를 검증합니다. 설치 후 플러그인이 자동으로 활성화되며 언제든 비활성화하거나 설정을 변경할 수 있습니다.",
+ "updateConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 기존 버전을 교체합니다. 현재 활성화 상태는 그대로 유지됩니다.",
+ "sources": {
+ "addMarketplace": "플러그인 마켓 추가…",
+ "dialogTitle": "플러그인 마켓 추가",
+ "dialogDescription": "GitHub 리포지토리, Git URL 또는 로컬 폴더에서 플러그인 마켓을 추가합니다.",
+ "learnMore": "자세히 알아보기",
+ "sourceLabel": "소스",
+ "sourcePlaceholder": "openai/plugins 또는 [email protected]:org/repo.git",
+ "refLabel": "Git 참조",
+ "refPlaceholder": "기본 브랜치",
+ "sparseLabel": "스파스 경로",
+ "sparsePlaceholder": "한 줄에 하나의 경로(예: plugins/codex)",
+ "gitUnavailable": "Git이 설치되어 있지 않거나 버전이 2.25 미만입니다. Git 소스는 사용할 수 없으며 로컬 폴더 소스는 계속 사용할 수 있습니다.",
+ "listTitle": "추가된 마켓",
+ "pluginCount": "플러그인 {{count}}개",
+ "sourceError": "읽기 실패",
+ "localBadge": "로컬",
+ "defaultRef": "기본 브랜치",
+ "neverSynced": "동기화되지 않음",
+ "refresh": "새로고침",
+ "remove": "제거",
+ "removeConfirmTitle": "마켓 \"{{name}}\"을(를) 제거할까요?",
+ "removeConfirmDescription": "제거하면 이 마켓의 플러그인이 더 이상 표시되지 않습니다. 설치된 플러그인은 유지됩니다.",
+ "close": "닫기",
+ "add": "마켓 추가",
+ "errors": {
+ "invalidSource": "소스 형식이 올바르지 않습니다. GitHub owner/repo, Git URL 또는 로컬 폴더 경로를 사용하세요.",
+ "gitUnavailable": "Git이 설치되어 있지 않거나 버전이 2.25 미만이므로 Git 소스를 추가할 수 없습니다.",
+ "cloneAuthFailed": "이 리포지토리에 접근할 수 없습니다. 비공개 리포지토리의 경우 먼저 시스템에 Git 인증(credential helper 또는 SSH key)을 구성하세요.",
+ "credentialsNotAllowed": "소스 URL에 사용자 이름이나 비밀번호를 포함할 수 없습니다. 시스템 Git 인증(credential helper 또는 SSH key)을 사용하세요.",
+ "cloneFailed": "리포지토리를 클론하지 못했습니다. 네트워크 또는 프록시 설정을 확인한 후 다시 시도하세요.",
+ "refNotFound": "지정한 Git 참조를 찾을 수 없습니다. 브랜치 또는 태그 이름을 확인하세요.",
+ "manifestMissing": "이 소스에서 지원되는 marketplace.json 매니페스트를 찾을 수 없습니다.",
+ "duplicate": "이 마켓은 이미 추가되어 있습니다.",
+ "notFound": "이 마켓이 존재하지 않거나 이미 제거되었습니다."
+ },
+ "guide": {
+ "title": "사용자 지정 플러그인 마켓 가이드",
+ "intro": "플러그인 마켓은 매니페스트 파일을 포함하는 Git 리포지토리 또는 로컬 폴더로, Cindy 플러그인 세트를 배포하는 데 사용됩니다.",
+ "structureTitle": "디렉터리 구조",
+ "structureBody": "마켓에는 매니페스트 파일 하나와 플러그인별 디렉터리가 필요합니다. 각 플러그인 디렉터리에는 유효한 ghost.json(플러그인 신원 카드)이 있어야 합니다.",
+ "structureLabelManifest": "매니페스트",
+ "structureLabelGhostCard": "플러그인 카드",
+ "structureLabelEntry": "플러그인 진입점",
+ "structureNote": "매니페스트는 다음 위치 중 하나에 둘 수 있습니다:",
+ "manifestTitle": "매니페스트 형식",
+ "manifestBody": "name은 마켓의 고유 식별자입니다(추가 후 이 이름으로 관리합니다). plugins 배열의 source는 리포지토리 내 플러그인 디렉터리를 상대 경로로 가리킵니다. {\"source\": \"local\", \"path\": \"…\"} 객체 형식도 지원합니다.",
+ "sourceTitle": "소스 형식",
+ "sourceBody": "GitHub 약칭 owner/repo, 전체 Git URL(https / ssh / git@), 로컬 폴더 경로(~ 지원)를 사용할 수 있습니다. Git 참조에는 브랜치, 태그 또는 commit을 입력하고, 비우면 기본 브랜치를 사용합니다. 스파스 경로는 한 줄에 하나씩 입력하며 리포지토리의 지정된 하위 디렉터리만 체크아웃합니다(대형 리포지토리에 유용).",
+ "authTitle": "비공개 리포지토리",
+ "authBody": "인증은 전적으로 시스템 Git 구성에 의존하며 Cindy는 Git 자격 증명을 저장하지 않습니다. SSH: 이 머신에 사용 가능한 key가 구성되어 있어야 합니다. 조직이 SAML SSO를 강제하는 경우 GitHub SSH key 설정에서 Configure SSO로 해당 조직에 key를 승인해야 합니다. HTTPS: Personal Access Token을 사용하고 시스템 credential helper에 저장합니다.",
+ "rulesTitle": "설치 규칙",
+ "rulesBody": "플러그인 id는 전역적으로 고유하며 선착순입니다. 설치된 플러그인과의 충돌은 명확히 표시됩니다. cindy- 같은 공식 예약 접두사를 사용하는 플러그인은 사용자 지정 마켓에서 설치할 수 없습니다. 설치 전에 플러그인이 선언한 권한을 모두 보여주며, 확인하면 설치가 완료되고 자동으로 활성화됩니다.",
+ "copy": "가이드 복사",
+ "copied": "가이드를 클립보드에 복사했습니다.",
+ "copyFailed": "복사에 실패했습니다. 다시 시도하세요."
+ }
+ }
},
+ "reapproval": {
+ "badge": "권한 재확인 필요",
+ "action": "권한 다시 확인",
+ "actionAria": "플러그인 {{name}}의 권한 다시 확인",
+ "noticeTitle": "권한 재확인 필요",
+ "bodyLegacy": "Cindy에 이 플러그인의 권한 확인 기록이 없어 사용 중지한 상태입니다. [권한 다시 확인]에서 요청하는 권한을 확인하고 다시 허용해 주세요.",
+ "bodyInvalid": "이 플러그인의 권한 확인 기록이 손상되어 사용 중지한 상태입니다. [권한 다시 확인]에서 요청하는 권한을 확인하고 다시 허용해 주세요.",
+ "bodyBuiltinRestart": "이 내장 플러그인의 승인 기록에 문제가 발생했습니다. Cindy를 다시 시작하면 자동으로 복구되며, 다른 조치는 필요하지 않습니다."
+ },
"install": "플러그인 설치…",
"empty": "아직 설치된 플러그인이 없습니다",
"emptyHint": "마켓에서 설치하거나 위 메뉴에서 .cindy 파일을 가져올 수 있습니다",
diff --cc apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 68a19e8676,513798b673..31437a1b70
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@@ -2925,17 -3219,66 +3219,75 @@@
"noPermissions": "此插件未声明额外能力。",
"installConfirmTitle": "安装「{{name}}」?",
"installConfirmDescription": "安装包将经过完整性与清单校验。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",
- "updateConfirmDescription": "安装包将经过完整性与清单校验,并替换现有版本。当前生效状态保持不变。"
+ "customInstallConfirmDescription": "插件来自自定义市场,未经服务端完整性校验,安装前将校验插件清单。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",
+ "updateConfirmDescription": "安装包将经过完整性与清单校验,并替换现有版本。当前生效状态保持不变。",
+ "sources": {
+ "addMarketplace": "添加插件市场…",
+ "dialogTitle": "添加插件市场",
+ "dialogDescription": "从 GitHub 仓库、Git URL 或本地文件夹添加插件市场。",
+ "learnMore": "了解更多",
+ "sourceLabel": "来源",
+ "sourcePlaceholder": "owner/repo 或 [email protected]:org/repo.git",
+ "refLabel": "Git 引用",
+ "refPlaceholder": "主分支",
+ "sparseLabel": "稀疏路径",
+ "sparsePlaceholder": "每行一个路径,如 team/tools",
+ "gitUnavailable": "未检测到 Git 或版本低于 2.25。Git 来源不可用,本地文件夹来源不受影响。",
+ "listTitle": "已添加的市场",
+ "pluginCount": "{{count}} 个插件",
+ "sourceError": "读取失败",
+ "localBadge": "本地",
+ "defaultRef": "默认分支",
+ "neverSynced": "尚未同步",
+ "refresh": "刷新",
+ "remove": "移除",
+ "removeConfirmTitle": "移除市场「{{name}}」?",
+ "removeConfirmDescription": "移除后,来自该市场的插件将不再显示;已安装的插件保留。",
+ "close": "关闭",
+ "add": "添加市场",
+ "errors": {
+ "invalidSource": "来源格式无效。支持 GitHub owner/repo、Git URL 或本地文件夹路径。",
+ "gitUnavailable": "未检测到 Git 或版本低于 2.25,无法添加 Git 来源。",
+ "cloneAuthFailed": "无法访问该仓库。私有仓库需要先在系统中配置 Git 认证(credential helper 或 SSH key)。",
+ "credentialsNotAllowed": "来源 URL 不能内嵌用户名或密码。请改用系统 Git 认证(credential helper 或 SSH key)。",
+ "cloneFailed": "克隆仓库失败,请检查网络连接后重试。",
+ "refNotFound": "找不到指定的 Git 引用,请检查分支或标签名是否正确。",
+ "manifestMissing": "该来源中找不到受支持的 marketplace.json 清单。",
+ "duplicate": "该市场已添加。",
+ "notFound": "该市场不存在或已被移除。"
+ },
+ "guide": {
+ "title": "自定义插件市场指南",
+ "intro": "插件市场是一个带有清单文件的 Git 仓库或本地文件夹,用来分发一组 Cindy 插件。",
+ "structureTitle": "目录结构",
+ "structureBody": "市场仓库需要一份清单文件,以及若干插件目录。每个插件目录必须包含合法的 ghost.json(插件身份卡)。",
+ "structureLabelManifest": "清单",
+ "structureLabelGhostCard": "插件身份卡",
+ "structureLabelEntry": "插件入口",
+ "structureNote": "清单可以放在以下位置之一:",
+ "manifestTitle": "清单格式",
+ "manifestBody": "name 是市场的唯一标识(添加后按它管理)。清单的插件数组里,每个条目的 source 指向仓库内的插件目录,使用相对路径;也支持 {\"source\": \"local\", \"path\": \"…\"} 的对象写法。",
+ "sourceTitle": "来源格式",
+ "sourceBody": "支持 GitHub 简写 owner/repo、完整 Git URL(https / ssh / git@)和本地文件夹路径(含 ~)。Git 引用可填分支、标签或 commit,不填则用默认分支。稀疏路径每行一个,只检出仓库的指定子目录,适合大型仓库。",
+ "authTitle": "私有仓库",
+ "authBody": "认证完全依赖系统的 Git 配置,Cindy 不保存任何 Git 凭证。SSH 方式:本机已配置可用的 key;若组织开启了 SAML SSO,还需在 GitHub 的 SSH key 设置里为该组织点 Configure SSO 授权。HTTPS 方式:使用 Personal Access Token,并由系统 credential helper 保存。",
+ "rulesTitle": "安装规则",
+ "rulesBody": "插件 id 全局唯一、先装先得——与已安装插件冲突时会明确提示。使用 cindy- 等官方保留前缀的插件不能从自定义市场安装。安装前会逐项展示插件声明的权限,确认后即完成安装并自动开启。",
+ "copy": "复制指南",
+ "copied": "指南已复制到剪贴板。",
+ "copyFailed": "复制失败,请重试。"
+ }
+ }
},
+ "reapproval": {
+ "badge": "需要重新确认权限",
+ "action": "重新确认权限",
+ "actionAria": "重新确认插件「{{name}}」的权限",
+ "noticeTitle": "需要重新确认权限",
+ "bodyLegacy": "Cindy 没有这个插件的权限确认记录,所以先把它停用了。点「重新确认权限」重新过一遍它要的权限,确认后即可继续使用。",
+ "bodyInvalid": "这个插件的权限确认记录已损坏,所以先把它停用了。点「重新确认权限」重新过一遍它要的权限,确认后即可继续使用。",
+ "bodyBuiltinRestart": "这个内置插件的权限记录出了点问题。重启 Cindy 即可自动恢复,无需其他操作。"
+ },
"install": "安装插件…",
"empty": "还没有安装任何插件",
"emptyHint": "可从插件市场安装,或点击右上角导入 .cindy 文件",
diff --cc apps/desktop/src/shared/__tests__/ghost.test.ts
index bd701177a2,3318d27b00..d3bab71951
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@@ -14,7 -16,7 +16,8 @@@ import
parseGhostNodeChildToHostMessage,
ghostPartition,
ghostPermissionItems,
+ ghostPermissionProjectionFingerprint,
+ unreviewedGhostPermissionItems,
ghostWebviewEntryPaths,
isGhostCallToolName,
isValidGhostId,
diff --cc apps/desktop/src/shared/ghost.ts
index b8ab1e6543,aa84a0ce32..767579d877
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@@ -20,9 -21,13 +21,15 @@@ import { DEFAULT_LOCALE, SUPPORTED_LOCA
/** 清单文件名(zip 根部)。 */
export const GHOST_MANIFEST_FILE = 'ghost.json';
+/** Maximum manifest bytes accepted by both Forge and package ingestion. */
+export const GHOST_MANIFEST_MAX_BYTES = 256 * 1024;
+ /**
+ * 安装器读取包内 ghost.json 的硬上限。源码目录的发现/预读取可以使用更宽的
+ * 安全预算,但最终写进 .cindy 的清单必须落在这个上限内。
+ */
+ export const GHOST_INSTALL_MANIFEST_MAX_BYTES = 256 * 1024;
+
/** 意识文件扩展名。 */
export const CINDY_FILE_EXT = '.cindy';
@@@ -1336,12 -1388,11 +1424,17 @@@ export interface InstalledGhost
* 文件缺失或超限时缺省)。renderer 直接作 <img src> 用,无需 loading 态。
*/
iconDataUrl?: string;
+ /**
+ * 是否随包内置插件(id 在随包种子清单里,由 main 投影;renderer 不自判前缀 ——
+ * 企业种子不带 `cindy-` 前缀)。批准态异常时 UI 据此换文案:随包插件由启动对账
+ * 自动补批准,「重启应用即恢复」,不走人工重新确认。
+ */
+ builtin?: boolean;
+ /** 插件详情页宿主角标所需的最小陈旧授权投影;不含账号或 scope 明细。 */
+ oauthScopeStale?: {
+ secretKey: string;
+ missingScopeCount: number;
+ };
}
/** 插件包的来源与审核等级;决定 UI 徽标,不改变运行时 slot 权限。 */
@@@ -1887,25 -1976,26 +2051,49 @@@ export function diffGhostPermissionItem
return { added, removed, unchanged };
}
+/**
+ * Compare an installed Plugin with a candidate package without trusting a
+ * mutable live manifest. Legacy or invalid installs have no approved baseline,
+ * so every permission in the candidate must be reviewed as newly requested.
+ */
+export function diffInstalledGhostPermissionItems(
+ installed: InstalledGhost,
+ next: GhostManifest,
+): GhostPermissionDiff {
+ if (installed.approval.state === 'approved') {
+ return diffGhostPermissionItems(installed.manifest, next);
+ }
+ return {
+ added: ghostPermissionItems(next),
+ removed: [],
+ unchanged: [],
+ };
+}
+
+ /**
+ * 返回未被发布清单或已批准旧版本覆盖的包权限。
+ *
+ * 第二个来源用于兼容旧市场元数据:旧详情投影可能漏掉已存在的权限,
+ * 但这些权限此前已经被用户批准,更新时应继续保留。
++ *
++ * 注(receipt 模型整合):receipt 模型下"已批准的旧版本清单"即 receipt 的 manifest,
++ * 由整合任务①在 packagePermissionReview 落点用 receipt 已批准 manifest 作 baseline;
++ * 保留本函数以支持 main 现有 market 调用点,不额外引入 previouslyInstalled 认证路径。
+ */
+ export function unreviewedGhostPermissionItems(
+ reviewed: GhostManifest,
+ previouslyInstalled: GhostManifest | undefined,
+ actual: GhostManifest,
+ ): GhostPermissionItem[] {
+ const approvalKey = (item: GhostPermissionItem): string =>
+ JSON.stringify([item.key, item.detail ?? '']);
+ const approved = new Set(ghostPermissionItems(reviewed).map(approvalKey));
+ for (const item of ghostPermissionItems(previouslyInstalled ?? reviewed)) {
+ approved.add(approvalKey(item));
+ }
+ return ghostPermissionItems(actual).filter((item) => !approved.has(approvalKey(item)));
+ }
+
/**
* icon 允许的图片扩展名 → mime(校验与 main 读盘供图共用同一口径)。
* 不收 svg:svg 可携带脚本,虽经 <img> 渲染不执行,仍不给这个面。
diff --cc apps/desktop/src/shared/pluginMarket.ts
index db401fd3b6,2b946bac98..f902fb0479
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@@ -35,3 -44,112 +44,117 @@@ export interface PluginMarketSnapshot
export interface PluginMarketDetail extends PluginMarketItem {
manifest: GhostManifest;
}
+
+ /** Main 验证真实下载包后,交给 Renderer 展示的权限复核事实。 */
+ export interface PluginMarketPackageReview {
+ /** 已按当前界面语言本地化,仅用于展示;安全指纹由 Main 基于原始清单计算。 */
+ manifest: GhostManifest;
+ packageSha256: string;
+ /** 产生复核结果时的已装权限基线;null 表示当时尚未安装。 */
+ installedBaseline: string | null;
+ }
+
+ export interface PluginMarketInstallOptions {
+ /** 用户审阅时看到的目标 release;Main 会在下载前重新核对。 */
+ expectedReleaseId: string;
+ /** 自定义市场审阅过的完整清单;服务端市场由 Main 读取 release 清单。 */
+ expectedManifest?: GhostManifest;
+ allowPermissionExpansion?: boolean;
+ /** 用户审阅扩权时的已装权限基线。 */
+ reviewedBaseline?: string;
+ /** 用户确认过的真实下载包;Main 会重新下载并核对 SHA。 */
+ approvedPackageSha256?: string;
++ /**
++ * receipt 模型的并发护栏:receipt 派生 token。确认与落位之间批准状态若变过即拒
++ * (与 reviewedBaseline/approvedPackageSha256 的 main 硬化叠加,见约束文档 §11 整合任务①)。
++ */
++ expectedInstalledApproval?: string;
+ }
+
+ /** 安装成功,或真实包权限与市场展示不一致而需要用户复核。 */
+ export type PluginMarketInstallResult =
+ | { ghost: InstalledGhost; reviewRequired?: never }
+ | { ghost?: never; reviewRequired: PluginMarketPackageReview };
+
+ /* ------------------------------------------------------------------------ */
+ /* 自定义市场源(Git / 本地文件夹) */
+ /* ------------------------------------------------------------------------ */
+
+ /** 用户添加的市场来源。Git 源支持可选引用与稀疏检出;本地源指向文件夹。 */
+ export type MarketSource =
+ | { type: 'git'; url: string; ref?: string; sparsePaths: string[] }
+ | { type: 'local'; path: string };
+
+ /** 持久化的市场来源配置(sources.v1.json)。 */
+ export interface MarketSourceConfig {
+ /** 市场名,来自 marketplace.json 的 name;全局唯一,作为管理主键。 */
+ name: string;
+ addedAt: string;
+ lastSyncedAt: string | null;
+ /** 最近一次同步到的 Git commit SHA;本地源为 null。 */
+ lastRevision: string | null;
+ source: MarketSource;
+ }
+
+ /** Renderer 管理视图使用的来源摘要。 */
+ export interface MarketSourceSummary extends MarketSourceConfig {
+ /** 最近一次发现到的插件数;发现失败时为 0 并携带 status。 */
+ pluginCount: number;
+ status: 'ok' | 'error';
+ /** status === 'error' 时的 IPC 错误码(Renderer 按码本地化)。 */
+ errorCode: string | null;
+ }
+
+ /**
+ * 来源的规范化指纹。市场名是 marketplace.json 自报的、**可复用**——移除来源 A 后
+ * 添加一个同名的来源 B,`customMarketPluginId` 完全相同;账本所有权若只锚在
+ * pluginId 上,无关甚至恶意仓库就能借同名市场"更新"A 装出来的插件。所以自定义
+ * 安装的账本记录同时记下这个指纹,所有权校验必须两者都对上。
+ * 与 sources/store 的 sourcesEqual、sources/index 的 marketCloneSlug 同一套
+ * 判定维度(type + 定位 + ref + 稀疏路径)。
+ *
+ * 序列化必须**无歧义**:用分隔符拼接(`join(',')`、`#ref:sparse`)会产生可构造的
+ * 碰撞——`sparsePaths:['a,b','c']` 与 `['a','b,c']`、`ref:'x' + ['p']` 与
+ * `ref:'x:p' + []` 都会得到同一 key,两个不同来源被判成同一个,所有权校验随之
+ * 失效。JSON 数组序列化对每个元素定界,不存在拼接歧义。
+ */
+ export function marketSourceKey(source: MarketSource): string {
+ return source.type === 'local'
+ ? JSON.stringify(['local', source.path])
+ : JSON.stringify(['git', source.url, source.ref ?? null, source.sparsePaths]);
+ }
+
+ /**
+ * 自定义市场插件的合成 pluginId。与服务端 CUID(^c[a-z0-9]{24}$)互不相交,
+ * Main 在 detail/install/uninstall 入口据此分流,Renderer 无需感知差异。
+ */
+ export const CUSTOM_MARKET_PLUGIN_ID_PREFIX = 'custom:';
+
+ export function customMarketPluginId(marketName: string, ghostId: string): string {
+ return `${CUSTOM_MARKET_PLUGIN_ID_PREFIX}${encodeURIComponent(marketName)}/${encodeURIComponent(ghostId)}`;
+ }
+
+ export function parseCustomMarketPluginId(
+ pluginId: string,
+ ): { marketName: string; ghostId: string } | null {
+ if (!pluginId.startsWith(CUSTOM_MARKET_PLUGIN_ID_PREFIX)) return null;
+ const rest = pluginId.slice(CUSTOM_MARKET_PLUGIN_ID_PREFIX.length);
+ const slash = rest.indexOf('/');
+ if (slash <= 0 || slash === rest.length - 1) return null;
+ try {
+ return {
+ marketName: decodeURIComponent(rest.slice(0, slash)),
+ ghostId: decodeURIComponent(rest.slice(slash + 1)),
+ };
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * 自定义市场插件的合成 releaseId。版本变化即产生新 releaseId,
+ * 从而复用服务端市场既有的 update-available / expectedReleaseId 机制。
+ */
+ export function customMarketReleaseId(marketName: string, ghostId: string, version: string): string {
+ return `custom:${encodeURIComponent(marketName)}:${encodeURIComponent(ghostId)}:${encodeURIComponent(version)}`;
+ }
diff --cc docs/dev-rules/plugin-security-and-authoring.md
index 1eaa0095c0,a55208acd4..b4eb68df43
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@@ -30,8 -30,7 +30,8 @@@
| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |
| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |
| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |
-| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |
+| 安装批准事实(receipt / 技能快照 / revision) | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,批准态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |
- | 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |
++| 能力 slot(网络/通知/角标/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |
| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |
| 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |
| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |
@@@ -273,44 -218,30 +300,55 @@@
以下缺口在触及相关链路时必须一并修复,或在 PR 中保留明确的正式跟踪,不得静默丢弃:
-- **【待重做】授权事实与可变安装目录解耦(原 #636)。** 原修复(#1080 的批准 receipt
- 改造)已于 2026-08-01 回滚,**因此 #636 的漏洞当前是敞开的**:就地改写安装目录里的
- `ghost.json` 能让更新确认框的权限 diff 以被改过的现场为基线显示"无新增",未经确认的
- slot 因此拿到运行授权。回滚原因不是方向错,而是它违反第 5 节红线——把"无批准记录 =
- 不构成运行授权"一次性作用到全部存量安装,只给随包内置插件留了自动补批准的路
- (provisioning 逐字节对账后走 `approveTrustedBundledInstall`,那条路有权威字节可比,
- 正是第 5 节要求的迁移形态),市场与本地安装没有 backfill,升级后全部非随包插件同时
- 失效、需逐个重新确认,本地包还要求重新提供原始 `.cindy`(包已丢失即无从恢复)。
- **重做时必须一并带上第 5 节要求的迁移**:从安装目录的 `ghost.json` /
- `.cindy-trust.json` / `.disabled` 重建等价批准记录(只在从未有过该记录/已判损坏时、
- 权限原样不扩权、来源记日志),本地包要有"不必重新提供原始包、但仍逐条确认"的恢复
- 路径,格式 bump 走"按旧编码核对 → 原地升级"而不是 fail closed。不得再把一次内部
- 机制升级变成全体用户重新确认。
+- **【已修复|第 5 节红线迁移】存量安装的 receipt backfill。** receipt 机制上线前装的
+ 插件没有 receipt,`GhostManager.migrateLegacyApprovalsOnce()` 在每轮对账前跑一次(首次
+ 之后凭迁移 ledger 瞬时 no-op),从旧的三份事实源(`ghost.json` / `.cindy-trust.json` /
+ `.disabled`)重建等价 receipt,让市场与本地安装升级后无感可用;随包内置插件仍走
+ provisioning 的 `approveTrustedBundledInstall`(有权威字节可比,是更强的迁移形态),不
+ 重复迁移。三条不变量:**全局一次性且崩溃安全**(ledger 是 in-progress→completed 两态状态机:
+ 首个 backfill 动笔前先原子落 `in-progress` 并钉死本轮 `pendingIds`,全部处理完才原子
+ 改写成 `completed`;`completed`/存在但读不出 = 门关死,此后缺 receipt 一律 fail closed
+ ——否则删 receipt 就能骗一次"从可变安装目录重建授权";`in-progress` = 上一轮中途崩溃,
+ 续跑**只认清单内的 id**,迁移窗口期间新装再删 receipt 的 id 骗不到重铸;receipt 首写
+ 在 receipt rename 生效**之前**先补落 completed 台账,且落账失败就拒绝本次批准;它只在
+ "完全没有台账"时动笔,不覆盖 in-progress。该门是充分
+ 守卫,因为能删/改 ledger 的进程本就能直接写伪造 receipt,见下「批准状态根无写保护」)、**不扩权**(权限集原样取当前 `ghost.json`,等价于旧模型无条件
+ 授权的那一组,此后任何 manifest/权限变化照旧走完整确认)、**只写状态根不动安装目录**
+ (三份旧文件原样保留,回滚到旧客户端时仍按安装目录判定,符合第 5 节兜底第 4 条)。核心
+ 授权事实读不出(manifest 不合法、技能目录含链接、声明的 locale 装入后损坏)才对该插件
+ fail closed、走恢复 UI;trust 镜像缺失降级为 `unverified`、`packageSha256` audit-only
+ 故省略。改动装入/迁移链路时保持这些不变量,尤其不得把迁移改成"每次缺 receipt 就补"
+ (那就是把授权事实重新交给可变安装目录,等于回到 #636)。迁移之后批准再丢失的恢复
+ 路径:市场包走市场重装确认;本地包走「从已装目录重新确认」(`ghosts:reapprove-inspect`
+ → 确认卡全量权限清单 → `ghosts:reapprove-installed`,清单字节以 manifestSha256 绑定
+ 确认间隙,trust 走与迁移同一个封顶读取器,装入侧的指令查重/tokenBroker/保留前缀
+ 门禁照走)—— 不要求用户重新提供原始 `.cindy`,不存在不可恢复状态;随包插件不走人工
+ 确认,由启动对账自动补(UI 提示「重启应用即恢复」)。一次性门的完整判据:ledger
+ `completed`(或存在但读不出)永久关门;`in-progress` 只按动笔前钉死的 `pendingIds`
+ 续跑;无 ledger 时先扫描完整安装根,不能因某一个有效 receipt 提前关门——曾短暂合入
+ 后回滚的 #1080 可能留下「部分有效 receipt + 其余 legacy 安装 + 无 ledger」的历史 mixed
+ 状态,提前关门会让其余插件永久失效。新代码必须在**首次写任何 receipt 前**先原子落
+ completed ledger,落账失败则 receipt 不得生效(否则「新装 receipt 后、下一轮对账前」
+ 删 receipt 可骗一次按已扩权 manifest 的重铸);legacy migration/recovery 已先落
+ in-progress,因此首份 backfill receipt 不会覆盖迁移清单。
+ 安装根为空/未诞生时**不落 ledger**——门要留给 owner 命名空间 legacy 恢复流程随后搬入
+ 的旧目录;恢复流程对刚搬入的 id 走 `backfillRecoveredLegacyGhosts` 旁路(信任级与首轮
+ 迁移等同,只作用于恢复流程自己搬动的 id)。安装根读失败(非 ENOENT)整轮放弃且不落
+ ledger,下次启动重试。迁移失败的 id 记进 ledger 的 `failedIds` 供排查,逐个走上面的
+ 恢复入口。整轮对账(迁移+播种+批准写入)与「从已装目录重新确认」都必须持
+ GhostMutationCoordinator 的 owner 租约——状态根路径是每次调用现解析的,不持租约时
+ 异步 hash/copy 中途账号切换落定,写入会漏进新 owner 的状态根。
+ - **manifest 枚举扩展在客户端降级方向不兼容(#1283 披露)。** `validateGhostManifest()`
+ 对 `slots` / `subscribe.topics` 的未知枚举值、以及 `schemaVersion` 不等于 2,都是整份
+ 判无效(`return { ok: false }`);而 `GhostManager.list()` 每次调用都重新校验已装目录,
+ 无效即 `continue` 跳过。所以用户把客户端**降级**到某个枚举值引入之前的版本后,声明了该值
+ 的插件会从已装列表**整个消失**(不是能力降级)——界面上看不到、无从修复,已存凭证与偏好
+ 变成孤儿。这不是某次扩展的疏漏:校验器只在**字段**级向前兼容(「宽进严出:忽略未知字段」),
+ 不在**取值**级向前兼容,历史上每次新增卡槽都有同样特征。已发布的旧版无法追改,唯一可行
+ 方向是让**新版**把未知枚举值降级为「忽略 + warn」而非整份拒绝,使此后的扩展天然降级安全
+ (救不了「从引入版降到引入前」那一段,任何方案都救不了)。改动方向本身要过第 5 节红线
+ 评估:放宽校验等于让主机接受读不全的权限声明,不能顺手做。**触及 `validateGhostManifest()`
+ 的枚举白名单、或 `GhostManager.list()` 的跳过逻辑时必须一并考虑。**
- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见
`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。
- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机