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): verify built-in Skill identity at discovery

xd-bobob9887e2b26e5
diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
index 9b1fb8a74a..1c917bb3f3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
@@ -2,6 +2,12 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { Maker } from '@cindy/maker-core';
+import { scanAllSkills } from '../../skillhub/scanner';
+
+vi.mock('../../skillhub/registry', () => ({
+ registryService: { listAllInstalls: vi.fn(async () => []), getInstall: vi.fn(async () => null) },
+}));
import {
activeCindyBuiltInAgentSkills,
@@ -473,6 +479,52 @@ describe('built-in Skills', () => {
);
});
+ it.each(['directory', 'outside-link', 'wrong-bundle', 'modified-content', 'missing-manifest', 'linked-bundle'])(
+ 'withholds official identity from %s even after successful preparation',
+ async (damage) => {
+ const input = fixture();
+ const prepared = await prepareBuiltInSkills(input);
+ const root = path.join(input.appDataDir, 'Cindy', 'shared-system-skills');
+ const active = path.join(root, '.active');
+ const target = fs.realpathSync(active);
+ const skillPath = path.join(active, 'cindy-skill-creator');
+ expect(prepared.projectionSafe).toBe(true);
+ expect(builtInSkillDescriptors(input.userDataDir, input.appDataDir)).toHaveLength(2);
+ if (damage === 'modified-content') {
+ fs.appendFileSync(path.join(skillPath, 'SKILL.md'), '\nChanged');
+ } else if (damage === 'missing-manifest') {
+ fs.unlinkSync(path.join(root, '.cindy-system-skills.json'));
+ } else if (damage === 'linked-bundle') {
+ const outside = path.join(input.homeDir, 'substituted-bundle');
+ fs.renameSync(target, outside);
+ fs.symlinkSync(outside, target, process.platform === 'win32' ? 'junction' : 'dir');
+ } else {
+ fs.unlinkSync(active);
+ const replacement = damage === 'directory' ? active
+ : damage === 'outside-link' ? path.join(input.homeDir, 'outside-bundle')
+ : path.join(root, '.versions', 'v10-0123456789abcdef-11111111-1111-1111-1111-111111111111');
+ fs.cpSync(target, replacement, { recursive: true });
+ if (damage !== 'directory') {
+ fs.symlinkSync(replacement, active, process.platform === 'win32' ? 'junction' : 'dir');
+ }
+ }
+ const descriptors = builtInSkillDescriptors(input.userDataDir, input.appDataDir);
+ expect(descriptors).toEqual([]);
+ const [command] = markCindyBuiltInAgentSkills([{
+ kind: 'agent-skill', name: 'cindy-skill-creator', source: 'skill',
+ path: path.join(skillPath, 'SKILL.md'), scope: 'user', enabled: true, builtIn: true,
+ }], descriptors);
+ expect(command?.builtIn).toBeUndefined();
+ const maker = { listCustomizations: async () => ({ errors: [], items: [{
+ engine: 'codex', kind: 'skill', scope: 'user', name: 'cindy-skill-creator',
+ absolutePath: skillPath, mdPath: path.join(skillPath, 'SKILL.md'), files: [],
+ }] }) } as unknown as Maker;
+ const scanned = await scanAllSkills({}, maker, [], descriptors);
+ expect(scanned.skills).toHaveLength(1);
+ expect(scanned.skills[0]?.builtIn).not.toBe(true);
+ },
+ );
+
it('does not overwrite a non-link active pointer placeholder', async () => {
const input = fixture();
await prepareBuiltInSkills(input);
@@ -489,6 +541,7 @@ describe('built-in Skills', () => {
expect(failed.changed).toBe(false);
expect(failed.projectionSafe).toBe(false);
+ expect(failed.descriptors).toEqual([]);
expect(failed.warnings.join('\n')).toContain('active pointer is not a link');
expect(fs.lstatSync(activePath).isDirectory()).toBe(true);
expect(fs.readFileSync(path.join(activePath, 'cindy-skill-creator', 'SKILL.md'), 'utf8')).toBe(
@@ -703,7 +756,8 @@ describe('built-in Skills', () => {
expect(result.changed).toBe(false);
expect(result.warnings.join('\n')).toContain('another Skill mutation is in progress');
- expect(fs.existsSync(result.descriptors[0]!.absolutePath)).toBe(false);
+ expect(result.descriptors).toEqual([]);
+ expect(fs.existsSync(path.join(input.appDataDir, 'Cindy', 'shared-system-skills', '.active'))).toBe(false);
expect(fs.existsSync(path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator'))).toBe(false);
});
@@ -756,12 +810,12 @@ describe('built-in Skills', () => {
it('keeps a user-owned Skill in the isolated Claude config directory', async () => {
const input = fixture();
- const descriptor = builtInSkillDescriptors(input.userDataDir, input.appDataDir)[0]!;
- fs.mkdirSync(descriptor.nativeClaudePath, { recursive: true });
- fs.writeFileSync(path.join(descriptor.nativeClaudePath, 'SKILL.md'), '# Claude user copy\n');
+ const nativeClaudePath = path.join(input.userDataDir, 'claude-home', 'skills', 'cindy-skill-creator');
+ fs.mkdirSync(nativeClaudePath, { recursive: true });
+ fs.writeFileSync(path.join(nativeClaudePath, 'SKILL.md'), '# Claude user copy\n');
const result = await prepareAndProjectBuiltInSkills(input);
- expect(fs.readFileSync(path.join(descriptor.nativeClaudePath, 'SKILL.md'), 'utf8')).toBe(
+ expect(fs.readFileSync(path.join(nativeClaudePath, 'SKILL.md'), 'utf8')).toBe(
'# Claude user copy\n',
);
expect(result.warnings.join('\n')).toContain('already owned by the user');
diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts
index 7ab9b1f495..c8fc4b848a 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -114,8 +114,32 @@ export function builtInSkillDescriptors(
const root = appDataDir
? sharedBuiltInSkillsRoot(appDataDir)
: builtInSkillsRoot(userDataDir);
- const activeRoot = activeBuiltInSkillsRoot(root);
- return builtInSkillDescriptorsAtRoot(activeRoot, userDataDir);
+ // These descriptors confer official identity. Never infer trust from a path's
+ // existence, including after preparation failed or another process changed it.
+ try {
+ const raw = readAtomicFileSync(path.join(root, MANIFEST_FILE));
+ const manifest = raw === null ? null : parseManifest(raw);
+ if (manifest?.schemaVersion !== 3 || !manifest.activeBundle) return [];
+ const active = path.join(root, ACTIVE_BUNDLE_LINK);
+ const target = activeBundleTarget(root, manifest.activeBundle);
+ if (!fs.lstatSync(active).isSymbolicLink()) return [];
+ if (!samePath(path.resolve(root, fs.readlinkSync(active)), target)) return [];
+ // A lexical in-root link must not escape through a substituted parent,
+ // bundle, or Skill directory either.
+ for (const directory of [path.dirname(target), target]) {
+ if (!fs.lstatSync(directory).isDirectory()) return [];
+ }
+ if (!samePath(fs.realpathSync.native(active), fs.realpathSync.native(target))) return [];
+ const descriptors = stableBuiltInSkillDescriptors(root, userDataDir);
+ for (const descriptor of descriptors) {
+ if (!fs.lstatSync(descriptor.absolutePath).isDirectory()) return [];
+ if (hashDirectorySync(descriptor.absolutePath) !== manifest.fingerprints[descriptor.name]) return [];
+ if (!fs.lstatSync(path.join(descriptor.absolutePath, 'SKILL.md')).isFile()) return [];
+ }
+ return descriptors;
+ } catch {
+ return [];
+ }
}
function builtInSkillDescriptorsAtRoot(
@@ -215,6 +239,25 @@ function activeBuiltInSkillsRoot(root: string): string {
}
}
+/** Same fingerprint format as materialization, for synchronous identity readers. */
+function hashDirectorySync(root: string): string {
+ const hash = createHash('sha256');
+ const visit = (directory: string): void => {
+ const entries = fs.readdirSync(directory, { withFileTypes: true });
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const entry of entries) {
+ const absolute = path.join(directory, entry.name);
+ const relative = path.relative(root, absolute).split(path.sep).join('/');
+ hash.update(entry.isDirectory() ? `d\0${relative}\0` : `f\0${relative}\0`);
+ if (entry.isDirectory()) visit(absolute);
+ else if (entry.isFile()) hash.update(fs.readFileSync(absolute));
+ else throw new Error(`unsupported bundled Skill entry: ${relative}`);
+ }
+ };
+ visit(root);
+ return hash.digest('hex');
+}
+
async function hashDirectory(root: string): Promise<string> {
const hash = createHash('sha256');
const visit = async (directory: string): Promise<void> => {
@@ -998,7 +1041,9 @@ export async function prepareBuiltInSkills(
await fsp.mkdir(root, { recursive: true });
const homeDir = options.homeDir ?? os.homedir();
const stableDescriptors = stableBuiltInSkillDescriptors(root, options.userDataDir);
- let descriptors = builtInSkillDescriptors(options.userDataDir, options.appDataDir);
+ // Preparation needs destinations even before a trusted bundle exists.
+ // Keep these private; public readers receive only verified descriptors.
+ let descriptors = builtInSkillDescriptorsAtRoot(activeBuiltInSkillsRoot(root), options.userDataDir);
let manifest: MaterializationManifest;
try {
manifest = await readManifest(root);
@@ -1240,7 +1285,7 @@ export async function prepareBuiltInSkills(
}
return {
- descriptors: builtInSkillDescriptors(options.userDataDir, options.appDataDir),
+ descriptors: projectionSafe ? builtInSkillDescriptors(options.userDataDir, options.appDataDir) : [],
projectionSafe,
changed,
warnings,
diff --git a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
index b7e6f97a8d..c682e85589 100644
--- a/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/activationPreferences.test.ts
@@ -1,11 +1,24 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterAll, describe, expect, it, vi } from 'vitest';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-skill-preferences-'));
vi.mock('electron', () => ({ app: { getPath: () => root } }));
vi.mock('../../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
+beforeAll(async () => {
+ const bundledRoot = path.join(root, 'bundled');
+ for (const name of ['cindy-skill-creator', 'learn']) {
+ fs.mkdirSync(path.join(bundledRoot, name), { recursive: true });
+ fs.writeFileSync(path.join(bundledRoot, name, 'SKILL.md'), `# ${name}\n`);
+ }
+ const { prepareBuiltInSkills } = await import('../../maker-host/built-in-skills');
+ const result = await prepareBuiltInSkills({
+ userDataDir: root, appDataDir: root, homeDir: path.join(root, 'fixture-home'), bundledRoot,
+ withSharedMutation: async (_names, operation) => operation(),
+ });
+ expect(result.projectionSafe).toBe(true);
+});
afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
describe('Skill activation preferences', () => {
@@ -98,8 +111,8 @@ describe('Skill activation preferences', () => {
const prefs = await import('../activationPreferences');
const descriptor = (await import('../../maker-host/built-in-skills')).builtInSkillDescriptors(root, root)[0]!;
fs.mkdirSync(descriptor.absolutePath, { recursive: true });
- fs.writeFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), '# Built in\n');
fs.mkdirSync(path.dirname(descriptor.nativeClaudePath), { recursive: true });
+ fs.rmSync(descriptor.nativeClaudePath, { force: true });
fs.symlinkSync(
descriptor.absolutePath,
descriptor.nativeClaudePath,
@@ -118,7 +131,6 @@ describe('Skill activation preferences', () => {
const userSkill = path.join(root, 'user-owned-cindy-skill-creator');
fs.mkdirSync(descriptor.absolutePath, { recursive: true });
fs.mkdirSync(userSkill, { recursive: true });
- fs.writeFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), '# Built in\n');
fs.writeFileSync(path.join(userSkill, 'SKILL.md'), '# User owned\n');
fs.rmSync(descriptor.nativeClaudePath, { recursive: true, force: true });
fs.mkdirSync(path.dirname(descriptor.nativeClaudePath), { recursive: true });
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 9af78ffa13..47b6820af2 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -95,6 +95,11 @@
| 跨 profile 的 worktree 回收日志位置 | `app.getPath('appData')/Cindy/shared-worktree-recycle-journals`,按日志目录哈希登记原 profile 日志位置,启动日志监听和写入回收记录前原子发布;借用方只读目标资源的原始日志,不复制恢复状态、不代替 owner 执行恢复。索引跨重启保留,原日志不存在时不产生回收意图 |
| 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |
+- 内置 Skill 的官方身份只授予当前 manifest 已提交且指纹匹配的 bundle:`.active` 必须是
+ 指向该版本的合法链接,版本目录与 Skill 内容不能经替换的符号链接越界。物化失败或目录
+ 存在本身不构成官方身份;扫描、命令标记与 Learn 发现共用经验证的描述符。异常占位内容
+ 不覆盖、不认领。实现与回归见 `maker-host/built-in-skills.ts` 及其同名单测。
+
- 禁止把 `process.cwd()`、仓库根或源码目录作为 userData、凭证目录或临时目录的默认回退。
特别不要写 `process.env.TEMP ?? process.cwd()` 一类跨平台会落入仓库的逻辑。
- 使用 `path.join`、`path.resolve` 和现有路径策略,不硬编码平台分隔符,不手拼 `~`、