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): 安装与打包 .cindy 时保留 Unix 执行位

zhanghengxdfbb612a66c27
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 20ff728b52..7baae09260 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -56,6 +56,7 @@ import {
decodeGhostManualMarkdown,
ghostManualLogicalPathForEntry,
} from './ghostManualValidation.js';
+import { installedFileModeFromZip, isZipSymbolicLinkMode } from './ghostZipPermissions.js';
/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */
export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;
@@ -112,9 +113,7 @@ const DISABLED_MARKER_FILE = '.disabled';
export const TRUST_METADATA_FILE = '.cindy-trust.json';
function isZipSymbolicLink(entry: JSZip.JSZipObject): boolean {
- return (
- typeof entry.unixPermissions === 'number' && (entry.unixPermissions & 0o170000) === 0o120000
- );
+ return isZipSymbolicLinkMode(entry.unixPermissions);
}
/** 只有宿主安装/播种路径可以写入的 Cindy 官方身份。 */
@@ -3774,6 +3773,8 @@ 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 (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.ts
index b26b8b4d23..d01b7d1487 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -12,6 +12,10 @@ import {
type InstalledGhost,
} from '../../../shared/ghost';
import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager, readLegacyGhostApprovalProjection } from '../GhostManager';
+import {
+ installedFileModeFromZip,
+ unixPermissionsForRepackedEntry,
+} from '../ghostZipPermissions';
import { hashApprovedSkillContent } from '../ghostInstallReceipt';
import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess';
@@ -72,6 +76,22 @@ function goodManifest(id = 'hello'): Record<string, unknown> {
};
}
+describe('installedFileModeFromZip', () => {
+ it('normalizes strings, strips special bits, and skips Windows or missing metadata', () => {
+ expect(installedFileModeFromZip('755', 'linux')).toBe(0o755);
+ expect(installedFileModeFromZip(0o4755, 'darwin')).toBe(0o755);
+ expect(installedFileModeFromZip(0o000, 'linux')).toBe(0o600);
+ expect(installedFileModeFromZip(0o120777, 'linux')).toBeNull();
+ expect(installedFileModeFromZip(null, 'linux')).toBeNull();
+ expect(installedFileModeFromZip(0o755, 'win32')).toBeNull();
+ });
+
+ it('does not turn non-directory entry types into executable directories when repacking', () => {
+ expect(unixPermissionsForRepackedEntry(0o120777, true)).toBe(0o040755);
+ expect(unixPermissionsForRepackedEntry(0o040700, true)).toBe(0o040700);
+ });
+});
+
function setupKvManifest(id = 'hello'): Record<string, unknown> {
return {
...goodManifest(id),
@@ -119,6 +139,24 @@ async function makeCindy(
return out;
}
+/** 用 UNIX central-directory metadata 构造 mode 回归包。 */
+async function makeUnixModeCindy(
+ fileName: string,
+ manifest: Record<string, unknown>,
+ versionMarker: string,
+): Promise<string> {
+ const zip = new JSZip();
+ zip.file('ghost.json', JSON.stringify(manifest), { unixPermissions: 0o644 });
+ zip.file('main.js', '// browser entry', { unixPermissions: 0o644 });
+ zip.file('bin/tool', `#!/bin/sh\necho ${versionMarker}\n`, { unixPermissions: 0o755 });
+ zip.file('config.txt', versionMarker, { unixPermissions: 0o644 });
+ zip.file('bin/special', '#!/bin/sh\n', { unixPermissions: 0o4755 });
+ const buf = await zip.generateAsync({ type: 'nodebuffer', platform: 'UNIX' });
+ const out = path.join(workDir, fileName);
+ await fs.promises.writeFile(out, buf);
+ return out;
+}
+
/**
* 造一份**旧布局**安装(#1080 之前的形态):直接把文件写进 rootDir/<id>/,不经
* manager.install() —— 因此状态根里**没有** receipt。用于「从旧状态升级」的迁移回归。
@@ -4629,6 +4667,54 @@ 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');
+
+ if (process.platform !== 'win32') {
+ expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o777)
+ .toBe(0o755);
+ expect((await fs.promises.stat(path.join(rootDir, 'hello', 'config.txt'))).mode & 0o777)
+ .toBe(0o644);
+ const special = await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'special'));
+ expect(special.mode & 0o777).toBe(0o755);
+ expect(special.mode & 0o4000).toBe(0);
+ }
+
+ const v2 = await makeUnixModeCindy(
+ 'modes-v2.cindy',
+ { ...goodManifest(), version: '2.0.0' },
+ 'v2',
+ );
+ expect(await updateGhost(v2)).toHaveProperty('ghost');
+ expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'config.txt'), 'utf8')).toBe('v2');
+ if (process.platform !== 'win32') {
+ expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'tool'))).mode & 0o777)
+ .toBe(0o755);
+ expect((await fs.promises.stat(path.join(rootDir, 'hello', 'config.txt'))).mode & 0o777)
+ .toBe(0o644);
+ expect((await fs.promises.stat(path.join(rootDir, 'hello', 'bin', 'special'))).mode & 0o777)
+ .toBe(0o755);
+ }
+ });
+
+ 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));
+ expect(loaded.files['plain.txt'].unixPermissions).toBeNull();
+ const chmodSpy = vi.spyOn(fs.promises, 'chmod');
+ try {
+ expect(await manager.install(cindy)).toHaveProperty('ghost');
+ expect(chmodSpy).not.toHaveBeenCalled();
+ await expect(fs.promises.readFile(path.join(rootDir, 'hello', 'plain.txt'), 'utf8'))
+ .resolves.toBe('plain');
+ } finally {
+ chmodSpy.mockRestore();
+ }
+ });
+});
+
describe('GhostManager · update(原位换版)', () => {
it('happy path:版本替换、旧文件清干净、目录不变、onChanged 广播', async () => {
await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts
index 12f6aacc12..55181c021e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts
@@ -137,6 +137,19 @@ function makeDeps(overrides: Partial<Parameters<typeof exportGhostPackage>[1]> =
}
describe('exportGhostPackage', () => {
+ it.skipIf(process.platform === 'win32')(
+ 'round-trips installed Unix execute bits while stripping special bits',
+ async () => {
+ await fs.promises.chmod(path.join(ghostDir, 'main.js'), 0o4755);
+ const result = await exportGhostPackage('hello', makeDeps());
+ expect(result.status).toBe('saved');
+ if (result.status !== 'saved') return;
+
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));
+ expect(Number(zip.files['main.js'].unixPermissions) & 0o7777).toBe(0o755);
+ },
+ );
+
it('打包安装目录为可重新装入的 .cindy(跳过主机点文件)', async () => {
const deps = makeDeps();
const result = await exportGhostPackage('hello', deps);
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 c8eb688065..eedec3ea69 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -137,6 +137,24 @@ async function makeSrcDir(files: Record<string, string | Buffer>): Promise<strin
}
describe('packGhostDir', () => {
+ it.skipIf(process.platform === 'win32')(
+ 'archives real Unix execute bits while stripping special bits',
+ async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': 'export default {};',
+ 'bin/tool': '#!/bin/sh\necho ok\n',
+ });
+ await fs.promises.chmod(path.join(dir, 'bin', 'tool'), 0o4755);
+
+ const packed = await packGhostDir(dir);
+ expect(packed).toMatchObject({ ok: true });
+ if (!packed.ok) return;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));
+ expect(Number(zip.files['bin/tool'].unixPermissions) & 0o7777).toBe(0o755);
+ },
+ );
+
it('writes an in-workdir alias output to the canonical source directory', async () => {
const sourceTarget = path.join(workDir, 'source-target');
const sourceAlias = path.join(workDir, 'source-alias');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts
index bd74b646b0..d0b5dda9fd 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts
@@ -52,6 +52,30 @@ async function readSignature(buffer: Buffer): Promise<GhostSignatureDocument> {
}
describe('ghostSignature · 发布者签名', () => {
+ it('signing and review preserve safe Unix executable metadata', async () => {
+ const source = new JSZip();
+ source.file('ghost.json', JSON.stringify(MANIFEST), { unixPermissions: 0o100644 });
+ source.file('main.js', '// browser brain', { unixPermissions: 0o100755 });
+ source.file('linked-dir/', null, { dir: true, unixPermissions: 0o120777 });
+ const unsigned = await source.generateAsync({ type: 'nodebuffer', platform: 'UNIX' });
+ const publisher = crypto.generateKeyPairSync('ed25519');
+ const reviewer = crypto.generateKeyPairSync('ed25519');
+
+ const signed = await signGhostPackage(unsigned, {
+ publisherName: 'Publisher',
+ privateKey: publisher.privateKey,
+ });
+ const signedZip = await JSZip.loadAsync(signed);
+ expect(Number(signedZip.files['main.js'].unixPermissions) & 0o7777).toBe(0o755);
+ expect(Number(signedZip.files['linked-dir/'].unixPermissions) & 0o7777).toBe(0o755);
+
+ const reviewed = await reviewGhostPackage(signed, {
+ reviewerPrivateKey: reviewer.privateKey,
+ });
+ const reviewedZip = await JSZip.loadAsync(reviewed);
+ expect(Number(reviewedZip.files['main.js'].unixPermissions) & 0o7777).toBe(0o755);
+ });
+
it('无签名可以安装,但明确标为未验证', async () => {
const zip = await JSZip.loadAsync(await unsignedPackage());
const result = await verifyGhostZipSignatures(zip, '', MANIFEST);
diff --git a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
index 6c1ab309fd..3fae769e31 100644
--- a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
+++ b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
@@ -47,6 +47,9 @@ import {
MAX_NODE_ZIP_ENTRIES,
} from './GhostManager.js';
import { GHOST_SIGNATURE_FILE, MAX_SIGNATURE_FILE_BYTES } from './ghostSignature.js';
+import {
+ unixRegularFilePermissionsForArchive,
+} from './ghostZipPermissions.js';
export type ExportGhostPackageResult =
| { status: 'saved'; savedPath: string }
@@ -130,6 +133,7 @@ const MAX_EXPORT_BASENAME_BYTES = 249;
interface PackageEntry {
rel: string;
data: Buffer;
+ unixPermissions: number;
}
// ---------------------------------------------------------------------------
@@ -139,6 +143,7 @@ interface PackageEntry {
interface SignedDoc {
/** 签名文件原始字节(原样进入导出包)。 */
raw: Buffer;
+ unixPermissions: number;
files: Array<{ path: string; sha256: string; bytes: number }>;
}
@@ -180,7 +185,11 @@ async function readSignedDoc(dir: string): Promise<SignedDoc | null> {
}
parsed.push({ path: item.path, sha256: item.sha256, bytes: item.bytes });
}
- return { raw, files: parsed };
+ return {
+ raw,
+ unixPermissions: unixRegularFilePermissionsForArchive(stat.mode),
+ files: parsed,
+ };
}
/** statement 路径必须相对且不逃逸——装入侧已校验,这里防一手目录被改。 */
@@ -195,14 +204,17 @@ function isSafeStatementPath(p: string): boolean {
* 通过即导出包内容——不多不少,可证可重装。
*/
async function readSignedEntries(dir: string, doc: SignedDoc): Promise<PackageEntry[] | null> {
- const out: PackageEntry[] = [{ rel: GHOST_SIGNATURE_FILE, data: doc.raw }];
+ const out: PackageEntry[] = [
+ { rel: GHOST_SIGNATURE_FILE, data: doc.raw, unixPermissions: doc.unixPermissions },
+ ];
for (const item of doc.files) {
if (!isSafeStatementPath(item.path)) return null;
// 先 stat 对尺寸:与 statement 不符必然哈希也不符,不必把可能超限
// 的文件读进内存(评审 P1:巨型缓存文件要先挡在分配之前)。
let data: Buffer;
+ let stat: fs.Stats;
try {
- const stat = await fs.promises.stat(path.join(dir, ...item.path.split('/')));
+ stat = await fs.promises.stat(path.join(dir, ...item.path.split('/')));
if (stat.size !== item.bytes) return null;
data = await fs.promises.readFile(path.join(dir, ...item.path.split('/')));
} catch {
@@ -210,7 +222,11 @@ async function readSignedEntries(dir: string, doc: SignedDoc): Promise<PackageEn
}
if (data.byteLength !== item.bytes) return null;
if (crypto.createHash('sha256').update(data).digest('hex') !== item.sha256) return null;
- out.push({ rel: item.path, data });
+ out.push({
+ rel: item.path,
+ data,
+ unixPermissions: unixRegularFilePermissionsForArchive(stat.mode),
+ });
}
return out;
}
@@ -301,7 +317,12 @@ async function walkTree(
if (budget.entriesLeft < 0 || budget.bytesLeft < 0) {
throw new ExportTooLargeError();
}
- items.push({ rel, data, sha256: sha256hex(data) });
+ items.push({
+ rel,
+ data,
+ sha256: sha256hex(data),
+ unixPermissions: unixRegularFilePermissionsForArchive(stat.mode),
+ });
} else {
const expect = limit as Map<string, number>;
const expectedSize = expect.get(rel);
@@ -309,11 +330,16 @@ async function walkTree(
expectedSize !== undefined ? await fs.promises.stat(abs) : null;
if (expectedSize === undefined || stat!.size !== expectedSize) {
// 第一遍没有的新文件/尺寸被换:与第一遍必然不一致,
- // 不读内容(校验遍读取量由第一遍锚住)。
- items.push({ rel, sha256: '' });
+ // 不读内容(校验遍读取量由第一遍锚住)。空 sha256 已足够让一致性
+ // 比对失败,mode 只需占位——0 在这里不代表"权限 0",不会入包。
+ items.push({ rel, sha256: '', unixPermissions: 0 });
} else {
const data = await fs.promises.readFile(abs);
- items.push({ rel, sha256: sha256hex(data) });
+ items.push({
+ rel,
+ sha256: sha256hex(data),
+ unixPermissions: unixRegularFilePermissionsForArchive(stat!.mode),
+ });
}
}
hasContent = true;
@@ -344,7 +370,9 @@ async function snapshotUnsignedTree(
first.items.length === verify.items.length &&
first.items.every(
(file, i) =>
- file.rel === verify.items[i]!.rel && file.sha256 === verify.items[i]!.sha256,
+ file.rel === verify.items[i]!.rel &&
+ file.sha256 === verify.items[i]!.sha256 &&
+ file.unixPermissions === verify.items[i]!.unixPermissions,
);
const dirsConsistent =
first.emptyDirs.length === verify.emptyDirs.length &&
@@ -458,7 +486,11 @@ async function snapshotPackage(
const tree = await snapshotUnsignedTree(dir, budget);
if (tree) {
return {
- entries: tree.files.map(({ rel, data }) => ({ rel, data })),
+ entries: tree.files.map(({ rel, data, unixPermissions }) => ({
+ rel,
+ data,
+ unixPermissions,
+ })),
emptyDirs: tree.emptyDirs,
};
}
@@ -508,14 +540,18 @@ export async function exportGhostPackage(
zip.folder(rel);
}
for (const file of snapshot.entries) {
- zip.file(file.rel, file.data);
+ zip.file(file.rel, file.data, { unixPermissions: file.unixPermissions });
}
if (Object.keys(zip.files).length > limits.maxEntries) {
return { status: 'error', code: 'too_large' };
}
let buf: Buffer;
try {
- buf = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
+ buf = await zip.generateAsync({
+ type: 'nodebuffer',
+ compression: 'DEFLATE',
+ platform: 'UNIX',
+ });
} catch {
// 压缩失败(zlib 等)如实落到结构化结果,不冒成未捕获的 IPC 异常。
return { status: 'error', code: 'compress_failed' };
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index caf1549d43..c54e0e042f 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -42,6 +42,10 @@ import {
} from './ghostManualValidation.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
import { GHOST_SIGNATURE_FILE } from './ghostSignature.js';
+import {
+ ARCHIVE_REGULAR_0644,
+ unixRegularFilePermissionsForArchive,
+} from './ghostZipPermissions.js';
import { isPathInsideDir } from './dirDeposit.js';
import { checkSkillMdConsistency } from './skillSlot.js';
@@ -721,20 +725,22 @@ async function buildGhostPackage(
// 文件耗尽内存。快照字节也必须出自这把闸,不能再按路径重读。
let manifestRaw: unknown;
let manifestBytes: Buffer;
+ let manifestUnixPermissions: number;
try {
- const bytes = await readBoundedFileNoFollow(
+ const read = await readBoundedFileNoFollowWithStat(
path.join(realDir, GHOST_MANIFEST_FILE),
GHOST_MANIFEST_MAX_BYTES,
{ containWithin: realDir },
);
- if (bytes === null) {
+ if (read === null) {
return {
ok: false,
errorCode: 'MANIFEST_INVALID',
message: `${GHOST_MANIFEST_FILE} 不是普通文件或超过 ${GHOST_MANIFEST_MAX_BYTES} 字节上限`,
};
}
- manifestBytes = bytes;
+ manifestBytes = read.bytes;
+ manifestUnixPermissions = unixRegularFilePermissionsForArchive(read.stat.mode);
manifestRaw = JSON.parse(manifestBytes.toString('utf-8'));
} catch (err) {
return {
@@ -846,7 +852,10 @@ async function buildGhostPackage(
// Markdown 文件;逐文件限量、严格 UTF-8,并拒绝并发截短与二进制内容。
// 缓存本次校验过的字节,生成 zip 时直接使用同一份快照,避免“预检一份、
// 入包时又读到另一份”的竞态。嵌套单元共享缓存,同一物理文件只校验一次。
- const manualFileSnapshots = new Map<string, Buffer>();
+ const manualFileSnapshots = new Map<
+ string,
+ { bytes: Buffer; unixPermissions: number }
+ >();
for (const item of manifest.manual?.items ?? []) {
const unitRoot = path.join(dir, ...item.dir.split('/'));
const validateManualDir = async (
@@ -932,7 +941,10 @@ async function buildGhostPackage(
message: `manual 文件不合格(${logicalPath}):${decoded.reason}`,
};
}
- manualFileSnapshots.set(logicalPath, read.bytes);
+ manualFileSnapshots.set(logicalPath, {
+ bytes: read.bytes,
+ unixPermissions: unixRegularFilePermissionsForArchive(read.stat.mode),
+ });
}
return null;
};
@@ -1129,29 +1141,35 @@ async function buildGhostPackage(
let packedBytes = 0;
for (const f of files) {
let content: Buffer;
+ let unixPermissions: number;
if (f.rel === GHOST_MANIFEST_FILE) {
content = manifestBytes;
+ unixPermissions = manifestUnixPermissions;
} else if (iconPng !== undefined && f.rel === FORGE_AI_ICON_PATH) {
content = iconPng;
+ unixPermissions = ARCHIVE_REGULAR_0644;
} else if (manualFileSnapshots.has(f.rel)) {
- content = manualFileSnapshots.get(f.rel)!;
+ const snapshot = manualFileSnapshots.get(f.rel)!;
+ content = snapshot.bytes;
+ unixPermissions = snapshot.unixPermissions;
} else {
- let bytes: Buffer | null;
+ let read: Awaited<ReturnType<typeof readBoundedFileNoFollowWithStat>>;
try {
- bytes = await readBoundedFileNoFollow(f.abs, maxTotalBytes - packedBytes, {
+ read = await readBoundedFileNoFollowWithStat(f.abs, maxTotalBytes - packedBytes, {
containWithin: realDir,
});
} catch {
- bytes = null;
+ read = null;
}
- if (bytes === null) {
+ if (read === null) {
return {
ok: false,
errorCode: 'TOO_LARGE',
message: `文件在打包期间被并发改动或超出剩余体积预算:${f.rel}`,
};
}
- content = bytes;
+ content = read.bytes;
+ unixPermissions = unixRegularFilePermissionsForArchive(read.stat.mode);
}
packedBytes += content.byteLength;
if (packedBytes > maxTotalBytes) {
@@ -1161,7 +1179,7 @@ async function buildGhostPackage(
message: `总体积超上限(${maxTotalBytes} 字节)`,
};
}
- zip.file(f.rel, content);
+ zip.file(f.rel, content, { unixPermissions });
}
if (iconPng !== undefined && !iconSourceEntry) {
packedBytes += iconPng.byteLength;
@@ -1172,9 +1190,13 @@ async function buildGhostPackage(
message: `总体积超上限(${maxTotalBytes} 字节)`,
};
}
- zip.file(FORGE_AI_ICON_PATH, iconPng);
+ zip.file(FORGE_AI_ICON_PATH, iconPng, { unixPermissions: ARCHIVE_REGULAR_0644 });
}
- const buf = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
+ const buf = await zip.generateAsync({
+ type: 'nodebuffer',
+ compression: 'DEFLATE',
+ platform: 'UNIX',
+ });
const maxCindyBytes = manifest.node ? MAX_NODE_CINDY_BYTES : MAX_BASIC_CINDY_BYTES;
if (buf.byteLength > maxCindyBytes) {
return {
@@ -4042,6 +4064,9 @@ const opened = await cindy.iosSimulator.request({
开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;
2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;
产物落在源码目录里(\`<id>-<version>.cindy\`,同版本覆盖,下次打包自动跳过);
+ macOS / Linux 源文件的普通 Unix 权限会原样进入包(特殊位会剥除),所以随包本机
+ 可执行程序必须在打包前就设好执行位(例如 \`chmod 755 path/to/program\`),不要靠
+ 文件扩展名或 \`bin/\` 目录让宿主猜测;
若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,
按上一步迁出源码后再打包;也可能返回 \`SOURCE_OUTSIDE_WORKDIR\`(源码不在会话工作目录内);
3. **告知用户去点弹窗**(装入默认沉睡,提醒用户勾"立即开启"或到主界面侧边栏「插件」中唤醒);
diff --git a/apps/desktop/src/main/cindy-brain/ghostSignature.ts b/apps/desktop/src/main/cindy-brain/ghostSignature.ts
index 742331bce0..3915e94e1d 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSignature.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSignature.ts
@@ -20,6 +20,9 @@ import {
type GhostTrustInfo,
validateGhostManifest,
} from '../../shared/ghost.js';
+import {
+ unixPermissionsForRepackedEntry,
+} from './ghostZipPermissions.js';
export const GHOST_SIGNATURE_FILE = 'cindy-signatures.json';
export const MAX_SIGNATURE_FILE_BYTES = 64 * 1024;
@@ -394,6 +397,17 @@ export interface SignGhostPackageOptions {
privateKey: crypto.KeyLike;
}
+/**
+ * Signing and review regenerate the ZIP central directory. Pin sanitized UNIX
+ * modes first so those pipeline steps do not erase Forge/export executable
+ * bits or propagate special/file-type bits from an untrusted input package.
+ */
+function preserveSafeUnixPermissionsForRepack(zip: JSZip): void {
+ for (const entry of Object.values(zip.files)) {
+ entry.unixPermissions = unixPermissionsForRepackedEntry(entry.unixPermissions, entry.dir);
+ }
+}
+
/** 发布流水线使用:给一个未签名/重签的 .cindy Buffer 添加 Ed25519 发布者签名。 */
export async function signGhostPackage(
packageBuffer: Buffer,
@@ -429,7 +443,8 @@ export async function signGhostPackage(
},
};
zip.file(`${prefix}${GHOST_SIGNATURE_FILE}`, `${JSON.stringify(document, null, 2)}\n`);
- return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
+ preserveSafeUnixPermissionsForRepack(zip);
+ return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE', platform: 'UNIX' });
}
export interface ReviewGhostPackageOptions {
@@ -465,7 +480,8 @@ export async function reviewGhostPackage(
},
};
zip.file(`${prefix}${GHOST_SIGNATURE_FILE}`, `${JSON.stringify(document, null, 2)}\n`);
- return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
+ preserveSafeUnixPermissionsForRepack(zip);
+ return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE', platform: 'UNIX' });
}
function detectSingleTopFolderPrefix(names: string[]): string {
diff --git a/apps/desktop/src/main/cindy-brain/ghostZipPermissions.ts b/apps/desktop/src/main/cindy-brain/ghostZipPermissions.ts
new file mode 100644
index 0000000000..5708c57840
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostZipPermissions.ts
@@ -0,0 +1,102 @@
+/**
+ * ZIP external-attribute 权限位的唯一归一化入口:解包侧(安装器)、打包侧
+ * (forge / export)与重打包侧(签名 / 审核)共用同一套判据,避免各自写一份掩码。
+ */
+
+/** POSIX `st_mode` 分区:文件类型位、普通权限位。 */
+const S_IFMT = 0o170000;
+const S_IFREG = 0o100000;
+const S_IFDIR = 0o040000;
+const S_IFLNK = 0o120000;
+const PERMISSION_BITS = 0o777;
+
+/**
+ * 归档里普通文件 / 目录的缺省形态:DOS 包没有 Unix 元数据时的回落值,也是宿主
+ * 自己生成(而非从磁盘读取)的条目该用的属性。
+ */
+export const ARCHIVE_REGULAR_0644 = S_IFREG | 0o644;
+const ARCHIVE_DIR_0755 = S_IFDIR | 0o755;
+
+/**
+ * Parse JSZip's public `unixPermissions` union without relying on its current
+ * load-time normalization to numbers. String permissions are octal by contract.
+ */
+function parseZipUnixPermissions(
+ unixPermissions: number | string | null | undefined,
+): number | null {
+ if (typeof unixPermissions === 'number') {
+ return Number.isSafeInteger(unixPermissions) && unixPermissions >= 0 ? unixPermissions : null;
+ }
+ if (typeof unixPermissions !== 'string' || !/^[0-7]+$/.test(unixPermissions)) {
+ return null;
+ }
+ const parsed = Number.parseInt(unixPermissions, 8);
+ return Number.isSafeInteger(parsed) ? parsed : null;
+}
+
+/** 文件类型位为 0 = 未声明,按调用方期待的类型采信;否则必须严格匹配。 */
+function declaresType(mode: number, type: number): boolean {
+ const fileType = mode & S_IFMT;
+ return fileType === 0 || fileType === type;
+}
+
+/** 归档声明的符号链接:装入侧一律拒绝,不跟随、不落盘。 */
+export function isZipSymbolicLinkMode(
+ unixPermissions: number | string | null | undefined,
+): boolean {
+ const parsed = parseZipUnixPermissions(unixPermissions);
+ return parsed !== null && (parsed & S_IFMT) === S_IFLNK;
+}
+
+/**
+ * 把真实文件的 mode 转成归档用的普通文件属性。只取 rwx 九位:setuid / setgid /
+ * sticky 与宿主的文件类型位都是本机元数据,绝不能进可分发的 `.cindy`。JSZip 需要
+ * POSIX 文件类型位才能写出符合规范的 UNIX external attributes。
+ */
+export function unixRegularFilePermissionsForArchive(mode: number | bigint): number {
+ return S_IFREG | (Number(mode) & PERMISSION_BITS);
+}
+
+/**
+ * Normalize an archive-declared mode before applying it to an extracted file.
+ *
+ * `& 0o777` strips file-type and special bits so an archive cannot install
+ * setuid/setgid/sticky files. `| 0o600` keeps the owner able to read and replace
+ * even a malicious mode-000 entry, which is required for later update/uninstall.
+ * Missing metadata is deliberately ignored for compatibility with DOS/legacy
+ * packages. Windows is also ignored because chmod there only changes the
+ * read-only attribute. The caller must use chmod *after* writeFile: writeFile's
+ * creation mode is filtered by umask, whereas chmod deterministically restores
+ * an archived 0755 as 0755.
+ *
+ * Directory entries are handled separately by the extractor. When an archive
+ * declares a non-regular UNIX file type, no mode is applied to the regular file
+ * bytes that JSZip exposes.
+ */
+export function installedFileModeFromZip(
+ unixPermissions: number | string | null | undefined,
+ platform: NodeJS.Platform = process.platform,
+): number | null {
+ if (platform === 'win32') return null;
+ const parsed = parseZipUnixPermissions(unixPermissions);
+ if (parsed === null || !declaresType(parsed, S_IFREG)) return null;
+ return (parsed & PERMISSION_BITS) | 0o600;
+}
+
+/**
+ * Re-emit an already loaded ZIP entry on the UNIX platform without carrying
+ * special/file-type bits. DOS entries receive ordinary deterministic defaults;
+ * non-regular UNIX entries are downgraded to a non-executable regular file.
+ */
+export function unixPermissionsForRepackedEntry(
+ unixPermissions: number | string | null | undefined,
+ isDirectory: boolean,
+): number {
+ const parsed = parseZipUnixPermissions(unixPermissions);
+ if (parsed === null) return isDirectory ? ARCHIVE_DIR_0755 : ARCHIVE_REGULAR_0644;
+ if (isDirectory) {
+ return declaresType(parsed, S_IFDIR) ? S_IFDIR | (parsed & PERMISSION_BITS) : ARCHIVE_DIR_0755;
+ }
+ if (!declaresType(parsed, S_IFREG)) return ARCHIVE_REGULAR_0644;
+ return S_IFREG | (parsed & PERMISSION_BITS);
+}