Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 已签名包不恢复签名未覆盖的 mode,导出读后复验
zhanghengxd09ac51a85c4c
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 7baae09260..e186877862 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -3756,6 +3756,13 @@ export class GhostManager {},): Promise<void> {await fs.promises.mkdir(stagingDir, { recursive: true });+ // 已签名 / 已审核包**不**采纳归档声明的 mode:签名 statement 只覆盖+ // (path, sha256, bytes),mode 不在其中(`buildStatement`)。恢复一个签名没+ // 覆盖的 mode,等于把未认证的 central-directory 元数据当成已签名事实 ——+ // 能篡改包字节的人可以在验签仍然通过的前提下翻转执行位。未签名包不存在+ // 越过签名边界的问题,照常按声明恢复。待 statement 升 v2 把归一化后的 mode+ // 签进去,这里再对签名包放开。+ const honorArchivedModes = !opts.trust.publisherSigned && !opts.trust.reviewed;let totalBytes = 0;for (const entry of allEntries) {const relName = entry.name.slice(prefix.length);@@ -3773,8 +3780,10 @@ export class GhostManager {}await fs.promises.mkdir(path.dirname(dest), { recursive: true });await fs.promises.writeFile(dest, data);- const mode = installedFileModeFromZip(entry.unixPermissions);- if (mode !== null) await fs.promises.chmod(dest, mode);+ if (honorArchivedModes) {+ const mode = installedFileModeFromZip(entry.unixPermissions);+ if (mode !== null) await fs.promises.chmod(dest, mode);+ }}if (opts.disabled) {await fs.promises.writeFile(path.join(stagingDir, DISABLED_MARKER_FILE), '');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 2acc3608d0..1e3223e811 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -1,3 +1,4 @@+import crypto from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -16,6 +17,7 @@ import {installedFileModeFromZip,unixPermissionsForRepackedEntry,} from '../ghostZipPermissions';+import { signGhostPackage } from '../ghostSignature';import { hashApprovedSkillContent } from '../ghostInstallReceipt';import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess';@@ -4674,7 +4676,20 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {describe('GhostManager · Unix file permissions', () => {it('fresh install and overwrite update preserve declared modes and strip setuid', async () => {const v1 = await makeUnixModeCindy('modes-v1.cindy', goodManifest(), 'v1');- expect(await manager.install(v1)).toHaveProperty('ghost');+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');+ try {+ expect(await manager.install(v1)).toHaveProperty('ghost');+ // Windows 不做正面 mode 断言(chmod 在那里只切只读位),但必须断言我们**确实+ // 没调 chmod**;非 win32 反过来断言确实调过,否则这条路径以后静默退化成+ // 「什么都没做」也会绿。+ if (process.platform === 'win32') {+ expect(chmodSpy).not.toHaveBeenCalled();+ } else {+ expect(chmodSpy).toHaveBeenCalled();+ }+ } finally {+ chmodSpy.mockRestore();+ }if (process.platform !== 'win32') {expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o777)@@ -4703,6 +4718,42 @@ describe('GhostManager · Unix file permissions', () => {}});+ it('signed packages do not restore archive modes the signature never covered', async () => {+ // 签名 statement 只覆盖 (path, sha256, bytes);mode 不在其中。若照旧恢复,+ // 能篡改包字节的人就能在验签仍然通过的前提下翻转执行位。所以已签名包一律+ // 不采纳归档 mode —— 等 statement 升 v2 把归一化 mode 签进去再放开。+ const unsigned = await makeUnixModeCindy('signed-modes.cindy', goodManifest(), 'v1');+ const publisher = crypto.generateKeyPairSync('ed25519');+ const signed = await signGhostPackage(await fs.promises.readFile(unsigned), {+ publisherName: 'Publisher',+ privateKey: publisher.privateKey,+ });+ const signedPath = path.join(workDir, 'signed-modes-out.cindy');+ await fs.promises.writeFile(signedPath, signed);++ // 前提自检:包里确实带着 0755,否则这条用例证明不了任何事。+ const loaded = await JSZip.loadAsync(signed);+ expect(Number(loaded.files['bin/tool'].unixPermissions) & 0o777).toBe(0o755);++ const chmodSpy = vi.spyOn(fs.promises, 'chmod');+ try {+ const installed = await manager.install(signedPath);+ expect(installed).toHaveProperty('ghost');+ expect((installed as { ghost: InstalledGhost }).ghost.trust?.publisherSigned).toBe(true);+ expect(chmodSpy).not.toHaveBeenCalled();+ } finally {+ chmodSpy.mockRestore();+ }+ // 内容照常落盘,只是执行位不恢复(留在文件系统缺省)。+ expect(+ await fs.promises.readFile(path.join(rootDir, 'hello', 'bin', 'tool'), 'utf8'),+ ).toContain('v1');+ if (process.platform !== 'win32') {+ expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o111)+ .toBe(0);+ }+ });+it('DOS packages without unixPermissions still install with filesystem defaults', async () => {const cindy = await makeCindy('dos-modes.cindy', goodManifest(), { 'plain.txt': 'plain' });const loaded = await JSZip.loadAsync(await fs.promises.readFile(cindy));diff --git a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts b/apps/desktop/src/main/cindy-brain/exportGhostPackage.tsindex f667fb5373..9b806d22c6 100644--- a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts+++ b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts@@ -46,10 +46,9 @@ import {MAX_NODE_UNCOMPRESSED_BYTES,MAX_NODE_ZIP_ENTRIES,} from './GhostManager.js';+import { sameStableFileState } from './ghostContentTree.js';import { GHOST_SIGNATURE_FILE, MAX_SIGNATURE_FILE_BYTES } from './ghostSignature.js';-import {- unixRegularFilePermissionsForArchive,-} from './ghostZipPermissions.js';+import { unixRegularFilePermissionsForArchive } from './ghostZipPermissions.js';export type ExportGhostPackageResult =| { status: 'saved'; savedPath: string }@@ -165,12 +164,20 @@ async function readSignedDoc(dir: string): Promise<SignedDoc | null> {throw err;}try {- const stat = await fileHandle.stat();- if (stat.size > MAX_SIGNATURE_FILE_BYTES) throw new Error('signature file too large');+ const stat = await fileHandle.stat({ bigint: true });+ if (stat.size > BigInt(MAX_SIGNATURE_FILE_BYTES)) {+ throw new Error('signature file too large');+ }const raw = await fileHandle.readFile();if (raw.byteLength > MAX_SIGNATURE_FILE_BYTES) {throw new Error('signature file too large');}+ // 同一句柄只挡住 open 与 stat 之间的窗口:chmod 落在读取过程中,仍能造出+ // 「读前的 mode + 读后的字节」。读后复验身份与稳定态(含 ctime,故覆盖 chmod),+ // 变了就如实失败,不把不同时刻的权限和内容拼成一个条目。+ if (!sameStableFileState(stat, await fileHandle.stat({ bigint: true }))) {+ throw new Error('signature file changed while reading');+ }const doc = JSON.parse(raw.toString('utf8')) as {statement?: { files?: Array<{ path?: unknown; sha256?: unknown; bytes?: unknown }> };};@@ -221,9 +228,12 @@ async function readSignedEntries(dir: string, doc: SignedDoc): Promise<PackageEntry {const fileHandle = await fs.promises.open(path.join(dir, ...item.path.split('/')), 'r');try {- const stat = await fileHandle.stat();- if (stat.size !== item.bytes) return null;+ const stat = await fileHandle.stat({ bigint: true });+ if (stat.size !== BigInt(item.bytes)) return null;data = await fileHandle.readFile();+ // 读后复验:同一句柄挡不住读取期间的 chmod,而 mode 与字节必须同时刻。+ // 稳定态判据含 ctime,权限变化也算失效;返回 null 交给调用方整体重试。+ if (!sameStableFileState(stat, await fileHandle.stat({ bigint: true }))) return null;unixPermissions = unixRegularFilePermissionsForArchive(stat.mode);} finally {await fileHandle.close();diff --git a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts b/apps/desktop/src/main/cindy-brain/ghostContentTree.tsindex a90acb84ba..75d8c3fa43 100644--- a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts@@ -184,7 +184,12 @@ function sameFileIdentity(return a.dev === b.dev && a.ino === b.ino;}-function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {+/**+ * 「读取期间这个文件没被换掉也没被改过」的统一判据。`ctimeNs` 让它同时覆盖+ * `chmod` —— 权限变化也算内容快照失效,导出侧据此拒绝把不同时刻的 mode 与字节+ * 拼进同一个归档条目。+ */+export function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {return after.isFile() &&sameFileIdentity(before, after) &&before.size === after.size &&