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): address plugin approval review findings

Yuewei-LL2c1a1a6fd1ef
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index b573abab64..9e4aaa48e2 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -3445,12 +3445,12 @@ async function copyBundledSeedDirectory(from: string, to: string): Promise<void>
* 本身就是缺陷温床。
*/
async function hashApprovedDirectory(root: string): Promise<string> {
- const { files } = await collectGhostContentFiles(root, {
+ const tree = await collectGhostContentFiles(root, {
dotEntries: 'skip',
nonRegular: 'throw',
label: 'bundled Plugin',
});
- return hashGhostContentFiles(root, files);
+ return hashGhostContentFiles(root, tree.files, tree.rootIdentity);
}
/**
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 77d24d9761..0e083db2d7 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -100,6 +100,16 @@ function packGhostDir(
return packGhostDirRaw(dir, { sessionWorkdir: workDir, ...options });
}
+async function expectSameExistingRealPath(actual: string, expected: string): Promise<void> {
+ const normalize = (value: string) =>
+ process.platform === 'win32' ? value.toLowerCase() : value;
+ const [actualReal, expectedReal] = await Promise.all([
+ fs.promises.realpath(actual),
+ fs.promises.realpath(expected),
+ ]);
+ expect(normalize(actualReal)).toBe(normalize(expectedReal));
+}
+
beforeEach(async () => {
workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-test-'));
});
@@ -146,7 +156,12 @@ describe('packGhostDir', () => {
process.platform === 'win32' ? 'junction' : 'dir',
);
const packed = await packGhostDir(sourceAlias);
- expect(packed).toMatchObject({ ok: true, cindyPath: path.join(sourceTarget, 'inside-1.0.0.cindy') });
+ expect(packed).toMatchObject({ ok: true });
+ if (!packed.ok) return;
+ await expectSameExistingRealPath(
+ packed.cindyPath,
+ path.join(sourceTarget, 'inside-1.0.0.cindy'),
+ );
await expect(fs.promises.access(path.join(sourceTarget, 'inside-1.0.0.cindy'))).resolves.toBeUndefined();
});
@@ -411,7 +426,7 @@ describe('packGhostDir', () => {
const r = await packGhostDir(dir);
expect(r.ok, JSON.stringify(r)).toBe(true);
if (!r.ok) return;
- expect(r.cindyPath).toBe(path.join(dir, 'demo-1.0.0.cindy'));
+ await expectSameExistingRealPath(r.cindyPath, path.join(dir, 'demo-1.0.0.cindy'));
expect(r.manifest.id).toBe('demo');
// 装入侧同一契约验证:inspect 直接吃打包产物。
@@ -1094,6 +1109,26 @@ describe('scaffoldGhostDir', () => {
).toMatchObject({ ok: true, dir });
});
+ it('拒绝仍指向工作目录内部的链接祖先,不把 8.3 路径兼容变成链接放行', async () => {
+ const realRoot = path.join(workDir, 'real-author-root');
+ const aliasRoot = path.join(workDir, 'author-alias');
+ await fs.promises.mkdir(path.join(realRoot, 'nested'), { recursive: true });
+ try {
+ await fs.promises.symlink(realRoot, aliasRoot, directoryLinkType);
+ } catch {
+ return;
+ }
+
+ const dir = path.join(aliasRoot, 'nested', 'plugin');
+ expect(
+ await scaffoldGhostDir(
+ { dir, template: 'plain', id: 'linked-parent', name: 'Linked parent' },
+ { sessionWorkdir: workDir },
+ ),
+ ).toMatchObject({ ok: false, errorCode: 'INVALID_INPUT' });
+ expect(fs.existsSync(path.join(realRoot, 'nested', 'plugin'))).toBe(false);
+ });
+
it('软链祖先把字面在工作目录内的路径引到外面 → 拒绝且外面不落盘', async () => {
// Windows 无特权时目录软链可能 EPERM,建不出夹具就跳过(守卫仍在)。
const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-outside-'));
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
index c84fa42012..92cf6196eb 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
@@ -35,11 +35,17 @@ afterEach(async () => {
/** 建目录链接;该环境无权限时返回 false 让用例跳过(判定逻辑与其他平台同源)。 */
async function tryLinkDir(target: string, linkPath: string): Promise<boolean> {
try {
- await fs.promises.symlink(
- target,
- linkPath,
- process.platform === 'win32' ? 'junction' : 'dir',
- );
+ await fs.promises.symlink(target, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** 建文件链接;Windows 无权限时返回 false。 */
+async function tryLinkFile(target: string, linkPath: string): Promise<boolean> {
+ try {
+ await fs.promises.symlink(target, linkPath, 'file');
return true;
} catch {
return false;
@@ -208,6 +214,85 @@ describe('hashGhostContentFiles', () => {
await hashGhostContentFiles(twoFiles, twoTree.files),
);
});
+
+ it('rejects an intermediate directory replaced by an outside link after collection', async () => {
+ const root = path.join(workDir, 'plugin');
+ const outside = path.join(workDir, 'outside');
+ await fs.promises.mkdir(path.join(root, 'nested'), { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'nested', 'x.txt'), 'inside');
+ await fs.promises.writeFile(path.join(outside, 'x.txt'), 'outside');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(path.join(root, 'nested'), { recursive: true, force: true });
+ if (!(await tryLinkDir(outside, path.join(root, 'nested')))) return;
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow(
+ /escaped its root|changed into a link/,
+ );
+ });
+
+ it('rejects an intermediate directory replaced by a link within the content root', async () => {
+ const root = path.join(workDir, 'plugin');
+ const alternate = path.join(root, 'alternate');
+ await fs.promises.mkdir(path.join(root, 'nested'), { recursive: true });
+ await fs.promises.mkdir(alternate, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'nested', 'x.txt'), 'inside');
+ await fs.promises.writeFile(path.join(alternate, 'x.txt'), 'alternate');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(path.join(root, 'nested'), { recursive: true, force: true });
+ if (!(await tryLinkDir(alternate, path.join(root, 'nested')))) return;
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow(
+ /ancestor changed into a link/,
+ );
+ });
+
+ it('rejects a leaf file replaced by a link after collection', async () => {
+ const root = path.join(workDir, 'plugin');
+ const outside = path.join(workDir, 'outside.txt');
+ await fs.promises.mkdir(root, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'main.js'), 'inside');
+ await fs.promises.writeFile(outside, 'outside');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(path.join(root, 'main.js'));
+ if (!(await tryLinkFile(outside, path.join(root, 'main.js')))) return;
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow();
+ });
+
+ it('rejects the content root being replaced between collection and hashing', async () => {
+ const root = path.join(workDir, 'plugin');
+ await fs.promises.mkdir(root, { recursive: true });
+ await fs.promises.writeFile(path.join(root, 'main.js'), 'inside');
+ const tree = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+
+ await fs.promises.rm(root, { recursive: true, force: true });
+ await fs.promises.mkdir(root);
+ await fs.promises.writeFile(path.join(root, 'main.js'), 'replacement');
+
+ await expect(hashGhostContentFiles(root, tree.files, tree.rootIdentity)).rejects.toThrow(
+ /root changed/,
+ );
+ });
});
describe('hashGhostContentBuffers', () => {
@@ -223,12 +308,12 @@ describe('hashGhostContentBuffers', () => {
for (const [rel, content] of Object.entries(tree)) {
await fs.promises.writeFile(path.join(root, ...rel.split('/')), content);
}
- const { files } = await collectGhostContentFiles(root, {
+ const collected = await collectGhostContentFiles(root, {
dotEntries: 'include',
nonRegular: 'throw',
label: 'test',
});
- const fromDisk = await hashGhostContentFiles(root, files);
+ const fromDisk = await hashGhostContentFiles(root, collected.files, collected.rootIdentity);
const fromMemory = hashGhostContentBuffers(
Object.entries(tree).map(([p2, c]) => ({ path: p2, bytes: Buffer.from(c) })),
);
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 01ed846cd8..02d51b5e32 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts
@@ -174,8 +174,43 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {
// 模拟崩溃残留:插件目录整个没了,链接悬空
await fs.promises.rm(path.join(brainRoot, 'my-ghost'), { recursive: true, force: true });
const result = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });
- expect(fs.existsSync(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo')))).toBe(false);
+ await expect(
+ fs.promises.lstat(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo'))),
+ ).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(result.changed).toBe(true);
+ });
+
+ it('回收词法根与物理根表示不同的悬空技能链接', async () => {
+ const physicalOwner = path.join(workDir, 'physical-owner');
+ const lexicalOwner = path.join(workDir, 'owner-alias');
+ await fs.promises.mkdir(physicalOwner, { recursive: true });
+ try {
+ await fs.promises.symlink(
+ physicalOwner,
+ lexicalOwner,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+ brainRoot = path.join(lexicalOwner, 'cindy-brain');
+ approvalStateRoot = path.join(lexicalOwner, 'cindy-brain-install-state');
+ await fs.promises.mkdir(brainRoot, { recursive: true });
+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');
+ const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];
+ await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });
+ const linkPath = path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo'));
+
+ await fs.promises.rm(path.join(brainRoot, 'my-ghost'), { recursive: true, force: true });
+ const result = await reconcileGhostSkillLinks({
+ ghosts: [],
+ brainRoot,
+ approvalStateRoot,
+ homeDir,
+ });
+
expect(result.changed).toBe(true);
+ await expect(fs.promises.lstat(linkPath)).rejects.toMatchObject({ code: 'ENOENT' });
});
it('技能改名/换目录 → 旧链撤、新链立', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index 56e82dc78c..f83b1175e8 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -924,7 +924,7 @@ export async function fingerprintDirContent(dir: string): Promise<DirContentFing
label: 'builtin seed content',
});
return {
- hash: await hashGhostContentFiles(dir, tree.files),
+ hash: await hashGhostContentFiles(dir, tree.files, tree.rootIdentity),
hasNonRegularEntry: tree.hasNonRegularEntry,
};
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 4a91b1cb5a..1fb46a08a0 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -39,11 +39,6 @@ import { checkSkillMdConsistency } from './skillSlot.js';
*/
const realpathNative = promisify(fs.realpath.native);
-function sameForgeCanonicalPath(left: string, right: string): boolean {
- const fold = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value);
- return fold(path.resolve(left)) === fold(path.resolve(right));
-}
-
/**
* 解析已存在祖先的真身、保留尚不存在的尾段,让受管根在首次落盘前就可比对。
*/
@@ -64,6 +59,25 @@ async function resolveThroughExistingAncestor(inputPath: string): Promise<string
}
}
+/**
+ * 逐段确认一个已存在目录路径没有 symlink / junction 祖先。
+ *
+ * 不能用 `realpath(path) === path` 判断:Windows 的 8.3 短路径会被 realpath
+ * 展开成长路径,二者文本不同但每一段仍都是普通目录。逐段 lstat 才能既放行
+ * 这种合法别名,又继续拒绝真正的 reparse-point 祖先。
+ */
+async function pathHasLinkSegment(inputPath: string): Promise<boolean> {
+ const resolved = path.resolve(inputPath);
+ const root = path.parse(resolved).root;
+ let current = root;
+ const relative = path.relative(root, resolved);
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
+ current = path.join(current, segment);
+ if ((await fs.promises.lstat(current)).isSymbolicLink()) return true;
+ }
+ return false;
+}
+
/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */
const MAX_BASIC_FILES = 256;
const MAX_NODE_FILES = 2_048;
@@ -563,7 +577,7 @@ export async function scaffoldGhostDir(
}
parentRealPath = await realpathNative(parentDir);
if (
- !sameForgeCanonicalPath(parentRealPath, parentDir) ||
+ (await pathHasLinkSegment(parentDir)) ||
!isPathInsideDir(realWorkdir, parentRealPath)
) {
return {
diff --git a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
index 9f2fef581c..0d36e7fa80 100644
--- a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
@@ -156,6 +156,91 @@ export interface GhostContentTree {
files: string[];
/** 是否遇到过非普通条目(仅 `nonRegular: 'flag'` 时可能为 true)。 */
hasNonRegularEntry: boolean;
+ /** 收集开始时钉住的规范根身份,供后续流式哈希拒绝 collect→hash 间的根替换。 */
+ rootIdentity: GhostContentRootIdentity;
+}
+
+export interface GhostContentRootIdentity {
+ realPath: string;
+ dev: bigint;
+ ino: bigint;
+}
+
+interface GhostContentAncestorIdentity {
+ relativePath: string;
+ dev: bigint;
+ ino: bigint;
+}
+
+function sameFileIdentity(
+ a: Pick<fs.BigIntStats, 'dev' | 'ino'>,
+ b: Pick<fs.BigIntStats, 'dev' | 'ino'>,
+): boolean {
+ if (a.dev === 0n || a.ino === 0n || b.dev === 0n || b.ino === 0n) return false;
+ return a.dev === b.dev && a.ino === b.ino;
+}
+
+async function captureGhostContentRootIdentity(rootDir: string): Promise<GhostContentRootIdentity> {
+ const realPath = await fs.promises.realpath(rootDir);
+ const [pathStat, realStat] = await Promise.all([
+ fs.promises.stat(rootDir, { bigint: true }),
+ fs.promises.stat(realPath, { bigint: true }),
+ ]);
+ if (!pathStat.isDirectory() || !realStat.isDirectory() || !sameFileIdentity(pathStat, realStat)) {
+ throw new Error(`ghost content root is not a stable directory: ${rootDir}`);
+ }
+ return { realPath, dev: realStat.dev, ino: realStat.ino };
+}
+
+async function assertGhostContentRootIdentity(
+ rootDir: string,
+ expected: GhostContentRootIdentity,
+): Promise<void> {
+ const current = await captureGhostContentRootIdentity(rootDir);
+ if (
+ current.realPath !== expected.realPath ||
+ current.dev !== expected.dev ||
+ current.ino !== expected.ino
+ ) {
+ throw new Error(`ghost content root changed while reading: ${rootDir}`);
+ }
+}
+
+async function captureGhostContentAncestorIdentities(
+ rootRealPath: string,
+ relativePath: string,
+): Promise<GhostContentAncestorIdentity[]> {
+ const identities: GhostContentAncestorIdentity[] = [];
+ const segments = relativePath.split('/').slice(0, -1);
+ let absolutePath = rootRealPath;
+ let currentRelativePath = '';
+ for (const segment of segments) {
+ absolutePath = path.join(absolutePath, segment);
+ currentRelativePath = currentRelativePath ? `${currentRelativePath}/${segment}` : segment;
+ const stat = await fs.promises.lstat(absolutePath, { bigint: true });
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
+ throw new Error(`ghost content ancestor changed into a link: ${currentRelativePath}`);
+ }
+ identities.push({ relativePath: currentRelativePath, dev: stat.dev, ino: stat.ino });
+ }
+ return identities;
+}
+
+function assertGhostContentAncestorIdentities(
+ expected: readonly GhostContentAncestorIdentity[],
+ current: readonly GhostContentAncestorIdentity[],
+): void {
+ if (
+ current.length !== expected.length ||
+ current.some(
+ (identity, index) =>
+ identity.relativePath !== expected[index]?.relativePath ||
+ identity.dev !== expected[index]?.dev ||
+ identity.ino !== expected[index]?.ino,
+ )
+ ) {
+ throw new Error('ghost content ancestor changed while reading');
+ }
}
/** 递归收集目录里的普通文件相对路径;类型判定与策略见 `CollectGhostContentOptions`。 */
@@ -163,11 +248,12 @@ export async function collectGhostContentFiles(
rootDir: string,
options: CollectGhostContentOptions,
): Promise<GhostContentTree> {
+ const rootIdentity = await captureGhostContentRootIdentity(rootDir);
const files: string[] = [];
let hasNonRegularEntry = false;
const collect = async (relativeDir: string): Promise<void> => {
- const absoluteDir = path.join(rootDir, ...relativeDir.split('/').filter(Boolean));
+ const absoluteDir = path.join(rootIdentity.realPath, ...relativeDir.split('/').filter(Boolean));
for (const entry of await fs.promises.readdir(absoluteDir, { withFileTypes: true })) {
const isDotEntry = entry.name.startsWith('.');
const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
@@ -193,8 +279,9 @@ export async function collectGhostContentFiles(
};
await collect('');
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
files.sort();
- return { files, hasNonRegularEntry };
+ return { files, hasNonRegularEntry, rootIdentity };
}
/**
@@ -214,11 +301,9 @@ export async function collectGhostContentFiles(
* JSZip 投影)算批准基线,而不是从已公开的可变安装目录首读 —— 后者在 publish 与
* 首次 hash 之间被换过的字节会自洽地成为批准事实(权威判据被污染源初始化)。
*/
-export function hashGhostContentBuffers(
- files: readonly { path: string; bytes: Buffer }[],
-): string {
+export function hashGhostContentBuffers(files: readonly { path: string; bytes: Buffer }[]): string {
const hash = crypto.createHash('sha256');
- hash.update('cindy-ghost-content-v2');
+ hash.update('cindy-ghost-content-v2\0');
const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
for (const file of sorted) {
const pathBytes = Buffer.from(file.path, 'utf8');
@@ -234,10 +319,14 @@ export function hashGhostContentBuffers(
export async function hashGhostContentFiles(
rootDir: string,
files: readonly string[],
+ collectedRootIdentity?: GhostContentRootIdentity,
): Promise<string> {
+ const rootIdentity = collectedRootIdentity ?? (await captureGhostContentRootIdentity(rootDir));
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
const hash = crypto.createHash('sha256');
hash.update('cindy-ghost-content-v2\0');
for (const relativePath of files) {
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
const pathBytes = Buffer.from(relativePath, 'utf8');
const pathLength = Buffer.allocUnsafe(8);
pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));
@@ -245,9 +334,52 @@ export async function hashGhostContentFiles(
hash.update(pathBytes);
const fileHash = crypto.createHash('sha256');
- const stream = fs.createReadStream(path.join(rootDir, ...relativePath.split('/')));
- for await (const chunk of stream) fileHash.update(chunk as Buffer);
+ const filePath = path.join(rootIdentity.realPath, ...relativePath.split('/'));
+ const ancestorIdentities = await captureGhostContentAncestorIdentities(
+ rootIdentity.realPath,
+ relativePath,
+ );
+ const noFollow = fs.constants.O_NOFOLLOW ?? null;
+ const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | (noFollow ?? 0));
+ try {
+ const handleStat = await handle.stat({ bigint: true });
+ if (!handleStat.isFile()) {
+ throw new Error(`ghost content entry is not a regular file: ${relativePath}`);
+ }
+ assertGhostContentAncestorIdentities(
+ ancestorIdentities,
+ await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),
+ );
+ if (noFollow === null) {
+ const linkStat = await fs.promises.lstat(filePath, { bigint: true });
+ if (linkStat.isSymbolicLink() || !sameFileIdentity(linkStat, handleStat)) {
+ throw new Error(`ghost content entry changed into a link: ${relativePath}`);
+ }
+ }
+ const [pathStat, realFilePath] = await Promise.all([
+ fs.promises.stat(filePath, { bigint: true }),
+ fs.promises.realpath(filePath),
+ ]);
+ const relativeRealPath = path.relative(rootIdentity.realPath, realFilePath);
+ const outsideRoot =
+ relativeRealPath === '..' ||
+ relativeRealPath.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(relativeRealPath);
+ if (!sameFileIdentity(pathStat, handleStat) || outsideRoot) {
+ throw new Error(`ghost content entry escaped its root: ${relativePath}`);
+ }
+
+ const stream = handle.createReadStream({ autoClose: false });
+ for await (const chunk of stream) fileHash.update(chunk as Buffer);
+ assertGhostContentAncestorIdentities(
+ ancestorIdentities,
+ await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),
+ );
+ } finally {
+ await handle.close();
+ }
hash.update(fileHash.digest());
}
+ await assertGhostContentRootIdentity(rootDir, rootIdentity);
return hash.digest('hex');
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 29802ab55c..0be8230a63 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -979,12 +979,12 @@ export async function hashApprovedSkillContent(
expect: 'directory',
label: 'approved skill',
});
- const { files } = await collectGhostContentFiles(itemRoot, {
+ const tree = await collectGhostContentFiles(itemRoot, {
dotEntries: 'include',
nonRegular: 'throw',
label: `approved skill ${item.dir}`,
});
- result[item.dir] = await hashGhostContentFiles(itemRoot, files);
+ result[item.dir] = await hashGhostContentFiles(itemRoot, tree.files, tree.rootIdentity);
}
return result;
}
diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.ts
index e371fc37fe..56f42e8a6c 100644
--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts
@@ -286,11 +286,20 @@ export async function reconcileGhostSkillLinks(
const { sharedSkillsDir } = sharedGlobalSkillsPaths(opts.homeDir);
// realpath 兼容 brainRoot 或其祖先是 symlink 的场景(relocated home dir)——
// 活链接 realpath 后必须与归一化的物理根比较才可靠。resolve 失败退化到词法。
+ const lexicalManagedRootCompares = [
+ normalizeForCompare(opts.brainRoot),
+ normalizeForCompare(opts.approvalStateRoot),
+ ];
const managedRootCompares = [
(await realPathOrNull(opts.brainRoot)) ?? normalizeForCompare(opts.brainRoot),
(await realPathOrNull(opts.approvalStateRoot)) ??
normalizeForCompare(opts.approvalStateRoot),
];
+ // 活链接按 realpath 归属当前 owner;断链只能读到 raw target,它可能保留 Windows
+ // 8.3 短路径或 symlink 祖先的词法表示,所以用物理根 + 词法根的并集判断。
+ const danglingManagedRootCompares = [
+ ...new Set([...managedRootCompares, ...lexicalManagedRootCompares]),
+ ];
const approvalStateDirName = path.basename(path.resolve(opts.approvalStateRoot));
try {
@@ -383,7 +392,14 @@ export async function reconcileGhostSkillLinks(
const absTarget = path.isAbsolute(rawTarget)
? rawTarget
: path.resolve(sharedSkillsDir, rawTarget);
- if (targetLooksGhostManaged(absTarget, entName, approvalStateDirName, managedRootCompares)) {
+ if (
+ targetLooksGhostManaged(
+ absTarget,
+ entName,
+ approvalStateDirName,
+ danglingManagedRootCompares,
+ )
+ ) {
toRemove.push(entName);
}
}
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index 4973ac4d56..3683ea6044 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
@@ -10,9 +10,21 @@ const runtime = vi.hoisted(() => ({
manifest: Record<string, unknown>;
dir: string;
enabled: boolean;
+ approval?:
+ | { state: 'approved'; revision: string }
+ | { state: 'legacy-unapproved' }
+ | { state: 'invalid' };
}>,
/** 测试可注入:每次 list() 调用返回不同快照(模拟打包窗口内运行时变动)。 */
- listSequence: null as null | (() => Array<{ manifest: Record<string, unknown>; dir: string; enabled: boolean }>),
+ listSequence: null as null | (() => Array<{
+ manifest: Record<string, unknown>;
+ dir: string;
+ enabled: boolean;
+ approval?:
+ | { state: 'approved'; revision: string }
+ | { state: 'legacy-unapproved' }
+ | { state: 'invalid' };
+ }>),
install: vi.fn(),
uninstall: vi.fn(),
builtinRemoved: new Set<string>(),
@@ -53,7 +65,14 @@ vi.mock('../../logger.js', () => ({
}));
vi.mock('../../cindy-brain/index.js', () => ({
getGhostManager: () => ({
- list: () => (runtime.listSequence ? runtime.listSequence() : runtime.ghosts),
+ list: () =>
+ (runtime.listSequence ? runtime.listSequence() : runtime.ghosts).map((ghost) => ({
+ ...ghost,
+ approval: ghost.approval ?? {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ })),
}),
isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),
installOrUpdateMarketGhostPackage: runtime.install,
@@ -67,6 +86,7 @@ vi.mock('../download.js', () => ({
import type { VisiblePluginSummary } from '@cindy/plugin-protocol';
+import { ghostPermissionBaselineKey, type GhostManifest } from '../../../shared/ghost';
import type { MarketSourceConfig } from '../../../shared/pluginMarket';
import { customMarketPluginId, customMarketReleaseId, marketSourceKey } from '../../../shared/pluginMarket';
import { PluginMarketLedger, ghostManifestDigest } from '../ledger';
@@ -76,6 +96,7 @@ 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 = [];
@@ -427,6 +448,123 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
});
});
+ it('requires full review for an unapproved custom update and carries its receipt token to commit', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const installedManifest = ghostManifest('alpha', '1.0.0');
+ const installedDir = path.join(root, 'installed-alpha');
+ fs.mkdirSync(installedDir, { recursive: true });
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));
+ runtime.ghosts = [
+ {
+ manifest: installedManifest,
+ dir: installedDir,
+ enabled: true,
+ approval: { state: 'legacy-unapproved' },
+ },
+ ];
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ ghostId: 'alpha',
+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(installedManifest),
+ });
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('alpha', '2.0.0'),
+ dir: installedDir,
+ enabled: true,
+ });
+ const pluginId = customMarketPluginId('team-lib', 'alpha');
+ const reviewed = await h.service.detail(pluginId);
+
+ await expect(
+ h.service.install(pluginId, {
+ expectedReleaseId: reviewed.releaseId,
+ expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: 'legacy-unapproved',
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(runtime.install).not.toHaveBeenCalled();
+
+ await h.service.install(pluginId, {
+ expectedReleaseId: reviewed.releaseId,
+ expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: 'legacy-unapproved',
+ allowPermissionExpansion: true,
+ reviewedBaseline: ghostPermissionBaselineKey(installedManifest as GhostManifest),
+ });
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ expectedInstalledApproval: 'legacy-unapproved' }),
+ );
+ });
+
+ it('rejects a custom update when the receipt changes during packaging', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const installedManifest = ghostManifest('alpha');
+ const installedDir = path.join(root, 'installed-alpha');
+ fs.mkdirSync(installedDir, { recursive: true });
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));
+ h.ledger.upsertInstallation({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ ghostId: 'alpha',
+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(installedManifest),
+ });
+ const calls = { n: 0 };
+ runtime.listSequence = () => {
+ calls.n += 1;
+ return [
+ {
+ manifest: installedManifest,
+ dir: installedDir,
+ enabled: true,
+ approval:
+ calls.n >= 2
+ ? { state: 'invalid' as const }
+ : {
+ state: 'approved' as const,
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ },
+ ];
+ };
+ const pluginId = customMarketPluginId('team-lib', 'alpha');
+ const reviewed = await h.service.detail(pluginId);
+
+ await expect(
+ h.service.install(pluginId, {
+ expectedReleaseId: reviewed.releaseId,
+ expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
it('rejects install when the reviewed release no longer matches', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
@@ -1073,6 +1211,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
expectedManifest: reviewed.manifest,
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
});
expect(h.ledger.installationForGhost('alpha')).toMatchObject({
installed: true,
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 d499ca05a3..524626af8a 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -4,17 +4,14 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ghostPermissionBaselineKey } from '../../../shared/ghost.js';
+import { ghostPermissionBaselineKey, type GhostInstallApproval } from '../../../shared/ghost.js';
const runtime = vi.hoisted(() => ({
ghosts: [] as Array<{
manifest: Record<string, unknown>;
dir: string;
enabled: boolean;
- approval?: {
- state: 'approved';
- revision: string;
- };
+ approval?: GhostInstallApproval;
}>,
install: vi.fn(),
uninstall: vi.fn(),
@@ -88,8 +85,7 @@ 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';
+const APPROVED_INSTALL_TOKEN = 'approved:00000000-0000-4000-8000-000000000001';
/** 手动可控 deferred,用于精确编排"安装在飞行中"的交错。 */
function deferred(): { promise: Promise<void>; resolve: () => void } {
@@ -134,9 +130,7 @@ function manifest(
};
}
-function summary(
- overrides: Partial<VisiblePluginSummary> = {},
-): VisiblePluginSummary {
+function summary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePluginSummary {
return {
id: PLUGIN_ID,
ghostId: 'cindy-test',
@@ -158,7 +152,10 @@ function summary(
};
}
-function detail(item = summary(), slots: ['notify'] | ['notify', 'fs'] = ['notify']): VisiblePluginDetail {
+function detail(
+ item = summary(),
+ slots: ['notify'] | ['notify', 'fs'] = ['notify'],
+): VisiblePluginDetail {
return {
...item,
currentRelease: {
@@ -168,9 +165,7 @@ function detail(item = summary(), slots: ['notify'] | ['notify', 'fs'] = ['notif
};
}
-function removal(
- overrides: Partial<PluginRemovalNotice> = {},
-): PluginRemovalNotice {
+function removal(overrides: Partial<PluginRemovalNotice> = {}): PluginRemovalNotice {
return {
pluginId: PLUGIN_ID,
ghostId: 'cindy-test',
@@ -182,10 +177,7 @@ function removal(
};
}
-function harness(
- items: VisiblePluginSummary[],
- removals: PluginRemovalNotice[] = [],
-) {
+function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[] = []) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-service-'));
roots.push(root);
const ledger = new PluginMarketLedger(path.join(root, 'ledger.json'));
@@ -214,10 +206,7 @@ function harness(
function removalRecord(
overrides: Partial<PluginMarketInstallationRecord> = {},
): PluginMarketInstallationRecord {
- return recordForTest(
- summary({ scope: 'organization', organizationId: 'org-1' }),
- overrides,
- );
+ return recordForTest(summary({ scope: 'organization', organizationId: 'org-1' }), overrides);
}
/** 清理通告测试的运行时 Ghost 目录项。 */
@@ -290,12 +279,14 @@ describe('PluginMarketService migration and defaultInstall', () => {
url: 'https://oss.example.invalid/icons/test.png',
expiresAt: '2026-07-23T00:05:00.000Z',
};
- const h = harness([summary({
- currentRelease: {
- ...summary().currentRelease,
- icon,
- },
- })]);
+ const h = harness([
+ summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ icon,
+ },
+ }),
+ ]);
await expect(h.service.snapshot()).resolves.toMatchObject({
items: [{ icon }],
@@ -304,10 +295,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
it('takes bounded local snapshots instead of reading the ledger per market item', async () => {
- const items = Array.from({ length: 50 }, (_, index) => summary({
- id: `c${index.toString(36).padStart(24, '0')}`,
- ghostId: `cindy-test-${index}`,
- }));
+ const items = Array.from({ length: 50 }, (_, index) =>
+ summary({
+ id: `c${index.toString(36).padStart(24, '0')}`,
+ ghostId: `cindy-test-${index}`,
+ }),
+ );
const h = harness(items);
const read = vi.spyOn(h.ledger, 'read');
@@ -454,14 +447,11 @@ describe('PluginMarketService migration and defaultInstall', () => {
const snapshot = await h.service.snapshot();
- expect(runtime.install).toHaveBeenCalledWith(
- expect.stringMatching(/\.cindy$/),
- {
- ghostId: 'cindy-test',
- version: '1.0.0',
- reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
- },
- );
+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {
+ ghostId: 'cindy-test',
+ version: '1.0.0',
+ reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
+ });
expect(snapshot.items[0]).toMatchObject({
installState: 'installed',
enabled: true,
@@ -538,16 +528,15 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- const { ghost } = await h.service.install(item.id, { expectedReleaseId: item.currentRelease.id });
+ const { ghost } = await h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ });
- expect(runtime.install).toHaveBeenCalledWith(
- expect.stringMatching(/\.cindy$/),
- {
- ghostId: 'cindy-test',
- version: '1.0.0',
- reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
- },
- );
+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {
+ ghostId: 'cindy-test',
+ version: '1.0.0',
+ reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),
+ });
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
expect(ghost?.enabled).toBe(true);
});
@@ -583,9 +572,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
packageSha256: 'a'.repeat(64),
installedBaseline: null,
};
- runtime.install.mockRejectedValueOnce(
- new GhostPackagePermissionReviewRequiredError(review),
- );
+ runtime.install.mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review));
const h = harness([item]);
await expect(
@@ -633,7 +620,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
- it('uses a digest-matched installed manifest as the legacy approval baseline', async () => {
+ it('uses a digest-matched installed manifest as the approved receipt baseline', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -646,6 +633,10 @@ describe('PluginMarketService migration and defaultInstall', () => {
manifest: { ...installed, name: 'Localized Test Plugin' },
dir: installedDir,
enabled: true,
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
},
];
runtime.install.mockResolvedValue({
@@ -742,16 +733,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
const snapshot = await h.service.snapshot();
- expect(runtime.install).toHaveBeenCalledWith(
- expect.stringMatching(/\.cindy$/),
- {
- ghostId: item.ghostId,
- version: item.currentRelease.version,
- // 权限绑定:用户确认的服务端清单(main 命名 reviewedManifest)必须随包传给装入侧
- // 比对(P0:服务端记录与包内 ghost.json 不一致时,不能让"看到 A 权限、批准 B 权限"发生)。
- reviewedManifest: expect.objectContaining({ id: item.ghostId }),
- },
- );
+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {
+ ghostId: item.ghostId,
+ version: item.currentRelease.version,
+ // 权限绑定:用户确认的服务端清单(main 命名 reviewedManifest)必须随包传给装入侧
+ // 比对(P0:服务端记录与包内 ghost.json 不一致时,不能让"看到 A 权限、批准 B 权限"发生)。
+ reviewedManifest: expect.objectContaining({ id: item.ghostId }),
+ });
expect(snapshot.items[0]).toMatchObject({
installState: 'installed',
enabled: true,
@@ -772,7 +760,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).resolves.toMatchObject({
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).resolves.toMatchObject({
ghost: { manifest: { id: 'cindy-test' }, enabled: false },
});
expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);
@@ -831,7 +821,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[NOT_FOUND]');
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).rejects.toThrow('[NOT_FOUND]');
expect(h.api.detail).not.toHaveBeenCalled();
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -992,9 +984,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(manifest()));
runtime.ghosts = [{ ...ghostEntry(notice.ghostId), dir: installDir }];
mockUninstallDropsGhost();
- h.ledger.upsertInstallation(
- removalRecord({ manifestDigest: ghostManifestDigest(manifest()) }),
- );
+ h.ledger.upsertInstallation(removalRecord({ manifestDigest: ghostManifestDigest(manifest()) }));
await expect(h.service.snapshot()).resolves.toMatchObject({
unavailableReason: null,
@@ -1114,15 +1104,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('purges a batch and exposes one combined user notice', async () => {
const secondPluginId = `c${'b'.repeat(24)}`;
- const notices = [
- removal(),
- removal({ pluginId: secondPluginId, ghostId: 'cindy-second' }),
- ];
+ const notices = [removal(), removal({ pluginId: secondPluginId, ghostId: 'cindy-second' })];
const h = harness([], notices);
- runtime.ghosts = [
- ghostEntry('cindy-test'),
- ghostEntry('cindy-second', 'Second Plugin'),
- ];
+ runtime.ghosts = [ghostEntry('cindy-test'), ghostEntry('cindy-second', 'Second Plugin')];
mockUninstallDropsGhost();
h.ledger.upsertInstallation(removalRecord());
h.ledger.upsertInstallation(
@@ -1176,15 +1160,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('continues the snapshot and later removals when one purge fails', async () => {
const secondPluginId = `c${'b'.repeat(24)}`;
- const notices = [
- removal(),
- removal({ pluginId: secondPluginId, ghostId: 'cindy-second' }),
- ];
+ const notices = [removal(), removal({ pluginId: secondPluginId, ghostId: 'cindy-second' })];
const h = harness([], notices);
- runtime.ghosts = [
- ghostEntry('cindy-test'),
- ghostEntry('cindy-second', 'Second Plugin'),
- ];
+ runtime.ghosts = [ghostEntry('cindy-test'), ghostEntry('cindy-second', 'Second Plugin')];
mockUninstallDropsGhost('cindy-test');
h.ledger.upsertInstallation(removalRecord());
h.ledger.upsertInstallation(
@@ -1251,7 +1229,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
installed: false,
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[ALREADY_EXISTS]');
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).rejects.toThrow('[ALREADY_EXISTS]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1283,7 +1263,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
await expect(
@@ -1298,6 +1280,66 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install).toHaveBeenCalledTimes(1);
});
+ it.each(['legacy-unapproved', 'invalid'] as const)(
+ 'requires a full Host-side review before a %s install can be re-approved',
+ async (approvalState) => {
+ const item = summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ id: 'release-2',
+ version: '2.0.0',
+ },
+ });
+ const installedManifest = manifest('cindy-test', '1.0.0', ['notify']);
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));
+ runtime.ghosts = [
+ {
+ manifest: installedManifest,
+ dir: installedDir,
+ enabled: true,
+ approval: { state: approvalState },
+ },
+ ];
+ runtime.install.mockResolvedValue({
+ manifest: manifest('cindy-test', '2.0.0', ['notify']),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(installedManifest),
+ });
+ h.api.detail.mockResolvedValue(detail(item, ['notify']));
+
+ await expect(
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedInstalledApproval: approvalState,
+ }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
+ expect(runtime.install).not.toHaveBeenCalled();
+
+ await expect(
+ h.service.install(item.id, {
+ expectedReleaseId: item.currentRelease.id,
+ expectedInstalledApproval: approvalState,
+ allowPermissionExpansion: true,
+ reviewedBaseline: ghostPermissionBaselineKey(installedManifest),
+ }),
+ ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ expectedInstalledApproval: approvalState }),
+ );
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('previouslyInstalledManifest');
+ },
+ );
+
it('re-checks the reviewed baseline inside the install lock before honouring an expansion', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
@@ -1319,7 +1361,11 @@ describe('PluginMarketService migration and defaultInstall', () => {
enabled: true,
});
const h = harness([item]);
- h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0' });
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ });
h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));
await expect(
@@ -1358,16 +1404,18 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
// 下载窗口期(锁外复核已通过之后)本地 ghosts:update 把已装换成只有 notify
// 的包——此刻目标包相对当前已装多出 fs,而这条从没被审阅过。
- const downloadMock = vi.mocked(
- (await import('../download.js')).downloadVerifiedPlugin,
- );
+ const downloadMock = vi.mocked((await import('../download.js')).downloadVerifiedPlugin);
downloadMock.mockImplementationOnce(async () => {
runtime.ghosts = [
{ manifest: manifest(), dir: '/userData/cindy-brain/cindy-test', enabled: true },
];
});
const h = harness([item]);
- h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0' });
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ });
h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));
await expect(
@@ -1517,7 +1565,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
sizeBytes: item.currentRelease.sizeBytes,
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1533,7 +1583,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
return { plugins: [item], removals: [] };
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
expect(runtime.install).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
@@ -1556,7 +1608,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
return installedGhost;
});
- await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).resolves.toEqual({
+ await expect(
+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
+ ).resolves.toEqual({
ghost: installedGhost,
});
expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.ts
index 99122d8353..fa50c21aa6 100644
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@ -55,6 +55,8 @@ function sanitizeInstallDetail(message: string): string {
export async function installCustomMarketPlugin(input: {
pluginDir: string;
expected: GhostManifest;
+ /** 更新时把审阅所绑定的 Host receipt token 贯穿到最终安装出口。 */
+ expectedInstalledApproval?: string;
/**
* 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。
* 自定义市场按调用方捕获的账户审阅 manifest;打包是异步的,装出前必须
@@ -169,6 +171,9 @@ export async function installCustomMarketPlugin(input: {
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: validated.manifest.id,
version: validated.manifest.version,
+ ...(input.expectedInstalledApproval
+ ? { expectedInstalledApproval: input.expectedInstalledApproval }
+ : {}),
});
// 溯源写入与落位同锁(见 afterCommit 注释)。
await input.afterCommit?.();
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 46234b53c8..f2926714e4 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -11,7 +11,7 @@ import {
import { app, dialog } from 'electron';
import {
- diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
ghostInstallApprovalToken,
ghostPermissionBaselineKey,
isOfficialGhostId,
@@ -52,10 +52,7 @@ import {
import { getClientEndpoint } from '../clientEndpointsService.js';
import { createLogger } from '../logger.js';
import { throwIpcError } from '../utils/ipcValidate.js';
-import {
- GHOST_MANIFEST_MAX_BYTES,
- readBoundedFileNoFollowSync,
-} from '../utils/readBoundedFile.js';
+import { GHOST_MANIFEST_MAX_BYTES, readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';
import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';
import { PluginMarketApi } from './api.js';
@@ -144,8 +141,7 @@ function visiblePluginsForOwner(
): VisiblePluginSummary[] {
return owner.mode === 'local'
? plugins.filter(
- (plugin) =>
- plugin.scope === 'public' && isGhostAvailableForActiveSession(plugin.ghostId),
+ (plugin) => plugin.scope === 'public' && isGhostAvailableForActiveSession(plugin.ghostId),
)
: [...plugins];
}
@@ -205,9 +201,7 @@ function legacyRecordFrom(
};
}
-function ghostIdCounts(
- plugins: readonly VisiblePluginSummary[],
-): Map<string, number> {
+function ghostIdCounts(plugins: readonly VisiblePluginSummary[]): Map<string, number> {
const counts = new Map<string, number>();
for (const plugin of plugins) {
counts.set(plugin.ghostId, (counts.get(plugin.ghostId) ?? 0) + 1);
@@ -249,7 +243,10 @@ function combinedDuplicateGhostIds(
*/
function stripDirectionalControls(text: string): string {
// eslint-disable-next-line no-control-regex
- return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
+ return text.replace(
+ /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,
+ '',
+ );
}
function installedGhostRawManifest(dir: string): GhostManifest | null {
@@ -386,10 +383,11 @@ export class PluginMarketService {
}
requireSameMarketOwner(owner);
const local = this.localInstallSnapshot(ledger);
- const serverItems = plugins.map((plugin) =>
- this.toItem(plugin, duplicateGhostIds, local),
- );
- const items = [...serverItems, ...this.projectCustomItems(customEntries, duplicateGhostIds, local)];
+ const serverItems = plugins.map((plugin) => this.toItem(plugin, duplicateGhostIds, local));
+ const items = [
+ ...serverItems,
+ ...this.projectCustomItems(customEntries, duplicateGhostIds, local),
+ ];
// 聚合完成、返回 Renderer 前最后校验:账号在任一 await 间隙漂移则拒绝,
// 不把按旧账号解析的自定义项/账本状态发给当前会话。
requireSameMarketOwner(owner);
@@ -413,7 +411,10 @@ export class PluginMarketService {
detail.id !== expected.pluginId ||
(expected.ghostId !== undefined && detail.ghostId !== expected.ghostId)
) {
- throwIpcError('GHOST_FILE_INVALID', 'Market detail response does not match the requested Plugin');
+ throwIpcError(
+ 'GHOST_FILE_INVALID',
+ 'Market detail response does not match the requested Plugin',
+ );
}
}
@@ -460,11 +461,7 @@ export class PluginMarketService {
const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);
requireSameMarketOwner(owner);
return {
- ...this.toItem(
- plugin,
- duplicates,
- this.localInstallSnapshot(this.ledgerForOwner(owner)),
- ),
+ ...this.toItem(plugin, duplicates, this.localInstallSnapshot(this.ledgerForOwner(owner))),
manifest: compatible.manifest,
};
});
@@ -479,7 +476,10 @@ export class PluginMarketService {
if (!options.expectedManifest) {
throwIpcError('INVALID_PARAMS', 'The reviewed Plugin manifest is required');
}
- return this.customInstall(customRef, options as typeof options & { expectedManifest: GhostManifest });
+ return this.customInstall(
+ customRef,
+ options as typeof options & { expectedManifest: GhostManifest },
+ );
}
if (!isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
@@ -495,9 +495,7 @@ export class PluginMarketService {
if (!selected) {
throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
}
- if (
- catalog.filter((plugin) => plugin.ghostId === selected.ghostId).length !== 1
- ) {
+ if (catalog.filter((plugin) => plugin.ghostId === selected.ghostId).length !== 1) {
throwIpcError('ALREADY_EXISTS', 'Multiple market Plugins use the same Plugin ID');
}
const plugin = await this.api.detail(pluginId);
@@ -506,10 +504,7 @@ export class PluginMarketService {
// 判定与 ghostId 唯一性判定都是基于 selected 做的,detail 换身份就全绕过了。
this.requireDetailIdentity(plugin, { pluginId, ghostId: selected.ghostId });
if (plugin.currentRelease.id !== options.expectedReleaseId) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin release changed after permission review',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');
}
const existing = getGhostManager()
.list()
@@ -518,9 +513,7 @@ export class PluginMarketService {
// 来源"合并计数,这里必须用同一口径重算,否则被标为 conflict 并禁用的服务端
// 项仍能经普通 UI 流程或直接 IPC 装进来并抢占 ghostId。
const record = ledger.installationForGhost(plugin.ghostId);
- const ownsInstall = Boolean(
- existing && record?.installed && record.pluginId === plugin.id,
- );
+ const ownsInstall = Boolean(existing && record?.installed && record.pluginId === plugin.id);
const assertOwnership = () =>
this.assertSourceOwnsGhostId({
owner,
@@ -561,10 +554,7 @@ export class PluginMarketService {
async uninstall(pluginId: string): Promise<{ ok: true }> {
// 自定义市场插件的卸载走同一账本路径,仅跳过服务端 CUID 形状校验。
- if (
- !parseCustomMarketPluginId(pluginId) &&
- !isValidPluginResourceId(pluginId)
- ) {
+ if (!parseCustomMarketPluginId(pluginId) && !isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
}
const owner = captureMarketOwner();
@@ -804,6 +794,8 @@ export class PluginMarketService {
allowPermissionExpansion?: boolean;
/** 扩权批准所依据的已装权限指纹;安装锁内复核,详见 install() 的说明。 */
reviewedBaseline?: string;
+ /** 审阅时捕获的 receipt 批准态 token;提交前必须仍与当前安装一致。 */
+ expectedInstalledApproval?: string;
},
): Promise<{ ghost: InstalledGhost }> {
const owner = captureMarketOwner();
@@ -825,10 +817,7 @@ export class PluginMarketService {
const pluginId = customMarketPluginId(ref.marketName, plugin.ghostId);
const releaseId = customMarketReleaseId(ref.marketName, plugin.ghostId, plugin.version);
if (releaseId !== options.expectedReleaseId) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin release changed after permission review',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');
}
const existing = getGhostManager()
.list()
@@ -845,11 +834,11 @@ export class PluginMarketService {
: null;
const ownsInstall = Boolean(
existing &&
- currentRecord?.installed &&
- currentRecord.pluginId === pluginId &&
- currentRecord.sourceKey === sourceKey &&
- currentRecord.manifestDigest != null &&
- currentRecord.manifestDigest === reviewInstalledDigest,
+ currentRecord?.installed &&
+ currentRecord.pluginId === pluginId &&
+ currentRecord.sourceKey === sourceKey &&
+ currentRecord.manifestDigest != null &&
+ currentRecord.manifestDigest === reviewInstalledDigest,
);
// 收养:运行时已装内容的声明与本来源候选**完全一致**(原始 manifest 摘要
// 相等)时,允许在没有有效账本记录的情况下重装并补写溯源。这是"包已落位
@@ -858,24 +847,35 @@ export class PluginMarketService {
// 确认框审阅过同一份 manifest;声明有任何差异都收养不了。
const adoptable = Boolean(
existing &&
- !ownsInstall &&
- reviewInstalledDigest === ghostManifestDigest(plugin.manifest),
+ !ownsInstall &&
+ reviewInstalledDigest === ghostManifestDigest(plugin.manifest),
);
if (existing && !ownsInstall && !adoptable) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
- await this.assertSourceOwnsGhostId({ owner, ghostId: plugin.ghostId, ownsInstall });
- if (
- existing &&
- // 与服务端安装同口径:对比已装 manifest 与候选包,只有新增权限才要求
- // 显式确认(upstream 已回退批准 receipt 基线,这里跟随主干口径)。
- diffGhostPermissionItems(existing.manifest, plugin.manifest).added.length > 0
- ) {
+ const assertCustomReviewApproved = (installedNow: InstalledGhost | null): void => {
+ if (!installedNow) return;
+ if (
+ options.expectedInstalledApproval !== undefined &&
+ ghostInstallApprovalToken(installedNow.approval) !== options.expectedInstalledApproval
+ ) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state changed after permission review',
+ );
+ }
+ const requiresFullReview =
+ installedNow.approval.state !== 'approved' ||
+ diffInstalledGhostPermissionItems(installedNow, plugin.manifest).added.length > 0;
+ if (!requiresFullReview) return;
if (options.allowPermissionExpansion !== true) {
throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
}
- assertReviewedBaselineFresh(existing.manifest, options.reviewedBaseline);
- }
+ assertReviewedBaselineFresh(installedNow.manifest, options.reviewedBaseline);
+ };
+ await this.assertSourceOwnsGhostId({ owner, ghostId: plugin.ghostId, ownsInstall });
+ // 无有效 receipt 时不信现场 manifest:目标包全部权限都必须重新确认。
+ assertCustomReviewApproved(existing ?? null);
requireSameMarketOwner(owner);
const ghost = await installCustomMarketPlugin({
pluginDir: plugin.dir,
@@ -916,7 +916,11 @@ export class PluginMarketService {
if (current && installedGhostRawManifestDigest(current.dir) !== reviewInstalledDigest) {
throwIpcError('PRECONDITION_FAILED', 'Installed Plugin changed during the install');
}
+ // raw manifest 摘要不含 Host receipt;内容未变但批准态失效同样必须拒绝
+ // 旧确认,并在下一轮按无批准基线展示全部权限。
+ assertCustomReviewApproved(current ?? null);
},
+ expectedInstalledApproval: options.expectedInstalledApproval,
// 复核与落位的双重互斥:
// - SOURCE_MUTATION_KEY:beforeCommit 返回后包检查还要跑一段,期间不能
// 让来源被增删,否则复核结论在落位前过期。
@@ -924,9 +928,7 @@ export class PluginMarketService {
// 按 id 互斥,beforeCommit 的 runtime 复核到 installOrUpdate 落位之间,
// 同 id 的本地装入/卸载插不进来(否则复核仍会在落位前过期)。
withCommitLock: (fn) =>
- this.withMutation(SOURCE_MUTATION_KEY, () =>
- withGhostInstallLock(plugin.ghostId, fn),
- ),
+ this.withMutation(SOURCE_MUTATION_KEY, () => withGhostInstallLock(plugin.ghostId, fn)),
// 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):
// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。
// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。
@@ -1031,8 +1033,7 @@ export class PluginMarketService {
duplicateGhostIds?: ReadonlySet<string>,
local?: LocalInstallSnapshot,
): PluginMarketItem[] {
- const duplicates =
- duplicateGhostIds ?? combinedDuplicateGhostIds([], entries);
+ const duplicates = duplicateGhostIds ?? combinedDuplicateGhostIds([], entries);
const snapshot = local ?? this.localInstallSnapshot();
return entries.map((entry) => this.customToItem(entry, duplicates, snapshot));
}
@@ -1053,25 +1054,25 @@ export class PluginMarketService {
// conflict 而不是 update-available。
const ownsInstall = Boolean(
ghost &&
- record?.installed &&
- record.pluginId === pluginId &&
- record.sourceKey === marketSourceKey(config.source) &&
- record.manifestDigest != null &&
- record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),
+ record?.installed &&
+ record.pluginId === pluginId &&
+ record.sourceKey === marketSourceKey(config.source) &&
+ record.manifestDigest != null &&
+ record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),
);
// 收养口径与 customInstall 一致:运行时内容声明与候选完全一致时不标 conflict,
// 投影成可安装——这是账本写失败后的自愈入口(conflict 在 UI 被禁用,没有它
// 用户连重试的按钮都没有)。
const adoptable = Boolean(
ghost &&
- !ownsInstall &&
- local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),
+ !ownsInstall &&
+ local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),
);
// 已拥有当前安装记录的来源保留所有权(installed / update-available);
// duplicate 只把未拥有安装的竞争来源标为冲突,避免“先装先得”被降格。
const conflict = Boolean(
(duplicateGhostIds.has(plugin.ghostId) && !ownsInstall) ||
- (ghost && !ownsInstall && !adoptable),
+ (ghost && !ownsInstall && !adoptable),
);
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
@@ -1087,12 +1088,12 @@ export class PluginMarketService {
// 显示成另一副样子(视觉欺骗),控制字符可撑破布局。展示投影一律剥掉
// (保留换行);市场名闸在 discover,这里补齐插件侧同一口径。
name: stripDirectionalControls(plugin.manifest.name),
- description: plugin.manifest.description != null
- ? stripDirectionalControls(plugin.manifest.description)
- : null,
- author: plugin.manifest.author != null
- ? stripDirectionalControls(plugin.manifest.author)
- : null,
+ description:
+ plugin.manifest.description != null
+ ? stripDirectionalControls(plugin.manifest.description)
+ : null,
+ author:
+ plugin.manifest.author != null ? stripDirectionalControls(plugin.manifest.author) : null,
// scope 是服务端授权概念,自定义市场项无服务端身份;展示层按 sourceType 分流。
scope: 'public',
organizationId: null,
@@ -1115,9 +1116,7 @@ export class PluginMarketService {
* 写操作落在错误账户。新增 owner-bound 方法只允许经此入口,从结构上
* 杜绝逐路径漏加 generation 校验。
*/
- private async runForOwner<T>(
- operation: (owner: ActiveAppSession) => Promise<T>,
- ): Promise<T> {
+ private async runForOwner<T>(operation: (owner: ActiveAppSession) => Promise<T>): Promise<T> {
const owner = captureMarketOwner();
let result: T;
try {
@@ -1136,9 +1135,7 @@ export class PluginMarketService {
private sourceManagerForOwner(owner: ActiveAppSession): MarketSourceManager {
requireSameMarketOwner(owner);
return new MarketSourceManager({
- store: this.sourceStore.bind(
- ownerScopedUserDataPath('plugin-market', 'sources.v1.json'),
- ),
+ store: this.sourceStore.bind(ownerScopedUserDataPath('plugin-market', 'sources.v1.json')),
cloneRoot: ownerScopedUserDataPath('plugin-market', 'sources'),
});
}
@@ -1182,13 +1179,9 @@ export class PluginMarketService {
if (
existing &&
options.expectedInstalledApproval !== undefined &&
- ghostInstallApprovalToken(existing.approval) !==
- options.expectedInstalledApproval
+ ghostInstallApprovalToken(existing.approval) !== options.expectedInstalledApproval
) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin approval state changed after permission review',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin approval state changed after permission review');
}
const compatible = validateGhostManifest(plugin.currentRelease.manifest);
@@ -1203,15 +1196,18 @@ export class PluginMarketService {
* 旧的 reviewedBaseline 会放行相对**新** manifest 多出来的权限——
* 那些权限用户从没审过。锁内这次才是不可绕过的那道。
*/
- const assertExpansionApproved = (installedNow: GhostManifest | null): void => {
+ const assertExpansionApproved = (installedNow: InstalledGhost | null): void => {
if (!installedNow) return;
- if (diffGhostPermissionItems(installedNow, compatible.manifest).added.length === 0) return;
+ const requiresFullReview =
+ installedNow.approval.state !== 'approved' ||
+ diffInstalledGhostPermissionItems(installedNow, compatible.manifest).added.length > 0;
+ if (!requiresFullReview) return;
if (options.allowPermissionExpansion !== true) {
throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
}
- assertReviewedBaselineFresh(installedNow, options.reviewedBaseline);
+ assertReviewedBaselineFresh(installedNow.manifest, options.reviewedBaseline);
};
- assertExpansionApproved(existing?.manifest ?? null);
+ assertExpansionApproved(existing ?? null);
const download = await this.api.download(plugin.id, plugin.currentRelease.id);
requireSameMarketOwner(owner);
if (
@@ -1245,12 +1241,10 @@ export class PluginMarketService {
);
}
// 同锁外那道:仅当确认时捕获过批准令牌才做锁内权威复核(TOCTOU)。
- // 未带令牌的更新(如相对 legacy 安装的原位更新)不受此闸,由 reviewedBaseline
- // 复核扩权、由 stillInstalled 存在性挡"下载期间被卸载"。
+ // 未带令牌的旧调用方仍由最终装入出口 fail closed;正常更新入口都应带 token。
if (
options.expectedInstalledApproval !== undefined &&
- ghostInstallApprovalToken(stillInstalled.approval) !==
- options.expectedInstalledApproval
+ ghostInstallApprovalToken(stillInstalled.approval) !== options.expectedInstalledApproval
) {
throwIpcError(
'PRECONDITION_FAILED',
@@ -1290,15 +1284,17 @@ export class PluginMarketService {
const installedNow = getGhostManager()
.list()
.find((ghost) => ghost.manifest.id === plugin.ghostId);
- assertExpansionApproved(installedNow?.manifest ?? null);
+ assertExpansionApproved(installedNow ?? null);
const currentRecordNow = ledger.installationForGhost(plugin.ghostId);
const installedRawManifest = installedNow
? installedGhostRawManifest(installedNow.dir)
: null;
const previouslyInstalledManifest =
+ installedNow?.approval.state === 'approved' &&
installedRawManifest &&
currentRecordNow?.installed &&
- (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&
+ (currentRecordNow.source === 'market' ||
+ currentRecordNow.source === 'legacy-adopted') &&
currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
? installedRawManifest
: undefined;
@@ -1352,15 +1348,13 @@ export class PluginMarketService {
): PluginMarketItem {
const ghost = local.ghostsById.get(plugin.ghostId);
const record = local.installations[plugin.ghostId];
- const ownsInstall = Boolean(
- ghost && record?.installed && record.pluginId === plugin.id,
- );
+ const ownsInstall = Boolean(ghost && record?.installed && record.pluginId === plugin.id);
// 与自定义侧 customToItem 对齐:已拥有当前安装记录的来源保留所有权
// (installed / update-available),duplicate 只标未拥有安装的竞争来源,
// 避免先安装者被重复 ghostId 降格、失去更新入口。
const conflict = Boolean(
(duplicateGhostIds.has(plugin.ghostId) && !ownsInstall) ||
- (ghost && (!record?.installed || record.pluginId !== plugin.id)),
+ (ghost && (!record?.installed || record.pluginId !== plugin.id)),
);
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
@@ -1434,9 +1428,7 @@ export class PluginMarketService {
): Promise<void> {
const candidates = Object.values(ledger.read().installations).filter(
(record) =>
- record.source === 'market' &&
- record.installed &&
- record.manifestDigest === undefined,
+ record.source === 'market' && record.installed && record.manifestDigest === undefined,
);
for (const record of candidates) {
const summary = summaries.find(
@@ -1477,9 +1469,7 @@ export class PluginMarketService {
const installed = getGhostManager()
.list()
.find((ghost) => ghost.manifest.id === record.ghostId);
- const installedDigest = installed
- ? installedGhostRawManifestDigest(installed.dir)
- : null;
+ const installedDigest = installed ? installedGhostRawManifestDigest(installed.dir) : null;
if (!installedDigest || installedDigest !== releaseDigest) return;
await this.withLedgerMutation(owner, () => {
const current = ledger.installationForGhost(record.ghostId);
@@ -1582,7 +1572,9 @@ export class PluginMarketService {
if (reason) return skip(removal, reason);
ghostsById ??= new Map(
- getGhostManager().list().map((ghost) => [ghost.manifest.id, ghost]),
+ getGhostManager()
+ .list()
+ .map((ghost) => [ghost.manifest.id, ghost]),
);
const installed = ghostsById.get(removal.ghostId);
if (!installed) return skip(removal, 'runtime-not-installed');
@@ -1623,8 +1615,7 @@ export class PluginMarketService {
}
if (removedNames.length === 0) return;
const key = removalNoticeKey(owner);
- const count =
- (this.pendingRemovalNotices.get(key)?.count ?? 0) + removedNames.length;
+ const count = (this.pendingRemovalNotices.get(key)?.count ?? 0) + removedNames.length;
this.pendingRemovalNotices.set(key, {
count,
name: count === 1 ? (removedNames[0] ?? null) : null,
@@ -1641,9 +1632,7 @@ export class PluginMarketService {
const installSubject = defaultInstallSubject(owner);
const counts = ghostIdCounts(plugins);
const uniqueGhostIds = new Set(
- plugins
- .filter((plugin) => counts.get(plugin.ghostId) === 1)
- .map((plugin) => plugin.ghostId),
+ plugins.filter((plugin) => counts.get(plugin.ghostId) === 1).map((plugin) => plugin.ghostId),
);
const ledgerData = ledger.read();
const local = this.localInstallSnapshot(ledger, ledgerData.installations);
@@ -1706,9 +1695,7 @@ export class PluginMarketService {
private ledgerForOwner(owner: ActiveAppSession): PluginMarketLedger {
requireSameMarketOwner(owner);
- return this.ledger.bind(
- ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
- );
+ return this.ledger.bind(ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'));
}
private withLedgerMutation<T>(
@@ -1747,9 +1734,7 @@ export class PluginMarketService {
private withMutation<T>(pluginId: string, operation: () => Promise<T>): Promise<T> {
const previous = this.mutations.get(pluginId) ?? Promise.resolve();
- const current = previous
- .catch(() => undefined)
- .then(operation);
+ const current = previous.catch(() => undefined).then(operation);
this.mutations.set(pluginId, current);
const cleanup = () => {
if (this.mutations.get(pluginId) === current) this.mutations.delete(pluginId);
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index d200b4fac7..c3ad155f58 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -71,7 +71,6 @@ import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkin
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
import { resolveSystemLocale } from '../../../shared/locale';
import {
- diffGhostPermissionItems,
diffInstalledGhostPermissionItems,
ghostInstallApprovalToken,
ghostPanelKind,
@@ -268,6 +267,13 @@ export const __installedPluginLayoutForTests = {
InstalledPluginDisclosure,
};
+export function diffMarketUpdatePermissionItems(
+ installed: InstalledGhost,
+ next: PluginMarketDetail['manifest'],
+) {
+ return diffInstalledGhostPermissionItems(installed, next);
+}
+
/** 读「忽略本轮更新」的持久值(键按数据归属分桶,见 ignoredRoundStorageKey)。 */
function readIgnoredRound(storageKey: string): string {
try {
@@ -836,14 +842,8 @@ export function GhostPluginPage() {
async (ghostId: string) => {
const marketItem = marketByGhostId.get(ghostId);
if (!marketItem) return;
- const installedGhost =
- ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;
- if (
- !marketReviewTargetsInstalledGhost(
- marketItem,
- installedGhost?.approval.state,
- )
- ) {
+ const installedGhost = ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;
+ if (!marketReviewTargetsInstalledGhost(marketItem, installedGhost?.approval.state)) {
return;
}
if (!installedGhost) {
@@ -857,7 +857,7 @@ export function GhostPluginPage() {
try {
const next = await window.electronAPI.pluginMarket.detail(marketItem.pluginId);
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
- const diff = diffInstalledGhostPermissionItems(installedGhost, next.manifest);
+ const diff = diffMarketUpdatePermissionItems(installedGhost, next.manifest);
const approved = await confirm({
title: t('settings.ghosts.updateConfirm.title', { name: next.name }),
description: t('settings.ghosts.updateConfirm.body', {
@@ -1242,7 +1242,7 @@ export function GhostPluginPage() {
return;
}
const diff = isUpdate
- ? diffGhostPermissionItems(installedGhost!.manifest, marketDetail.manifest)
+ ? diffMarketUpdatePermissionItems(installedGhost!, marketDetail.manifest)
: null;
try {
const confirmed = await confirm({
@@ -1830,9 +1830,7 @@ export function MarketPluginCard({
const unavailable = busy || item.installState === 'conflict';
const conflictDescriptionId = useId();
const conflictDescription =
- item.installState === 'conflict'
- ? t('settings.ghosts.market.conflictDescription')
- : undefined;
+ item.installState === 'conflict' ? t('settings.ghosts.market.conflictDescription') : undefined;
return (
<article
className={cn(
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 62881ec78c..7b5f73a92d 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -28,6 +28,7 @@ vi.mock('@/contexts/AuthContext', () => ({
import {
__installedPluginLayoutForTests,
+ diffMarketUpdatePermissionItems,
GhostPluginCard,
LegacyGhostRecoveryNotice,
MarketPluginCard,
@@ -47,6 +48,41 @@ const {
visibleInstalledPluginItems,
} = __installedPluginLayoutForTests;
+describe('diffMarketUpdatePermissionItems', () => {
+ it.each(['legacy-unapproved', 'invalid'] as const)(
+ 'reviews every target permission for a %s install',
+ (approvalState) => {
+ const manifest = {
+ schemaVersion: 2 as const,
+ id: 'legacy-plugin',
+ name: 'Legacy Plugin',
+ description: 'Legacy approval regression fixture',
+ author: 'Cindy',
+ version: '1.0.0',
+ kind: 'chip' as const,
+ entry: 'main.js',
+ slots: ['notify'] as ['notify'],
+ };
+ const installed = {
+ manifest,
+ dir: 'C:\\plugins\\legacy-plugin',
+ enabled: false,
+ approval: { state: approvalState },
+ };
+ const next = {
+ ...manifest,
+ version: '2.0.0',
+ slots: ['notify', 'fs'] as ['notify', 'fs'],
+ };
+
+ const diff = diffMarketUpdatePermissionItems(installed, next);
+ expect(diff.added.map((item) => item.key)).toEqual(expect.arrayContaining(['notify', 'fs']));
+ expect(diff.removed).toEqual([]);
+ expect(diff.unchanged).toEqual([]);
+ },
+ );
+});
+
const commandPlugin: GhostPluginListItem = {
id: 'filo-google',
name: 'Filo Google',
@@ -414,9 +450,7 @@ describe('MarketPluginCard', () => {
expect((cardBody as HTMLButtonElement).disabled).toBe(true);
expect(cardBody.className).toContain('cursor-not-allowed');
expect(cardBody.className).not.toContain('cursor-wait');
- const conflictDescription = screen.getByText(
- 'settings.ghosts.market.conflictDescription',
- );
+ const conflictDescription = screen.getByText('settings.ghosts.market.conflictDescription');
expect(conflictDescription.id).toBeTruthy();
expect(cardBody.getAttribute('aria-describedby')).toBe(conflictDescription.id);
const conflictAction = screen.getByRole('button', {
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
index 70dacc76f4..2d37b976c8 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
@@ -13,10 +13,19 @@ vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
let installedGhosts: Array<{
manifest: GhostManifest;
- approval?: { state: 'approved'; revision: string };
+ approval?: GhostInstallApproval;
}> = [];
vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
- readInstalledGhostsSnapshot: () => installedGhosts,
+ readInstalledGhostsSnapshot: () =>
+ installedGhosts.map((ghost) => ({
+ ...ghost,
+ dir: 'C:/test/ghost',
+ enabled: true,
+ approval: ghost.approval ?? {
+ state: 'approved',
+ revision: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ },
+ })),
}));
import {
@@ -24,7 +33,11 @@ import {
setDataOwnerGeneration,
} from '@/contexts/dataOwnerGeneration';
import { toast } from '@/lib/toast';
-import { ghostPermissionBaselineKey, type GhostManifest } from '../../../../shared/ghost';
+import {
+ ghostPermissionBaselineKey,
+ type GhostInstallApproval,
+ type GhostManifest,
+} from '../../../../shared/ghost';
import type { PluginMarketDetail, PluginMarketItem } from '../../../../shared/pluginMarket';
import {
__resetUpdateAllBatchForTest,
@@ -69,6 +82,7 @@ function marketItem(overrides: Partial<PluginMarketItem>): PluginMarketItem {
const detailMock = vi.fn<(pluginId: string) => Promise<PluginMarketDetail>>();
const installMock = vi.fn(async () => ({ ghost: { manifest: manifest({}) } }) as never);
+const DEFAULT_APPROVAL_TOKEN = 'approved:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
function stubDetail(overrides: {
manifest: GhostManifest;
@@ -136,6 +150,137 @@ describe('updateAllController', () => {
});
});
+ it.each(['legacy-unapproved', 'invalid'] as const)(
+ 'requires a full permission review for a %s install even when its live manifest matches',
+ async (approvalState) => {
+ const samePermissions = manifest({
+ version: '1.0.0',
+ network: { hosts: ['api.example.com'] },
+ });
+ installedGhosts = [{ manifest: samePermissions, approval: { state: approvalState } }];
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),
+ sourceType: 'server',
+ });
+
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+
+ const held = getUpdateAllBatchState().rows?.[0];
+ expect(held).toMatchObject({
+ status: 'needs-confirm',
+ reviewedApproval: approvalState,
+ });
+ expect(held?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);
+ expect(held?.permissionDiff?.unchanged).toEqual([]);
+ expect(installMock).not.toHaveBeenCalled();
+
+ await approveUpdateExpansion('plugin-a');
+ expect(installMock).toHaveBeenCalledWith('plugin-a', {
+ expectedReleaseId: 'release-2',
+ expectedInstalledApproval: approvalState,
+ allowPermissionExpansion: true,
+ reviewedBaseline: expect.any(String),
+ });
+ },
+ );
+
+ it('requires an explicit confirmation for an unapproved plugin with no optional capabilities', async () => {
+ installedGhosts = [
+ {
+ manifest: manifest({ version: '1.0.0' }),
+ approval: { state: 'legacy-unapproved' },
+ },
+ ];
+ stubDetail({ manifest: manifest({}), sourceType: 'server' });
+
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+
+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
+ status: 'needs-confirm',
+ reviewedApproval: 'legacy-unapproved',
+ permissionDiff: { removed: [], unchanged: [] },
+ });
+ expect(getUpdateAllBatchState().rows?.[0]?.permissionDiff?.added).toEqual([
+ expect.objectContaining({ kind: 'code' }),
+ ]);
+ expect(installMock).not.toHaveBeenCalled();
+ });
+
+ it('invalidates an approved review when its receipt becomes invalid before confirmation', async () => {
+ const revision = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+ installedGhosts = [
+ {
+ manifest: manifest({ version: '1.0.0' }),
+ approval: { state: 'approved', revision },
+ },
+ ];
+ stubDetail({
+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),
+ sourceType: 'server',
+ });
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+
+ installedGhosts = [
+ {
+ manifest: manifest({ version: '1.0.0' }),
+ approval: { state: 'invalid' },
+ },
+ ];
+ await approveUpdateExpansion('plugin-a');
+
+ const rereview = getUpdateAllBatchState().rows?.[0];
+ expect(rereview).toMatchObject({
+ status: 'needs-confirm',
+ staleReview: false,
+ reviewedApproval: 'invalid',
+ });
+ expect(rereview?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);
+ expect(installMock).not.toHaveBeenCalled();
+
+ await approveUpdateExpansion('plugin-a');
+ expect(installMock).toHaveBeenCalledWith('plugin-a', {
+ expectedReleaseId: 'release-2',
+ expectedInstalledApproval: 'invalid',
+ allowPermissionExpansion: true,
+ reviewedBaseline: expect.any(String),
+ });
+ });
+
+ it('keeps package-review permissions complete for an unapproved plugin', async () => {
+ installedGhosts = [
+ {
+ manifest: manifest({ version: '1.0.0' }),
+ approval: { state: 'legacy-unapproved' },
+ },
+ ];
+ const published = manifest({ network: { hosts: ['api.example.com'] } });
+ const actual = manifest({ network: { hosts: ['api.example.com', 'cdn.example.com'] } });
+ stubDetail({ manifest: published, sourceType: 'server' });
+ installMock.mockResolvedValueOnce({
+ reviewRequired: {
+ manifest: actual,
+ packageSha256: 'b'.repeat(64),
+ installedBaseline: ghostPermissionBaselineKey(installedGhosts[0].manifest),
+ },
+ } as never);
+
+ startUpdateAllBatch([marketItem({})]);
+ await waitForSettledBatch();
+ await approveUpdateExpansion('plugin-a');
+
+ const held = getUpdateAllBatchState().rows?.[0];
+ expect(held).toMatchObject({
+ status: 'needs-confirm',
+ reviewedApproval: 'legacy-unapproved',
+ packageReview: { packageSha256: 'b'.repeat(64) },
+ });
+ expect(held?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);
+ expect(held?.permissionDiff?.unchanged).toEqual([]);
+ });
+
it('holds actual package permissions for approval', async () => {
stubDetail({ manifest: manifest({}), sourceType: 'server' });
const review = {
@@ -188,7 +333,7 @@ describe('updateAllController', () => {
await approveUpdateExpansion('plugin-a');
expect(installMock).toHaveBeenLastCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
});
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
});
@@ -207,7 +352,7 @@ describe('updateAllController', () => {
await approveUpdateExpansion('plugin-a');
expect(installMock).toHaveBeenCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
expectedManifest: nextManifest,
allowPermissionExpansion: true,
reviewedBaseline: expect.any(String),
@@ -328,7 +473,7 @@ describe('updateAllController', () => {
expect(installMock).toHaveBeenCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
});
});
@@ -377,7 +522,7 @@ describe('updateAllController', () => {
await approveUpdateExpansion('plugin-a');
expect(installMock).toHaveBeenCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
allowPermissionExpansion: true,
reviewedBaseline: expect.any(String),
});
@@ -449,7 +594,7 @@ describe('updateAllController', () => {
// 目标 release 仍未落账 → 必须真正安装,不得凭版本号收成完成。
expect(installMock).toHaveBeenCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
allowPermissionExpansion: true,
reviewedBaseline: expect.any(String),
});
@@ -670,7 +815,7 @@ describe('updateAllController', () => {
expect(installMock).toHaveBeenLastCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
expectedManifest: expect.anything(),
});
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
@@ -800,7 +945,7 @@ describe('updateAllController', () => {
await approveUpdateExpansion('plugin-a');
expect(installMock).toHaveBeenLastCalledWith('plugin-a', {
expectedReleaseId: 'release-2',
- expectedInstalledApproval: 'legacy-unapproved',
+ expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,
expectedManifest: swappedManifest,
allowPermissionExpansion: true,
reviewedBaseline: expect.any(String),
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index 1cc57aec7c..63e6497bd4 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -23,7 +23,7 @@ import {
type DataOwnerGeneration,
} from '@/contexts/dataOwnerGeneration';
import {
- diffGhostPermissionItems,
+ diffInstalledGhostPermissionItems,
ghostInstallApprovalToken,
ghostPermissionBaselineKey,
type GhostManifest,
@@ -159,6 +159,7 @@ function holdRowForReReview(
staleReview: true,
permissionDiff: undefined,
packageReview: undefined,
+ reviewedApproval: undefined,
...patch,
releaseId,
});
@@ -195,10 +196,6 @@ function installedGhostOf(ghostId: string): InstalledGhost | null {
return readInstalledGhostsSnapshot().find((ghost) => ghost.manifest.id === ghostId) ?? null;
}
-function installedManifestOf(ghostId: string): GhostManifest | null {
- return installedGhostOf(ghostId)?.manifest ?? null;
-}
-
function holdPackageReview(
generation: number,
row: Pick<UpdateAllRow, 'pluginId' | 'ghostId'> & {
@@ -208,11 +205,12 @@ function holdPackageReview(
},
review: PluginMarketPackageReview,
): void {
- const installed = installedManifestOf(row.ghostId);
- if (!installed) {
+ const installedGhost = installedGhostOf(row.ghostId);
+ if (!installedGhost) {
patchRow(generation, row.pluginId, { status: 'skipped' });
return;
}
+ const installed = installedGhost.manifest;
const reviewedBaseline = ghostPermissionBaselineKey(installed);
if (reviewedBaseline !== review.installedBaseline) {
holdRowForReReview(generation, row.pluginId, {
@@ -228,9 +226,10 @@ function holdPackageReview(
fromVersion: installed.version,
toVersion: row.toVersion,
releaseId: row.releaseId,
- permissionDiff: diffGhostPermissionItems(installed, review.manifest),
+ permissionDiff: diffInstalledGhostPermissionItems(installedGhost, review.manifest),
staleReview: false,
reviewedBaseline,
+ reviewedApproval: ghostInstallApprovalToken(installedGhost.approval),
packageReview: review,
expectedManifest: row.expectedManifest,
});
@@ -319,22 +318,25 @@ async function runQueue(generation: number): Promise<void> {
continue;
}
const installedManifest = installedGhost.manifest;
- const diff = diffGhostPermissionItems(installedManifest, detail.manifest);
- if (diff.added.length > 0) {
- // 扩权不自动放行:停在待确认,由用户在弹窗里逐项同意或跳过。
+ const reviewedApproval = ghostInstallApprovalToken(installedGhost.approval);
+ const diff = diffInstalledGhostPermissionItems(installedGhost, detail.manifest);
+ if (installedGhost.approval.state !== 'approved' || diff.added.length > 0) {
+ // 扩权不自动放行;没有有效 receipt 时也不存在可沿用的批准基线,
+ // 即使目标包没有权限项仍要停下来完成一次明确确认。
patchRow(generation, next.pluginId, {
status: 'needs-confirm',
releaseId: detail.releaseId,
permissionDiff: diff,
// 审阅基线绑定权限指纹而非版本号:同版本换 manifest 也能识别。
reviewedBaseline: ghostPermissionBaselineKey(installedManifest),
+ reviewedApproval,
...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
});
continue;
}
const result = await window.electronAPI.pluginMarket.install(next.pluginId, {
expectedReleaseId: detail.releaseId,
- expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),
+ expectedInstalledApproval: reviewedApproval,
...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),
});
if (result.reviewRequired) {
@@ -500,9 +502,10 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
fromVersion: installed.version,
toVersion: detail.version,
releaseId: detail.releaseId,
- permissionDiff: diffGhostPermissionItems(installed, detail.manifest),
+ permissionDiff: diffInstalledGhostPermissionItems(installedGhost, detail.manifest),
staleReview: false,
reviewedBaseline: ghostPermissionBaselineKey(installed),
+ reviewedApproval: ghostInstallApprovalToken(installedGhost.approval),
packageReview: undefined,
expectedManifest: detail.sourceType !== 'server' ? detail.manifest : undefined,
});
@@ -525,9 +528,12 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
? true
: row.expectedManifest !== undefined &&
JSON.stringify(row.expectedManifest) === JSON.stringify(detail.manifest);
+ const reviewedApproval = row.reviewedApproval;
const reviewStillValid =
row.staleReview !== true &&
+ reviewedApproval !== undefined &&
ghostPermissionBaselineKey(installed) === row.reviewedBaseline &&
+ ghostInstallApprovalToken(installedGhost.approval) === reviewedApproval &&
detail.releaseId === row.releaseId &&
manifestStillMatches;
/**
@@ -580,7 +586,7 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
if (reviewStillValid) {
const didInstall = await installOrHoldForReReview({
expectedReleaseId: row.releaseId,
- expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),
+ expectedInstalledApproval: reviewedApproval,
...(row.expectedManifest ? { expectedManifest: row.expectedManifest } : {}),
allowPermissionExpansion: true,
// 审阅基线随批准回传:Main 在安装锁内用当时的已装 manifest 复核,
@@ -594,8 +600,12 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo
});
if (!didInstall) return;
patchRow(generation, pluginId, { status: 'done' });
- } else if (diffGhostPermissionItems(installed, detail.manifest).added.length > 0) {
- // 相对新事实仍是扩权:回到逐项审阅,绝不静默放行未审过的权限。
+ } else if (
+ installedGhost.approval.state !== 'approved' ||
+ diffInstalledGhostPermissionItems(installedGhost, detail.manifest).added.length > 0
+ ) {
+ // 相对新事实仍是扩权,或当前已没有有效批准基线:回到完整审阅,
+ // 绝不拿旧批准静默放行。
holdForReReview();
return;
} else {
@@ -655,26 +665,30 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]
let changed = false;
for (const row of state.rows) {
if (row.status !== 'needs-confirm') continue;
- const installed = installedManifestOf(row.ghostId);
- if (installed === null) {
+ const installedGhost = installedGhostOf(row.ghostId);
+ if (installedGhost === null) {
rows = updateRow(rows, row.pluginId, { status: 'skipped' });
changed = true;
} else if (installStateByPluginId.get(row.pluginId) === 'installed') {
// 目标 release 已落账(main 侧 record.releaseId 对上):无需再装。
rows = updateRow(rows, row.pluginId, { status: 'done' });
changed = true;
- } else if (ghostPermissionBaselineKey(installed) !== row.reviewedBaseline) {
- // 权限基线变了(换版本,或同版本换入不同权限声明):旧审阅作废。
+ } else if (
+ ghostPermissionBaselineKey(installedGhost.manifest) !== row.reviewedBaseline ||
+ ghostInstallApprovalToken(installedGhost.approval) !== row.reviewedApproval
+ ) {
+ // 权限基线或批准态变了(含 approved receipt 失效):旧审阅作废。
rows = updateRow(rows, row.pluginId, {
- fromVersion: installed.version,
+ fromVersion: installedGhost.manifest.version,
permissionDiff: undefined,
staleReview: true,
packageReview: undefined,
+ reviewedApproval: undefined,
});
changed = true;
- } else if (installed.version !== row.fromVersion) {
+ } else if (installedGhost.manifest.version !== row.fromVersion) {
// 权限面没变、只是版本号变了:审阅结论仍然成立,同步展示用版本即可。
- rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });
+ rows = updateRow(rows, row.pluginId, { fromVersion: installedGhost.manifest.version });
changed = true;
}
}
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
index 02b137c640..f0ce83bbeb 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
@@ -49,6 +49,12 @@ export interface UpdateAllRow {
* 当前已装 manifest 重算指纹比对,不一致即作废重审。
*/
reviewedBaseline?: string;
+ /**
+ * 审阅时 Host 下发的批准态 token。manifest 权限指纹相同也不代表授权事实
+ * 相同:approved receipt 失效成 invalid / legacy-unapproved 后,旧的局部 diff
+ * 必须作废并按“无批准基线”重新展示全部权限。
+ */
+ reviewedApproval?: string;
/**
* 非 server 源在审阅时取得的 manifest:主进程对这类来源强制要求安装时
* 传回同一份 reviewed manifest,approve 必须原样带上,否则 INVALID_PARAMS。