Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 快照校验改在复制后的字节上,撤销批准失败退回进程内隔离

Yuewei-LL6e5b181c3428
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 8c468910ce..4e6c5ff967 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -60,6 +60,8 @@ const TRUST_METADATA_FILE = '.cindy-trust.json';
export interface GhostManagerLogger {
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
+ /** 可选:仅用于"本该收敛却失败"的状态(如撤销批准失败后转进程内隔离)。 */
+ error?(message: string, meta?: Record<string, unknown>): void;
}
export interface GhostManagerOptions {
@@ -110,6 +112,15 @@ export type UninstallRejection =
export class GhostManager {
private readonly receiptStore: GhostInstallReceiptStore;
private mutationTail: Promise<void> = Promise.resolve();
+ /**
+ * 本进程内被判定"批准状态不可信"的插件 id。
+ *
+ * 用途只有一个:撤销陈旧批准**失败**时的兜底。撤销失败的成因(状态根不可写)与
+ * 写批准失败的成因是同一个,所以不能再指望往状态根写任何东西来表达"已失效" ——
+ * 内存标记是此时唯一还能用的机制。下次启动重新对账,成功即自愈;仍然失败就仍然
+ * 隔离,始终 fail closed。
+ */
+ private readonly untrustedApprovals = new Set<string>();
constructor(private readonly options: GhostManagerOptions) {
this.receiptStore = new GhostInstallReceiptStore(
@@ -138,6 +149,20 @@ export class GhostManager {
return this.receiptStore.rootDir();
}
+ /**
+ * 读批准状态的**唯一入口**:进程内隔离优先于磁盘上的 receipt。
+ *
+ * 所有消费方(list / setEnabled / update 的 token 比对)都必须走这里 —— 各自直接
+ * 调 receiptStore.read() 会让隔离在某条路径上失效,那类"同一判定散落多处"的分叉
+ * 正是本 PR 前几轮反复出问题的原因。
+ */
+ private readApproval(id: string): GhostInstallReceiptReadResult {
+ if (this.untrustedApprovals.has(id)) {
+ return { state: 'invalid', reason: '批准状态已被判定不可信(撤销失败)' };
+ }
+ return this.receiptStore.read(id);
+ }
+
/** Serialize content-directory and approval-receipt mutations as one Host transaction lane. */
async runExclusiveMutation<T>(operation: () => Promise<T>): Promise<T> {
const previous = this.mutationTail;
@@ -173,7 +198,7 @@ export class GhostManager {
this.options.log?.warn('ghost dir skipped: invalid directory id', { dir });
continue;
}
- const approvalResult = this.receiptStore.read(entry.name);
+ const approvalResult = this.readApproval(entry.name);
if (approvalResult.state === 'approved') {
const receipt = approvalResult.receipt;
const localizedManifest = this.localizeApprovedManifest(receipt);
@@ -324,7 +349,7 @@ export class GhostManager {
if (!(await pathExists(dir))) {
return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
}
- const receiptResult = this.receiptStore.read(id);
+ const receiptResult = this.readApproval(id);
if (receiptResult.state !== 'approved' && enabled) {
return {
rejection: {
@@ -797,6 +822,7 @@ export class GhostManager {
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
});
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ this.untrustedApprovals.delete(manifest.id);
} catch (error) {
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
throw error;
@@ -874,7 +900,7 @@ export class GhostManager {
if (!(await pathExists(finalDir))) {
return { rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` } };
}
- const approvalResult = this.receiptStore.read(manifest.id);
+ const approvalResult = this.readApproval(manifest.id);
const actualApproval = approvalTokenFor(approvalResult);
if (actualApproval !== opts.expectedInstalledApproval) {
return {
@@ -958,6 +984,7 @@ export class GhostManager {
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
});
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ this.untrustedApprovals.delete(manifest.id);
} catch (err) {
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
await fs.promises.rename(backupDir, finalDir).catch(() => undefined);
@@ -997,7 +1024,7 @@ export class GhostManager {
publisherVerified: false,
reviewed: true,
};
- const current = this.receiptStore.read(manifest.id);
+ const current = this.readApproval(manifest.id);
if (
current.state === 'approved' &&
isDeepStrictEqual(current.receipt.manifest, manifest) &&
@@ -1012,6 +1039,7 @@ export class GhostManager {
...current.receipt,
enabled,
});
+ this.untrustedApprovals.delete(manifest.id);
return true;
}
return false;
@@ -1028,12 +1056,30 @@ export class GhostManager {
}),
{ skillSourceDir: dir },
);
+ this.untrustedApprovals.delete(manifest.id);
return true;
}
- /** Remove Host approval for content deleted by the trusted seed provisioner. */
+ /**
+ * 撤销 Host 批准。**契约是"调用返回后该插件一定不再被授权运行"**:正常路径删掉
+ * receipt 与技能快照;删不掉(状态根不可写等)时退回进程内隔离,不把失败原样抛给
+ * 调用方去自己 fail closed —— 那正是上一版留下 fail-open 的地方。
+ */
async removeInstallApproval(id: string): Promise<void> {
- await this.receiptStore.remove(id);
+ try {
+ await this.receiptStore.remove(id);
+ this.untrustedApprovals.delete(id);
+ } catch (err) {
+ this.untrustedApprovals.add(id);
+ // 这行是"插件已转进程内隔离"的唯一可观测信号,不能因为注入的 logger 没实现
+ // error 就静默丢掉 —— 退化到 warn。
+ const log = this.options.log;
+ (log?.error ?? log?.warn)?.call(
+ log,
+ 'ghost approval could not be removed; kept untrusted in-process',
+ { id, error: err instanceof Error ? err.message : String(err) },
+ );
+ }
}
private readApprovedLocaleResources(
@@ -1125,17 +1171,10 @@ 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),
- });
- }
+ // 走同一个撤销入口:成功即清掉隔离记录,失败由该入口转进程内隔离并记日志。
+ // 内容目录已经删除,插件不可能再运行;孤立 receipt 与 skill snapshot 仅是待回收
+ // 状态,不能把“清理延后”误报成“插件仍已安装”。
+ await this.removeInstallApproval(id);
this.options.log?.info('ghost uninstalled', { id });
if (options.notify !== false) this.options.onChanged?.(this.list());
return { ok: true };
@@ -1247,9 +1286,17 @@ async function hashApprovedDirectory(root: string): Promise<string> {
const relativePath = relativeDir
? `${relativeDir}/${entry.name}`
: entry.name;
- if (entry.isDirectory()) {
+ // 判据与姊妹函数 hashApprovedSkillContent 对齐:逐条 lstat、链接显式拒,不依赖
+ // Dirent 的类型位。这里本身只是漂移检测器(packageSha256 不作授权判据),跟随
+ // 链接最多多写一次批准、不构成绕过;对齐是因为"同一判据散落两处且两处不一致"
+ // 本身就是缺陷温床。
+ const entryStat = await fs.promises.lstat(path.join(absoluteDir, entry.name));
+ if (entryStat.isSymbolicLink()) {
+ throw new Error(`bundled Plugin contains a link entry: ${relativePath}`);
+ }
+ if (entryStat.isDirectory()) {
await collect(relativePath);
- } else if (entry.isFile()) {
+ } else if (entryStat.isFile()) {
files.push(relativePath);
} else {
throw new Error(`bundled Plugin contains a non-regular entry: ${relativePath}`);
@@ -1262,7 +1309,9 @@ async function hashApprovedDirectory(root: string): Promise<string> {
for (const relativePath of files) {
hash.update(relativePath);
hash.update('\0');
- hash.update(await fs.promises.readFile(path.join(root, ...relativePath.split('/'))));
+ // 同 hashApprovedSkillContent:流式喂 hash,不让安装目录里的超大文件整份进内存。
+ const stream = fs.createReadStream(path.join(root, ...relativePath.split('/')));
+ for await (const chunk of stream) hash.update(chunk as Buffer);
hash.update('\0');
}
return hash.digest('hex');
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 ea70bc5679..32540725cd 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -468,6 +468,8 @@ describe('GhostManager · list', () => {
});
describe('GhostManager · Host approval receipt', () => {
+ /** 真实 copyFile 引用:mock 复制行为的用例要靠它放行非目标文件。 */
+ const realCopyFile = fs.promises.copyFile;
const receiptPath = (id = 'hello') =>
path.join(workDir, 'ghosts-install-state', `${id}.json`);
@@ -767,6 +769,97 @@ describe('GhostManager · Host approval receipt', () => {
expect(leaked).toEqual([]);
});
+ it('rejects bytes swapped after the hash check but before the snapshot copy finishes', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // 先停用、再删快照:停用本身会把快照重建回来(字节没动、校验放行),顺序颠倒
+ // 会让后面的启用走"快照已存在"的早退路径,根本不经过复制。
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+
+ // 模拟同权限本机进程抢在复制这一刻换掉源字节:复制动作落到 temp 的是被改写的
+ // 内容,而源目录事后看起来仍然"没问题"。所以校验必须落在**已经复制到 temp 的
+ // 那份字节**上;若校验读的是源目录,这里就会放行一份没人确认过的技能指令。
+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';
+ let swapped = 0;
+ const spy = vi
+ .spyOn(fs.promises, 'copyFile')
+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {
+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {
+ swapped += 1;
+ await fs.promises.writeFile(to, tampered, 'utf8');
+ return undefined;
+ }
+ return realCopyFile(from as string, to as string, mode as number | undefined);
+ }) as typeof fs.promises.copyFile);
+ try {
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(swapped).toBe(1); // 确认这一轮真的走到了复制
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('applies the SKILL.md size ceiling to the bytes that actually landed in the snapshot', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+
+ // 源目录看起来一切正常(预检放行),复制这一刻落到 temp 的却是超大文件。上限必须
+ // 作用在这份字节上,而不是只作用在预检读到的那份 —— 预检不是安全边界。
+ let swapped = 0;
+ const spy = vi
+ .spyOn(fs.promises, 'copyFile')
+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {
+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {
+ swapped += 1;
+ await fs.promises.writeFile(to, 'x'.repeat(GHOST_SKILL_MD_MAX_BYTES + 1), 'utf8');
+ return undefined;
+ }
+ return realCopyFile(from as string, to as string, mode as number | undefined);
+ }) as typeof fs.promises.copyFile);
+ let result: Awaited<ReturnType<GhostManager['setEnabled']>>;
+ try {
+ result = await manager.setEnabled('skilled', true);
+ } finally {
+ spy.mockRestore();
+ }
+ await expectRejection(result, 'io');
+ // 断言到 reason 才能区分校验顺序:上限先跑报"exceeds N bytes",指纹先跑报
+ // "no longer matches..."。只比 code 的话两种顺序都是 io,用例就退化成
+ // 行为钉住、测不出重排。
+ expect((result as { rejection: { reason: string } }).rejection.reason).toMatch(
+ /exceeds \d+ bytes/,
+ );
+ expect(swapped).toBe(1);
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('keeps an install unusable when a stale approval cannot be revoked', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest()));
+ // 撤销失败(状态根不可写等,与写批准失败同一成因)不得退回"继续拿旧批准跑":
+ // removeInstallApproval 的契约是返回后一定不再被授权运行。
+ const spy = vi
+ .spyOn(fs.promises, 'rm')
+ .mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
+ try {
+ await manager.removeInstallApproval('hello');
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');
+ });
+
it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {
await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
const snapshotRoot = manager.list()[0].approvedSkillRoot!;
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 9c7a625190..35e832cdbb 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -177,19 +177,6 @@ export class GhostInstallReceiptStore {
if (!skillSourceDir) {
throw new Error('approved skill snapshot is missing');
}
- // 快照缺失、要从可变安装目录重建:先逐字节对上批准时点钉住的指纹。
- // 只校验 SKILL.md frontmatter 不够 —— name/description 保持不变、改写正文或
- // 往技能目录塞辅助文件,同样会让一份没人确认过的技能指令被固化成已批准快照
- // 并全局挂链,而 skill 槽是以用户全部权限执行的。对不上就拒,让它退回完整
- // 重新确认,而不是就地"自愈"成新批准。
- const actualSkillContent = await hashApprovedSkillContent(receipt.manifest, skillSourceDir);
- for (const item of items) {
- if (actualSkillContent[item.dir] !== receipt.skillContentSha256[item.dir]) {
- throw new Error(
- `approved skill ${item.dir} no longer matches the bytes approved at install time`,
- );
- }
- }
const parent = path.dirname(target);
const temp = path.join(
parent,
@@ -198,26 +185,74 @@ export class GhostInstallReceiptStore {
await fs.promises.mkdir(parent, { recursive: true });
try {
await fs.promises.mkdir(temp, { recursive: false });
+
+ // 顺序是安全要点,不要改回"先校验源目录、再复制":源目录随时可被同权限进程
+ // 改写,校验和复制各读一次就有一个可换字节的窗口,复制出来的快照可能不是被
+ // 校验过的那一份。因此**先复制到 temp,再对 temp 里(即将成为快照的)那份字节
+ // 做全部权威校验**,校验通过才 rename 就位。
for (const item of items) {
const source = path.join(skillSourceDir, ...item.dir.split('/'));
- // 取字节的来源是可变的安装目录(快照缺失时从 dir 重建),所以这里要自己
- // 复现装入侧的门槛:先 lstat 定长再读,不然本机进程往安装目录塞一个超大
- // SKILL.md 就能让 Host 整份读进内存。lstat 而非 stat —— 与本文件其余
- // 位置一致地拒绝软链与非普通文件,不留跟随软链的绕过口。
- const skillMdPath = path.join(source, 'SKILL.md');
- const skillMdStat = await fs.promises.lstat(skillMdPath);
- if (!skillMdStat.isFile() || skillMdStat.size > GHOST_SKILL_MD_MAX_BYTES) {
+ // 复制前的便宜预检:只为早失败、少做无用功(避免整份拷一个超大 SKILL.md)。
+ // **这不是安全边界** —— 它读的是可变源目录,结论随时可能过期,真正说话的是
+ // 下面对 temp 的校验。
+ const sourceSkillMdStat = await fs.promises
+ .lstat(path.join(source, 'SKILL.md'))
+ .catch(() => null);
+ if (
+ sourceSkillMdStat &&
+ (!sourceSkillMdStat.isFile() || sourceSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES)
+ ) {
+ throw new Error(
+ `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,
+ );
+ }
+ await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));
+ }
+
+ // 权威校验一律针对 temp:此刻这些字节已经脱离可变安装目录,复制期间被换过也
+ // 会在这里暴露。**尺寸上限必须排在算指纹之前** —— 源目录那道预检不是安全边界
+ // (预检后可被换成超大文件),若先算指纹就等于上限在权威路径上一次都没生效。
+ for (const item of items) {
+ const copiedSkillMdPath = path.join(temp, ...item.dir.split('/'), 'SKILL.md');
+ // 包一层领域错误:这一段现在排在算指纹之前,SKILL.md 缺失时若直接抛裸 ENOENT,
+ // 日志里就看不出是"技能内容被动过"这件事(只有被篡改时才可达,两种写法都
+ // fail closed,纯粹为可读性)。
+ const copiedSkillMdStat = await fs.promises.lstat(copiedSkillMdPath).catch((error) => {
+ throw new Error(
+ `approved skill ${item.dir}/SKILL.md is unreadable in the snapshot: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ });
+ if (!copiedSkillMdStat.isFile() || copiedSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES) {
throw new Error(
`approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,
);
}
- const skillMd = await fs.promises.readFile(skillMdPath, 'utf8');
- const consistencyError = checkSkillMdConsistency(skillMd, item);
+ }
+ const copiedSkillContent = await hashApprovedSkillContent(receipt.manifest, temp);
+ for (const item of items) {
+ if (copiedSkillContent[item.dir] !== receipt.skillContentSha256[item.dir]) {
+ throw new Error(
+ `approved skill ${item.dir} no longer matches the bytes approved at install time`,
+ );
+ }
+ // 指纹相符已经蕴含 frontmatter 一致(批准时点那份过过这道校验),这里重跑一遍
+ // 是防止钉指纹那条路径本身有 bug,并给出更具体的错误。
+ const consistencyError = checkSkillMdConsistency(
+ await fs.promises.readFile(path.join(temp, ...item.dir.split('/'), 'SKILL.md'), 'utf8'),
+ item,
+ );
if (consistencyError) {
throw new Error(`approved skill ${item.dir} is inconsistent: ${consistencyError}`);
}
- await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));
}
+
+ // 残留窗口(已知、未关):rename 之前 temp 位于状态根内,同权限进程仍可改写它。
+ // 本地校验能保证"被校验的就是被复制的",保证不到"rename 的就是被校验的"。这属于
+ // 「批准状态根自身没有写保护」那一类,已正式登记在
+ // docs/dev-rules/plugin-security-and-authoring.md 第 6 节(与"内容根字节可变"
+ // 是两条并列的不同缺口),不在本函数能关掉的范围内。
await fs.promises.rename(temp, target);
} finally {
await fs.promises.rm(temp, { recursive: true, force: true }).catch(() => undefined);
@@ -325,7 +360,11 @@ export async function hashApprovedSkillContent(
for (const relativePath of files) {
hash.update(relativePath);
hash.update('\0');
- hash.update(await fs.promises.readFile(path.join(itemRoot, ...relativePath.split('/'))));
+ // 流式喂给 hash,不整份读进内存:技能目录里除 SKILL.md 之外的文件没有尺寸上限
+ // (SKILL.md 的上限在调用方 ensureSkillSnapshot 里先判),整份 readFile 会让
+ // 一个塞进来的超大辅助文件把 Host 撑爆。摘要与逐份读取完全一致。
+ const stream = fs.createReadStream(path.join(itemRoot, ...relativePath.split('/')));
+ for await (const chunk of stream) hash.update(chunk as Buffer);
hash.update('\0');
}
result[item.dir] = hash.digest('hex');
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 349b00e184..f26e5243eb 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -787,22 +787,23 @@ async function reconcileBuiltinGhostsLocked(
} catch (err) {
// 走到这里内容目录可能已经换成新种子字节,旧 receipt 却还是授权事实 ——
// 留着它就是拿旧批准跑新代码(新版删掉的 slot 仍被授予、版本与技能快照
- // 也停在旧 revision)。撤掉批准 fail closed 到 legacy-unapproved:随包
- // 插件下一轮启动对账会重新补批准,自愈,不需要用户介入。
- let approvalCleared = false;
- try {
- await manager.removeInstallApproval(manifest.id);
- approvalCleared = true;
- approvalChanged = true;
- } catch (cleanupErr) {
- log.error('builtin ghost stale approval could not be revoked', {
- id: manifest.id,
- error: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
- });
- }
- log.warn('builtin ghost approval receipt failed', {
+ // 也停在旧 revision)。
+ //
+ // removeInstallApproval 的契约是"返回后该插件一定不再被授权运行":删得掉就
+ // 删 receipt,删不掉(状态根不可写 —— 与这里写批准失败同一个成因)就转进程内
+ // 隔离。所以这里不需要、也不应该再自己判断撤销成不成功:那正是上一版在
+ // cleanup 失败时留下 fail-open 的地方。随包插件下一轮启动对账会重新补批准,
+ // 自愈,不需要用户介入。
+ await manager.removeInstallApproval(manifest.id);
+ // 撤销只让后续的 Host 能力调用与技能落链失效,不会自己结束已经跑起来的沙箱
+ // 进程 —— 登录触发对账时插件可能正在运行。与 beforeRemove 同款三连熄灯,
+ // 让"撤销后不再被授权运行"这句话对运行中的实例也成立。
+ getGhostRuntime().stop(manifest.id);
+ getGhostNodeRuntimeBroker().stop(manifest.id);
+ getGhostAgentSlot().clearGhost(manifest.id);
+ approvalChanged = true;
+ log.warn('builtin ghost approval receipt failed; approval revoked', {
id: manifest.id,
- approvalCleared,
error: err instanceof Error ? err.message : String(err),
});
}
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 79870c1d92..4877e61bc2 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -71,6 +71,13 @@
不许启用、不参与技能落链;恢复只能走一次完整重新确认(`diffInstalledGhostPermissionItems`
在无批准基线时把候选包的**全部**权限当新增项展示)。UI 必须如实说出这个状态并
给出恢复入口,不能让它看起来只是"被用户关掉了"。
+ - 通往"不构成运行授权"的还有第三条路:**撤销陈旧批准失败时的进程内隔离**。撤销的
+ 契约是"返回后该插件一定不再被授权运行",所以删不掉 receipt(状态根不可写——与写
+ 批准失败同一个成因,指望再往状态根写点什么表达"已失效"并不可靠)时退回内存标记,
+ 由读批准状态的**唯一入口**统一投影成 `invalid`。读批准状态的所有消费方都必须走
+ 那个入口:各自直接读 receipt 会让隔离在某条路径上失效。撤销同时要熄灯运行中的
+ 实例(runtime / node broker / agent slot 三连),否则"不再被授权运行"对已经跑起来
+ 的进程不成立。下一轮启动对账成功即自愈。
- 跨进程更新事务用 `ghostInstallApprovalToken()` 把批准态投影成 token:Renderer 把
确认时看到的 token 回传,Main 重新读状态比对,不一致就拒(`state-changed`)。
token 是前置条件不是凭证——真值一律由 Main 现读。
@@ -90,12 +97,19 @@
`<状态根>/skill-snapshots/<id>/<revision>`,只收普通文件,同时把逐 item 的内容
指纹钉进 receipt 的 `skillContentSha256`;确认框看到的 SKILL.md 必须就是 Agent 之后
读到的那份,所以共享技能根的链接指快照而不是可被改写的 `cindy-brain/<id>/<dir>`。
- 快照缺失需要从安装目录重建时**必须先重算指纹并逐字节对上**——只靠
- `checkSkillMdConsistency` 拦不住"frontmatter 不动、改写正文或塞辅助文件",那会把
- 一份没人确认过的指令在一次启用里固化成已批准快照并全局挂链。对不上一律拒、退回
- 完整重新确认,不许就地自愈成新批准;`skillContentSha256` 因此是**运行期判据**,与
- 只作审计用的 `packageSha256` 不同,且必填——留"字段缺失就跳过校验"的可选口子等于
- 给漂移开一条绕过路径)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在
+ 快照缺失需要从安装目录重建时,**顺序本身就是安全性质**:先把字节复制进状态根的
+ 临时目录,再对**临时目录里那份即将成为快照的字节**做全部权威校验(尺寸上限 →
+ 指纹逐字节比对 → frontmatter 一致性),通过才 rename 就位。**不得改成"先校验安装
+ 目录、再复制"**——安装目录随时可被同权限进程改写,校验与复制各读一次就有一个可换
+ 字节的窗口,复制出来的快照可能不是被校验过的那一份。同理,复制前对安装目录做的
+ 任何预检只是"早失败"优化,**不是安全边界**;尺寸上限必须排在算指纹之前——上限要在
+ 权威路径上真正生效,且不为一份注定被拒的字节先付一整趟读取成本。指纹计算一律流式
+ 喂入、不整份读进内存(技能目录里除 SKILL.md 之外的文件没有尺寸上限,整份读会被一个
+ 塞进来的超大辅助文件撑爆)。只靠 `checkSkillMdConsistency` 拦不住"frontmatter 不动、改写正文或塞
+ 辅助文件",那会把一份没人确认过的指令在一次启用里固化成已批准快照并全局挂链。
+ 对不上一律拒、退回完整重新确认,不许就地自愈成新批准;`skillContentSha256` 因此是
+ **运行期判据**,与只作审计用的 `packageSha256` 不同,且必填——留"字段缺失就跳过
+ 校验"的可选口子等于给漂移开一条绕过路径)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在
安装根或批准状态根内的 symlink/junction",绝不触碰真实目录与外来链接;
启用挂链、停用/卸载撤链、断链自愈)。快照目标带 revision,因此每次更新都换目标、
靠对账重指,旧 revision 在 receipt 提交后回收。改动技能落链、命名
@@ -168,6 +182,14 @@
代码,只是被限制在**此前已批准的权限集**内运行,且不能借改写 `ghost.json` 扩权。
技能目录因为越出沙箱已单独拷成快照(第 3 节),其余内容的持续完整性校验仍未做——
改动装入链路时不得声称已有内容完整性保证。
+- **批准状态根自身没有写保护。** 这是与上一条并列、但**不同**的缺口:上一条说的是
+ 内容根字节可变,这一条说的是 `<userData>/ghost-install-state/` 本身对同权限本机进程
+ 可写。两个已知后果:(a) 技能快照在 `rename` 就位**之前**先落在状态根的临时目录里,
+ 那一小段窗口内它可被改写,本地校验只能保证"被校验的就是被复制的",保证不到"rename
+ 的就是被校验的";(b) receipt 与已就位的快照事后同样可被改写——receipt 有严格结构与
+ 字段校验(改坏即判 `invalid`、fail closed),但没有签名或 MAC,能写状态根的进程可以
+ 伪造一份结构合法的批准。彻底关闭需要给状态根加签名/MAC 或 OS 级写保护,**尚未做**;
+ 改动批准链路时不得声称批准状态不可伪造。
## 7. 远程与手机版