Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 插件运行授权改由 Host 批准 receipt 持有,与安装目录解耦

Yuewei-LLec33f9aa2a3f
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 24477e077e..cc6307cd13 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -1,6 +1,7 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
+import { isDeepStrictEqual } from 'node:util';
import JSZip from 'jszip';
@@ -9,6 +10,7 @@ import {
GHOST_LOCALE_MAX_BYTES,
GHOST_SKILL_MD_MAX_BYTES,
ghostLocalePathFor,
+ ghostInstallApprovalToken,
ghostIconMimeType,
isValidGhostId,
resolveGhostManifestLocale,
@@ -26,6 +28,12 @@ import {
} from './ghostSignature.js';
import { isPathInsideDir } from './dirDeposit.js';
import { checkSkillMdConsistency } from './skillSlot.js';
+import {
+ createGhostInstallReceipt,
+ GhostInstallReceiptStore,
+ type GhostInstallReceipt,
+ type GhostInstallReceiptReadResult,
+} from './ghostInstallReceipt.js';
/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */
const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;
@@ -56,6 +64,8 @@ export interface GhostManagerLogger {
export interface GhostManagerOptions {
/** 意识仓库根目录(生产:userData/cindy-brain;测试:os.tmpdir 下临时目录)。 */
getRootDir: () => string;
+ /** Host 批准状态根;必须位于插件安装根之外。 */
+ getStateDir?: () => string;
/** 装/卸成功后通知(index.ts 用它广播 ghosts:changed 到所有窗口)。 */
onChanged?: (ghosts: InstalledGhost[]) => void;
/** 当前宿主语言;插件未提供时由 shared 契约固定回退英文。 */
@@ -72,19 +82,22 @@ export type InstallRejection =
| { code: 'already-installed'; reason: string }
| { code: 'not-installed'; reason: string }
| { code: 'command-conflict'; reason: string }
+ | { code: 'state-changed'; reason: string }
| { code: 'io'; reason: string };
export type UninstallRejection =
| { code: 'invalid-id'; reason: string }
| { code: 'not-installed'; reason: string }
+ | { code: 'approval-required'; reason: string }
| { code: 'io'; reason: string };
/**
- * 意识仓库的 main 端管理者:一个意识一个子目录(rootDir/<id>/),目录即事实。
+ * 插件仓库的 main 端管理者:一个插件一个内容目录(rootDir/<id>/),Host
+ * receipt 才是 manifest / trust / enabled / revision 的授权事实。
*
* 设计要点:
- * - **目录即注册表**:没有额外的 DB / 索引文件,list() 每次实扫磁盘 ——
- * 装了什么打开文件夹一目了然,坏一个目录只影响那一个意识(跳过 + warn);
+ * - **目录只证明在装**:list() 实扫内容目录,但批准状态来自安装根之外的
+ * receipt;旧安装没有 receipt 时保持不可运行,更新需完整重新确认;
* - **装载先落 staging 再切正式**(对齐 skillhub/installService 的做法):
* 解压全程发生在 `.cindy-installing-*` 临时目录,校验全过才 rename 到
* rootDir/<id>,任何一步失败都不会留下半截安装;
@@ -94,7 +107,51 @@ export type UninstallRejection =
* 目标是 rootDir 的直接子目录,杜绝借 id 删任意路径。
*/
export class GhostManager {
- constructor(private readonly options: GhostManagerOptions) {}
+ private readonly receiptStore: GhostInstallReceiptStore;
+ private mutationTail: Promise<void> = Promise.resolve();
+
+ constructor(private readonly options: GhostManagerOptions) {
+ this.receiptStore = new GhostInstallReceiptStore(
+ options.getStateDir ??
+ (() => {
+ const root = path.resolve(options.getRootDir());
+ return path.join(path.dirname(root), `${path.basename(root)}-install-state`);
+ }),
+ );
+ const contentRoot = path.resolve(options.getRootDir());
+ const stateRoot = this.receiptStore.rootDir();
+ if (
+ isPathInsideDir(contentRoot, stateRoot) ||
+ isPathInsideDir(stateRoot, contentRoot)
+ ) {
+ throw new Error('ghost install content and approval state roots must be disjoint');
+ }
+ }
+
+ /** Forge 等 Host 能力必须排除的受管根(内容根 + 批准状态根)。 */
+ managedRootDirs(): string[] {
+ return [path.resolve(this.options.getRootDir()), this.receiptStore.rootDir()];
+ }
+
+ approvalStateRoot(): string {
+ return this.receiptStore.rootDir();
+ }
+
+ /** Serialize content-directory and approval-receipt mutations as one Host transaction lane. */
+ async runExclusiveMutation<T>(operation: () => Promise<T>): Promise<T> {
+ const previous = this.mutationTail;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ this.mutationTail = previous.then(() => gate);
+ await previous;
+ try {
+ return await operation();
+ } finally {
+ release();
+ }
+ }
/** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */
list(): InstalledGhost[] {
@@ -111,6 +168,41 @@ export class GhostManager {
if (!entry.isDirectory()) continue;
if (entry.name.startsWith('.')) continue; // staging / 系统目录
const dir = path.join(root, entry.name);
+ if (!isValidGhostId(entry.name)) {
+ this.options.log?.warn('ghost dir skipped: invalid directory id', { dir });
+ continue;
+ }
+ const approvalResult = this.receiptStore.read(entry.name);
+ if (approvalResult.state === 'approved') {
+ const receipt = approvalResult.receipt;
+ const localizedManifest = this.localizeApprovedManifest(receipt);
+ result.push({
+ manifest: localizedManifest,
+ dir,
+ enabled: 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 } : {}),
+ });
+ 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 当成运行授权。
const manifestPath = path.join(dir, GHOST_MANIFEST_FILE);
let raw: unknown;
try {
@@ -137,12 +229,11 @@ export class GhostManager {
// icon 读失败只降级为无图标(warn),不影响意识本体可用。
const iconDataUrl = this.readInstalledIconDataUrl(dir, v.manifest);
const localizedManifest = this.readInstalledLocalizedManifest(dir, v.manifest);
- const trust = this.readInstalledTrust(dir);
result.push({
manifest: localizedManifest,
dir,
- enabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),
- ...(trust ? { trust } : {}),
+ enabled: false,
+ approval: { state: approvalResult.state },
...(iconDataUrl !== null ? { iconDataUrl } : {}),
});
}
@@ -150,6 +241,20 @@ export class GhostManager {
return result;
}
+ /** receipt 内的 base manifest + 已批准 locale 资源;不再读取可变安装目录。 */
+ private localizeApprovedManifest(receipt: GhostInstallReceipt): GhostManifest {
+ const requestedLocale = this.options.getLocale?.();
+ const runtimeManifest = withGhostResolvedLocale(receipt.manifest, requestedLocale);
+ const localePath = ghostLocalePathFor(receipt.manifest, requestedLocale);
+ const fallbackPath = receipt.manifest.locales?.en;
+ const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];
+ for (const candidate of candidates) {
+ const resource = receipt.localeResources[candidate];
+ if (resource) return resolveGhostManifestLocale(runtimeManifest, resource);
+ }
+ return runtimeManifest;
+ }
+
/**
* 读取当前宿主语言对应的 locale 文件。已安装目录被用户手工改坏时不让
* 整个插件消失:记录告警并回退原 manifest;正常安装路径已在 parse 阶段严验。
@@ -193,10 +298,24 @@ export class GhostManager {
}
/**
- * 启用 / 停用一张意识。停用不删任何东西,只在安装目录里放一个 `.disabled`
- * 标记文件(目录即事实:打开文件夹一眼可见);启用即删掉标记。幂等。
+ * 启用 / 停用一张意识。停用不删任何东西,只把批准 receipt 的 enabled 翻过来
+ * (安装目录里的 `.disabled` 只作为旧版本兼容镜像同步维护)。幂等。
+ *
+ * 两个方向不对称:**启用需要有效批准状态**(无批准的存量安装必须先重新确认
+ * 权限),**停用必须永远能成功** —— 停用是安全的收敛方向,不能因为技能快照
+ * 被外部删掉之类的环境问题把插件卡在"既不能用也不能关"。
*/
- async setEnabled(id: string, enabled: boolean): Promise<{ ok: true } | { rejection: UninstallRejection }> {
+ async setEnabled(
+ id: string,
+ enabled: boolean,
+ ): Promise<{ ok: true } | { rejection: UninstallRejection }> {
+ return this.runExclusiveMutation(() => this.setEnabledUnlocked(id, enabled));
+ }
+
+ private async setEnabledUnlocked(
+ id: string,
+ enabled: boolean,
+ ): Promise<{ ok: true } | { rejection: UninstallRejection }> {
if (!isValidGhostId(id)) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
@@ -204,14 +323,41 @@ export class GhostManager {
if (!(await pathExists(dir))) {
return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
}
+ const receiptResult = this.receiptStore.read(id);
+ if (receiptResult.state !== 'approved' && enabled) {
+ return {
+ rejection: {
+ code: 'approval-required',
+ reason: `插件 ${id} 缺少有效的安装批准状态,请重新选择安装包并确认权限`,
+ },
+ };
+ }
const marker = path.join(dir, DISABLED_MARKER_FILE);
+ const previousEnabled =
+ receiptResult.state === 'approved' ? receiptResult.receipt.enabled : false;
try {
if (enabled) {
await fs.promises.rm(marker, { force: true });
} else {
await fs.promises.writeFile(marker, '');
}
+ if (receiptResult.state === 'approved') {
+ // 快照被外部删掉时从当前安装目录重建(内容与批准 manifest 的一致性由
+ // ensureSkillSnapshot 的 SKILL.md 逐字校验兜住);停用方向即使重建不了
+ // 也照样落盘,由技能对账把落链撤掉。
+ await this.receiptStore.write(
+ { ...receiptResult.receipt, enabled },
+ { skillSourceDir: dir, requireSkillSnapshot: enabled },
+ );
+ }
} catch (err) {
+ // `.disabled` 是旧版本兼容镜像;receipt 写失败时尽力把镜像回滚,
+ // 避免降级运行旧客户端时看到与批准状态相反的启用态。
+ if (previousEnabled) {
+ await fs.promises.rm(marker, { force: true }).catch(() => undefined);
+ } else {
+ await fs.promises.writeFile(marker, '').catch(() => undefined);
+ }
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
this.options.log?.info('ghost enabled state changed', { id, enabled });
@@ -239,24 +385,6 @@ export class GhostManager {
}
}
- /** 读取主机安装时写下的签名验证快照;坏文件只降级未显示,不信作者自报。 */
- private readInstalledTrust(dir: string): GhostTrustInfo | null {
- try {
- const raw = JSON.parse(fs.readFileSync(path.join(dir, TRUST_METADATA_FILE), 'utf8')) as GhostTrustInfo;
- if (
- !raw ||
- typeof raw !== 'object' ||
- !['cindy-official', 'reviewed', 'verified-publisher', 'unverified'].includes(raw.level) ||
- typeof raw.publisherSigned !== 'boolean' ||
- typeof raw.publisherVerified !== 'boolean' ||
- typeof raw.reviewed !== 'boolean'
- ) return null;
- return raw;
- } catch {
- return null;
- }
- }
-
/**
* 只验不装:读 .cindy → 解包 → 校验清单,返回清单(含 icon data URL),
* 零副作用。「装意识前弹确认」(README 安全原则)的数据来源 —— 三个装入
@@ -289,6 +417,8 @@ export class GhostManager {
): Promise<
| {
manifest: GhostManifest;
+ approvedManifest: GhostManifest;
+ localeResources: Record<string, GhostManifestLocaleResource>;
trust: GhostTrustInfo;
packageSha256: string;
iconDataUrl?: string;
@@ -425,6 +555,7 @@ export class GhostManager {
};
}
let localizedManifest = withGhostResolvedLocale(v.manifest, this.options.getLocale?.());
+ const localeResources: Record<string, GhostManifestLocaleResource> = {};
if (v.manifest.locales !== undefined) {
const resources = new Map<string, GhostManifestLocaleResource>();
for (const localePath of Object.values(v.manifest.locales)) {
@@ -465,6 +596,7 @@ export class GhostManager {
};
}
resources.set(localePath, validated.resource);
+ localeResources[localePath] = validated.resource;
}
const localePath = ghostLocalePathFor(v.manifest, this.options.getLocale?.());
const resource = localePath ? resources.get(localePath) : undefined;
@@ -563,6 +695,8 @@ export class GhostManager {
return {
manifest: localizedManifest,
+ approvedManifest: v.manifest,
+ localeResources,
trust: signature.trust,
packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
@@ -574,6 +708,13 @@ export class GhostManager {
async install(
lizFilePath: string,
opts?: { initiallyEnabled?: boolean; expectedPackageSha256?: string },
+ ) {
+ return this.runExclusiveMutation(() => this.installUnlocked(lizFilePath, opts));
+ }
+
+ private async installUnlocked(
+ lizFilePath: string,
+ opts?: { initiallyEnabled?: boolean; expectedPackageSha256?: string },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
// 装入初始启用态由 UI 层决定(装入确认框勾选,默认沉睡);缺省 true
// 保持既有调用方(测试等)语义不变。
@@ -592,7 +733,16 @@ export class GhostManager {
},
};
}
- const { manifest, trust, iconDataUrl, allEntries, prefix } = parsed;
+ const {
+ manifest,
+ approvedManifest,
+ localeResources,
+ trust,
+ packageSha256,
+ iconDataUrl,
+ allEntries,
+ prefix,
+ } = parsed;
// 4) 目标目录冲突检查
const root = this.options.getRootDir();
@@ -621,6 +771,14 @@ export class GhostManager {
// 5) 解压到 staging(zip-slip / zip bomb 防御),全过才切正式目录
const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`);
+ const receipt = createGhostInstallReceipt({
+ manifest: approvedManifest,
+ localeResources,
+ enabled: initiallyEnabled,
+ trust,
+ packageSha256,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ });
try {
// 初始沉睡:标记在 staging 阶段就位,rename 后首个广播即沉睡态,
// 不存在"先启用一帧再熄灯"的跳变(规则 7)。
@@ -632,6 +790,12 @@ export class GhostManager {
trust,
});
await fs.promises.rename(stagingDir, finalDir);
+ try {
+ await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ } catch (error) {
+ await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
+ throw error;
+ }
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
if (err instanceof InstallExtractError) {
@@ -644,6 +808,7 @@ export class GhostManager {
manifest,
dir: finalDir,
enabled: initiallyEnabled,
+ approval: { state: 'approved', revision: receipt.revision },
trust,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
};
@@ -663,7 +828,14 @@ export class GhostManager {
*/
async update(
lizFilePath: string,
- opts?: { expectedPackageSha256?: string },
+ opts: { expectedInstalledApproval: string; expectedPackageSha256?: string },
+ ) {
+ return this.runExclusiveMutation(() => this.updateUnlocked(lizFilePath, opts));
+ }
+
+ private async updateUnlocked(
+ lizFilePath: string,
+ opts: { expectedInstalledApproval: string; expectedPackageSha256?: string },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
const parsed = await this.parse(lizFilePath);
if ('rejection' in parsed) return parsed;
@@ -678,15 +850,40 @@ export class GhostManager {
},
};
}
- const { manifest, trust, iconDataUrl, allEntries, prefix } = parsed;
+ const {
+ manifest,
+ approvedManifest,
+ localeResources,
+ trust,
+ packageSha256,
+ iconDataUrl,
+ allEntries,
+ prefix,
+ } = parsed;
const root = this.options.getRootDir();
const finalDir = path.join(root, manifest.id);
if (!(await pathExists(finalDir))) {
return { rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` } };
}
- // 延续当前唤醒/沉睡状态。
- const enabled = !fs.existsSync(path.join(finalDir, DISABLED_MARKER_FILE));
+ const approvalResult = this.receiptStore.read(manifest.id);
+ const actualApproval = approvalTokenFor(approvalResult);
+ if (actualApproval !== opts.expectedInstalledApproval) {
+ return {
+ rejection: {
+ code: 'state-changed',
+ reason: '插件批准状态在确认后发生了变化,请重新检查权限',
+ },
+ };
+ }
+ // 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时只在完整重新确认后
+ // 采用原 `.disabled` 镜像;损坏 receipt 一律保持停用。
+ const enabled =
+ approvalResult.state === 'approved'
+ ? approvalResult.receipt.enabled
+ : approvalResult.state === 'legacy-unapproved'
+ ? !fs.existsSync(path.join(finalDir, DISABLED_MARKER_FILE))
+ : false;
// 指令查重同 install,但豁免自己(新版本沿用/改名自己的指令都合法)。
if (manifest.command !== undefined) {
@@ -710,6 +907,14 @@ export class GhostManager {
const rand = crypto.randomBytes(4).toString('hex');
const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${rand}`);
const backupDir = path.join(root, `.cindy-updating-${manifest.id}-${rand}`);
+ const receipt = createGhostInstallReceipt({
+ manifest: approvedManifest,
+ localeResources,
+ enabled,
+ trust,
+ packageSha256,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ });
try {
await this.extractToStaging(allEntries, prefix, stagingDir, {
disabled: !enabled,
@@ -740,12 +945,20 @@ export class GhostManager {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
+ try {
+ await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ } catch (err) {
+ await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
+ await fs.promises.rename(backupDir, finalDir).catch(() => undefined);
+ return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ }
await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});
const ghost: InstalledGhost = {
manifest,
dir: finalDir,
enabled,
+ approval: { state: 'approved', revision: receipt.revision },
trust,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
};
@@ -754,6 +967,81 @@ export class GhostManager {
return { ghost };
}
+ /**
+ * 随包种子已经由 provisioning 层逐字节对账后,为其建立 Host 批准状态。
+ * 该入口不得用于市场包或任意本地目录;它不替代用户安装确认。
+ */
+ async approveTrustedBundledInstall(
+ manifest: GhostManifest,
+ enabled: boolean,
+ ): Promise<boolean> {
+ const dir = path.join(this.options.getRootDir(), manifest.id);
+ const localeResources = this.readApprovedLocaleResources(dir, manifest);
+ const iconDataUrl = this.readInstalledIconDataUrl(dir, manifest) ?? undefined;
+ const packageSha256 = await hashApprovedDirectory(dir);
+ const trust: GhostTrustInfo = {
+ level: 'cindy-official',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: true,
+ };
+ const current = this.receiptStore.read(manifest.id);
+ if (
+ current.state === 'approved' &&
+ isDeepStrictEqual(current.receipt.manifest, manifest) &&
+ isDeepStrictEqual(current.receipt.localeResources, localeResources) &&
+ isDeepStrictEqual(current.receipt.trust, trust) &&
+ current.receipt.packageSha256 === packageSha256 &&
+ current.receipt.iconDataUrl === iconDataUrl
+ ) {
+ if (current.receipt.enabled !== enabled) {
+ await this.receiptStore.write({
+ ...current.receipt,
+ enabled,
+ });
+ return true;
+ }
+ return false;
+ }
+ await this.receiptStore.write(
+ createGhostInstallReceipt({
+ manifest,
+ localeResources,
+ enabled,
+ trust,
+ packageSha256,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ }),
+ { skillSourceDir: dir },
+ );
+ return true;
+ }
+
+ /** Remove Host approval for content deleted by the trusted seed provisioner. */
+ async removeInstallApproval(id: string): Promise<void> {
+ await this.receiptStore.remove(id);
+ }
+
+ private readApprovedLocaleResources(
+ dir: string,
+ manifest: GhostManifest,
+ ): Record<string, GhostManifestLocaleResource> {
+ const resources: Record<string, GhostManifestLocaleResource> = {};
+ for (const localePath of Object.values(manifest.locales ?? {})) {
+ if (!localePath) continue;
+ const absPath = path.join(dir, ...localePath.split('/'));
+ const stat = fs.lstatSync(absPath);
+ if (!stat.isFile() || stat.size > GHOST_LOCALE_MAX_BYTES) {
+ throw new Error(`bundled locale missing or oversized: ${localePath}`);
+ }
+ const raw = JSON.parse(fs.readFileSync(absPath, 'utf8')) as unknown;
+ const validated = validateGhostManifestLocaleResource(raw, manifest);
+ if (!validated.ok) throw new Error(`bundled locale invalid: ${localePath}`);
+ resources[localePath] = validated.resource;
+ }
+ return resources;
+ }
+
/** 解压 zip 条目到 staging 目录(install / update 共用;含 zip-slip / bomb 防御)。 */
private async extractToStaging(
allEntries: JSZip.JSZipObject[],
@@ -798,6 +1086,13 @@ export class GhostManager {
async uninstall(
id: string,
options: { notify?: boolean } = {},
+ ) {
+ return this.runExclusiveMutation(() => this.uninstallUnlocked(id, options));
+ }
+
+ private async uninstallUnlocked(
+ id: string,
+ options: { notify?: boolean } = {},
): Promise<{ ok: true } | { rejection: UninstallRejection }> {
if (!isValidGhostId(id)) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
@@ -816,6 +1111,17 @@ export class GhostManager {
} catch (err) {
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
+ try {
+ await this.receiptStore.remove(id);
+ } catch (err) {
+ // 内容目录已经删除,插件不可能再运行。此时把卸载视为成功,让上层继续
+ // 清凭证/KV/私有文件;孤立 receipt 与 skill snapshot 仅是待回收状态,
+ // 不能把“清理延后”误报成“插件仍已安装”。
+ this.options.log?.warn('ghost approval cleanup deferred after uninstall', {
+ id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
this.options.log?.info('ghost uninstalled', { id });
if (options.notify !== false) this.options.onChanged?.(this.list());
return { ok: true };
@@ -825,6 +1131,15 @@ export class GhostManager {
/** staging 期的"内容不合格"错误(与环境 IO 错误区分,映射 file-invalid)。 */
class InstallExtractError extends Error {}
+function approvalTokenFor(result: GhostInstallReceiptReadResult): string {
+ return result.state === 'approved'
+ ? ghostInstallApprovalToken({
+ state: 'approved',
+ revision: result.receipt.revision,
+ })
+ : ghostInstallApprovalToken({ state: result.state });
+}
+
/** 流式读取 zip 单条目;超过上限立刻停流,不先分配整个恶意条目。 */
async function readZipEntryBufferWithLimit(
entry: JSZip.JSZipObject,
@@ -908,6 +1223,37 @@ async function pathExists(p: string): Promise<boolean> {
}
}
+async function hashApprovedDirectory(root: string): Promise<string> {
+ const files: string[] = [];
+ const collect = async (relativeDir: string): Promise<void> => {
+ const absoluteDir = path.join(root, relativeDir);
+ const entries = await fs.promises.readdir(absoluteDir, { withFileTypes: true });
+ for (const entry of entries) {
+ if (entry.name.startsWith('.')) continue;
+ const relativePath = relativeDir
+ ? `${relativeDir}/${entry.name}`
+ : entry.name;
+ if (entry.isDirectory()) {
+ await collect(relativePath);
+ } else if (entry.isFile()) {
+ files.push(relativePath);
+ } else {
+ throw new Error(`bundled Plugin contains a non-regular entry: ${relativePath}`);
+ }
+ }
+ };
+ await collect('');
+ files.sort();
+ const hash = crypto.createHash('sha256');
+ for (const relativePath of files) {
+ hash.update(relativePath);
+ hash.update('\0');
+ hash.update(await fs.promises.readFile(path.join(root, ...relativePath.split('/'))));
+ hash.update('\0');
+ }
+ return hash.digest('hex');
+}
+
/**
* 检测所有条目是否都在同一个顶层文件夹下(用户右键压缩常见形态),
* 是则返回该前缀(含尾部 /),否则返回空串。
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index d3e5b71b54..77ed8b0176 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -5,7 +5,10 @@ import path from 'node:path';
import JSZip from 'jszip';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { InstalledGhost } from '../../../shared/ghost';
+import {
+ ghostInstallApprovalToken,
+ type InstalledGhost,
+} from '../../../shared/ghost';
import { GhostManager } from '../GhostManager';
/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */
@@ -76,13 +79,26 @@ async function makeCindy(
}
async function expectRejection(
- result: Awaited<ReturnType<GhostManager['install']>>,
+ result: unknown,
code: string,
): Promise<void> {
- expect('rejection' in result, JSON.stringify(result)).toBe(true);
+ expect(
+ typeof result === 'object' && result !== null && 'rejection' in result,
+ JSON.stringify(result),
+ ).toBe(true);
expect((result as { rejection: { code: string } }).rejection.code).toBe(code);
}
+async function updateGhost(
+ cindyPath: string,
+ id = 'hello',
+): ReturnType<GhostManager['update']> {
+ const installed = manager.list().find((ghost) => ghost.manifest.id === id);
+ return manager.update(cindyPath, {
+ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),
+ });
+}
+
describe('GhostManager · install', () => {
it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
const manifest = {
@@ -129,7 +145,7 @@ describe('GhostManager · install', () => {
});
});
- it('已安装 locale 或其父目录被替换为目录外软链时拒绝读取并回退基础清单', async () => {
+ it('installed locale symlinks cannot replace the Host-approved locale snapshot', async () => {
hostLocale = 'en';
const manifest = {
...goodManifest(),
@@ -155,9 +171,9 @@ describe('GhostManager · install', () => {
}
expect(manager.list()[0].manifest).toMatchObject({
- name: 'Base name',
+ name: 'Packaged name',
resolvedLocale: 'en',
- tools: [{ name: 'do_thing', description: '做点事' }],
+ tools: [{ name: 'do_thing', description: 'Localized tool' }],
});
const localesDir = path.dirname(localePath);
@@ -171,7 +187,7 @@ describe('GhostManager · install', () => {
process.platform === 'win32' ? 'junction' : 'dir',
);
expect(manager.list()[0].manifest).toMatchObject({
- name: 'Base name',
+ name: 'Packaged name',
resolvedLocale: 'en',
});
});
@@ -450,6 +466,234 @@ describe('GhostManager · list', () => {
});
});
+describe('GhostManager · Host approval receipt', () => {
+ const receiptPath = (id = 'hello') =>
+ path.join(workDir, 'ghosts-install-state', `${id}.json`);
+
+ /** 带 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);
+ expect(after.enabled).toBe(true);
+ expect(after.trust).toEqual(before.trust);
+ expect(after.approval.state).toBe('approved');
+ });
+
+ 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('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('treats receipt cleanup failure after content removal as a completed uninstall', 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([]);
+ });
+
+ 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('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' }),
+ }),
+ );
+ 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' },
+ });
+ });
+});
+
describe('GhostManager · setEnabled(启用/停用)', () => {
it('停用:目录里出现 .disabled 标记、list 报 enabled=false、onChanged 广播;启用即恢复', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
@@ -562,13 +806,13 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {
await expectRejection(await manager.install(cindy), 'file-invalid');
});
- it('已装意识的 icon 文件事后丢失 → list 降级为无图标,不影响意识本体', async () => {
+ it('installed icon removal cannot replace the Host-approved icon snapshot', async () => {
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'));
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');
});
@@ -586,7 +830,7 @@ describe('GhostManager · update(原位换版)', () => {
onChanged.mockClear();
const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }, { 'new.txt': 'v2' });
- const result = await manager.update(v2);
+ const result = await updateGhost(v2);
expect('ghost' in result, JSON.stringify(result)).toBe(true);
const { ghost } = result as { ghost: InstalledGhost };
expect(ghost.manifest.version).toBe('2.0.0');
@@ -601,18 +845,18 @@ describe('GhostManager · update(原位换版)', () => {
it('唤醒状态延续:沉睡中更新仍沉睡,唤醒中更新仍唤醒', async () => {
await manager.install(await makeCindy('v1.cindy', goodManifest()), { initiallyEnabled: false });
- const r1 = await manager.update(await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }));
+ const r1 = await updateGhost(await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }));
expect((r1 as { ghost: InstalledGhost }).ghost.enabled).toBe(false);
expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);
await manager.setEnabled('hello', true);
- const r2 = await manager.update(await makeCindy('v3.cindy', { ...goodManifest(), version: '3.0.0' }));
+ const r2 = await updateGhost(await makeCindy('v3.cindy', { ...goodManifest(), version: '3.0.0' }));
expect((r2 as { ghost: InstalledGhost }).ghost.enabled).toBe(true);
expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
});
it('未装入 → not-installed 拒绝', async () => {
- await expectRejection(await manager.update(await makeCindy('a.cindy', goodManifest())), 'not-installed');
+ await expectRejection(await updateGhost(await makeCindy('a.cindy', goodManifest())), 'not-installed');
});
it('指令查重豁免自己,但仍拦别人的指令', async () => {
@@ -620,15 +864,17 @@ describe('GhostManager · update(原位换版)', () => {
await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'Paint')));
// 自己沿用自己的指令 → 放行。
- const keep = await manager.update(
+ const keep = await updateGhost(
await makeCindy('a2.cindy', { ...chipManifestWithCommand('alpha', 'draw'), version: '2.0.0' }),
+ 'alpha',
);
expect('ghost' in keep, JSON.stringify(keep)).toBe(true);
// 新版本改用别人占用的指令 → 拒,且旧版原样在位。
await expectRejection(
- await manager.update(
+ await updateGhost(
await makeCindy('a3.cindy', { ...chipManifestWithCommand('alpha', 'paint'), version: '3.0.0' }),
+ 'alpha',
),
'command-conflict',
);
@@ -640,7 +886,7 @@ describe('GhostManager · update(原位换版)', () => {
await manager.install(await makeCindy('v1.cindy', goodManifest()));
const bad = path.join(workDir, 'bad.cindy');
await fs.promises.writeFile(bad, 'nope');
- await expectRejection(await manager.update(bad), 'file-invalid');
+ await expectRejection(await updateGhost(bad), 'file-invalid');
expect(manager.list().find((g) => g.manifest.id === 'hello')?.manifest.version).toBe('1.0.0');
});
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 2a82f84fb6..33465d3a8b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -47,6 +47,69 @@ async function makeSrcDir(files: Record<string, string>): Promise<string> {
}
describe('packGhostDir', () => {
+ 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('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),
@@ -335,6 +398,72 @@ describe('scaffoldGhostDir', () => {
await expect(fs.promises.stat(invalid)).rejects.toMatchObject({ code: 'ENOENT' });
});
+ it('拒绝把骨架落进 Host 受管根:根内、后代、大小写别名与 junction 别名都不行', async () => {
+ // 受管根恰好落在会话工作目录里(用户把 userData 当工作目录打开的情形):
+ // 工作目录检查放行,受管根检查必须接着挡住。
+ const managedRoot = path.join(workDir, 'cindy-brain');
+ const installedDir = path.join(managedRoot, 'demo');
+ await fs.promises.mkdir(installedDir, { recursive: true });
+ const scaffold = (dir: string, forbidden: readonly string[]) =>
+ scaffoldGhostDir(
+ { dir, template: 'plain', id: 'managed-demo', name: 'Managed demo' },
+ { sessionWorkdir: workDir, forbiddenRootDirs: forbidden },
+ );
+
+ expect(await scaffold(path.join(managedRoot, 'fresh'), [managedRoot])).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ });
+ expect(
+ await scaffold(path.join(installedDir, 'src'), [managedRoot]),
+ ).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ expect(fs.existsSync(path.join(installedDir, 'src'))).toBe(false);
+
+ // 状态根还没建出来也要挡住(首次装入前就该拒)。
+ const stateRoot = path.join(workDir, 'ghost-install-state');
+ expect(await scaffold(path.join(stateRoot, 'nested'), [stateRoot])).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ });
+
+ if (process.platform === 'win32') {
+ expect(
+ await scaffold(path.join(managedRoot.toUpperCase(), 'fresh'), [
+ managedRoot.toLowerCase(),
+ ]),
+ ).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ }
+
+ // junction/软链别名:字面在别处,realpath 落在受管根内。
+ const alias = path.join(workDir, 'managed-alias');
+ try {
+ fs.symlinkSync(installedDir, alias, process.platform === 'win32' ? 'junction' : 'dir');
+ } catch {
+ return; // Windows 无特权时建不出夹具,守卫仍在
+ }
+ expect(await scaffold(path.join(alias, 'src'), [managedRoot])).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ });
+ expect(fs.existsSync(path.join(installedDir, 'src'))).toBe(false);
+ });
+
+ it('工作目录里的独立作者目录不受受管根禁区影响', async () => {
+ const dir = path.join(workDir, 'my-plugin');
+ expect(
+ await scaffoldGhostDir(
+ { dir, template: 'plain', id: 'my-plugin', name: 'My plugin' },
+ {
+ sessionWorkdir: workDir,
+ forbiddenRootDirs: [
+ path.join(workDir, 'cindy-brain'),
+ path.join(workDir, 'ghost-install-state'),
+ ],
+ },
+ ),
+ ).toMatchObject({ ok: true, dir });
+ });
+
it('软链祖先把字面在工作目录内的路径引到外面 → 拒绝且外面不落盘', async () => {
// Windows 无特权时目录软链可能 EPERM,建不出夹具就跳过(守卫仍在)。
const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-outside-'));
@@ -362,6 +491,15 @@ describe('scaffoldGhostDir', () => {
});
describe('FORGE_GUIDE', () => {
+ it('documents installed-directory isolation and the structured refusal', () => {
+ expect(FORGE_GUIDE).toContain('已安装插件目录');
+ expect(FORGE_GUIDE).toContain('SOURCE_IS_INSTALLED_PLUGIN');
+ // 脚手架侧的同一禁区也要写进手册,否则 agent 会先把骨架建进安装目录再撞墙。
+ expect(FORGE_GUIDE).toContain('也不能落在已安装插件目录或 Host 状态目录内');
+ expect(FORGE_GUIDE).toContain('复制/迁出');
+ expect(FORGE_GUIDE).toContain('junction');
+ });
+
it('分章体量守卫:每个 ## 章节须留在单次工具结果安全体量内(#890 分章投递的不变量)', () => {
// 手册"随主机版本演进"持续增长;任一章越过单次 MCP 结果上限会静默复现 #890 于该章。
// 上限取 32KB:当前最大章 ~22KB,余量 ~45%,越线即该拆小节。
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
index db9842ef1a..d5dc542e8c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts
@@ -26,6 +26,7 @@ function makeGhost(slots: string[]): InstalledGhost {
},
dir: '/tmp/fake-install-dir',
enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
};
}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts
index aad121cd58..6089550963 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts
@@ -11,6 +11,7 @@ function ghost(
return {
dir: `/plugins/${id}`,
enabled: options.enabled ?? true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
manifest: {
schemaVersion: 2,
id,
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
index 753ee18550..debbce0723 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
@@ -17,11 +17,14 @@ import {
let workDir: string;
let homeDir: string;
let brainRoot: string;
+/** 与 GhostManager 缺省状态根同名(`<安装根>-install-state`),判据口径一致。 */
+let approvalStateRoot: string;
beforeEach(async () => {
workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-slot-test-'));
homeDir = path.join(workDir, 'home');
brainRoot = path.join(workDir, 'owners', 'aaa', 'cindy-brain');
+ approvalStateRoot = path.join(workDir, 'owners', 'aaa', 'cindy-brain-install-state');
await fs.promises.mkdir(homeDir, { recursive: true });
await fs.promises.mkdir(brainRoot, { recursive: true });
});
@@ -55,6 +58,8 @@ function ghost(
manifest,
dir: path.join(brainRoot, id),
enabled: opts.enabled ?? true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ approvedSkillRoot: path.join(brainRoot, id),
};
}
@@ -106,7 +111,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
await writeSkillDir('my-ghost', 'skills/foo', 'foo');
const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];
- const first = await reconcileGhostSkillLinks({ ghosts, brainRoot, homeDir });
+ const first = await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });
expect(first.changed).toBe(true);
expect(first.warnings).toEqual([]);
const linkName = ghostSkillLinkName('my-ghost', 'foo');
@@ -116,7 +121,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
// .claude 兼容扇出(经 prepareSharedGlobalSkillLinks)
expect(sameRealPath(path.join(claudeDir(), linkName), target)).toBe(true);
- const second = await reconcileGhostSkillLinks({ ghosts, brainRoot, homeDir });
+ const second = await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });
expect(second.changed).toBe(false);
expect(second.actions.filter((a) => a.op !== 'kept')).toEqual([]);
});
@@ -124,19 +129,19 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
it('停用/卸载 → 撤链,.claude 悬空兼容链接一并回收', async () => {
await writeSkillDir('my-ghost', 'skills/foo', 'foo');
const enabled = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];
- await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, approvalStateRoot, homeDir });
const linkName = ghostSkillLinkName('my-ghost', 'foo');
// 停用:期望态清空 → 双侧链接消失
const disabled = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }], { enabled: false })];
- const result = await reconcileGhostSkillLinks({ ghosts: disabled, brainRoot, homeDir });
+ const result = await reconcileGhostSkillLinks({ ghosts: disabled, brainRoot, approvalStateRoot, homeDir });
expect(result.changed).toBe(true);
expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);
expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);
// 卸载(清单里没有它)语义相同:再建再收敛一次验证
- await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, homeDir });
- const gone = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, approvalStateRoot, homeDir });
+ const gone = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
expect(gone.changed).toBe(true);
expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);
});
@@ -144,10 +149,10 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
it('目标目录被删(异常残留)→ 断链回收', async () => {
await writeSkillDir('my-ghost', 'skills/foo', 'foo');
const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];
- await reconcileGhostSkillLinks({ ghosts, brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });
// 模拟崩溃残留:插件目录整个没了,链接悬空
await fs.promises.rm(path.join(brainRoot, 'my-ghost'), { recursive: true, force: true });
- const result = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ const result = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
expect(fs.existsSync(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo')))).toBe(false);
expect(result.changed).toBe(true);
});
@@ -157,12 +162,14 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
await reconcileGhostSkillLinks({
ghosts: [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])],
brainRoot,
+ approvalStateRoot,
homeDir,
});
await writeSkillDir('my-ghost', 'skills/bar', 'bar');
const result = await reconcileGhostSkillLinks({
ghosts: [ghost('my-ghost', [{ dir: 'skills/bar', name: 'bar' }])],
brainRoot,
+ approvalStateRoot,
homeDir,
});
expect(result.changed).toBe(true);
@@ -185,6 +192,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
const result = await reconcileGhostSkillLinks({
ghosts: [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])],
brainRoot,
+ approvalStateRoot,
homeDir,
});
expect(result.warnings.some((w) => w.includes(linkName))).toBe(true);
@@ -194,7 +202,13 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
expect(st.isSymbolicLink()).toBe(false);
});
- it('外来链接(目标不在任何 cindy-brain 内)→ 活链断链都不碰', async () => {
+ it('漏传批准状态根在类型层就被挡住(否则指向快照的活链接会被判成外来链接而永不撤链)', () => {
+ // @ts-expect-error approvalStateRoot 必填:这行编译不报错就说明保护没了。
+ const missingStateRoot = () => reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ expect(typeof missingStateRoot).toBe('function');
+ });
+
+ it('外来链接(目标不在任何受管根内)→ 活链断链都不碰', async () => {
const foreignTarget = path.join(workDir, 'foreign-skill');
await fs.promises.mkdir(foreignTarget, { recursive: true });
await fs.promises.writeFile(
@@ -209,15 +223,43 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
process.platform === 'win32' ? 'junction' : 'dir',
);
- await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
expect(fs.existsSync(foreignLink)).toBe(true);
// 变成断链(目标删除)也不碰:目标路径不含 cindy-brain 段
await fs.promises.rm(foreignTarget, { recursive: true, force: true });
- await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
expect(fs.lstatSync(foreignLink).isSymbolicLink()).toBe(true);
});
+ it('外来 skill-snapshots 目录下的断链不碰(判据要求状态根名相邻,不认通用目录名)', async () => {
+ // 用户自己在别处建的 `skill-snapshots/` —— 名字撞上我们的内部目录名,但不在
+ // 批准状态根下,回收判据不能只看这一段就删。
+ const foreignTarget = path.join(workDir, 'my-notes', 'skill-snapshots', 'x', 'y');
+ await fs.promises.mkdir(foreignTarget, { recursive: true });
+ await fs.promises.mkdir(sharedDir(), { recursive: true });
+ const foreignLink = path.join(sharedDir(), 'looks--managed');
+ await fs.promises.symlink(
+ foreignTarget,
+ foreignLink,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ await fs.promises.rm(path.join(workDir, 'my-notes'), { recursive: true, force: true });
+
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
+ expect(fs.lstatSync(foreignLink).isSymbolicLink()).toBe(true);
+
+ // 对照:真正落在批准状态根下的同形断链要回收。
+ const managedLink = path.join(sharedDir(), 'managed--skill');
+ await fs.promises.symlink(
+ path.join(approvalStateRoot, 'skill-snapshots', 'managed', 'rev', 'skills', 'demo'),
+ managedLink,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
+ expect(fs.existsSync(managedLink)).toBe(false);
+ });
+
it('他 owner 的活链接不碰(多账号隔离);他 owner 的断链回收(防积尘)', async () => {
// 另一个 owner 的 brainRoot 与真实技能
const otherBrainRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');
@@ -235,11 +277,11 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
process.platform === 'win32' ? 'junction' : 'dir',
);
- await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
expect(fs.existsSync(liveLink)).toBe(true); // 活链保留
await fs.promises.rm(path.join(otherBrainRoot, 'other-ghost'), { recursive: true, force: true });
- await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });
+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
expect(fs.existsSync(liveLink)).toBe(false); // 断链回收(目标带 cindy-brain 段)
});
@@ -249,6 +291,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
const result = await reconcileGhostSkillLinks({
ghosts: [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])],
brainRoot,
+ approvalStateRoot,
homeDir,
});
expect(fs.existsSync(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo')))).toBe(false);
@@ -268,6 +311,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
]),
],
brainRoot,
+ approvalStateRoot,
homeDir,
});
expect(result.warnings.some((w) => w.includes('冲突'))).toBe(true);
@@ -315,20 +359,39 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'
expect('ghost' in installed, JSON.stringify(installed)).toBe(true);
// 3) 对账:共享根与 .claude 双端可见,realpath 落在安装目录
- await reconcileGhostSkillLinks({ ghosts: manager.list(), brainRoot, homeDir });
+ await reconcileGhostSkillLinks({
+ ghosts: manager.list(),
+ brainRoot,
+ approvalStateRoot: manager.approvalStateRoot(),
+ homeDir,
+ });
const linkName = ghostSkillLinkName('e2e-ghost', 'demo');
- const target = path.join(brainRoot, 'e2e-ghost', 'skills', 'demo');
+ const approvedSkillRoot = manager.list()[0].approvedSkillRoot;
+ expect(approvedSkillRoot).toBeTruthy();
+ const target = path.join(approvedSkillRoot!, 'skills', 'demo');
expect(sameRealPath(path.join(sharedDir(), linkName), target)).toBe(true);
expect(sameRealPath(path.join(claudeDir(), linkName), target)).toBe(true);
// 链接指向的 SKILL.md 就是包里那份
expect(
await fs.promises.readFile(path.join(sharedDir(), linkName, 'SKILL.md'), 'utf8'),
).toContain('演示技能');
+ await fs.promises.writeFile(
+ path.join(brainRoot, 'e2e-ghost', 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: 演示技能\n---\n\n篡改后的指令\n',
+ );
+ expect(
+ await fs.promises.readFile(path.join(sharedDir(), linkName, 'SKILL.md'), 'utf8'),
+ ).not.toContain('篡改后的指令');
// 4) 卸载 → 对账 → 双端链接消失
const removed = await manager.uninstall('e2e-ghost');
expect(removed).toMatchObject({ ok: true });
- await reconcileGhostSkillLinks({ ghosts: manager.list(), brainRoot, homeDir });
+ await reconcileGhostSkillLinks({
+ ghosts: manager.list(),
+ brainRoot,
+ approvalStateRoot: manager.approvalStateRoot(),
+ homeDir,
+ });
expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);
expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);
});
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index 2e5eed45e5..1f81a64d9f 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -106,6 +106,8 @@ export interface ProvisionDeps {
}
export interface ProvisionOutcome {
+ /** First-party seed manifests whose installed bytes reconciled successfully. */
+ approved: GhostManifest[];
/** 本次首装的意识(装完默认唤醒;调用方负责停靠面板 + 广播 + 常驻点火)。 */
installed: GhostManifest[];
/** 本次覆盖更新的意识(`.disabled` 已保留;调用方负责广播)。 */
@@ -303,7 +305,13 @@ function readProvisioningConfig(
export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<ProvisionOutcome> {
const { seedRootDirs, repoRootDir, log } = deps;
const identity = deps.identity ?? null;
- const outcome: ProvisionOutcome = { installed: [], updated: [], removed: [], skipped: [] };
+ const outcome: ProvisionOutcome = {
+ approved: [],
+ installed: [],
+ updated: [],
+ removed: [],
+ skipped: [],
+ };
// 每根独立列种子 + 读配置。空根不读配置(未初始化 submodule 的目录里连
// provisioning.json 都没有,读了必 warn,徒增噪音)。
@@ -386,6 +394,7 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
const seedHash = await hashDirContent(seedDir);
const installedHash = await hashDirContent(installedDir);
if (seedHash === installedHash) {
+ outcome.approved.push(manifest);
outcome.skipped.push(id);
continue;
}
@@ -393,12 +402,14 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
markApplyStart();
await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: wasDisabled });
seeded.add(id);
+ outcome.approved.push(manifest);
outcome.updated.push(manifest);
log?.info('builtin ghost updated to bundled content', { id, version: manifest.version });
} else {
markApplyStart();
await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: false });
seeded.add(id);
+ outcome.approved.push(manifest);
outcome.installed.push(manifest);
log?.info('builtin ghost installed', { id, version: manifest.version });
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 6d5cbd1c1f..3d574badd9 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -25,6 +25,7 @@ import {
type GhostManifest,
} from '../../shared/ghost.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
+import { isPathInsideDir } from './dirDeposit.js';
import { checkSkillMdConsistency } from './skillSlot.js';
/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */
@@ -47,7 +48,13 @@ 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_IS_INSTALLED_PLUGIN'
+ | 'MANIFEST_INVALID'
+ | 'ENTRY_MISSING'
+ | 'TOO_LARGE'
+ | 'INTERNAL';
message: string;
};
@@ -400,10 +407,14 @@ function hasFsErrorCode(err: unknown, code: string): boolean {
*
* 文件先写进同目录临时文件夹,全部成功后再一次 rename 到目标;目标已经
* 存在时直接拒绝,因此并发调用也不会把用户原文件覆盖一半。
+ *
+ * `forbiddenRootDirs` 与打包侧同源(Host 受管的安装根 + 批准状态根):骨架也不
+ * 许落进已安装插件或状态目录 —— 那既会改写已批准插件的内容(随包种子还会因此
+ * 翻转播种指纹被整目录换回),又会诱导作者继续在安装目录里改代码。
*/
export async function scaffoldGhostDir(
input: ForgeScaffoldInput,
- options?: { sessionWorkdir?: string | null },
+ options?: { sessionWorkdir?: string | null; forbiddenRootDirs?: readonly string[] },
): Promise<ForgeScaffoldResult> {
const template = input.template;
if (!FORGE_SCAFFOLD_TEMPLATES.includes(template)) {
@@ -453,6 +464,26 @@ export async function scaffoldGhostDir(
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),
+ };
+ }
+ if (isPathInsideDir(resolvedForbiddenRoot, realTarget)) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_INPUT',
+ message:
+ 'dir 不能落在已安装插件目录或 Host 管理的状态目录内;请在工作目录里换一个独立的作者目录',
+ };
+ }
+ }
const files = scaffoldFiles(input);
// 显式收窄而非 as 断言:manifest 恒为 JSON 字符串,二进制项(占位图标)另存;
// 未来若误把 manifest 写成 Buffer,这里在编译/测试期就报,而不是运行期 parse 炸。
@@ -541,7 +572,10 @@ export async function scaffoldGhostDir(
* 同名覆盖——同 id 同版本重打包语义上就是同一个包),用户在自己的意识目录里
* 就能拿到成品;出错返回结构化分类,agent 按 message 修源码即可,不抛异常。
*/
-export async function packGhostDir(dir: string): Promise<ForgePackResult> {
+export async function packGhostDir(
+ dir: string,
+ options: { forbiddenRootDirs?: readonly string[] } = {},
+): Promise<ForgePackResult> {
try {
let stat: fs.Stats;
try {
@@ -552,6 +586,18 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {
if (!stat.isDirectory()) {
return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `不是目录:${dir}` };
}
+ const realSourceDir = await fs.promises.realpath(dir);
+ for (const forbiddenRoot of options.forbiddenRootDirs ?? []) {
+ const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
+ if (isPathInsideDir(resolvedForbiddenRoot, realSourceDir)) {
+ return {
+ ok: false,
+ 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',
+ };
+ }
+ }
// 1) 清单先行:与装入侧同一套校验,错在打包期就报清楚。
let manifestRaw: unknown;
@@ -702,6 +748,27 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {
}
}
+/**
+ * Resolve symlinks/junctions in the existing prefix while retaining a
+ * non-existent tail. This keeps managed roots comparable before first use.
+ */
+async function resolveThroughExistingAncestor(inputPath: string): Promise<string> {
+ let cursor = path.resolve(inputPath);
+ const tail: string[] = [];
+ while (true) {
+ try {
+ const real = await fs.promises.realpath(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;
+ }
+ }
+}
+
/**
* 《意识编写手册》——ghost_forge_guide 的返回体。随主机版本演进,改了机制
* 就同步改这里;agent 每次做意识前现拿现读,永不过期。
@@ -2552,13 +2619,19 @@ const ensured = await cindy.workspace({
## 7. 打包与测试
1. 新插件先调 \`ghost_forge_scaffold\` 生成骨架,或把已有源码放在用户工作目录下的
- 一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件;
-2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;
+ 一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件,
+ 也不能落在已安装插件目录或 Host 状态目录内(会被拒,理由同下一条);
+2. **Forge 源码必须是当前会话工作目录里的独立作者目录**。已安装插件目录以及
+ Host 管理的状态目录都不是源码区,禁止直接修改、打包或用路径别名绕过;若要继续
+ 开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;
+3. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;
产物落在源码目录里(\`<id>-<version>.cindy\`,同版本覆盖,下次打包自动跳过);
-3. **告知用户去点弹窗**(装入默认沉睡,提醒用户勾"立即开启"或到主界面侧边栏「插件」中唤醒);
-4. 改代码后重新 pack:同 id 会弹"更新 vX → vY",唤醒状态与面板位置自动保留
+ 若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,
+ 按上一步迁出源码后再打包;
+4. **告知用户去点弹窗**(装入默认沉睡,提醒用户勾"立即开启"或到主界面侧边栏「插件」中唤醒);
+5. 改代码后重新 pack:同 id 会弹"更新 vX → vY",唤醒状态与面板位置自动保留
(记得 bump ghost.json 的 version);
-5. 验证:让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
+6. 验证:让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
## 8. 发布签名与审核
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
new file mode 100644
index 0000000000..2334231d27
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -0,0 +1,381 @@
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ GHOST_LOCALE_MAX_BYTES,
+ isValidGhostId,
+ validateGhostManifest,
+ validateGhostManifestLocaleResource,
+ type GhostManifest,
+ type GhostManifestLocaleResource,
+ type GhostTrustInfo,
+} from '../../shared/ghost.js';
+import { checkSkillMdConsistency } from './skillSlot.js';
+
+const RECEIPT_SCHEMA_VERSION = 1;
+const MAX_RECEIPT_BYTES = 2 * 1024 * 1024;
+const MAX_ICON_DATA_URL_BYTES = 768 * 1024;
+/**
+ * 受管 icon 快照的完整形态:声明的图片 mime + 严格 base64 载荷。载荷字符集也要
+ * 校验 —— 只认前缀会让被改写的 receipt 把任意字符串塞进 renderer 的 img src。
+ */
+const ICON_DATA_URL_RE =
+ /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/;
+
+/**
+ * 一次明确批准的插件安装事实;只允许 Host 写入安装目录之外的状态根。
+ *
+ * receipt 钉住的是**授权事实**(批准过的 manifest / trust / 启停 / revision)。
+ * 它不保证安装目录里的内容字节此后一直没被改过 —— 逻辑页代码仍从可变的安装
+ * 目录加载,只有技能目录因为越出沙箱而被拷成快照。
+ */
+export interface GhostInstallReceipt {
+ schemaVersion: typeof RECEIPT_SCHEMA_VERSION;
+ id: string;
+ revision: string;
+ manifest: GhostManifest;
+ localeResources: Record<string, GhostManifestLocaleResource>;
+ enabled: boolean;
+ trust: GhostTrustInfo;
+ /**
+ * 批准时点的来源指纹,仅供审计与人工比对:市场/本地包是 `.cindy` 文件哈希,
+ * 随包种子是内容目录哈希。**运行时不校验它**,不要据此认为安装内容持续完整。
+ */
+ packageSha256?: string;
+ iconDataUrl?: string;
+}
+
+export type GhostInstallReceiptReadResult =
+ | { state: 'approved'; receipt: GhostInstallReceipt }
+ | { state: 'legacy-unapproved' }
+ | { state: 'invalid'; reason: string };
+
+/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */
+export class GhostInstallReceiptStore {
+ constructor(private readonly getRootDir: () => string) {}
+
+ rootDir(): string {
+ return path.resolve(this.getRootDir());
+ }
+
+ read(id: string): GhostInstallReceiptReadResult {
+ const receiptPath = this.receiptPath(id);
+ let stat: fs.Stats;
+ try {
+ stat = fs.lstatSync(receiptPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return { state: 'legacy-unapproved' };
+ }
+ return {
+ state: 'invalid',
+ reason: error instanceof Error ? error.message : String(error),
+ };
+ }
+ if (!stat.isFile() || stat.size > MAX_RECEIPT_BYTES) {
+ return { state: 'invalid', reason: 'receipt 不是普通文件或超过大小上限' };
+ }
+ try {
+ const parsed = JSON.parse(fs.readFileSync(receiptPath, 'utf8')) as unknown;
+ const validated = validateReceipt(parsed, id);
+ return validated.ok
+ ? { state: 'approved', receipt: validated.receipt }
+ : { state: 'invalid', reason: validated.reason };
+ } catch (error) {
+ return {
+ state: 'invalid',
+ reason: error instanceof Error ? error.message : String(error),
+ };
+ }
+ }
+
+ /**
+ * 写入批准事实。`skillSourceDir` 是快照缺失时的取字节来源:装入/更新传新
+ * 内容目录,纯状态改写(启停)传当前安装目录即可自愈。
+ *
+ * `requireSkillSnapshot: false` 用于**必须成功的收敛方向**(停用):快照
+ * 已被外部删掉时不该把插件卡在"既不能用也不能关"的状态,此时按无 skill
+ * 落链继续写批准事实,由对账撤掉链接。
+ */
+ async write(
+ receipt: GhostInstallReceipt,
+ options: { skillSourceDir?: string; requireSkillSnapshot?: boolean } = {},
+ ): Promise<void> {
+ const validated = validateReceipt(receipt, receipt.id);
+ if (!validated.ok) throw new Error(`refusing to write invalid ghost receipt: ${validated.reason}`);
+
+ const root = this.rootDir();
+ await fs.promises.mkdir(root, { recursive: true });
+ try {
+ await this.ensureSkillSnapshot(receipt, options.skillSourceDir);
+ } catch (error) {
+ if (options.requireSkillSnapshot !== false) throw error;
+ }
+ const target = this.receiptPath(receipt.id);
+ const temp = path.join(
+ root,
+ `.${receipt.id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
+ );
+ try {
+ await fs.promises.writeFile(temp, `${JSON.stringify(receipt, null, 2)}\n`, {
+ encoding: 'utf8',
+ flag: 'wx',
+ mode: 0o600,
+ });
+ await fs.promises.rename(temp, target);
+ } finally {
+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);
+ }
+ await this.pruneStaleSkillSnapshots(receipt);
+ }
+
+ async remove(id: string): Promise<void> {
+ await fs.promises.rm(this.receiptPath(id), { force: true });
+ await fs.promises.rm(path.join(this.rootDir(), 'skill-snapshots', id), {
+ recursive: true,
+ force: true,
+ });
+ }
+
+ skillSnapshotRoot(id: string, revision: string): string {
+ if (!isValidGhostId(id) || !isRevision(revision)) {
+ throw new Error('invalid ghost skill snapshot identity');
+ }
+ return path.join(this.rootDir(), 'skill-snapshots', id, revision);
+ }
+
+ private receiptPath(id: string): string {
+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for receipt path');
+ return path.join(this.rootDir(), `${id}.json`);
+ }
+
+ private async ensureSkillSnapshot(
+ receipt: GhostInstallReceipt,
+ skillSourceDir: string | undefined,
+ ): Promise<void> {
+ const items = receipt.manifest.skill?.items ?? [];
+ if (items.length === 0) return;
+ const target = this.skillSnapshotRoot(receipt.id, receipt.revision);
+ try {
+ if ((await fs.promises.lstat(target)).isDirectory()) return;
+ throw new Error('approved skill snapshot target is not a directory');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ if (!skillSourceDir) {
+ throw new Error('approved skill snapshot is missing');
+ }
+ const parent = path.dirname(target);
+ const temp = path.join(
+ parent,
+ `.${receipt.revision}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
+ );
+ await fs.promises.mkdir(parent, { recursive: true });
+ try {
+ await fs.promises.mkdir(temp, { recursive: false });
+ for (const item of items) {
+ const source = path.join(skillSourceDir, ...item.dir.split('/'));
+ const skillMd = await fs.promises.readFile(path.join(source, 'SKILL.md'), 'utf8');
+ const consistencyError = checkSkillMdConsistency(skillMd, item);
+ if (consistencyError) {
+ throw new Error(`approved skill ${item.dir} is inconsistent: ${consistencyError}`);
+ }
+ await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));
+ }
+ await fs.promises.rename(temp, target);
+ } finally {
+ await fs.promises.rm(temp, { recursive: true, force: true }).catch(() => undefined);
+ }
+ }
+
+ /**
+ * 回收同一插件下非当前 revision 的技能快照与崩溃残留的 `.tmp` 目录。
+ *
+ * 只在新 receipt 已经原子提交之后跑:此刻旧 revision 已不是批准事实,留着
+ * 就是每次更新泄漏一份完整拷贝。共享技能根里指向旧 revision 的链接会因此
+ * 短暂断链,直到下一轮对账重指——对越出沙箱的 skill 槽来说,短暂"技能不可
+ * 用"是正确的收敛方向,留着旧批准版本继续生效不是。
+ *
+ * best-effort:批准事实已经落盘,回收失败只记为待清理状态,不回滚安装。
+ */
+ private async pruneStaleSkillSnapshots(receipt: GhostInstallReceipt): Promise<void> {
+ const parent = path.join(this.rootDir(), 'skill-snapshots', receipt.id);
+ let entries: fs.Dirent[];
+ try {
+ entries = await fs.promises.readdir(parent, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ await Promise.all(
+ entries
+ .filter((entry) => entry.name !== receipt.revision)
+ .map((entry) =>
+ fs.promises
+ .rm(path.join(parent, entry.name), { recursive: true, force: true })
+ .catch(() => undefined),
+ ),
+ );
+ }
+}
+
+export function createGhostInstallReceipt(input: {
+ manifest: GhostManifest;
+ localeResources: Record<string, GhostManifestLocaleResource>;
+ enabled: boolean;
+ trust: GhostTrustInfo;
+ packageSha256?: string;
+ iconDataUrl?: string;
+}): GhostInstallReceipt {
+ return {
+ schemaVersion: RECEIPT_SCHEMA_VERSION,
+ id: input.manifest.id,
+ revision: crypto.randomUUID(),
+ manifest: input.manifest,
+ localeResources: input.localeResources,
+ enabled: input.enabled,
+ trust: input.trust,
+ ...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),
+ ...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),
+ };
+}
+
+function validateReceipt(
+ raw: unknown,
+ expectedId: string,
+): { ok: true; receipt: GhostInstallReceipt } | { ok: false; reason: string } {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ok: false, reason: 'receipt 必须是对象' };
+ }
+ const value = raw as Record<string, unknown>;
+ if (value.schemaVersion !== RECEIPT_SCHEMA_VERSION) {
+ return { ok: false, reason: 'receipt schemaVersion 不受支持' };
+ }
+ if (value.id !== expectedId || !isValidGhostId(expectedId)) {
+ return { ok: false, reason: 'receipt id 与安装目录不一致' };
+ }
+ if (typeof value.revision !== 'string' || !isRevision(value.revision)) {
+ return { ok: false, reason: 'receipt revision 不合法' };
+ }
+ const manifestResult = validateGhostManifest(value.manifest);
+ if (!manifestResult.ok || manifestResult.manifest.id !== expectedId) {
+ return {
+ ok: false,
+ reason: manifestResult.ok ? 'receipt manifest id 不一致' : manifestResult.reason,
+ };
+ }
+ if (typeof value.enabled !== 'boolean') {
+ return { ok: false, reason: 'receipt enabled 不合法' };
+ }
+ const trust = validateTrust(value.trust);
+ if (!trust) return { ok: false, reason: 'receipt trust 不合法' };
+ if (
+ value.packageSha256 !== undefined &&
+ (typeof value.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.packageSha256))
+ ) {
+ return { ok: false, reason: 'receipt packageSha256 不合法' };
+ }
+ if (
+ value.iconDataUrl !== undefined &&
+ (
+ typeof value.iconDataUrl !== 'string' ||
+ Buffer.byteLength(value.iconDataUrl, 'utf8') > MAX_ICON_DATA_URL_BYTES ||
+ !ICON_DATA_URL_RE.test(value.iconDataUrl)
+ )
+ ) {
+ return { ok: false, reason: 'receipt iconDataUrl 不合法' };
+ }
+ if (!value.localeResources || typeof value.localeResources !== 'object' || Array.isArray(value.localeResources)) {
+ return { ok: false, reason: 'receipt localeResources 不合法' };
+ }
+ const expectedLocalePaths = [
+ ...new Set(Object.values(manifestResult.manifest.locales ?? {})),
+ ].sort();
+ const actualLocalePaths = Object.keys(
+ value.localeResources as Record<string, unknown>,
+ ).sort();
+ if (
+ expectedLocalePaths.length !== actualLocalePaths.length ||
+ expectedLocalePaths.some((localePath, index) => localePath !== actualLocalePaths[index])
+ ) {
+ return { ok: false, reason: 'receipt localeResources 与 manifest 声明不一致' };
+ }
+ const localeResources: Record<string, GhostManifestLocaleResource> = {};
+ for (const [localePath, resource] of Object.entries(
+ value.localeResources as Record<string, unknown>,
+ )) {
+ if (Buffer.byteLength(JSON.stringify(resource), 'utf8') > GHOST_LOCALE_MAX_BYTES) {
+ return { ok: false, reason: `receipt locale 超过大小上限:${localePath}` };
+ }
+ const validated = validateGhostManifestLocaleResource(resource, manifestResult.manifest);
+ if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };
+ localeResources[localePath] = validated.resource;
+ }
+ return {
+ ok: true,
+ receipt: {
+ schemaVersion: RECEIPT_SCHEMA_VERSION,
+ id: expectedId,
+ revision: value.revision,
+ manifest: manifestResult.manifest,
+ localeResources,
+ enabled: value.enabled,
+ trust,
+ ...(typeof value.packageSha256 === 'string'
+ ? { packageSha256: value.packageSha256 }
+ : {}),
+ ...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),
+ },
+ };
+}
+
+function isRevision(value: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
+ value,
+ );
+}
+
+async function copyRegularDirectory(source: string, target: string): Promise<void> {
+ const sourceStat = await fs.promises.lstat(source);
+ if (!sourceStat.isDirectory()) throw new Error(`skill source is not a directory: ${source}`);
+ await fs.promises.mkdir(target, { recursive: true });
+ const entries = await fs.promises.readdir(source, { withFileTypes: true });
+ for (const entry of entries) {
+ const from = path.join(source, entry.name);
+ const to = path.join(target, entry.name);
+ if (entry.isDirectory()) {
+ await copyRegularDirectory(from, to);
+ } else if (entry.isFile()) {
+ await fs.promises.copyFile(from, to, fs.constants.COPYFILE_EXCL);
+ } else {
+ throw new Error(`skill snapshot rejects non-regular entry: ${from}`);
+ }
+ }
+}
+
+function validateTrust(raw: unknown): GhostTrustInfo | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const value = raw as Record<string, unknown>;
+ if (
+ !['cindy-official', 'reviewed', 'verified-publisher', 'unverified'].includes(
+ String(value.level),
+ ) ||
+ typeof value.publisherSigned !== 'boolean' ||
+ typeof value.publisherVerified !== 'boolean' ||
+ typeof value.reviewed !== 'boolean'
+ ) {
+ return null;
+ }
+ const optionalStrings = [
+ 'publisherName',
+ 'publisherKeyId',
+ 'reviewerName',
+ ] as const;
+ for (const key of optionalStrings) {
+ if (value[key] !== undefined && typeof value[key] !== 'string') return null;
+ }
+ if (value.unknownReviewer !== undefined && typeof value.unknownReviewer !== 'boolean') {
+ return null;
+ }
+ return value as unknown as GhostTrustInfo;
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 5b159321c9..08f45d93fc 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -13,6 +13,7 @@ import {
GHOST_CARD_HEIGHT_MIN,
GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,
GHOST_NOTIFY_MIN_INTERVAL_MS,
+ isGhostInstallApprovalToken,
ghostWebviewEntryPaths,
isCindyAccountGhostId,
isOfficialGhostId,
@@ -692,6 +693,15 @@ function migrateGhostKvOnRename(fromId: string, toId: string): void {
/** 单轮对账:播种 → (有变化时)广播 + 首装停靠 + 常驻点火。 */
async function reconcileBuiltinGhosts(reason: string): Promise<void> {
const manager = getGhostManager();
+ await manager.runExclusiveMutation(() =>
+ reconcileBuiltinGhostsLocked(reason, manager),
+ );
+}
+
+async function reconcileBuiltinGhostsLocked(
+ reason: string,
+ manager: GhostManager,
+): Promise<void> {
// 改名前置:用户自主状态(墓碑=卸载过 / .disabled=停用)随改名带到新 id,
// 不能让"明确卸载/停用过"的用户在升级后被以新 id 重新装上并点亮(播种器
// "用户自主权豁免"支柱)。墓碑:旧 id 有 → 给新 id 记墓碑并清掉旧墓碑
@@ -720,10 +730,11 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
repoRootDir: brainRootDir(),
identity: currentProvisionIdentity(),
// 回收先熄灯沙箱再删目录(Windows 文件锁:运行中的电子脑可能占着句柄)。
- beforeRemove: (id) => {
+ beforeRemove: async (id) => {
getGhostRuntime().stop(id);
getGhostNodeRuntimeBroker().stop(id);
getGhostAgentSlot().clearGhost(id);
+ await manager.removeInstallApproval(id);
},
onApplyStart: () => {
tipShown = true;
@@ -765,12 +776,35 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
});
}
}
- if (outcome.installed.length === 0 && outcome.updated.length === 0 && outcome.removed.length === 0) return;
+ let approvalChanged = false;
+ for (const manifest of outcome.approved) {
+ try {
+ approvalChanged =
+ (await manager.approveTrustedBundledInstall(
+ manifest,
+ !fs.existsSync(path.join(brainRootDir(), manifest.id, '.disabled')),
+ )) || approvalChanged;
+ } catch (err) {
+ log.warn('builtin ghost approval receipt failed', {
+ id: manifest.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ if (
+ outcome.installed.length === 0 &&
+ outcome.updated.length === 0 &&
+ outcome.removed.length === 0 &&
+ !approvalChanged
+ ) {
+ return;
+ }
log.info('builtin ghost reconcile applied changes', {
reason,
installed: outcome.installed.map((m) => m.id),
updated: outcome.updated.map((m) => m.id),
removed: outcome.removed,
+ approvalChanged,
});
// 播种绕过 manager 写盘,广播由这里补上(renderer 首帧 sendSync 早于对账
// 完成时,靠 ghosts:changed 热更新兜底,多窗口同一套通道)。
@@ -797,6 +831,7 @@ export function getGhostManager(): GhostManager {
if (!managerSingleton) {
managerSingleton = new GhostManager({
getRootDir: brainRootDir,
+ getStateDir: () => ownerScopedUserDataPath('ghost-install-state'),
onChanged: broadcastGhostsChanged,
getLocale: getResolvedMainLocale,
trustRegistry: loadGhostTrustRegistry(),
@@ -2429,6 +2464,8 @@ function throwInstallError(rejection: InstallRejection): never {
throwIpcError('NOT_FOUND', rejection.reason);
case 'command-conflict':
throwIpcError('GHOST_COMMAND_CONFLICT', rejection.reason);
+ case 'state-changed':
+ throwIpcError('PRECONDITION_FAILED', rejection.reason);
default:
throwIpcError('INTERNAL', rejection.reason);
}
@@ -2441,6 +2478,8 @@ function throwUninstallError(rejection: UninstallRejection): never {
throwIpcError('INVALID_PARAMS', rejection.reason);
case 'not-installed':
throwIpcError('NOT_FOUND', rejection.reason);
+ case 'approval-required':
+ throwIpcError('PRECONDITION_FAILED', rejection.reason);
default:
throwIpcError('INTERNAL', rejection.reason);
}
@@ -2494,6 +2533,7 @@ export async function installOrUpdateMarketGhostPackage(
expected: {
ghostId: string;
version: string;
+ expectedInstalledApproval?: string;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@ -2536,7 +2576,15 @@ export async function installOrUpdateMarketGhostPackage(
getGhostAgentSlot().clearGhost(expected.ghostId);
let result: Awaited<ReturnType<typeof manager.update>>;
try {
- result = await manager.update(cindyFilePath);
+ if (!expected.expectedInstalledApproval) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state was not bound to the market update',
+ );
+ }
+ result = await manager.update(cindyFilePath, {
+ expectedInstalledApproval: expected.expectedInstalledApproval,
+ });
} catch (error) {
spawnIfResident(installed);
throw error;
@@ -3535,14 +3583,26 @@ export function registerGhostIpc(): void {
if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');
}
- const expectedPackageSha256 = (opts as { expectedPackageSha256?: unknown } | undefined)
- ?.expectedPackageSha256;
+ const updateOptions = opts as
+ | {
+ expectedPackageSha256?: unknown;
+ expectedInstalledApproval?: unknown;
+ }
+ | undefined;
+ const expectedPackageSha256 = updateOptions?.expectedPackageSha256;
+ const expectedInstalledApproval = updateOptions?.expectedInstalledApproval;
if (
typeof expectedPackageSha256 !== 'string' ||
!/^[a-f0-9]{64}$/.test(expectedPackageSha256)
) {
throwIpcError('INVALID_PARAMS', 'expectedPackageSha256 must come from ghosts:inspect');
}
+ if (!isGhostInstallApprovalToken(expectedInstalledApproval)) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'expectedInstalledApproval must come from ghosts:list',
+ );
+ }
const inspected = await manager.inspect(lizFilePath);
if ('rejection' in inspected) throwInstallError(inspected.rejection);
if (inspected.packageSha256 !== expectedPackageSha256) {
@@ -3556,7 +3616,10 @@ export function registerGhostIpc(): void {
getGhostAgentSlot().clearGhost(inspected.manifest.id);
let result: Awaited<ReturnType<typeof manager.update>>;
try {
- result = await manager.update(lizFilePath, { expectedPackageSha256 });
+ result = await manager.update(lizFilePath, {
+ expectedPackageSha256,
+ expectedInstalledApproval,
+ });
} catch (err) {
// 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)
if (previousGhost) spawnIfResident(previousGhost);
@@ -3612,7 +3675,14 @@ export function registerGhostIpc(): void {
// 官方前缀在 inspect 就拒(确认弹窗都不该弹出来),install/update 双保险再拦。
rejectReservedGhostId(result.manifest.id);
rejectUnauthorizedTokenBroker(result.manifest);
- return result;
+ return {
+ manifest: result.manifest,
+ trust: result.trust,
+ packageSha256: result.packageSha256,
+ ...(result.iconDataUrl !== undefined
+ ? { iconDataUrl: result.iconDataUrl }
+ : {}),
+ };
});
ipcMain.handle('ghosts:uninstall', async (_event, id: unknown) => {
@@ -3908,6 +3978,7 @@ function scheduleGhostSkillReconcile(): void {
const result = await reconcileGhostSkillLinks({
ghosts: getGhostManager().list(),
brainRoot: brainRootDir(),
+ approvalStateRoot: getGhostManager().approvalStateRoot(),
});
if (result.warnings.length > 0) {
log.warn('ghost skill reconcile warnings', { warnings: result.warnings });
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
index cfb73f7802..c72faaa2df 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
@@ -36,6 +36,7 @@ function chipGhost(id = 'demo'): InstalledGhost {
},
dir: `/fake/brain/${id}`,
enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
};
}
diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.ts
index 4673cb282e..80a71c8199 100644
--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts
@@ -9,20 +9,31 @@
* - **单一幂等 reconciler**:`reconcileGhostSkillLinks` 以"期望态 vs 实际态"
* 对账,不做增量命令式挂链——install/update/启停/卸载全走同一条广播管线
* 触发对账,崩溃残留(悬空链接)下一轮自动自愈。
- * - **链接不复制字节**:共享技能根 `~/.agents/skills/<id>--<name>` 是指向插件
- * 安装目录(brainRoot/<id>/<dir>)的 junction(win32)/dir symlink。更新插件
- * 时安装目录路径稳定,链接跨版本存活;卸载即断链,由对账回收。
- * - **绝不误伤**:只删"确认为 symlink/junction 且目标落在 cindy-brain 安装根"
+ * - **链接指向 Host 批准快照,不指向可变安装目录**:共享技能根
+ * `~/.agents/skills/<id>--<name>` 是指向**批准状态根**里
+ * `skill-snapshots/<id>/<revision>/<dir>` 的 junction(win32)/dir symlink。
+ * skill 槽是唯一越出沙箱的能力,确认框看到的 SKILL.md 必须就是 Agent 之后
+ * 读到的那份,所以装入/更新确认时把技能目录逐字节拷成快照(只收普通文件),
+ * 链接指快照而不是随后可被改写的 `brainRoot/<id>/<dir>`。代价是目标路径按
+ * revision 变化:每次更新都换一个新目标,靠对账重指(旧 revision 快照在
+ * receipt 提交后回收)。卸载即断链,由对账回收。
+ * - **两个受管根**:因此本文件同时管理安装根(brainRoot)与批准状态根
+ * (approvalStateRoot);两者都必须由调用方给出,漏给会让活链接被判成外来
+ * 链接而永不撤链 —— 停用/卸载后技能仍对主 Agent 生效,故 approvalStateRoot
+ * 是必填项。
+ * - **绝不误伤**:只删"确认为 symlink/junction 且目标落在上述两个受管根之一"
* 的条目。真实目录(SkillHub 实体技能、用户手放的技能)与外来链接一律不碰,
* 占位冲突只 warn 不覆盖(同 shared-global-skills 的冲突哲学)。
* - **`.claude` 扇出与回收都不归这里管**:对账后调 prepareSharedGlobalSkillLinks,
* 它负责把 `.agents` 新条目 link 进 `.claude`;我们撤链后留下的 `.claude`
* 悬空兼容链接目标指向 `.agents` 受管根,同样由它的 cleanupBrokenManagedLinks
- * 回收——职责分界干净:目标在 brainRoot 的链接归本文件,受管根内的归它。
- * - 多账号:brainRoot 是 owner-scoped,`~/.agents/skills` 是全局的。本函数只
- * 管理 realpath 落在**当前 brainRoot** 内的活链接;他 owner 的活链接不碰
- * (与 SkillHub 实体技能同一跨账号可见性现状)。悬空链接只要目标带
- * `cindy-brain` 路径段就回收(断链对所有消费方都是死重,跨 owner 清理防积尘)。
+ * 回收——职责分界干净:目标在本文件受管根内的链接归本文件,目标在 `.agents`
+ * 受管根内的归它。
+ * - 多账号:两个受管根都是 owner-scoped,`~/.agents/skills` 是全局的。本函数只
+ * 管理 realpath 落在**当前 owner 的受管根**内的活链接;他 owner 的活链接不碰
+ * (与 SkillHub 实体技能同一跨账号可见性现状)。悬空链接按结构判据回收
+ * (断链对所有消费方都是死重,跨 owner 清理防积尘),判据见
+ * `targetLooksGhostManaged`。
*/
import { promises as fsp } from 'node:fs';
@@ -85,6 +96,11 @@ interface ReconcileOptions {
ghosts: InstalledGhost[];
/** 当前 owner 的插件安装根(userData/.../cindy-brain)。 */
brainRoot: string;
+ /**
+ * Host-owned root containing approval-revision-bound skill snapshots.
+ * 必填:漏给会让指向快照的活链接被判成外来链接而永不撤链(见头注释)。
+ */
+ approvalStateRoot: string;
/** 覆盖 home 目录(仅测试)。 */
homeDir?: string;
}
@@ -107,19 +123,33 @@ async function realPathOrNull(value: string): Promise<string | null> {
}
}
-/** 断链回收判据:链接名符合 `<id>--<name>` ghost 命名且目标路径带 `cindy-brain`
- * 段才视为 ghost 托管(跨 owner 通用)。两条同时满足才动手,避免误伤用户创建
- * 的恰巧含该路径段的外来链接。 */
-function targetLooksGhostManaged(target: string, linkName: string): boolean {
+/**
+ * 断链回收判据:链接名符合 `<id>--<name>` ghost 命名,且目标路径命中我们自己
+ * 铺出来的结构 —— 安装根的 `cindy-brain` 段,或批准状态根的
+ * `<状态根名>/skill-snapshots` **相邻两段**。两条同时满足才动手。
+ *
+ * 状态根名要求相邻匹配而不是单看 `skill-snapshots`:后者是个通用名字,单独匹配
+ * 会误删用户自己在别处的 `skill-snapshots/` 下建的外来悬空链接。owner 段在路径
+ * 中间,所以这条判据仍跨 owner 通用。
+ */
+function targetLooksGhostManaged(
+ target: string,
+ linkName: string,
+ approvalStateDirName: string,
+): boolean {
if (!linkName.includes('--')) return false;
- return target
- .split(/[\\/]/)
- .some((segment) => segment.toLowerCase() === 'cindy-brain');
+ const segments = target.split(/[\\/]/).map((segment) => segment.toLowerCase());
+ const stateDirName = approvalStateDirName.toLowerCase();
+ return segments.some(
+ (segment, index) =>
+ segment === 'cindy-brain' ||
+ (segment === stateDirName && segments[index + 1] === 'skill-snapshots'),
+ );
}
/**
- * 共享技能根对账:期望态(启用且带 skill 槽的插件)vs 实际态(根下目标落在
- * brainRoot 的链接)。幂等、best-effort、不 throw;warnings 交调用方记日志。
+ * 共享技能根对账:期望态(启用、已批准且带 skill 槽的插件)vs 实际态(根下目标
+ * 落在受管根内的链接)。幂等、best-effort、不 throw;warnings 交调用方记日志。
*/
export async function reconcileGhostSkillLinks(
opts: ReconcileOptions,
@@ -131,7 +161,12 @@ export async function reconcileGhostSkillLinks(
const { sharedSkillsDir } = sharedGlobalSkillsPaths(opts.homeDir);
// realpath 兼容 brainRoot 或其祖先是 symlink 的场景(relocated home dir)——
// 活链接 realpath 后必须与归一化的物理根比较才可靠。resolve 失败退化到词法。
- const brainRootCompare = (await realPathOrNull(opts.brainRoot)) ?? normalizeForCompare(opts.brainRoot);
+ const managedRootCompares = [
+ (await realPathOrNull(opts.brainRoot)) ?? normalizeForCompare(opts.brainRoot),
+ (await realPathOrNull(opts.approvalStateRoot)) ??
+ normalizeForCompare(opts.approvalStateRoot),
+ ];
+ const approvalStateDirName = path.basename(path.resolve(opts.approvalStateRoot));
try {
await fsp.mkdir(sharedSkillsDir, { recursive: true });
@@ -144,7 +179,14 @@ export async function reconcileGhostSkillLinks(
// first-wins + warn 兜底(name 正则已保证结构上不可能,防御纵深)。
const desired = new Map<string, { target: string; item: GhostSkillItem }>();
const eligible = opts.ghosts
- .filter((g) => g.enabled && g.manifest.slots.includes('skill') && g.manifest.skill)
+ .filter(
+ (g) =>
+ g.enabled &&
+ g.approval.state === 'approved' &&
+ Boolean(g.approvedSkillRoot) &&
+ g.manifest.slots.includes('skill') &&
+ g.manifest.skill,
+ )
.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
for (const ghost of eligible) {
const sortedItems = [...(ghost.manifest.skill?.items ?? [])].sort((a, b) =>
@@ -157,7 +199,7 @@ export async function reconcileGhostSkillLinks(
continue;
}
desired.set(linkName, {
- target: path.join(opts.brainRoot, ghost.manifest.id, ...item.dir.split('/')),
+ target: path.join(ghost.approvedSkillRoot!, ...item.dir.split('/')),
item,
});
}
@@ -179,8 +221,8 @@ export async function reconcileGhostSkillLinks(
const linkPath = path.join(sharedSkillsDir, entName);
const real = await realPathOrNull(linkPath);
if (real !== null) {
- // 活链接:目标在当前 brainRoot 内才归我们管;他 owner / 外来链接不碰。
- if (!isSameOrInside(real, brainRootCompare)) continue;
+ // 活链接:目标在当前 owner 的受管根内才归我们管;他 owner / 外来链接不碰。
+ if (!managedRootCompares.some((root) => isSameOrInside(real, root))) continue;
const want = desired.get(entName);
const wantCompare = want
? ((await realPathOrNull(want.target)) ?? normalizeForCompare(want.target))
@@ -192,7 +234,7 @@ export async function reconcileGhostSkillLinks(
}
continue;
}
- // 断链:目标带 cindy-brain 段即回收(含他 owner 与登出态临时根的残留)。
+ // 断链:目标命中受管结构即回收(含他 owner 与登出态临时根的残留)。
let rawTarget: string;
try {
rawTarget = await fsp.readlink(linkPath);
@@ -202,7 +244,9 @@ export async function reconcileGhostSkillLinks(
const absTarget = path.isAbsolute(rawTarget)
? rawTarget
: path.resolve(sharedSkillsDir, rawTarget);
- if (targetLooksGhostManaged(absTarget, entName)) toRemove.push(entName);
+ if (targetLooksGhostManaged(absTarget, entName, approvalStateDirName)) {
+ toRemove.push(entName);
+ }
}
// —— 删除步:先撤旧再建新,防"改目标"落进冲突分支。
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
index f0b0fbb8c3..040787fc1b 100644
--- a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
@@ -64,7 +64,12 @@ function ghost(id: string, opts: { enabled?: boolean; position?: 'left' | 'tab'
...(opts.position !== undefined ? { position: opts.position } : {}),
},
};
- return { manifest, dir: `/fake/${id}`, enabled: opts.enabled ?? true };
+ return {
+ manifest,
+ dir: `/fake/${id}`,
+ enabled: opts.enabled ?? true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ };
}
function makeHarness(detachableIds: Set<string>) {
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 1fe0f0bd99..a0894ffc11 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -967,7 +967,10 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
},
async forgeScaffold(request): Promise<CindyForgeScaffoldResult> {
const sessionWorkdir = resolveSessionContext()?.workingDir ?? null;
- const result = await scaffoldGhostDir(request, { sessionWorkdir });
+ const result = await scaffoldGhostDir(request, {
+ sessionWorkdir,
+ forbiddenRootDirs: getGhostManager().managedRootDirs(),
+ });
if (result.ok) {
log.info('ghost forge scaffold created', {
dir: result.dir,
@@ -978,7 +981,9 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
return result;
},
async forgePack({ dir }): Promise<CindyForgePackResult> {
- const packed = await packGhostDir(dir);
+ const packed = await packGhostDir(dir, {
+ forbiddenRootDirs: getGhostManager().managedRootDirs(),
+ });
if (!packed.ok) return packed;
// 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
// 自动转"更新 vX → vY"),用户点头才真装。
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 3f0c5256ed..a9a5171108 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -9,6 +9,10 @@ const runtime = vi.hoisted(() => ({
manifest: Record<string, unknown>;
dir: string;
enabled: boolean;
+ approval?: {
+ state: 'approved';
+ revision: string;
+ };
}>,
install: vi.fn(),
uninstall: vi.fn(),
@@ -45,7 +49,16 @@ vi.mock('../../logger.js', () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
vi.mock('../../cindy-brain/index.js', () => ({
- getGhostManager: () => ({ list: () => runtime.ghosts }),
+ getGhostManager: () => ({
+ list: () =>
+ runtime.ghosts.map((ghost) => ({
+ ...ghost,
+ approval: ghost.approval ?? {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ })),
+ }),
isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),
installOrUpdateMarketGhostPackage: runtime.install,
isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),
@@ -63,6 +76,8 @@ import type { PluginMarketApi } from '../api';
const roots: string[] = [];
const PLUGIN_ID = `c${'a'.repeat(24)}`;
+const APPROVED_INSTALL_TOKEN =
+ 'approved:00000000-0000-4000-8000-000000000001';
afterEach(() => {
runtime.ghosts = [];
@@ -690,6 +705,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
allowPermissionExpansion: true,
}),
).resolves.toMatchObject({
@@ -725,7 +741,77 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
await expect(
- h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('rejects a first install when the same Plugin appears during download', async () => {
+ const item = summary();
+ const h = harness([item]);
+ h.api.download.mockImplementationOnce(async () => {
+ runtime.ghosts = [
+ {
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ },
+ ];
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256,
+ sizeBytes: item.currentRelease.sizeBytes,
+ };
+ });
+
+ await expect(
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('rejects an update when the approved revision changes during download', async () => {
+ const item = summary({
+ currentRelease: { ...summary().currentRelease, version: '2.0.0' },
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-0',
+ version: '1.0.0',
+ });
+ runtime.ghosts = [
+ {
+ manifest: manifest('cindy-test', '1.0.0'),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ },
+ ];
+ h.api.download.mockImplementationOnce(async () => {
+ runtime.ghosts[0]!.approval = {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ };
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256,
+ sizeBytes: item.currentRelease.sizeBytes,
+ };
+ });
+
+ await expect(
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }),
).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 1ae767143c..cf758fe251 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -1,6 +1,7 @@
import { ipcMain } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
+import { isGhostInstallApprovalToken } from '../../shared/ghost.js';
import { setGhostUninstallLedgerPreparer } from '../cindy-brain/index.js';
import { createLogger } from '../logger.js';
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
@@ -58,14 +59,28 @@ export function registerPluginMarketIpc(): void {
typeof options === 'object' && options !== null
? (options as {
expectedReleaseId?: unknown;
+ expectedInstalledApproval?: unknown;
allowPermissionExpansion?: 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 allowPermissionExpansion = obj?.allowPermissionExpansion === true;
return invokePluginMarket(() =>
service().install(requireString(pluginId, 'pluginId'), {
expectedReleaseId,
+ ...(expectedInstalledApproval !== undefined
+ ? { expectedInstalledApproval }
+ : {}),
allowPermissionExpansion,
}),
);
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 4e29b13345..adb3f1aeda 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -10,7 +10,8 @@ import {
import { app, type WebContents } from 'electron';
import {
- diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
+ ghostInstallApprovalToken,
isOfficialGhostId,
validateGhostManifest,
type InstalledGhost,
@@ -234,6 +235,7 @@ export class PluginMarketService {
/** Renderer 确认框实际展示过的 release。Main 重拉详情后必须仍一致,
* 否则用户审阅 A、实际安装/启用 B(review P1)。 */
expectedReleaseId: string;
+ expectedInstalledApproval?: string;
allowPermissionExpansion?: boolean;
},
): Promise<{ ghost: InstalledGhost }> {
@@ -266,12 +268,13 @@ export class PluginMarketService {
}
const existing = getGhostManager()
.list()
- .some((ghost) => ghost.manifest.id === plugin.ghostId);
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
return {
ghost: await this.installDetail(
plugin,
{
- expectedInstalled: existing,
+ expectedInstalled: Boolean(existing),
+ expectedInstalledApproval: options.expectedInstalledApproval,
allowPermissionExpansion: options.allowPermissionExpansion === true,
},
owner,
@@ -344,6 +347,7 @@ export class PluginMarketService {
plugin: VisiblePluginDetail,
options: {
allowPermissionExpansion?: boolean;
+ expectedInstalledApproval?: string;
/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
} = { expectedInstalled: false },
@@ -361,6 +365,16 @@ export class PluginMarketService {
if (existing && (!currentRecord?.installed || currentRecord.pluginId !== plugin.id)) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
+ if (
+ existing &&
+ ghostInstallApprovalToken(existing.approval) !==
+ options.expectedInstalledApproval
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state changed after permission review',
+ );
+ }
const compatible = validateGhostManifest(plugin.currentRelease.manifest);
if (!compatible.ok) {
@@ -368,7 +382,7 @@ export class PluginMarketService {
}
if (
existing &&
- diffGhostPermissionItems(existing.manifest, compatible.manifest).added.length > 0 &&
+ diffInstalledGhostPermissionItems(existing, compatible.manifest).added.length > 0 &&
options.allowPermissionExpansion !== true
) {
throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
@@ -396,7 +410,7 @@ export class PluginMarketService {
if (options.expectedInstalled) {
const stillInstalled = getGhostManager()
.list()
- .some((ghost) => ghost.manifest.id === plugin.ghostId);
+ .find((ghost) => ghost.manifest.id === plugin.ghostId);
if (!stillInstalled) {
// 用户确认的是更新;下载期间若另一窗口已卸载目标,不能把操作
// 降级成首装并自动启用。按状态变化拒绝,由 renderer 刷新重试。
@@ -405,12 +419,36 @@ export class PluginMarketService {
'Plugin was uninstalled while the update was downloading',
);
}
+ if (
+ ghostInstallApprovalToken(stillInstalled.approval) !==
+ 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,
+ ...(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.
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 9f06c78d15..cbca158e93 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -848,7 +848,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:install', lizFilePath, opts),
update: (
lizFilePath: string,
- opts: { expectedPackageSha256: string },
+ opts: {
+ expectedPackageSha256: string;
+ expectedInstalledApproval: string;
+ },
): Promise<{ ghost: unknown }> =>
ipcRenderer.invoke('ghosts:update', lizFilePath, opts),
cindyPrefsSync: (
@@ -973,7 +976,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('plugin-market:detail', pluginId),
install: (
pluginId: string,
- options: { expectedReleaseId: string; allowPermissionExpansion?: boolean },
+ options: {
+ expectedReleaseId: string;
+ expectedInstalledApproval?: string;
+ allowPermissionExpansion?: boolean;
+ },
): Promise<{ ghost: import('../shared/ghost').InstalledGhost }> =>
ipcRenderer.invoke('plugin-market:install', pluginId, options),
uninstall: (pluginId: string): Promise<{ ok: true }> =>
diff --git a/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts b/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts
index 7ab7ef1e8f..fa98706fa4 100644
--- a/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts
@@ -65,6 +65,7 @@ function makeGhost(
manifest,
dir: '',
enabled: opts.enabled ?? true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
...(opts.icon ? { iconDataUrl: opts.icon } : {}),
};
}
diff --git a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
index dd78e8eb36..54b224d0eb 100644
--- a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts
@@ -32,6 +32,7 @@ function ghost(command: string, id = command, enabled = true): InstalledGhost {
},
dir: `/tmp/${id}`,
enabled,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
};
}
diff --git a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts
index 1ae575437f..01c24ad653 100644
--- a/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/planModeComposerEntry.test.ts
@@ -50,6 +50,7 @@ const installedPlugin: InstalledGhost = {
},
dir: '/tmp/cindy-art',
enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
};
const installedMermaidPlugin: InstalledGhost = {
@@ -66,6 +67,7 @@ const installedMermaidPlugin: InstalledGhost = {
},
dir: '/tmp/cindy-mermaid',
enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
};
afterEach(() => {
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx
index 0cce10488b..799d81dcfb 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx
@@ -36,7 +36,12 @@ function ghost(id: string, enabled = true): InstalledGhost {
slots: ['panel'],
panel: { title: `${id} 面板`, html: 'panel.html' },
};
- return { manifest, dir: `/fake/${id}`, enabled };
+ return {
+ manifest,
+ dir: `/fake/${id}`,
+ enabled,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ };
}
function stubGhostsBridge(ghosts: InstalledGhost[]): void {
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
index f555426fb5..4603ad0774 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx
@@ -26,7 +26,12 @@ function ghost(id: string, panel?: GhostManifest['panel'] | null, enabled = true
slots: panel === null ? ['tool'] : ['panel'],
...(panel === null ? {} : { panel: panel ?? { title: id, html: 'panel.html' } }),
};
- return { manifest, dir: `/fake/${id}`, enabled };
+ return {
+ manifest,
+ dir: `/fake/${id}`,
+ enabled,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ };
}
afterEach(() => {
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
index 76570075a6..41a821e0d8 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts
@@ -54,6 +54,7 @@ function installed(overrides: Partial<InstalledGhost> = {}): InstalledGhost {
manifest: manifest(),
dir: '/tmp/cindy-brain/xd-mivo',
enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
...overrides,
};
}
@@ -101,6 +102,7 @@ describe('ghostPluginViewModel', () => {
version: '1',
enabled: true,
canUse: true,
+ approvalState: 'approved',
},
{
id: 'lizi-mivo',
@@ -109,6 +111,7 @@ describe('ghostPluginViewModel', () => {
version: '1',
enabled: true,
canUse: true,
+ approvalState: 'approved',
},
{
id: 'slack',
@@ -117,6 +120,7 @@ describe('ghostPluginViewModel', () => {
version: '1',
enabled: true,
canUse: true,
+ approvalState: 'approved',
},
] satisfies GhostPluginListItem[];
@@ -212,6 +216,16 @@ describe('ghostPluginViewModel', () => {
expect(item).not.toHaveProperty('whenToUse');
});
+ it('carries the Host approval state so the list can explain an unrunnable install', () => {
+ expect(toGhostPluginListItem(installed()).approvalState).toBe('approved');
+ expect(
+ toGhostPluginListItem(installed({ approval: { state: 'legacy-unapproved' } })).approvalState,
+ ).toBe('legacy-unapproved');
+ expect(
+ toGhostPluginDetail(installed({ approval: { state: 'invalid' } })).approvalState,
+ ).toBe('invalid');
+ });
+
it('derives detail permissions and runtime declarations from the manifest', () => {
const detail = toGhostPluginDetail(installed());
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
index 99fd1a5f85..eaaffd1bca 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
@@ -27,7 +27,12 @@ function ghost(id: string, panel?: GhostManifest['panel'], enabled = true): Inst
slots: ['panel'],
panel: panel ?? { html: 'panel.html', position: 'tab' },
};
- return { manifest, dir: `/fake/${id}`, enabled };
+ return {
+ manifest,
+ dir: `/fake/${id}`,
+ enabled,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ };
}
afterEach(() => {
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
index 73b1d77288..c4c1ea5157 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { toast } from '@/lib/toast';
import { confirmAndInstallGhost } from '../installFlow';
+import type { InstalledGhost } from '../../../shared/ghost';
vi.mock('@/lib/toast', () => ({
toast: { success: vi.fn(), error: vi.fn() },
@@ -30,8 +31,10 @@ const baseManifest = {
function setupWindow(
manifest: object,
installResult: { ghost: { manifest: object } } = { ghost: { manifest } },
+ installedGhosts: InstalledGhost[] = [],
) {
const install = vi.fn(async () => installResult);
+ const update = vi.fn(async () => installResult);
const electronAPI = {
ghosts: {
inspect: vi.fn(async () => ({
@@ -44,15 +47,16 @@ function setupWindow(
reviewed: false,
},
})),
- listSync: vi.fn(() => ({ ghosts: [] })),
+ listSync: vi.fn(() => ({ ghosts: installedGhosts })),
install,
+ update,
},
};
Object.defineProperty(globalThis, 'window', {
value: { electronAPI },
configurable: true,
});
- return { install };
+ return { install, update };
}
function deps(confirm: (options: unknown) => Promise<boolean>) {
@@ -98,6 +102,61 @@ 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 型插件「立即开启并打开页签」', () => {
const tabManifest = {
schemaVersion: 2 as const,
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx
index f11d30d794..63e2682822 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx
@@ -30,6 +30,7 @@ const ghost = (id: string, name = id): InstalledGhost => ({
},
dir: `/brain/${id}`,
enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
});
type ChangedCb = (payload: { ghosts: InstalledGhost[] }) => void;
diff --git a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts b/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts
index 9d079f58fc..4e58f05bce 100644
--- a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts
+++ b/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts
@@ -15,6 +15,10 @@ export function ghostInstallErrorKey(code: string | undefined): string {
return 'settings.ghosts.errors.idReserved';
case 'NOT_FOUND':
return 'settings.ghosts.errors.sourceMissing';
+ // 批准状态相关的前置条件失败在这条链路上只有一种下一步动作:重新确认权限。
+ // 缺少批准记录(启用存量安装)与批准态在确认后变化(更新)都归到这里。
+ case 'PRECONDITION_FAILED':
+ return 'settings.ghosts.errors.approvalRequired';
default:
return 'settings.ghosts.errors.generic';
}
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index fc0a5df0b3..fd1aea7c44 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -5,7 +5,8 @@ import { createLogger } from '@/lib/logger';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
import {
- diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
+ ghostInstallApprovalToken,
ghostPermissionItems,
type GhostManifest,
type GhostTrustInfo,
@@ -91,7 +92,7 @@ async function confirmAndRunUpdate(
): Promise<void> {
const { t, confirm } = deps;
// 权限 diff:只把新增/移除的权限亮给用户,不变项折叠计数。
- const diff = diffGhostPermissionItems(installed.manifest, manifest);
+ const diff = diffInstalledGhostPermissionItems(installed, manifest);
const ok = await confirm({
title: t('settings.ghosts.updateConfirm.title', { name: manifest.name }),
description: t('settings.ghosts.updateConfirm.body', {
@@ -107,6 +108,7 @@ async function confirmAndRunUpdate(
try {
const { ghost } = await window.electronAPI.ghosts.update(lizFilePath, {
expectedPackageSha256: packageSha256,
+ expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
});
toast.success(
t('settings.ghosts.toast.updated', {
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 1e41072555..55f9dd1335 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -67,6 +67,8 @@ interface GhostPluginDetailViewProps {
onToggle: (enabled: boolean) => void;
onUse: () => void;
onUpdate: () => void;
+ /** 缺少批准状态时的恢复入口(重新走一次完整权限确认)。 */
+ onReapprove: () => void;
updateLabel?: string;
/** 市场存在新版本时的目标版本号;设置后头部展示显著的更新按钮。 */
updateVersion?: string;
@@ -128,6 +130,7 @@ export function GhostPluginDetailView({
onToggle,
onUse,
onUpdate,
+ onReapprove,
updateLabel,
updateVersion,
updateBusy = false,
@@ -139,7 +142,9 @@ export function GhostPluginDetailView({
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
const [descriptionOverflows, setDescriptionOverflows] = useState(false);
const descriptionRef = useRef<HTMLParagraphElement>(null);
- const enabled = enabledOverride ?? detail.enabled;
+ // 未批准的安装不可运行:说明现状 + 给恢复入口,不让它看起来只是"被关掉了"。
+ const needsReapproval = detail.approvalState !== 'approved';
+ const enabled = (enabledOverride ?? detail.enabled) && !needsReapproval;
const canUse = enabled && detail.canUse;
const cindyCapabilities = detail.cindyCapabilities;
const hasConfiguration = detail.hasSettingsUi || cindyCapabilities.length > 0;
@@ -220,7 +225,21 @@ export function GhostPluginDetailView({
className="plugin-detail-actions flex shrink-0 flex-nowrap items-center gap-1.5"
style={WINDOW_NO_DRAG_STYLE}
>
- {updateVersion ? (
+ {needsReapproval ? (
+ <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 ? (
<button
type="button"
onClick={onUpdate}
@@ -255,7 +274,7 @@ export function GhostPluginDetailView({
<Switch
checked={enabled}
onCheckedChange={onToggle}
- disabled={toggleDisabled}
+ disabled={toggleDisabled || needsReapproval}
aria-label={t('settings.ghosts.enableAria', { name: detail.name })}
/>
<DropdownMenu>
@@ -318,6 +337,27 @@ export function GhostPluginDetailView({
</button>
) : null}
</div>
+
+ {needsReapproval ? (
+ <div
+ className={cn(
+ 'mt-5 rounded-xl px-4 py-3.5',
+ DETAIL_SURFACE_CLASS,
+ )}
+ role="status"
+ >
+ <p className="text-13 font-medium text-[var(--text-primary)]">
+ {t('settings.ghosts.reapproval.noticeTitle')}
+ </p>
+ <p className="mt-1 text-13 leading-5 text-[var(--text-secondary)]">
+ {t(
+ detail.approvalState === 'invalid'
+ ? 'settings.ghosts.reapproval.bodyInvalid'
+ : 'settings.ghosts.reapproval.bodyLegacy',
+ )}
+ </p>
+ </div>
+ ) : null}
</header>
{hasConfiguration ? (
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 0a9d93c359..8666baee82 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -41,7 +41,8 @@ import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkin
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
import { resolveSystemLocale } from '../../../shared/locale';
import {
- diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
+ ghostInstallApprovalToken,
ghostPanelKind,
ghostPermissionItems,
type GhostSetupStatus,
@@ -71,6 +72,8 @@ import { GhostPluginIcon } from './GhostPluginIcon';
import { MarketPluginDetailView } from './MarketPluginDetailView';
import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker';
import {
+ ghostReapprovalRoute,
+ marketReviewTargetsInstalledGhost,
orderPluginCatalogItems,
pluginPresentationOrigin,
pluginUpdateForInstalledVersion,
@@ -450,21 +453,35 @@ export function GhostPluginPage() {
// 市场更新流程由列表卡片和详情页共用:先取目标 release 的完整 manifest 做
// 权限 diff,经用户确认后才安装,不做静默升级。
+ //
+ // 同版本的 `installed` 也走这里:缺少批准状态的存量安装靠"用市场包重装同一
+ // release"恢复,此时权限 diff 会把目标包的全部权限当新增项逐条列出。
const handleMarketUpdate = useCallback(
async (ghostId: string) => {
const marketItem = marketByGhostId.get(ghostId);
- if (!marketItem || marketItem.installState !== 'update-available') return;
- const installedGhost = ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;
+ if (!marketItem) return;
+ const installedGhost =
+ ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;
+ if (
+ !marketReviewTargetsInstalledGhost(
+ marketItem,
+ installedGhost?.approval.state,
+ )
+ ) {
+ return;
+ }
+ if (!installedGhost) {
+ toast.error(t('settings.ghosts.market.errors.stateChanged'));
+ await refreshMarket();
+ return;
+ }
// 列表每张卡都有直达入口,同步互斥防止并发更新互相覆盖忙碌状态。
const marketBusyLease = acquireMarketBusy(marketItem.pluginId);
if (!marketBusyLease) return;
try {
const next = await window.electronAPI.pluginMarket.detail(marketItem.pluginId);
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
- const diff = diffGhostPermissionItems(
- installedGhost?.manifest ?? next.manifest,
- next.manifest,
- );
+ const diff = diffInstalledGhostPermissionItems(installedGhost, next.manifest);
const approved = await confirm({
title: t('settings.ghosts.updateConfirm.title', { name: next.name }),
description: t('settings.ghosts.updateConfirm.body', {
@@ -479,6 +496,7 @@ export function GhostPluginPage() {
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,
});
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
@@ -518,6 +536,22 @@ export function GhostPluginPage() {
await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });
}, [confirm, confirmWithCheckbox, handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);
+ /**
+ * 缺少批准状态时的恢复入口。市场自有的包重走市场安装确认(重新下载 + 逐项
+ * 权限确认);本地包让用户重新选一次 `.cindy`。两条路都落到同一套权限确认,
+ * 不存在"点一下就悄悄恢复运行"的分支。
+ */
+ const handleReapprove = useCallback(
+ async (ghostId: string) => {
+ if (ghostReapprovalRoute(marketByGhostId.get(ghostId)) === 'market') {
+ await handleMarketUpdate(ghostId);
+ return;
+ }
+ await pickAndUpdateGhost(ghostId, { t, confirm, confirmWithCheckbox });
+ },
+ [confirm, confirmWithCheckbox, handleMarketUpdate, marketByGhostId, t],
+ );
+
const handleInstall = useCallback(async () => {
const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
if (!picked || 'canceled' in picked) return;
@@ -758,7 +792,7 @@ export function GhostPluginPage() {
return;
}
const diff = isUpdate
- ? diffGhostPermissionItems(installedGhost!.manifest, marketDetail.manifest)
+ ? diffInstalledGhostPermissionItems(installedGhost!, marketDetail.manifest)
: null;
try {
const confirmed = await confirm({
@@ -790,6 +824,13 @@ export function GhostPluginPage() {
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 }
: {}),
@@ -858,6 +899,7 @@ export function GhostPluginPage() {
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')
@@ -1033,6 +1075,7 @@ export function GhostPluginPage() {
? () => void handleMarketUpdate(catalogItem.item.id)
: undefined
}
+ onReapprove={() => void handleReapprove(catalogItem.item.id)}
effectiveEnabled={effectiveEnabled(
catalogItem.item.id,
catalogItem.item.enabled,
@@ -1295,6 +1338,7 @@ export function GhostPluginCard({
onUpdate,
updateVersion,
updateBusy = false,
+ onReapprove,
onToggle,
effectiveEnabled,
toggleDisabled = false,
@@ -1308,12 +1352,16 @@ export function GhostPluginCard({
onUpdate?: () => void;
updateVersion?: string;
updateBusy?: boolean;
+ /** 缺少批准状态时的恢复入口;此时它取代"使用"与"更新"按钮。 */
+ onReapprove?: () => void;
onToggle?: (enabled: boolean) => void;
effectiveEnabled?: boolean;
toggleDisabled?: boolean;
onIconLoadError?: () => void;
}) {
const { t } = useTranslation();
+ // 未批准的安装不可运行:开关不给点(点了 Main 也会拒),主动作换成重新确认。
+ const needsReapproval = item.approvalState !== 'approved';
return (
<article
className={cn(
@@ -1342,7 +1390,11 @@ export function GhostPluginCard({
<span className="truncate text-15 font-medium text-[var(--text-primary)]">
{item.name}
</span>
- {updateVersion ? (
+ {needsReapproval ? (
+ <span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium leading-4 text-[var(--text-secondary)]">
+ {t('settings.ghosts.reapproval.badge')}
+ </span>
+ ) : updateVersion ? (
<span className="shrink-0 rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-10 font-medium leading-4 text-[var(--text-secondary)]">
{t('settings.ghosts.market.updateAvailable')}
</span>
@@ -1368,12 +1420,30 @@ export function GhostPluginCard({
{onToggle ? (
<Switch
checked={effectiveEnabled ?? item.enabled}
- disabled={toggleDisabled}
+ disabled={toggleDisabled || needsReapproval}
onCheckedChange={onToggle}
aria-label={t('settings.ghosts.enableAria', { name: item.name })}
/>
) : null}
- {updateVersion && onUpdate ? (
+ {needsReapproval ? (
+ onReapprove ? (
+ <button
+ type="button"
+ onClick={onReapprove}
+ disabled={updateBusy}
+ className={cn(
+ 'inline-flex h-8 shrink-0 items-center justify-center self-center rounded-lg border border-[var(--border-default)] bg-transparent px-3 text-12 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',
+ )}
+ aria-label={t('settings.ghosts.reapproval.actionAria', { name: item.name })}
+ >
+ {t('settings.ghosts.reapproval.action')}
+ </button>
+ ) : null
+ ) : updateVersion && onUpdate ? (
<button
type="button"
onClick={onUpdate}
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index a5528cb774..2710d4dee5 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -37,6 +37,7 @@ const installedPlugin: GhostPluginListItem = {
version: '1.0.0',
enabled: true,
canUse: true,
+ approvalState: 'approved',
};
const marketPlugin: PluginMarketItem = {
@@ -187,6 +188,65 @@ describe('GhostPluginCard', () => {
expect(screen.queryByRole('button', { name: 'settings.ghosts.page.useAria' })).toBeNull();
});
+ it.each(['legacy-unapproved', 'invalid'] as const)(
+ 'states the %s approval and offers review instead of a silent disabled switch',
+ (approvalState) => {
+ const onReapprove = vi.fn();
+ const onToggle = vi.fn();
+ const onAction = vi.fn();
+ render(
+ <GhostPluginCard
+ item={{ ...installedPlugin, approvalState, enabled: false }}
+ onSelect={vi.fn()}
+ onAction={onAction}
+ onUpdate={vi.fn()}
+ updateVersion="1.1.1"
+ onReapprove={onReapprove}
+ onToggle={onToggle}
+ />,
+ );
+
+ expect(screen.getByText('settings.ghosts.reapproval.badge')).toBeTruthy();
+ // 缺批准时状态说明优先于"可更新",不给用户两个互相打架的下一步。
+ expect(screen.queryByText('settings.ghosts.market.updateAvailable')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.page.useAria' })).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'settings.ghosts.market.updateAria' }),
+ ).toBeNull();
+
+ // 开关不给点:点了 Main 也会拒,这里不制造"看着能开却开不了"。
+ const toggle = screen.getByRole('switch') as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ fireEvent.click(toggle);
+ expect(onToggle).not.toHaveBeenCalled();
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'settings.ghosts.reapproval.actionAria' }),
+ );
+ expect(onReapprove).toHaveBeenCalledTimes(1);
+ expect(onAction).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps the approved card on the normal Use and update affordances', () => {
+ render(
+ <GhostPluginCard
+ item={installedPlugin}
+ onSelect={vi.fn()}
+ onAction={vi.fn()}
+ onReapprove={vi.fn()}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ expect(screen.queryByText('settings.ghosts.reapproval.badge')).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'settings.ghosts.reapproval.actionAria' }),
+ ).toBeNull();
+ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(false);
+ expect(screen.getByRole('button', { name: 'settings.ghosts.page.useAria' })).toBeTruthy();
+ });
+
it('keeps the update action interactive while Use is locked, and blocks it when busy', () => {
const onUpdate = vi.fn();
render(
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 9caf4ab337..5ce6a72568 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -99,6 +99,7 @@ const detail: GhostPluginDetail = {
version: '1.2.3',
enabled: true,
canUse: true,
+ approvalState: 'approved',
author: 'XD',
contents: ['code'],
permissions: [],
@@ -144,6 +145,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={vi.fn()}
+ onReapprove={vi.fn()}
onUninstall={vi.fn()}
toggleDisabled={false}
/>,
@@ -185,6 +187,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={vi.fn()}
+ onReapprove={vi.fn()}
onUninstall={vi.fn()}
toggleDisabled={false}
onIconLoadError={onIconLoadError}
@@ -215,6 +218,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={onUpdate}
+ onReapprove={vi.fn()}
updateVersion={detail.version}
onUninstall={vi.fn()}
toggleDisabled={false}
@@ -230,6 +234,56 @@ describe('Ghost plugin detail sections', () => {
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}
+ 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();
+ expect(
+ (screen.getByRole('button', { name: 'settings.ghosts.detail.useAction' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+
+ const toggle = screen.getByRole('switch') 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',
@@ -250,6 +304,7 @@ describe('Ghost plugin detail sections', () => {
onToggle={vi.fn()}
onUse={vi.fn()}
onUpdate={onUpdate}
+ onReapprove={vi.fn()}
updateLabel="Update from market"
updateVersion="1.2.4"
updateBusy
diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
index 5461987c1a..a579447a7b 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import type { PluginMarketItem } from '../../../../../shared/pluginMarket';
import {
+ ghostReapprovalRoute,
+ marketReviewTargetsInstalledGhost,
orderPluginCatalogItems,
pluginPresentationOrigin,
pluginUpdateForInstalledVersion,
@@ -29,6 +31,51 @@ 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');
diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index 9d2e0703e7..a81e3795ea 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@ -9,6 +9,7 @@
import {
ghostContentKeys,
ghostPermissionItems,
+ type GhostInstallApproval,
type GhostPermissionItem,
type GhostTrustInfo,
type GhostToolDecl,
@@ -23,6 +24,11 @@ export interface GhostPluginListItem {
version: string;
enabled: boolean;
canUse: boolean;
+ /**
+ * Host 是否持有一次明确的安装/更新确认。非 `approved` 的安装不可运行,列表与
+ * 详情都必须如实说明并给出重新确认入口,而不是让它看起来只是"被关掉了"。
+ */
+ approvalState: GhostInstallApproval['state'];
trust?: GhostTrustInfo;
iconDataUrl?: string;
}
@@ -163,6 +169,7 @@ export function toGhostPluginListItem(
version: manifest.version,
enabled: ghost.enabled,
canUse: Boolean(manifest.command),
+ approvalState: ghost.approval.state,
trust: ghost.trust ?? {
level: 'unverified',
publisherSigned: false,
diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
index 09964e33ad..ab9d6f94fc 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts
@@ -5,6 +5,7 @@
* public Plugin is installed by default is an installation policy, not a source.
* An installed Ghost without a matching market record remains local.
*/
+import type { GhostInstallApproval } from '../../../../shared/ghost';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
export type PluginPresentationOrigin =
@@ -40,6 +41,36 @@ export function pluginUpdateForInstalledVersion(
return item?.installState === 'update-available' ? item : null;
}
+/**
+ * Whether the market install flow may run against an already-installed Plugin.
+ *
+ * A pending release is the usual case. The same release is also allowed when the
+ * install carries no Host approval: re-installing that exact release is how such
+ * an install gets reviewed again, and the flow shows every permission as newly
+ * requested. An approved install at the current release has nothing to review.
+ */
+export function marketReviewTargetsInstalledGhost(
+ item: Pick<PluginMarketItem, 'installState'> | null | undefined,
+ approvalState: GhostInstallApproval['state'] | undefined,
+): boolean {
+ if (item?.installState === 'update-available') return true;
+ return item?.installState === 'installed' && approvalState !== undefined && approvalState !== 'approved';
+}
+
+/**
+ * Where an unapproved install gets reviewed again. Market-owned installs replay
+ * the market confirmation; anything else needs the user to point at a `.cindy`
+ * package. Both routes end in the same permission confirmation — there is no
+ * path that restores an install without one.
+ */
+export function ghostReapprovalRoute(
+ item: Pick<PluginMarketItem, 'installState'> | null | undefined,
+): 'market' | 'local-package' {
+ return item?.installState === 'installed' || item?.installState === 'update-available'
+ ? 'market'
+ : 'local-package';
+}
+
/**
* Keeps the complete catalog in server order while rendering an installed card
* for market records already owned by this client. Local-only installs have no
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 94bbf48cb4..30ab8388e6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2563,6 +2563,14 @@
"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."
},
+ "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."
+ },
"install": "Install Plugin…",
"empty": "No plugins installed yet",
"emptyHint": "Install from the market, or import a .cindy file from the menu above",
@@ -2731,6 +2739,7 @@
"errors": {
"fileInvalid": "Not a valid .cindy plugin file",
"alreadyInstalled": "This plugin is already installed",
+ "approvalRequired": "This plugin's permissions must be reviewed again before continuing.",
"commandConflict": "Its command conflicts with an installed plugin. Uninstall the other one or rename the command.",
"idReserved": "This id uses the reserved official prefix cindy-; it is only available to plugins bundled with the app",
"sourceMissing": "The selected file could not be found",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 67f1e2c0d5..d421fb8c3b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2562,6 +2562,14 @@
"installConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してからインストールします。インストール完了後は自動的に有効になり、いつでも無効化や設定の変更ができます。",
"updateConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してから、既存のバージョンを置き換えます。現在の有効/無効の状態は変わりません。"
},
+ "reapproval": {
+ "badge": "権限の再確認が必要",
+ "action": "権限を再確認",
+ "actionAria": "プラグイン「{{name}}」の権限を再確認",
+ "noticeTitle": "権限の再確認が必要",
+ "bodyLegacy": "このプラグインの権限確認の記録が Cindy にないため、無効のままにしています。「権限を再確認」から要求される権限を確認し、あらためて許可してください。",
+ "bodyInvalid": "このプラグインの権限確認の記録が壊れているため、無効のままにしています。「権限を再確認」から要求される権限を確認し、あらためて許可してください。"
+ },
"install": "プラグインをインストール…",
"empty": "まだプラグインがインストールされていません",
"emptyHint": "マーケットからインストールするか、上のメニューから .cindy ファイルを読み込めます",
@@ -2730,6 +2738,7 @@
"errors": {
"fileInvalid": "有効な .cindy プラグインファイルではありません",
"alreadyInstalled": "このプラグインは既にインストールされています",
+ "approvalRequired": "続けるには、このプラグインの権限を再確認する必要があります",
"commandConflict": "コマンドがインストール済みのプラグインと重複しています。先に相手をアンインストールするか、コマンド名を変更してください。",
"idReserved": "この id は公式予約プレフィックス cindy- を使用しています。アプリに同梱されたプラグインのみ使用できます",
"sourceMissing": "選択したファイルが見つかりません",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index aa647ed5c5..d9f299e782 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2562,6 +2562,14 @@
"installConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 설치합니다. 설치가 완료되면 자동으로 활성화되며, 언제든지 비활성화하거나 설정을 변경할 수 있습니다.",
"updateConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 기존 버전을 교체합니다. 현재 활성화 상태는 그대로 유지됩니다."
},
+ "reapproval": {
+ "badge": "권한 재확인 필요",
+ "action": "권한 다시 확인",
+ "actionAria": "플러그인 {{name}}의 권한 다시 확인",
+ "noticeTitle": "권한 재확인 필요",
+ "bodyLegacy": "Cindy에 이 플러그인의 권한 확인 기록이 없어 사용 중지한 상태입니다. [권한 다시 확인]에서 요청하는 권한을 확인하고 다시 허용해 주세요.",
+ "bodyInvalid": "이 플러그인의 권한 확인 기록이 손상되어 사용 중지한 상태입니다. [권한 다시 확인]에서 요청하는 권한을 확인하고 다시 허용해 주세요."
+ },
"install": "플러그인 설치…",
"empty": "아직 설치된 플러그인이 없습니다",
"emptyHint": "마켓에서 설치하거나 위 메뉴에서 .cindy 파일을 가져올 수 있습니다",
@@ -2730,6 +2738,7 @@
"errors": {
"fileInvalid": "유효한 .cindy 플러그인 파일이 아닙니다",
"alreadyInstalled": "이 플러그인은 이미 설치되어 있습니다",
+ "approvalRequired": "계속하려면 이 플러그인의 권한을 다시 확인해야 합니다",
"commandConflict": "명령어가 설치된 플러그인과 충돌합니다. 먼저 상대를 제거하거나 명령어 이름을 변경하세요.",
"idReserved": "이 id는 공식 예약 접두사 cindy-를 사용합니다. 앱에 내장된 플러그인만 사용할 수 있습니다",
"sourceMissing": "선택한 파일을 찾을 수 없습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 811bc6441a..0c83ca18aa 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2562,6 +2562,14 @@
"installConfirmDescription": "安装包将经过完整性与清单校验。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",
"updateConfirmDescription": "安装包将经过完整性与清单校验,并替换现有版本。当前生效状态保持不变。"
},
+ "reapproval": {
+ "badge": "需要重新确认权限",
+ "action": "重新确认权限",
+ "actionAria": "重新确认插件「{{name}}」的权限",
+ "noticeTitle": "需要重新确认权限",
+ "bodyLegacy": "Cindy 没有这个插件的权限确认记录,所以先把它停用了。点「重新确认权限」重新过一遍它要的权限,确认后即可继续使用。",
+ "bodyInvalid": "这个插件的权限确认记录已损坏,所以先把它停用了。点「重新确认权限」重新过一遍它要的权限,确认后即可继续使用。"
+ },
"install": "安装插件…",
"empty": "还没有安装任何插件",
"emptyHint": "可从插件市场安装,或点击右上角导入 .cindy 文件",
@@ -2730,6 +2738,7 @@
"errors": {
"fileInvalid": "不是合法的 .cindy 插件文件",
"alreadyInstalled": "这个插件已经安装",
+ "approvalRequired": "需要重新确认这个插件的权限后才能继续",
"commandConflict": "它的指令和已装插件撞名了,先卸载占用方或让作者改名",
"idReserved": "该 id 使用了官方保留前缀 cindy-,仅随应用内置的插件可用",
"sourceMissing": "找不到所选文件",
diff --git a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
index 4c10098ccc..894589ab27 100644
--- a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
@@ -37,7 +37,12 @@ function ghost(
},
}),
};
- return { manifest, dir: `/fake/${id}`, enabled: opts.enabled ?? true };
+ return {
+ manifest,
+ dir: `/fake/${id}`,
+ enabled: opts.enabled ?? true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ };
}
afterEach(() => {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6242f060ea..040748999d 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1073,7 +1073,10 @@ interface ElectronAPI {
/** 原位更新(同 id 换版):唤醒状态与面板位置延续,沙箱熄灯待重拉。 */
update: (
lizFilePath: string,
- opts: { expectedPackageSha256: string },
+ opts: {
+ expectedPackageSha256: string;
+ expectedInstalledApproval: string;
+ },
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
/**
* cindy 槽后端覆盖:首帧同步读(规则 7);overrides 键为 "image.generate"
@@ -1281,7 +1284,11 @@ interface ElectronAPI {
) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;
install: (
pluginId: string,
- options: { expectedReleaseId: string; allowPermissionExpansion?: boolean },
+ options: {
+ expectedReleaseId: string;
+ expectedInstalledApproval?: string;
+ allowPermissionExpansion?: boolean;
+ },
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
uninstall: (pluginId: string) => Promise<{ ok: true }>;
};
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 87f57cd1f9..ea16043014 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1248,16 +1248,50 @@ export interface GhostManifestLocaleResource {
/** 单个插件 locale JSON 的字节上限。Forge 与装入侧共用,避免两端契约漂移。 */
export const GHOST_LOCALE_MAX_BYTES = 64 * 1024;
-/** 已装入主机的意识(清单 + 安装位置 + 启用态)。 */
+/**
+ * Host 对插件安装状态的批准结论。
+ *
+ * `approved` 的 revision 由 Main 在一次完整安装/更新确认事务中生成;另外两态
+ * 都不构成运行授权,更新 UI 必须把目标包的全部权限按新增项重新展示。
+ */
+export type GhostInstallApproval =
+ | { state: 'approved'; revision: string }
+ | { state: 'legacy-unapproved' }
+ | { state: 'invalid' };
+
+/** 把批准态投影成跨进程更新事务使用的稳定 token。 */
+export function ghostInstallApprovalToken(approval: GhostInstallApproval | undefined): string {
+ if (approval?.state === 'approved') return `approved:${approval.revision}`;
+ return approval?.state ?? 'legacy-unapproved';
+}
+
+/** 更新 IPC 只接受 Host 列表曾下发过的批准态 token。 */
+export function isGhostInstallApprovalToken(value: unknown): value is string {
+ return (
+ value === 'legacy-unapproved' ||
+ value === 'invalid' ||
+ (typeof value === 'string' &&
+ /^approved:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(
+ value,
+ ))
+ );
+}
+
+/** 已装入主机的插件(批准清单 + 安装位置 + 启用态)。 */
export interface InstalledGhost {
manifest: GhostManifest;
/** 安装目录绝对路径(userData/brain/<id>)。 */
dir: string;
/**
- * 是否启用。停用 = 面板与能力休眠(不注册、不渲染),但意识仍装着、
- * 布局位置保留;重新启用即恢复。真身是安装目录里的 `.disabled` 标记文件。
+ * 是否启用。停用 = 面板与能力休眠(不注册、不渲染),但插件仍装着、
+ * 布局位置保留;重新启用即恢复。批准安装的真身在 Host receipt 中;
+ * 安装目录里的 `.disabled` 只保留为旧版本兼容镜像。
*/
enabled: boolean;
+ /** Host 是否持有一次明确安装/更新确认形成的批准快照。 */
+ approval: GhostInstallApproval;
+ /** Host-owned approval-revision snapshot root for approved skill directories. */
+ approvedSkillRoot?: string;
/** 安装时由主机验出的来源/签名等级;作者清单不能自报。 */
trust?: GhostTrustInfo;
/**
@@ -1759,6 +1793,25 @@ export function diffGhostPermissionItems(
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: [],
+ };
+}
+
/**
* icon 允许的图片扩展名 → mime(校验与 main 读盘供图共用同一口径)。
* 不收 svg:svg 可携带脚本,虽经 <img> 渲染不执行,仍不给这个面。
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index a45f57606e..6063512c8d 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -28,6 +28,7 @@
| 身份卡字段与校验、管子协议类型 | `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` |
+| 安装批准事实(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`、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts` |
| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |
| 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |
@@ -60,14 +61,42 @@
也不构成授权。
- 新增或修改 slot 时,除同步编写手册与校验(下节 5)外,还必须同步 shared 类型、
preload/host handler、权限 UI(`GhostPermissionList.tsx`)、错误边界和测试。
+- **授权事实由 Host receipt 持有,不由安装目录持有。** 一次明确的安装/更新确认写出
+ 一份 receipt(`ghostInstallReceipt.ts`),落在**安装根之外**的 owner-scoped 状态根里,
+ 钉住这次批准过的 manifest、trust、启停态和一个随机 `revision`;`GhostManager.list()`
+ 只从 receipt 取这些字段,安装目录里的 `ghost.json` / `.cindy-trust.json` / `.disabled`
+ 退化为旧版本兼容镜像。理由是可变安装目录曾经就是授权事实本身:就地改写
+ `ghost.json` 能让权限 diff 显示"无新增",未确认的 slot 因此拿到运行授权。
+ - 没有 receipt(旧安装)或 receipt 损坏 = **不构成运行授权**:一律按停用列出、
+ 不许启用、不参与技能落链;恢复只能走一次完整重新确认(`diffInstalledGhostPermissionItems`
+ 在无批准基线时把候选包的**全部**权限当新增项展示)。UI 必须如实说出这个状态并
+ 给出恢复入口,不能让它看起来只是"被用户关掉了"。
+ - 跨进程更新事务用 `ghostInstallApprovalToken()` 把批准态投影成 token:Renderer 把
+ 确认时看到的 token 回传,Main 重新读状态比对,不一致就拒(`state-changed`)。
+ token 是前置条件不是凭证——真值一律由 Main 现读。
+ - receipt 保证的是**授权事实**,**不是安装内容此后一直没被改过**:逻辑页代码仍从可变
+ 安装目录加载,`packageSha256` 只是批准时点的来源指纹、运行时不校验(见第 6 节)。
+- **Forge 的源码区与 Host 受管根互斥。** `ghost_forge_scaffold` / `ghost_forge_pack` 的目标
+ 必须是当前会话工作目录里的独立作者目录;命中安装根或批准状态根一律拒
+ (pack 返回 `SOURCE_IS_INSTALLED_PLUGIN`)。判定按 realpath 比对受管根,同时挡住大小写
+ 折叠与软链/junction 别名。理由不是洁癖:在已安装目录里就地制作"更新包"会让版本与
+ 权限 diff 以被改过的现场为基线,把未经确认的 manifest 送进运行时授权。
- `skill` 槽是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局
生效、不随 workdir 级停用隐藏。其安全边界是**声明一致性**(manifest 里的
name/description 必须与 SKILL.md frontmatter 逐字一致,`skillSlot.ts` 的
- `checkSkillMdConsistency` 是唯一裁判,打包与装入两侧共用)+ **链接对账**
- (`reconcileGhostSkillLinks` 只增删"目标落在 cindy-brain 安装根内的
- symlink/junction",绝不触碰真实目录与外来链接;启用挂链、停用/卸载撤链、
- 断链自愈)。改动技能落链、命名(`<id>--<name>`,name 侧禁 `--`)或对账判据前,
- 必须先读 `skillSlot.ts` 头注释并保持上述不变量。
+ `checkSkillMdConsistency` 是唯一裁判,打包与装入、以及批准快照三侧共用)+
+ **批准快照**(确认时把技能目录逐字节拷进
+ `<状态根>/skill-snapshots/<id>/<revision>`,只收普通文件;确认框看到的 SKILL.md
+ 必须就是 Agent 之后读到的那份,所以共享技能根的链接指快照而不是可被改写的
+ `cindy-brain/<id>/<dir>`)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在
+ 安装根或批准状态根内的 symlink/junction",绝不触碰真实目录与外来链接;
+ 启用挂链、停用/卸载撤链、断链自愈)。快照目标带 revision,因此每次更新都换目标、
+ 靠对账重指,旧 revision 在 receipt 提交后回收。改动技能落链、命名
+ (`<id>--<name>`,name 侧禁 `--`)、快照或对账判据前,必须先读 `skillSlot.ts`
+ 头注释并保持上述不变量;`approvalStateRoot` 是必填项——漏给会让指向快照的活链接被
+ 判成外来链接而永不撤链,停用/卸载后技能仍对主 Agent 生效。
+- 收敛方向不对称:**启用需要有效批准状态,停用必须永远能成功**。停用是安全方向,不
+ 能因为快照缺失之类的环境问题把插件卡在"既不能用也不能关"。
## 4. 网络、凭证与资源交接
@@ -125,6 +154,13 @@
- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机
同名路径,无法证明来源时 **fail closed**。
- 手机版仍需把历史 mivo 动作按钮降级为纯展示。
+- **安装内容字节仍可变、且加载时不校验。** 批准 receipt 钉住的是授权事实
+ (manifest/trust/启停/revision),逻辑页代码仍从 `cindy-brain/<id>/` 现读;
+ `packageSha256` 只是批准时点的来源指纹(市场/本地包 = `.cindy` 文件哈希,随包种子 =
+ 内容目录哈希),**没有任何运行期校验消费它**。因此能写这个目录的本机进程仍可替换
+ 代码,只是被限制在**此前已批准的权限集**内运行,且不能借改写 `ghost.json` 扩权。
+ 技能目录因为越出沙箱已单独拷成快照(第 3 节),其余内容的持续完整性校验仍未做——
+ 改动装入链路时不得声称已有内容完整性保证。
## 7. 远程与手机版
@@ -140,16 +176,21 @@ topic 路由;产品层多端语义见
1. 沙箱是否保持进程隔离、专属 partition、无 Node/宿主 FS/网络直连?身份是否由主机
反查而非信任 sender 自报?
2. 新能力是否先在 manifest 声明 slot、走同一套校验、在确认框如实展示后才由 host 授权?
-3. 网络是否限白名单域名、凭证无明文读回?附件/媒体/目录是否经归属校验的
+3. 运行授权是否只取自 Host receipt,而不是可变安装目录?无批准/损坏批准是否 fail
+ closed(列为停用、不许启用、不落技能链),且 UI 如实说明并给出重新确认入口?停用
+ 方向是否无论环境如何都能成功?改了技能落链或快照时 `approvalStateRoot` 是否仍必填?
+4. 网络是否限白名单域名、凭证无明文读回?附件/媒体/目录是否经归属校验的
grant/deposit/ledger 交接,未暴露宿主绝对路径?
-4. 内联凭证是否只走 trusted Desktop 专用 IPC,未登记 device-link?Main 是否重新校验
+5. 内联凭证是否只走 trusted Desktop 专用 IPC,未登记 device-link?Main 是否重新校验
sender、request、revision、action、精确字段集合与 manifest 绑定,且没有把 Renderer
字段 id 直接当作 Secret key/路径?保险库写失败是否不 emit,写成功后是否仍重新
assessment,而不是把“提交完成”当作 ready?
-5. 改动是否命中作者可见契约(身份卡/管子/模型 slot/面板供片/打包)?命中就必须
+6. Forge(scaffold/pack)是否排除了 Host 受管根(安装根 + 批准状态根),且按 realpath
+ 判定、挡住大小写与软链/junction 别名?
+7. 改动是否命中作者可见契约(身份卡/管子/模型 slot/面板供片/打包)?命中就必须
同步 `FORGE_GUIDE` 并在 PR 说明;漏同步 = P1。
-6. 第 6 节的已知缺口是否被触及?触及是否一并修复或留了正式跟踪?
-7. 新增 IPC/推送是否需要远程/手机版?需要就登记 device-link 白名单与 topic 路由。
+8. 第 6 节的已知缺口是否被触及?触及是否一并修复或留了正式跟踪?
+9. 新增 IPC/推送是否需要远程/手机版?需要就登记 device-link 白名单与 topic 路由。
最小验证入口:
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 8af395fe89..da64c706fc 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -154,6 +154,7 @@ export type CindyGhostCallResult =
/** ghost_forge_pack 的结构化失败分类(host 侧产生,原样透传给 agent)。 */
export type CindyForgePackErrorCode =
| 'DIR_NOT_FOUND' // 目录不存在或不是目录
+ | 'SOURCE_IS_INSTALLED_PLUGIN' // 源目录命中 Host 管理的已安装插件或批准状态根
| 'MANIFEST_INVALID' // ghost.json 缺失 / 不合法(message 带具体原因)
| 'ENTRY_MISSING' // 清单声明的 entry / panel.html 等文件不在目录里
| 'TOO_LARGE' // 文件数或总体积超上限