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。

feat(desktop): support gh-cli plugin credentials (#2023)

Chris Zhang3c3a78f304d0
diff --git a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
index 7a7848346a..37b7281891 100644
--- a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
@@ -112,4 +112,42 @@ describe('createGhCliTokenSource', () => {
expect(await Promise.all([p1, p2])).toEqual(['gho_x', 'gho_x']);
expect(execFileFn).toHaveBeenCalledTimes(1);
});
+
+ it('可用性探测只执行 gh auth status,不读取或污染 token cache', async () => {
+ const execFileFn = vi.fn(
+ (
+ _file: string,
+ args: string[],
+ opts: { timeout: number },
+ cb: ExecCb,
+ ) => {
+ if (args[1] === 'status') {
+ expect(opts.timeout).toBeLessThanOrEqual(1_000);
+ cb(null, 'logged in as octocat', '');
+ } else {
+ expect(opts.timeout).toBe(3_000);
+ cb(null, 'gho_after_probe', '');
+ }
+ },
+ );
+ const src = createGhCliTokenSource({ execFileFn, existsFn: () => false });
+ const expectedGhExecutable = process.platform === 'win32' ? 'gh.exe' : 'gh';
+
+ expect(await src.probeAvailability()).toBe(true);
+ expect(execFileFn).toHaveBeenCalledWith(
+ expectedGhExecutable,
+ ['auth', 'status', '--hostname', 'github.com'],
+ { timeout: expect.any(Number) },
+ expect.any(Function),
+ );
+ expect(await src.readToken()).toBe('gho_after_probe');
+ expect(execFileFn).toHaveBeenCalledTimes(2);
+ });
+
+ it('可用性探测失败只返回 false,不把 stderr/输出写进日志', async () => {
+ const execFileFn = execMock((_file, cb) => cb(new Error('not logged in'), 'secret-like-output', ''));
+ const src = createGhCliTokenSource({ execFileFn, existsFn: () => false });
+ expect(await src.probeAvailability()).toBe(false);
+ expect(execFileFn).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index f6276bc7e5..a06150626a 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -45,7 +45,49 @@ export const MAX_NODE_ZIP_ENTRIES = 2_048;
/** 停用标记文件名(安装目录内;存在即停用)。 */
const DISABLED_MARKER_FILE = '.disabled';
/** 安装时由主机写入的信任快照与权限 receipt;作者包不能提供。 */
-const TRUST_METADATA_FILE = '.cindy-trust.json';
+export const TRUST_METADATA_FILE = '.cindy-trust.json';
+
+/** 只有宿主安装/播种路径可以写入的 Cindy 官方身份。 */
+export const CINDY_OFFICIAL_GHOST_TRUST: GhostTrustInfo = Object.freeze({
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Cindy Plugin Market',
+});
+
+export type GhostHostTrustOverride = 'cindy-official';
+
+/**
+ * 判断一个已投影的 trust 是否确实来自完整官方 receipt。
+ *
+ * 这是 gh-cli 凭证路径的共同安全谓词:不能只看 level,否则残缺或被篡改
+ * 的 `.cindy-trust.json` 可能被误当成官方插件。其它 trust level 仍保留其
+ * 原有兼容字段语义;只有官方 level 要求这组不可缺省的完整字段。
+ */
+export function isCindyOfficialTrustInfo(
+ trust: GhostTrustInfo | null | undefined,
+): boolean {
+ return (
+ trust?.level === CINDY_OFFICIAL_GHOST_TRUST.level &&
+ trust.publisherSigned === CINDY_OFFICIAL_GHOST_TRUST.publisherSigned &&
+ trust.publisherVerified === CINDY_OFFICIAL_GHOST_TRUST.publisherVerified &&
+ trust.reviewed === CINDY_OFFICIAL_GHOST_TRUST.reviewed &&
+ trust.publisherName === CINDY_OFFICIAL_GHOST_TRUST.publisherName
+ );
+}
+
+/** 完整校验官方 Host receipt;只看 level 会把损坏 receipt 误当成已回填。 */
+export function hasCindyOfficialTrustMetadata(dir: string): boolean {
+ try {
+ const bytes = readBoundedFileNoFollowSync(path.join(dir, TRUST_METADATA_FILE), 64 * 1024);
+ if (bytes === null) return false;
+ const raw = JSON.parse(bytes.toString('utf8')) as Record<string, unknown>;
+ return isCindyOfficialTrustInfo(raw as unknown as GhostTrustInfo);
+ } catch {
+ return false;
+ }
+}
interface GhostInstalledHostMetadata {
trust: GhostTrustInfo;
@@ -281,6 +323,10 @@ export class GhostManager {
...(typeof raw.reviewerName === 'string' ? { reviewerName: raw.reviewerName } : {}),
...(typeof raw.unknownReviewer === 'boolean' ? { unknownReviewer: raw.unknownReviewer } : {}),
};
+ // Official trust is a capability-bearing identity. A malformed receipt is
+ // not downgraded into a partially trusted official object; it disappears
+ // from the projection so every consumer fails closed.
+ if (trust.level === 'cindy-official' && !isCindyOfficialTrustInfo(trust)) return null;
const approval = raw.approvedAtResourceProvider;
const approvedAtResourceProviderTool =
approval
@@ -622,7 +668,11 @@ export class GhostManager {
async install(
lizFilePath: string,
- opts?: { initiallyEnabled?: boolean; expectedPackageSha256?: string },
+ opts?: {
+ initiallyEnabled?: boolean;
+ expectedPackageSha256?: string;
+ trustOverride?: GhostHostTrustOverride;
+ },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
// 装入初始启用态由 UI 层决定(装入确认框勾选,默认沉睡);缺省 true
// 保持既有调用方(测试等)语义不变。
@@ -641,7 +691,10 @@ export class GhostManager {
},
};
}
- const { manifest, trust, iconDataUrl, allEntries, prefix } = parsed;
+ const { manifest, iconDataUrl, allEntries, prefix } = parsed;
+ const trust = opts?.trustOverride === 'cindy-official'
+ ? CINDY_OFFICIAL_GHOST_TRUST
+ : parsed.trust;
// 4) 目标目录冲突检查
const root = this.options.getRootDir();
@@ -712,7 +765,7 @@ export class GhostManager {
*/
async update(
lizFilePath: string,
- opts?: { expectedPackageSha256?: string },
+ opts?: { expectedPackageSha256?: string; trustOverride?: GhostHostTrustOverride },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
const parsed = await this.parse(lizFilePath);
if ('rejection' in parsed) return parsed;
@@ -727,7 +780,10 @@ export class GhostManager {
},
};
}
- const { manifest, trust, iconDataUrl, allEntries, prefix } = parsed;
+ const { manifest, iconDataUrl, allEntries, prefix } = parsed;
+ const trust = opts?.trustOverride === 'cindy-official'
+ ? CINDY_OFFICIAL_GHOST_TRUST
+ : parsed.trust;
const root = this.options.getRootDir();
const finalDir = path.join(root, manifest.id);
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 354e6f5898..0406ab8a0b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -6,7 +6,7 @@ import JSZip from 'jszip';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { InstalledGhost } from '../../../shared/ghost';
-import { GhostManager } from '../GhostManager';
+import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager } from '../GhostManager';
/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */
let workDir: string;
@@ -237,6 +237,33 @@ describe('GhostManager · install', () => {
expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);
});
+ it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {
+ const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));
+ const localResult = await manager.install(local);
+ expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });
+ await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });
+
+ const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });
+ expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });
+ const receipt = JSON.parse(
+ await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),
+ ) as { level?: unknown };
+ expect(receipt.level).toBe('cindy-official');
+ expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);
+ expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);
+ });
+
+ it('残缺的官方 receipt 不会被投影为可用的官方 trust', async () => {
+ const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));
+ await manager.install(local, { trustOverride: 'cindy-official' });
+ const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');
+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;
+ delete metadata.publisherName;
+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);
+
+ expect(manager.list()[0]?.trust).toBeUndefined();
+ });
+
it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {
const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
const installed = await manager.install(cindy);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
index 449f0ba731..be23e1c6bd 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
@@ -5,6 +5,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { provisionBuiltinGhosts } from '../builtinGhostProvisioner.js';
+import { isGhostInstallLockHeld } from '../ghostInstallLock.js';
const tempDirs: string[] = [];
@@ -64,4 +65,54 @@ describe('builtinGhostProvisioner locale validation', () => {
expect.objectContaining({ reason: expect.stringContaining('locale.tools 含未知工具') }),
);
});
+
+ it('cindy-github 内置种子首装和旧安装回填都写入官方 Host trust', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ const seedDir = path.join(seedRoot, 'cindy-github');
+ await fs.promises.mkdir(seedDir, { recursive: true });
+ await fs.promises.writeFile(path.join(seedDir, 'main.js'), '// github');
+ await fs.promises.writeFile(
+ path.join(seedDir, 'ghost.json'),
+ JSON.stringify({
+ schemaVersion: 2,
+ id: 'cindy-github',
+ name: 'Cindy GitHub',
+ version: '1.0.0',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'github', description: 'GitHub' }],
+ }),
+ );
+
+ await provisionBuiltinGhosts({ seedRootDirs: [seedRoot], repoRootDir: repoRoot });
+ const trustPath = path.join(repoRoot, 'cindy-github', '.cindy-trust.json');
+ expect(JSON.parse(await fs.promises.readFile(trustPath, 'utf8'))).toMatchObject({
+ level: 'cindy-official',
+ publisherName: 'Cindy Plugin Market',
+ });
+
+ await fs.promises.writeFile(path.join(repoRoot, 'cindy-github', '.disabled'), '');
+ // level 看似正确但其余必填字段缺失:GhostManager 会把它判坏,播种器也必须自愈。
+ await fs.promises.writeFile(trustPath, JSON.stringify({ level: 'cindy-official' }));
+ const second = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ onApplyStart: () => {
+ expect(isGhostInstallLockHeld('cindy-github')).toBe(true);
+ },
+ });
+ expect(second.skipped).toContain('cindy-github');
+ expect(JSON.parse(await fs.promises.readFile(trustPath, 'utf8'))).toMatchObject({
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Cindy Plugin Market',
+ });
+ expect(fs.existsSync(path.join(repoRoot, 'cindy-github', '.disabled'))).toBe(true);
+ expect(await fs.promises.readFile(path.join(repoRoot, 'cindy-github', 'main.js'), 'utf8'))
+ .toBe('// github');
+ });
});
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 e20c53ecb0..2be14db4fa 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -813,6 +813,9 @@ describe('FORGE_GUIDE', () => {
'exchange',
'tokenPath',
'login-email',
+ 'gh-cli',
+ 'gh auth token',
+ 'hostAvailable',
// 多连接(connections,2026-07-14):声明形态 / 设置页协议 / 主机受信确认。
'connections',
'/connections',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts
index 7ff1023375..cba1402976 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts
@@ -24,7 +24,7 @@ const action: Extract<GhostSetupAllowedAction, { kind: 'inline_form' }> = {
},
};
-function manifest(source?: 'user' | 'oauth' | 'login-email' | 'oidc-token'): GhostManifest {
+function manifest(source?: 'user' | 'oauth' | 'login-email' | 'gh-cli' | 'oidc-token'): GhostManifest {
return {
schemaVersion: 2,
id: 'demo',
@@ -141,6 +141,7 @@ describe('executeGhostSetupInlineSubmission', () => {
{ current: assessment('inline_form:different'), currentManifest: manifest() },
{ current: assessment(), currentManifest: manifest('oauth') },
{ current: assessment(), currentManifest: manifest('login-email') },
+ { current: assessment(), currentManifest: manifest('gh-cli') },
{ current: assessment(), currentManifest: manifest('oidc-token') },
]) {
const storeSecret = vi.fn(() => true);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts
index 67eac9cdd8..e745f1e8d8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts
@@ -88,6 +88,31 @@ describe('evaluateGhostSetup · 启发式回落(无 setup 声明)', () => {
});
});
+ it('gh-cli 优先凭证不因备用 PAT 未保存而阻塞插件调用', () => {
+ const m = manifest({
+ id: 'cindy-github',
+ slots: ['tool', 'network'],
+ tools: [{ name: 'github', description: 'GitHub' }],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub authentication',
+ source: 'gh-cli',
+ inject: { ...INJECT, hosts: ['api.github.com'] },
+ },
+ ],
+ },
+ });
+ expect(evaluateGhostSetup(m, probes())).toEqual({
+ ready: true,
+ missingGroups: [],
+ reauth: [],
+ });
+ });
+
it('双 key 任一已保存即就绪(Web Search 形态)', () => {
const m = manifest({
slots: ['tool', 'network'],
@@ -500,7 +525,7 @@ describe('evaluateGhostSetupAssessment · Setup Runtime 完整判定', () => {
expect(evaluateGhostSetup(drifted, probes()).ready).toBe(true);
});
- it('严格模式统一拒绝悬空 connection、缺 settingsHtml 的 kv 与 login-email requirement', () => {
+ it('严格模式统一拒绝悬空 connection、缺 settingsHtml 的 kv 与 Host 派生 requirement', () => {
const connectionDrift = manifest({
slots: ['tool', 'network'],
tools: [{ name: 'work', description: '干活' }],
@@ -555,6 +580,30 @@ describe('evaluateGhostSetupAssessment · Setup Runtime 完整判定', () => {
expect(() => evaluateGhostSetupAssessment(loginEmailDrift, probes(), { revision: 1 })).toThrow(
GhostSetupAssessmentError,
);
+
+ const ghCliDrift = manifest({
+ id: 'cindy-github',
+ slots: ['tool', 'network'],
+ tools: [{ name: 'work', description: '干活' }],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub authentication',
+ source: 'gh-cli',
+ inject: { ...INJECT, hosts: ['api.github.com'] },
+ },
+ ],
+ },
+ });
+ ghCliDrift.setup = {
+ requires: [{ anyOf: [{ kind: 'secret', key: 'github_pat' }] }],
+ };
+ expect(() => evaluateGhostSetupAssessment(ghCliDrift, probes(), { revision: 1 })).toThrow(
+ GhostSetupAssessmentError,
+ );
});
it('OAuth client 未配置时先打开插件设置,client 可用后才允许授权', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
index a9ebfca3b4..1cd6992e54 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
@@ -21,8 +21,10 @@ import {
function fakeGhost(
overrides: {
+ id?: string;
enabled?: boolean;
slots?: string[];
+ trust?: InstalledGhost['trust'];
/** null = 有槽无详单(老包语义);undefined = 默认 brave+tavily 双域名。 */
network?: GhostNetworkNeeds | null;
} = {},
@@ -45,7 +47,7 @@ function fakeGhost(
return {
manifest: {
schemaVersion: 2,
- id: 'web-search',
+ id: overrides.id ?? 'web-search',
name: '搜索',
version: '1.0.0',
kind: 'chip',
@@ -56,6 +58,7 @@ function fakeGhost(
},
dir: '/fake/brain/web-search',
enabled: overrides.enabled ?? true,
+ ...(overrides.trust ? { trust: overrides.trust } : {}),
} as InstalledGhost;
}
@@ -1198,6 +1201,168 @@ describe('networkSlot · 登录邮箱派生凭证(source:login-email)', () => {
});
});
+describe('networkSlot · GitHub CLI 优先凭证(source:gh-cli)', () => {
+ const GITHUB_URL = 'https://api.github.com/user';
+ const githubNetwork: GhostNetworkNeeds = {
+ hosts: ['api.github.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub authentication',
+ source: 'gh-cli',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com'],
+ },
+ },
+ ],
+ };
+
+ function makeGithubSlot(overrides: Partial<NetworkSlotDeps> = {}) {
+ return makeSlot({
+ getGhost: () => fakeGhost({
+ id: 'cindy-github',
+ network: githubNetwork,
+ trust: {
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Cindy Plugin Market',
+ },
+ }),
+ readSecret: () => 'github_pat_fallback',
+ ...overrides,
+ });
+ }
+
+ it('本机 gh token 优先于保险库 PAT,且令牌不回流沙箱', async () => {
+ const readSecret = vi.fn(() => 'github_pat_fallback');
+ const { slot, fetchImpl } = makeGithubSlot({
+ readGhCliToken: async () => 'gho_from_cli',
+ readSecret,
+ });
+ const result = await slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(true);
+ expect(readSecret).not.toHaveBeenCalled();
+ expect((fetchImpl.mock.calls[0][1].headers as Record<string, string>).Authorization).toBe(
+ 'Bearer gho_from_cli',
+ );
+ expect(JSON.stringify(result)).not.toContain('gho_from_cli');
+ });
+
+ it('gh 未安装或未登录时回落到已保存 PAT', async () => {
+ const { slot, fetchImpl } = makeGithubSlot({ readGhCliToken: async () => null });
+ const result = await slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(true);
+ expect((fetchImpl.mock.calls[0][1].headers as Record<string, string>).Authorization).toBe(
+ 'Bearer github_pat_fallback',
+ );
+ });
+
+ it('gh 来源异常仍可回落 PAT;两边都不可用时才阻断并给出双路径指引', async () => {
+ const fallback = makeGithubSlot({
+ readGhCliToken: async () => {
+ throw new Error('spawn failed');
+ },
+ });
+ expect((await fallback.slot.handleFetchRequest('web-search', { url: GITHUB_URL })).ok).toBe(
+ true,
+ );
+
+ const unavailable = makeGithubSlot({
+ readGhCliToken: async () => null,
+ readSecret: () => null,
+ });
+ const result = await unavailable.slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.message).toContain('gh auth login');
+ expect(result.message).toContain('Personal Access Token');
+ }
+ expect(unavailable.fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('仅自报 cindy-github 但没有 Host 官方 trust 时 fail-closed,不读取 gh token 也不发请求', async () => {
+ const readGhCliToken = vi.fn(async () => 'gho_should_not_be_read');
+ const readSecret = vi.fn(() => 'github_pat_fallback');
+ const { slot, fetchImpl } = makeGithubSlot({
+ getGhost: () => fakeGhost({ id: 'cindy-github', network: githubNetwork }),
+ readGhCliToken,
+ readSecret,
+ });
+ const result = await slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(false);
+ expect(readGhCliToken).not.toHaveBeenCalled();
+ expect(readSecret).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('官方 trust receipt 缺少 publisherName 时 fail-closed,不读取 gh token 也不发请求', async () => {
+ const readGhCliToken = vi.fn(async () => 'gho_should_not_be_read');
+ const readSecret = vi.fn(() => 'github_pat_fallback');
+ const { slot, fetchImpl } = makeGithubSlot({
+ getGhost: () => fakeGhost({
+ id: 'cindy-github',
+ network: githubNetwork,
+ trust: {
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ },
+ }),
+ readGhCliToken,
+ readSecret,
+ });
+ const result = await slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(false);
+ expect(readGhCliToken).not.toHaveBeenCalled();
+ expect(readSecret).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['publisherSigned', { publisherSigned: false }],
+ ['publisherVerified', { publisherVerified: false }],
+ ['reviewed', { reviewed: false }],
+ ])('官方 trust receipt 的 %s 被篡改时 fail-closed', async (_field, override) => {
+ const readGhCliToken = vi.fn(async () => 'gho_should_not_be_read');
+ const { slot, fetchImpl } = makeGithubSlot({
+ getGhost: () => fakeGhost({
+ id: 'cindy-github',
+ network: githubNetwork,
+ trust: {
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Cindy Plugin Market',
+ ...override,
+ },
+ }),
+ readGhCliToken,
+ });
+ const result = await slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(false);
+ expect(readGhCliToken).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('保留 ID 检查之外,非 cindy-github 也不能借 gh-cli trust', async () => {
+ const readGhCliToken = vi.fn(async () => 'gho_should_not_be_read');
+ const { slot, fetchImpl } = makeGithubSlot({
+ getGhost: () => fakeGhost({ id: 'third-party', network: githubNetwork }),
+ readGhCliToken,
+ });
+ const result = await slot.handleFetchRequest('web-search', { url: GITHUB_URL });
+ expect(result.ok).toBe(false);
+ expect(readGhCliToken).not.toHaveBeenCalled();
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
+
describe('networkSlot · 目录上传(uploadDir,过户票据)', () => {
const DEPLOY_URL = 'https://api.search.brave.com/deploy';
const VALID_TOKEN = '11111111-2222-4333-8444-555555555555';
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index 2e5eed45e5..6fb124f530 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -9,6 +9,11 @@ import {
type GhostManifest,
} from '../../shared/ghost.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
+import {
+ CINDY_OFFICIAL_GHOST_TRUST,
+ hasCindyOfficialTrustMetadata,
+} from './GhostManager.js';
+import { withGhostInstallLock } from './ghostInstallLock.js';
/**
* builtinGhostProvisioner — 内置意识的启动播种(第一方可信通道)。
@@ -363,45 +368,64 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
continue;
}
- const installedDir = path.join(repoRootDir, id);
- const installedExists = fs.existsSync(path.join(installedDir, GHOST_MANIFEST_FILE));
+ await withGhostInstallLock(id, async () => {
+ const installedDir = path.join(repoRootDir, id);
+ const installedExists = fs.existsSync(path.join(installedDir, GHOST_MANIFEST_FILE));
+
+ // 3) 受众:不命中 → 回收"播种装的"(seeded 台账内),手动装的不动。
+ if (!matchesAudience(config.get(id)?.audience, identity)) {
+ if (seeded.has(id) && installedExists) {
+ markApplyStart();
+ await deps.beforeRemove?.(id);
+ await fs.promises.rm(installedDir, { recursive: true, force: true });
+ seeded.delete(id);
+ outcome.removed.push(id);
+ log?.info('builtin ghost removed: audience no longer matches', { id });
+ } else {
+ outcome.skipped.push(id);
+ }
+ return;
+ }
- // 3) 受众:不命中 → 回收"播种装的"(seeded 台账内),手动装的不动。
- if (!matchesAudience(config.get(id)?.audience, identity)) {
- if (seeded.has(id) && installedExists) {
+ // 4) 指纹比对(忽略点开头文件:`.disabled` 是用户状态不是内容)。
+ if (installedExists) {
+ const seedHash = await hashDirContent(seedDir);
+ const installedHash = await hashDirContent(installedDir);
+ if (seedHash === installedHash) {
+ if (id === 'cindy-github' && !hasCindyOfficialTrustMetadata(installedDir)) {
+ // receipt 与官方字节必须在同一把安装锁内、经同一次 staging swap
+ // 原子落位;不能在 hash 后单独给可能已被替换的目录补 trust。
+ const wasDisabled = fs.existsSync(path.join(installedDir, '.disabled'));
+ markApplyStart();
+ await swapInSeed(seedDir, installedDir, repoRootDir, id, {
+ disabled: wasDisabled,
+ trust: CINDY_OFFICIAL_GHOST_TRUST,
+ });
+ }
+ outcome.skipped.push(id);
+ return;
+ }
+ const wasDisabled = fs.existsSync(path.join(installedDir, '.disabled'));
markApplyStart();
- await deps.beforeRemove?.(id);
- await fs.promises.rm(installedDir, { recursive: true, force: true });
- seeded.delete(id);
- outcome.removed.push(id);
- log?.info('builtin ghost removed: audience no longer matches', { id });
- } else {
- outcome.skipped.push(id);
+ await swapInSeed(seedDir, installedDir, repoRootDir, id, {
+ disabled: wasDisabled,
+ ...(id === 'cindy-github' ? { trust: CINDY_OFFICIAL_GHOST_TRUST } : {}),
+ });
+ seeded.add(id);
+ outcome.updated.push(manifest);
+ log?.info('builtin ghost updated to bundled content', { id, version: manifest.version });
+ return;
}
- continue;
- }
- // 4) 指纹比对(忽略点开头文件:`.disabled` 是用户状态不是内容)。
- if (installedExists) {
- const seedHash = await hashDirContent(seedDir);
- const installedHash = await hashDirContent(installedDir);
- if (seedHash === installedHash) {
- outcome.skipped.push(id);
- continue;
- }
- const wasDisabled = fs.existsSync(path.join(installedDir, '.disabled'));
markApplyStart();
- await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: wasDisabled });
- seeded.add(id);
- outcome.updated.push(manifest);
- log?.info('builtin ghost updated to bundled content', { id, version: manifest.version });
- } else {
- markApplyStart();
- await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: false });
+ await swapInSeed(seedDir, installedDir, repoRootDir, id, {
+ disabled: false,
+ ...(id === 'cindy-github' ? { trust: CINDY_OFFICIAL_GHOST_TRUST } : {}),
+ });
seeded.add(id);
outcome.installed.push(manifest);
log?.info('builtin ghost installed', { id, version: manifest.version });
- }
+ });
} catch (err) {
outcome.skipped.push(id);
log?.warn('builtin ghost provisioning failed', {
@@ -628,7 +652,7 @@ async function swapInSeed(
finalDir: string,
repoRootDir: string,
id: string,
- opts: { disabled: boolean },
+ opts: { disabled: boolean; trust?: typeof CINDY_OFFICIAL_GHOST_TRUST },
): Promise<void> {
const rand = crypto.randomBytes(4).toString('hex');
const stagingDir = path.join(repoRootDir, `.cindy-provisioning-${id}-${rand}`);
@@ -639,6 +663,12 @@ async function swapInSeed(
if (opts.disabled) {
await fs.promises.writeFile(path.join(stagingDir, '.disabled'), '');
}
+ if (opts.trust) {
+ await fs.promises.writeFile(
+ path.join(stagingDir, '.cindy-trust.json'),
+ `${JSON.stringify(opts.trust, null, 2)}\n`,
+ );
+ }
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
throw err;
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 05d2bada7c..eea79247bf 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1258,7 +1258,7 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它
"secrets": [{ // 可选 0–4 条:需要用户填的凭证(你只声明名字和注入位置,值用户填、主机保管)
"key": "api_token", // 小写字母开头,小写/数字/下划线,1–32;禁用宿主保留键(见 §2.1)
"label": "Example API Token", // 给用户看的名称(设置页/确认框)
- "source": "user", // 可选:凭证值来源。"user"(缺省)=用户可在调用前的主机 Setup 卡内填写,也可在你的 settingsHtml 里长期管理/替换/清除(当前仍要求同时声明 settingsHtml,见 §4.7);"login-email"=主机登录邮箱自动派生(用户不填;声明它时不允许再写 url,见 §4.7);"oauth"=主机托管 OAuth 授权,值 = 授权换来的 access token(必须同时声明 oauth 详单,见 §4.7 与下方 oauth 字段);"oidc-token"=主机为当前企业 Membership 按需签发短时 Connection JWT(插件不可读取,必须显式限制 inject.hosts,固定 Authorization: Bearer {value},见 §4.7)
+ "source": "user", // 可选:凭证值来源。"user"(缺省)=用户可在调用前的主机 Setup 卡内填写,也可在你的 settingsHtml 里长期管理/替换/清除(当前仍要求同时声明 settingsHtml,见 §4.7);"login-email"=主机登录邮箱自动派生(用户不填;声明它时不允许再写 url,见 §4.7);"oauth"=主机托管 OAuth 授权,值 = 授权换来的 access token(必须同时声明 oauth 详单,见 §4.7 与下方 oauth 字段);"gh-cli"=仅官方 cindy-github 可用,优先复用本机 gh 登录、不可用时回落同 key 的设置页 PAT;"oidc-token"=主机为当前企业 Membership 按需签发短时 Connection JWT(插件不可读取,必须显式限制 inject.hosts,固定 Authorization: Bearer {value},见 §4.7)
"hint": "在控制台生成后粘贴", // 可选提示(主机 Setup 卡与 settingsHtml 都会用到)
"url": "https://example.com/settings/keys", // 可选:控制台/申请地址(仅 https)。调用前缺凭证时,主机 Setup 卡会在输入框旁展示本地化的「获取凭证」入口;settingsHtml 也可用 <a href> 逐字引用它,点击经主机转系统浏览器打开(见 §4.8「外链」)
"inject": { // 必填:这条凭证怎么进请求
@@ -1319,8 +1319,9 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它
话术)、\`connection:<key>\`(该连接声明下至少添加一条)、
\`{ "kv": "<键名>", "label": "..." }\`(你 /kv 参数里的顶层键非空且不能是宿主保留键;键名主机无先验,
label 必填)。Node 凭证同样可参与 setup.requires。
-- 引用必须逐字指向已声明的 key,悬空引用**打包期就拒**;\`login-email\` 源凭证恒就绪,
- 引用它同样拒(没有配置动作可引导)。kv 引用要求已声明 settingsHtml(没有设置页没人填)。
+- 引用必须逐字指向已声明的 key,悬空引用**打包期就拒**;\`login-email\` /
+ \`gh-cli\` / \`oidc-token\` 这类 Host 派生或优先来源不允许引用(没有可靠的
+ 同步配置动作可引导)。kv 引用要求已声明 settingsHtml(没有设置页没人填)。
- **绝大多数意识不需要写本字段**:不声明时主机走启发式——声明过凭证/连接的意识,
任一项配好即算就绪;什么都没声明的恒就绪。只有启发式判不准才需要显式声明,两种
典型:"必须**同时**配 A 和 B"(多组声明)、"凭证全是**可选项**、一个不配也能用"
@@ -2230,6 +2231,16 @@ BroadcastChannel、日志或任何自存路径(review 必查)。凭证只会注
照"请重新登录"画)——确认框已如实披露,除展示外别拿它做别的;对该 key 的
PUT/DELETE 一律 405(派生身份不可配置)。
+**GitHub CLI 优先凭证(source:"gh-cli",保留能力)**:仅官方 \`cindy-github\`
+插件可声明。主机每次 GitHub API 请求时优先复用本机 \`gh auth token\` 的登录态;
+本机没装 gh、未登录或读取超时时,再回落到同一 key 经 \`/secrets\` 保存的备用 PAT。
+两种 token 都只在 Main 的 networkSlot 内存中进入请求头,插件沙箱、settings 页面、
+Renderer、Agent、KV 和日志都拿不到。设置页 GET \`/secrets\` 对这条 key 额外返回
+\`hostSource:"gh-cli"\` 与 \`hostAvailable:boolean\`,其中 \`saved/tail\` 仍只描述备用
+PAT;页面可据此展示“已检测到 gh,可直接使用”,但不能读取 gh 的账号或 token。
+此来源的注入形态固定为 \`api.github.com\` 的
+\`Authorization: Bearer {value}\`,不允许 exchange,也不要放进 \`setup.requires\`。
+
**Cindy 企业身份断言(source:"oidc-token",可选)**:适用于接入 Cindy Connection
Auth 的企业服务。主机只在当前登录账号属于组织 Membership、且该插件拥有当前组织的
Plugin Market organization 安装记录、安装 manifest digest 未被篡改并声明了目标服务域名时,
@@ -3484,8 +3495,10 @@ if (r.ok && r.confirmed) {
- network 详单格式错(hosts 缺失/裸 TLD/IP/带端口/通配不在最左、secret 缺 inject、
inject.format 没有 {value} 占位、inject.header 用了 Host/Cookie 等协议关键头、
inject.hosts 不是 hosts 声明条目的子集、有详单但 slots 没有 "network"、
- secret.source 不是 "user"/"login-email"/"oauth"/"oidc-token"、
+ secret.source 不是 "user"/"login-email"/"oauth"/"gh-cli"/"oidc-token"、
source:"login-email" 或 source:"oidc-token" 声明了 url 或 exchange、
+ source:"gh-cli" 不是官方 cindy-github、注入形态不是 api.github.com 的
+ Authorization Bearer、或声明了 exchange、
声明了 user 凭证但没声明 settingsHtml、遗留 input 字段值不是 "ghost")
- exchange 声明格式错(url 非 https/域名不在 hosts 白名单、bodyFormat 不是恰含一个
{value}、contentType 不在白名单、tokenPath 不是点分路径、ttlSeconds 越界)
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts
index bf12a5e24d..9d96c225a3 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts
@@ -75,6 +75,7 @@ export function executeGhostSetupInlineSubmission(
secret.key === secretKey &&
secret.source !== 'oauth' &&
secret.source !== 'login-email' &&
+ secret.source !== 'gh-cli' &&
secret.source !== 'oidc-token',
);
const nodeDecl = manifest.node?.secretBindings?.find((secret) => secret.key === secretKey);
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
index 1278aeec5d..eb9bfd3f71 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts
@@ -14,8 +14,9 @@
* - user 源凭证:保险库已保存(等价 /secrets GET 的 saved);
* - oauth 源凭证:client 可用(自填或内置)且 ≥1 个 connected 账号;
* 账号存在但全部 expired 时归入 reauth(弹窗文案区分「重新连接」);
- * - login-email / oidc-token 源凭证:Host 派生,没有用户配置动作;校验层
- * 禁止 setup 引用,启发式也不把它们伪装成待填写 Secret;
+ * - login-email / gh-cli / oidc-token 源凭证:Host 派生或优先复用宿主能力,
+ * 没有可靠的同步用户配置判定;校验层禁止 setup 引用,启发式也不把
+ * 它们伪装成待填写 Secret;
* - 连接:该声明键下至少一条连接;
* - kv 参数:意识 /kv 文件顶层键非空(undefined / null / 空白字符串算
* 未配置;false / 0 等有值形态算已配置——存在性检查,不做语义校验)。
@@ -102,7 +103,7 @@ function deriveRequirementGroups(manifest: GhostManifest): GhostSetupRequirement
}
const implicit: GhostSetupRequirement[] = [];
for (const s of manifest.network?.secrets ?? []) {
- if (s.source === 'login-email' || s.source === 'oidc-token') continue;
+ if (s.source === 'login-email' || s.source === 'gh-cli' || s.source === 'oidc-token') continue;
implicit.push({ kind: 'secret', key: s.key });
}
for (const s of manifest.node?.secretBindings ?? []) {
@@ -247,7 +248,7 @@ function verdictOf(
}
if (nodeDecl) return probes.secretSaved(req.key) ? 'satisfied' : 'missing';
if (!decl) return 'satisfied';
- if (decl.source === 'login-email' || decl.source === 'oidc-token') {
+ if (decl.source === 'login-email' || decl.source === 'gh-cli' || decl.source === 'oidc-token') {
if (strict) {
throw new GhostSetupAssessmentError(
`setup requirement ${requirementRef(req)} cannot use a Host-derived secret`,
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index a80395c110..2adc225958 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -47,7 +47,13 @@ import {
type ActiveAppSession,
} from '../appSessionState.js';
import { getLayoutStore } from '../layout/index.js';
-import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';
+import {
+ GhostManager,
+ isCindyOfficialTrustInfo,
+ type GhostHostTrustOverride,
+ type InstallRejection,
+ type UninstallRejection,
+} from './GhostManager.js';
import { exportGhostPackage } from './exportGhostPackage.js';
import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';
import { withGhostInstallLock } from './ghostInstallLock.js';
@@ -244,6 +250,7 @@ import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';
import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';
import { readProviderOrder } from '../maker-host/provider-order-store.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
+import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';
import { hasCodexOAuthLoginReadOnly } from '../maker-host/codex-oauth-readiness.js';
import { getUtilityModelChainProfiles } from '../utility-model/UtilityModelSelection.js';
import { utilityModelPinOptions } from '../../shared/utilityModelProfiles.js';
@@ -3297,6 +3304,7 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {
return ghost ? { ...ghost, manifest: withRuntimeFiloGoogleClient(ghost.manifest) } : null;
},
readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),
+ readGhCliToken: () => getSharedGhCliTokenSource().readToken(),
// source:'login-email' 凭证的值来源:现读登录态(切号/登出下一单即生效)。
getLoginEmail: () => getAuthState().user?.email ?? null,
// 用 Node 侧 undici fetch 而非 Electron net.fetch:redirect:'manual' 在 undici
@@ -3522,7 +3530,12 @@ export async function installAndDock(
* 可信。做成必填而不是可选,是为了让新增装入路径无法"忘记取锁"——签名逼着
* 它交出 id,锁在这里自动获取(外层已持有时按可重入 no-op)。
*/
- opts: { ghostId: string; enable?: boolean; expectedPackageSha256?: string },
+ opts: {
+ ghostId: string;
+ enable?: boolean;
+ expectedPackageSha256?: string;
+ trustOverride?: GhostHostTrustOverride;
+ },
): Promise<InstalledGhost> {
return withGhostInstallLock(opts.ghostId, () => installAndDockLocked(manager, lizFilePath, opts));
}
@@ -3530,7 +3543,12 @@ export async function installAndDock(
async function installAndDockLocked(
manager: GhostManager,
lizFilePath: string,
- opts: { ghostId: string; enable?: boolean; expectedPackageSha256?: string },
+ opts: {
+ ghostId: string;
+ enable?: boolean;
+ expectedPackageSha256?: string;
+ trustOverride?: GhostHostTrustOverride;
+ },
): Promise<InstalledGhost> {
// 默认沉睡(2026-07-09 Lizi 定案):装入 ≠ 授权运行,用户在确认框显式勾选
// "立即开启"才带电;沉睡态面板不渲染、总机不列、沙箱不拉起。
@@ -3539,6 +3557,7 @@ async function installAndDockLocked(
...(opts.expectedPackageSha256
? { expectedPackageSha256: opts.expectedPackageSha256 }
: {}),
+ ...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),
});
if ('rejection' in result) throwInstallError(result.rejection);
// 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。
@@ -3587,6 +3606,8 @@ export async function installOrUpdateMarketGhostPackage(
/** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */
approvedPackageSha256?: string;
reviewedBaseline?: string;
+ /** 仅 server-market 主机路径可传;custom/local 不传。 */
+ officialCindyGithub?: boolean;
},
): Promise<InstalledGhost> {
// 卡点:按 ghostId 上锁,覆盖 inspect → 落位整段。服务端与自定义两条市场路径
@@ -3606,6 +3627,7 @@ async function installOrUpdateMarketGhostPackageLocked(
permissionBaselineManifest?: GhostManifest;
approvedPackageSha256?: string;
reviewedBaseline?: string;
+ officialCindyGithub?: boolean;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@ -3624,6 +3646,10 @@ async function installOrUpdateMarketGhostPackageLocked(
'下载包清单与市场 Release 不一致',
);
}
+ const trustOverride: GhostHostTrustOverride | undefined =
+ expected.officialCindyGithub === true && expected.ghostId === 'cindy-github'
+ ? 'cindy-official'
+ : undefined;
requireGhostAvailableForActiveSession(expected.ghostId);
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
if (expected.reviewedManifest) {
@@ -3687,6 +3713,7 @@ async function installOrUpdateMarketGhostPackageLocked(
ghostId: expected.ghostId,
enable: true,
expectedPackageSha256: inspected.packageSha256,
+ ...(trustOverride ? { trustOverride } : {}),
});
}
@@ -3700,6 +3727,7 @@ async function installOrUpdateMarketGhostPackageLocked(
// 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。
result = await manager.update(cindyFilePath, {
expectedPackageSha256: inspected.packageSha256,
+ ...(trustOverride ? { trustOverride } : {}),
});
} catch (error) {
spawnIfResident(installed);
@@ -3982,6 +4010,15 @@ export function registerGhostIpc(): void {
key: s.key,
saved: isConnectionSecretReady(s.inject.hosts ?? [], connectionResolution),
}));
+ const isOfficialCindyGithub =
+ ghost.manifest.id === 'cindy-github' && isCindyOfficialTrustInfo(ghost.trust);
+ const ghCliSecretDecls = isOfficialCindyGithub
+ ? networkSecretDecls.filter((s) => s.source === 'gh-cli')
+ : [];
+ const ghCliAvailable =
+ ghCliSecretDecls.length > 0
+ ? await getSharedGhCliTokenSource().probeAvailability()
+ : false;
return handleGhostSecretsRequest({
method,
pathname,
@@ -3989,6 +4026,11 @@ export function registerGhostIpc(): void {
userSecretKeys,
identitySecretKeys,
managedSecretStates,
+ hostCredentialStates: ghCliSecretDecls.map((s) => ({
+ key: s.key,
+ source: 'gh-cli' as const,
+ available: ghCliAvailable,
+ })),
getLoginEmail: () => getAuthState().user?.email ?? null,
ghostId,
vault: {
diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.ts
index 0fd7de5372..9460b3b081 100644
--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts
@@ -24,6 +24,7 @@
import { randomUUID } from 'node:crypto';
import { sniffMediaMime, additionalMp3BytesNeeded } from '../cindy-media/sniffMediaMime.js';
+import { isCindyOfficialTrustInfo } from './GhostManager.js';
import {
GHOST_FETCH_BODY_MAX_BYTES,
@@ -66,6 +67,8 @@ export interface NetworkSlotDeps {
* 即生效);未配置 / 读失败返回 null。
*/
readSecret(ghostId: string, secretKey: string): string | null;
+ /** source:'gh-cli' 的宿主 GitHub CLI 登录 token;不可用返回 null。 */
+ readGhCliToken?: () => Promise<string | null>;
/**
* 当前登录账号的邮箱(source:'login-email' 凭证的值来源;现读登录态,
* 登出/切号下一单即生效)。未登录 / 登录态缺 email 返回 null。
@@ -1012,6 +1015,13 @@ export class GhostNetworkSlot {
if (!net || (net.hosts.length === 0 && connectionDecls.length === 0)) {
return { ok: false, message: '本意识未声明域名白名单(身份卡缺 network.hosts),请意识作者更新声明' };
}
+ const ghCliSecrets = net.secrets?.filter((secret) => secret.source === 'gh-cli') ?? [];
+ if (
+ ghCliSecrets.length > 0 &&
+ (ghost.manifest.id !== 'cindy-github' || !isCindyOfficialTrustInfo(ghost.trust))
+ ) {
+ return { ok: false, message: '本意识未通过官方 GitHub 宿主凭证信任校验,已阻断 gh-cli 凭证请求' };
+ }
// 连接地址每单现读快照(用户在设置页增删地址下一单即生效);本单内含
// 重定向逐跳都用同一份快照,避免跳转中途清单变化产生放行摇摆。
const connectionHosts =
@@ -1529,7 +1539,8 @@ export class GhostNetworkSlot {
/**
* 解析一条凭证的注入值:无 exchange 声明 = 保险库原始值(source:'login-email'
- * 则是登录邮箱);有 exchange = 换来的令牌(缓存命中直接用;用户改了 key /
+ * 则是登录邮箱;source:'gh-cli' 先取本机 gh 登录 token,再回落同 key 的 PAT);
+ * 有 exchange = 换来的令牌(缓存命中直接用;用户改了 key /
* 换了登录账号或缓存过期则重换,单飞去重——交换缓存按 sourceValue 失配重换,
* 登录邮箱变更天然生效)。
*/
@@ -1546,6 +1557,23 @@ export class GhostNetworkSlot {
}
| { error: string }
> {
+ if (secret.source === 'gh-cli') {
+ let ghToken: string | null = null;
+ try {
+ ghToken = (await this.deps.readGhCliToken?.()) ?? null;
+ } catch (error) {
+ this.deps.log?.warn('ghost gh-cli credential source failed', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ if (ghToken && ghToken.trim().length > 0) return { value: ghToken.trim() };
+ const fallback = this.deps.readSecret(ghostId, secret.key);
+ if (fallback && fallback.length > 0) return { value: fallback };
+ return {
+ error: `凭证「${secret.label}」不可用——未检测到本机 gh 登录,且尚未配置备用 Personal Access Token;请先运行 gh auth login,或到主界面侧边栏「插件」的本插件详情页填写 PAT`,
+ };
+ }
if (secret.source === 'oidc-token') {
const manager = this.deps.connectionTokens;
if (!manager) {
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
index 7471fbc688..52acbfc4b4 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
@@ -126,6 +126,37 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
}
});
+ it('gh-cli 状态只附可用布尔;备用 PAT 仍可写、可清并保留独立 saved/tail', async () => {
+ const vault = memVault({ github_pat: 'github_pat_abcdefgh1234' });
+ const base = {
+ readBodyText: () => Promise.resolve(''),
+ userSecretKeys: ['github_pat'],
+ hostCredentialStates: [
+ { key: 'github_pat', source: 'gh-cli' as const, available: true },
+ ],
+ vault,
+ ghostId: 'cindy-github',
+ };
+ const list = await handleGhostSecretsRequest({ ...base, method: 'GET', pathname: '/secrets' });
+ expect(JSON.parse(list.body ?? '')).toEqual([
+ {
+ key: 'github_pat',
+ saved: true,
+ tail: '1234',
+ hostSource: 'gh-cli',
+ hostAvailable: true,
+ },
+ ]);
+ expect(list.body).not.toContain('github_pat_abcdefgh');
+ const cleared = await handleGhostSecretsRequest({
+ ...base,
+ method: 'DELETE',
+ pathname: '/secrets/github_pat',
+ });
+ expect(cleared.status).toBe(204);
+ expect(vault.data).not.toHaveProperty('github_pat');
+ });
+
it('oidc-token 只回 Host 托管就绪状态,不回 token/audience/身份资料且不可写删', async () => {
const base = {
readBodyText: () => Promise.resolve('{"value":"forged"}'),
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
index de1c4e5df0..4509021fe3 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
@@ -15,6 +15,9 @@
* 供设置页只读展示"用的是哪个身份"。回给意识不算新增泄露面:装入确认
* 框已披露"将使用你的登录邮箱",且该凭证每次代发都注给它自己的服务端。
* 未登录/登录态缺邮箱 → saved:false 无 identity,页面照"请重新登录"画);
+ * - gh-cli 优先 + PAT 备用:{ key, saved, tail?, hostSource:'gh-cli',
+ * hostAvailable }。saved/tail 只描述保险库里的备用 PAT;hostAvailable
+ * 只描述主机能否复用本机 gh 登录,不暴露 token 或账号资料;
* - PUT /secrets/<key> → body {"value":"..."} 存入主机保险库,204;
* - DELETE /secrets/<key> → 清除,204(幂等);
* - login-email / Host 托管凭证键的任意单键操作 → 405(派生身份不可配置);
@@ -70,6 +73,12 @@ export async function handleGhostSecretsRequest(args: {
getLoginEmail?: () => string | null;
/** Host 托管凭证(source:'oidc-token')的就绪状态;值不进入意识可见接口。 */
managedSecretStates?: Array<{ key: string; saved: boolean }>;
+ /** 宿主优先凭证来源状态(当前仅 gh-cli),只回可用布尔。 */
+ hostCredentialStates?: Array<{
+ key: string;
+ source: 'gh-cli';
+ available: boolean;
+ }>;
vault: GhostSecretsVault;
ghostId: string;
/**
@@ -84,6 +93,9 @@ export async function handleGhostSecretsRequest(args: {
const identityKeys = args.identitySecretKeys ?? [];
const managedStates = args.managedSecretStates ?? [];
const managedKeys = managedStates.map(({ key }) => key);
+ const hostCredentialStates = new Map(
+ (args.hostCredentialStates ?? []).map((state) => [state.key, state] as const),
+ );
if (pathname === '/secrets') {
if (method !== 'GET') return { status: 405 };
@@ -92,7 +104,13 @@ export async function handleGhostSecretsRequest(args: {
const saved = vault.saved(ghostId, key);
// 指纹只在"确实存了"时给(没存过的键即便留有孤儿指纹也不回)。
const tail = saved ? vault.tail(ghostId, key) : null;
- return tail ? { key, saved, tail } : { key, saved };
+ const hostState = hostCredentialStates.get(key);
+ const hostFields = hostState
+ ? { hostSource: hostState.source, hostAvailable: hostState.available }
+ : {};
+ return tail
+ ? { key, saved, tail, ...hostFields }
+ : { key, saved, ...hostFields };
});
// 身份凭证:现读登录邮箱只读展示;identityKeys 为空时不碰登录态。
const email = identityKeys.length > 0 ? (args.getLoginEmail?.()?.trim() ?? '') : '';
diff --git a/apps/desktop/src/main/git-context/ghCliTokenSource.ts b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
index 182e686dba..95c1fc895d 100644
--- a/apps/desktop/src/main/git-context/ghCliTokenSource.ts
+++ b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
@@ -2,7 +2,8 @@
* ghCliTokenSource — 从本地 GitHub CLI(gh)登录态读取 token 的零配置来源。
*
* 动机:绝大多数开发者本机已 `gh auth login` 过,不该强迫再去设置页手填 PAT。
- * token 解析层级(ipc.ts 组装):设置页 PAT(显式,优先)→ 本来源(自动)。
+ * GitHub 插件网络层优先读取本来源,不可用时再回落设置页 PAT;其它宿主
+ * GitHub 功能可直接复用同一个共享 token source。
*
* 实现要点:
* - `gh auth token` 输出当前登录 token(通常 gho_ 前缀 OAuth token),
@@ -35,6 +36,7 @@ const GH_CANDIDATES: Record<string, string[]> = {
const DEFAULT_CACHE_TTL_MS = 5 * 60_000;
const DEFAULT_NEGATIVE_CACHE_TTL_MS = 30_000;
const GH_TIMEOUT_MS = 3_000;
+const GH_PROBE_TIMEOUT_MS = 800;
export interface GhCliTokenSourceDeps {
execFileFn?: (
@@ -54,6 +56,8 @@ export interface GhCliTokenSourceDeps {
export interface GhCliTokenSource {
/** 返回本地 gh 登录 token;未安装 / 未登录 / 超时返回 null,永不抛错。 */
readToken(): Promise<string | null>;
+ /** 只探测 github.com 登录可用性,不读取或缓存 token。 */
+ probeAvailability(): Promise<boolean>;
}
export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTokenSource {
@@ -95,7 +99,25 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
});
}
+ async function probeAvailability(): Promise<boolean> {
+ const bin = resolveGhBinary();
+ return new Promise<boolean>((resolve) => {
+ try {
+ // stdout/stderr 都不进入日志;该调用只消费退出码,绝不取得 token。
+ execFileFn(
+ bin,
+ ['auth', 'status', '--hostname', 'github.com'],
+ { timeout: GH_PROBE_TIMEOUT_MS },
+ (err) => resolve(err === null),
+ );
+ } catch {
+ resolve(false);
+ }
+ });
+ }
+
return {
+ probeAvailability,
async readToken(): Promise<string | null> {
if (cached && cached.expiresAt > now()) return cached.token;
if (inFlight) return inFlight;
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 79dd710a6e..aa0c63465e 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
@@ -450,6 +450,32 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
});
});
+ it('custom market 即使自报 cindy-github 也不会获得 server-market 官方标记', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-github-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [
+ { rel: 'plugins/github', id: 'cindy-github' },
+ ]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('cindy-github'),
+ dir: '/ghosts/cindy-github',
+ enabled: true,
+ });
+ const pluginId = customMarketPluginId('team-lib', 'cindy-github');
+ const reviewed = await h.service.detail(pluginId);
+
+ await h.service.install(pluginId, {
+ expectedReleaseId: customMarketReleaseId('team-lib', 'cindy-github', '1.0.0'),
+ expectedManifest: reviewed.manifest,
+ });
+
+ expect(runtime.install.mock.calls[0]?.[1]).toEqual({
+ ghostId: 'cindy-github',
+ version: '1.0.0',
+ });
+ });
+
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);
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 6b82679059..d41341ed70 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -576,6 +576,276 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(ghost?.enabled).toBe(true);
});
+ it('server-market 只为 cindy-github 安装显式传 Host 官方身份', async () => {
+ const github = summary({ ghostId: 'cindy-github' });
+ runtime.install.mockResolvedValue({
+ manifest: manifest('cindy-github'),
+ dir: '/userData/cindy-brain/cindy-github',
+ enabled: true,
+ });
+ const h = harness([github]);
+
+ await h.service.install(github.id, reviewedInstallOptions(github));
+
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ ghostId: 'cindy-github',
+ officialCindyGithub: true,
+ });
+
+ runtime.install.mockReset();
+ const ordinary = summary();
+ runtime.install.mockResolvedValue({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const ordinaryHarness = harness([ordinary]);
+ await ordinaryHarness.service.install(ordinary.id, reviewedInstallOptions(ordinary));
+ expect(runtime.install.mock.calls[0]?.[1]).toEqual({
+ ghostId: 'cindy-test',
+ version: '1.0.0',
+ reviewedManifest: manifest(),
+ });
+ });
+
+ it('旧 source:market + manifestDigest 安装会回填 cindy-github 官方 trust', async () => {
+ const item = summary({ ghostId: 'cindy-github' });
+ const rawManifest = manifest('cindy-github');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ const digest = ghostManifestDigest(rawManifest);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ manifestDigest: digest,
+ });
+
+ runtime.install.mockResolvedValue({
+ manifest: rawManifest,
+ dir: installDir,
+ enabled: true,
+ trust: { level: 'cindy-official' },
+ });
+
+ await h.service.snapshot();
+
+ expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/cindy-plugin-trust-backfill-.*\.cindy$/),
+ {
+ ghostId: 'cindy-github',
+ version: item.currentRelease.version,
+ officialCindyGithub: true,
+ },
+ );
+ });
+
+ it('完整官方 receipt 已存在时不会重复回填 cindy-github trust', async () => {
+ const item = summary({ ghostId: 'cindy-github' });
+ const rawManifest = manifest('cindy-github');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-trusted-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
+ fs.writeFileSync(
+ path.join(installDir, '.cindy-trust.json'),
+ JSON.stringify({
+ level: 'cindy-official',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: true,
+ publisherName: 'Cindy Plugin Market',
+ }),
+ );
+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(rawManifest),
+ });
+
+ await h.service.snapshot();
+
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('legacy-adopted 记录不能成为开发版冒充 cindy-github 的官方 trust 来源', async () => {
+ const item = summary({ ghostId: 'cindy-github' });
+ const rawManifest = manifest('cindy-github');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-legacy-github-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: `legacy-unresolved:${item.currentRelease.version}`,
+ version: item.currentRelease.version,
+ sha256: 'legacy-unverified',
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'legacy-adopted',
+ installed: true,
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(rawManifest),
+ });
+
+ await h.service.snapshot();
+
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('旧 market trust 回填遇到下载 SHA 漂移时 fail-closed', async () => {
+ const item = summary({ ghostId: 'cindy-github' });
+ const rawManifest = manifest('cindy-github');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-sha-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(rawManifest),
+ });
+ h.api.download.mockResolvedValueOnce({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'b'.repeat(64),
+ sizeBytes: 42,
+ });
+
+ await h.service.snapshot();
+
+ expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('旧 market trust 回填下载期间被卸载时不会把插件重新装回', async () => {
+ const item = summary({ ghostId: 'cindy-github' });
+ const rawManifest = manifest('cindy-github');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-race-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: false }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(rawManifest),
+ });
+ const releaseDownload = deferred();
+ h.api.download.mockImplementationOnce(async () => {
+ await releaseDownload.promise;
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256,
+ sizeBytes: 42,
+ };
+ });
+
+ const snapshot = h.service.snapshot();
+ await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledTimes(1));
+ runtime.ghosts = [];
+ h.ledger.markRemoved('cindy-github', 'user-1');
+ releaseDownload.resolve();
+ await snapshot;
+
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost('cindy-github')).toMatchObject({ installed: false });
+ });
+
+ it('旧 market trust 回填下载期间 ownership 改为 custom 时不会覆盖新包', async () => {
+ const item = summary({ ghostId: 'cindy-github' });
+ const rawManifest = manifest('cindy-github');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-owner-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ const serverRecord: PluginMarketInstallationRecord = {
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-08-07T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(rawManifest),
+ };
+ h.ledger.upsertInstallation(serverRecord);
+ const releaseDownload = deferred();
+ h.api.download.mockImplementationOnce(async () => {
+ await releaseDownload.promise;
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256,
+ sizeBytes: 42,
+ };
+ });
+
+ const snapshot = h.service.snapshot();
+ await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledTimes(1));
+ h.ledger.upsertInstallation({
+ ...serverRecord,
+ pluginId: 'custom:team-lib:cindy-github',
+ releaseId: 'custom-release',
+ source: 'local-market',
+ sourceKey: 'local:test',
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ });
+ releaseDownload.resolve();
+ await snapshot;
+
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost('cindy-github')).toMatchObject({
+ source: 'local-market',
+ });
+ });
+
it('passes the reviewed server manifest to the package verification boundary', async () => {
const item = summary();
runtime.install.mockResolvedValue({
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 995959aecb..4bb2fc6f50 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -44,6 +44,7 @@ import {
isBuiltinGhostRemovedByUser,
uninstallGhostAndCleanup,
} from '../cindy-brain/index.js';
+import { hasCindyOfficialTrustMetadata } from '../cindy-brain/GhostManager.js';
import {
getActiveAppSession,
isAppSessionBoundaryPending,
@@ -306,6 +307,32 @@ function serverMarketOwnsInstalledGhost(
);
}
+function canBackfillOfficialCindyGithubTrust(
+ record: PluginMarketInstallationRecord,
+ installed: InstalledGhost,
+): boolean {
+ return (
+ record.installed &&
+ record.source === 'market' &&
+ record.manifestDigest !== undefined &&
+ !hasCindyOfficialTrustMetadata(installed.dir) &&
+ serverMarketOwnsInstalledGhost(record.pluginId, installed, record)
+ );
+}
+
+function sameMarketInstallation(
+ current: PluginMarketInstallationRecord,
+ expected: PluginMarketInstallationRecord,
+): boolean {
+ return (
+ current.pluginId === expected.pluginId &&
+ current.releaseId === expected.releaseId &&
+ current.version === expected.version &&
+ current.sha256 === expected.sha256 &&
+ current.manifestDigest === expected.manifestDigest
+ );
+}
+
/** Stable local facts reused while projecting one market catalog response. */
interface LocalInstallSnapshot {
/** Installed Ghost runtime facts indexed once for one market operation. */
@@ -400,6 +427,7 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const ledger = this.ledgerForOwner(owner);
await this.adoptLegacyInstallations(plugins, ledger, owner);
+ await this.backfillOfficialCindyGithubTrust(ledger, owner);
await this.reconcileRemovedInstallations(ledger, owner);
await this.applyServerRemovals(removals, owner, ledger);
// 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
@@ -1202,6 +1230,7 @@ export class PluginMarketService {
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
+ ...(plugin.ghostId === 'cindy-github' ? { officialCindyGithub: true } : {}),
...(options.reviewedManifest
? {
reviewedManifest: options.reviewedManifest,
@@ -1319,6 +1348,70 @@ export class PluginMarketService {
}
}
+ /**
+ * 旧版 server-market 安装已经有 Host ledger + manifestDigest,但尚未写
+ * cindy-official receipt。不能只按 manifestDigest 抬权:攻击者可保留清单、
+ * 只替换 main.js。这里按 ledger 的 releaseId + sha256 重新下载原官方包,
+ * 校验后原位恢复官方字节并由市场安装路径写 receipt。
+ * legacy-adopted 只是“按 id 收养”的历史记录,绝不进入本路径。
+ */
+ private async backfillOfficialCindyGithubTrust(
+ ledger: PluginMarketLedger,
+ owner: ActiveAppSession,
+ ): Promise<void> {
+ const record = ledger.installationForGhost('cindy-github');
+ requireSameMarketOwner(owner);
+ const installed = getGhostManager().list().find((ghost) => ghost.manifest.id === 'cindy-github');
+ if (!record || !installed || !canBackfillOfficialCindyGithubTrust(record, installed)) return;
+ const tempPath = path.join(
+ app.getPath('temp'),
+ `cindy-plugin-trust-backfill-${crypto.randomUUID()}.cindy`,
+ );
+ try {
+ const download = await this.api.download(record.pluginId, record.releaseId);
+ requireSameMarketOwner(owner);
+ if (download.sha256 !== record.sha256) {
+ log.warn('cindy-github trust backfill release hash changed');
+ return;
+ }
+ const expiresAt = Date.parse(download.expiresAt);
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
+ log.warn('cindy-github trust backfill authorization expired');
+ return;
+ }
+ await downloadVerifiedPlugin(download.url, download, tempPath);
+ requireSameMarketOwner(owner);
+ await withGhostInstallLock('cindy-github', async () => {
+ requireSameMarketOwner(owner);
+ const currentRecord = ledger.installationForGhost('cindy-github');
+ const currentInstalled = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === 'cindy-github');
+ if (
+ !currentRecord?.installed ||
+ currentRecord.source !== 'market' ||
+ !currentInstalled ||
+ !sameMarketInstallation(currentRecord, record) ||
+ !canBackfillOfficialCindyGithubTrust(currentRecord, currentInstalled)
+ ) {
+ return;
+ }
+ await installOrUpdateMarketGhostPackage(tempPath, {
+ ghostId: 'cindy-github',
+ version: currentRecord.version,
+ officialCindyGithub: true,
+ });
+ });
+ requireSameMarketOwner(owner);
+ } catch (error) {
+ log.warn('cindy-github trust backfill deferred', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);
+ }
+ }
+
private async reconcileRemovedInstallations(
ledger: PluginMarketLedger,
owner: ActiveAppSession,
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
index 8bd3b021fb..42fc91193b 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx
@@ -74,6 +74,7 @@ function itemIcon(item: GhostPermissionItem): LucideIcon {
if (
item.labelKey === 'networkSecret' ||
item.labelKey === 'networkSecretOauth' ||
+ item.labelKey === 'networkSecretGhCli' ||
item.labelKey === 'networkSecretOrganizationIdentity' ||
item.labelKey === 'nodeSecret'
)
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 20016413d0..d2941568bc 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -121,6 +121,7 @@ function permissionItemIcon(item: GhostPermissionItem): LucideIcon {
if (
item.labelKey === 'networkSecret' ||
item.labelKey === 'networkSecretOauth' ||
+ item.labelKey === 'networkSecretGhCli' ||
item.labelKey === 'networkSecretIdentity'
) {
return KeyRound;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3903cf3c79..4380e3a15a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3479,6 +3479,8 @@
"networkSecretGhostInputDetail": "Collected by this plugin's own settings UI — the plugin page sees the value at entry time. It is then handed to the host in one step for encrypted storage; once stored, the plugin can never read it back, and the host injects it only for the domains it declares.",
"networkSecretIdentity": "Will use your login email as the credential \"{{name}}\"",
"networkSecretIdentityDetail": "The value comes from your signed-in account's email, derived and injected by the host at request time; nothing to fill in. The plugin can read this email to show the current identity in its settings UI.",
+ "networkSecretGhCli": "Will prefer your local GitHub CLI login for the credential \"{{name}}\"",
+ "networkSecretGhCliDetail": "The host reads the local gh login token only when needed and injects it only into GitHub API requests; plugin code cannot read or store the token. If gh is unavailable, you can configure a fallback Personal Access Token in the plugin settings.",
"networkSecretOrganizationIdentity": "Will use your Cindy organization identity as the credential \"{{name}}\"",
"networkSecretOrganizationIdentityDetail": "Cindy issues a short-lived identity assertion when needed, and the host sends it only to the explicitly listed service hosts. The plugin code cannot read or store the token.",
"networkSecretOauth": "Will guide you through OAuth authorization at {{host}} ({{name}})",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f6237cecef..78042053de 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3478,6 +3478,8 @@
"networkSecretGhostInputDetail": "この資格情報はプラグイン自身の設定画面で入力を受け付けるため、入力時にはプラグインのページを経由します。その後ホストへ一度だけ渡されて暗号化保存され、保存後はプラグインから読み出せません。注入は宣言されたドメインへのリクエスト時のみホストが行います。",
"networkSecretIdentity": "ログインメールアドレスを認証情報「{{name}}」として使用します",
"networkSecretIdentityDetail": "値はログイン中のアカウントのメールアドレスから取得され、リクエスト時にホストが自動的に導出・注入します。入力は不要です。プラグインは設定画面に現在の身元を表示する目的で、このメールアドレスを読み取れます。",
+ "networkSecretGhCli": "認証情報「{{name}}」にはローカルの GitHub CLI ログインを優先して使用します",
+ "networkSecretGhCliDetail": "ホストは必要なときだけローカルの gh ログイントークンを読み取り、GitHub API リクエストにだけ注入します。プラグインのコードはトークンを読み取ったり保存したりできません。gh を利用できない場合は、プラグイン設定で予備の Personal Access Token を設定できます。",
"networkSecretOrganizationIdentity": "Cindy の組織ユーザー ID を認証情報「{{name}}」として使用します",
"networkSecretOrganizationIdentityDetail": "Cindy は必要なときに短時間有効な ID アサーションを発行し、ホストだけが明示されたサービスホストへ送信します。プラグインのコードはトークンを読み取ったり保存したりできません。",
"networkSecretOauth": "{{host}} で OAuth 認可を行うよう案内します({{name}})",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5ecfee3b82..ce2b117d65 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3478,6 +3478,8 @@
"networkSecretGhostInputDetail": "이 자격 증명은 플러그인 자체 설정 화면에서 입력받으므로 입력 시점에 플러그인 페이지를 거칩니다. 이후 호스트에 한 번만 전달되어 암호화 저장되며, 저장 후에는 플러그인이 다시 읽을 수 없습니다. 주입은 선언된 도메인 요청 시에만 호스트가 수행합니다.",
"networkSecretIdentity": "로그인 이메일을 자격 증명 \"{{name}}\"(으)로 사용합니다",
"networkSecretIdentityDetail": "값은 로그인된 계정의 이메일에서 가져오며, 요청 시 호스트가 자동으로 파생하여 주입합니다. 입력할 필요가 없으며, 플러그인은 설정 화면에 현재 신원을 표시하기 위해 이 이메일을 읽을 수 있습니다.",
+ "networkSecretGhCli": "자격 증명 \"{{name}}\"에는 로컬 GitHub CLI 로그인을 우선 사용합니다",
+ "networkSecretGhCliDetail": "호스트는 필요할 때만 로컬 gh 로그인 토큰을 읽어 GitHub API 요청에만 주입합니다. 플러그인 코드는 토큰을 읽거나 저장할 수 없습니다. gh를 사용할 수 없으면 플러그인 설정에서 예비 Personal Access Token을 구성할 수 있습니다.",
"networkSecretOrganizationIdentity": "Cindy 조직 사용자 신원을 자격 증명 \"{{name}}\"(으)로 사용합니다",
"networkSecretOrganizationIdentityDetail": "Cindy가 필요할 때 단기 신원 어설션을 발급하며, 호스트만 명시된 서비스 호스트로 전송합니다. 플러그인 코드는 토큰을 읽거나 저장할 수 없습니다.",
"networkSecretOauth": "{{host}}에서 OAuth 인증을 진행하도록 안내합니다({{name}})",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 61f6d15417..0bc0e54664 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3478,6 +3478,8 @@
"networkSecretGhostInputDetail": "凭证由这个插件自己的设置界面收集,录入时会经过插件页面;随后一次性交给主机加密保管,存入后插件无法读回,主机只在请求它声明的域名时注入。",
"networkSecretIdentity": "将使用你的登录邮箱作为凭证「{{name}}」",
"networkSecretIdentityDetail": "值取自当前登录账号的邮箱,请求时由主机自动派生注入;无需填写。插件可读取该邮箱,用于在它的设置界面里展示当前身份。",
+ "networkSecretGhCli": "将优先使用本机 GitHub CLI 登录作为凭证「{{name}}」",
+ "networkSecretGhCliDetail": "主机按需读取本机 gh 登录令牌,并且只注入 GitHub API 请求;插件代码无法读取或保存令牌。若 gh 不可用,可在插件设置中配置备用 Personal Access Token。",
"networkSecretOrganizationIdentity": "将使用你的 Cindy 企业身份作为凭证「{{name}}」",
"networkSecretOrganizationIdentityDetail": "Cindy 会按需签发短时身份断言,仅由主机发送给明确列出的服务域名;插件代码无法读取或保存令牌。",
"networkSecretOauth": "将引导你在 {{host}} 完成 OAuth 授权({{name}})",
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index e247472870..e540fe1475 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -2334,6 +2334,118 @@ describe('ghost · network 详单校验', () => {
if (!r.ok) expect(r.reason).toContain('source');
});
+ it('secrets.source:gh-cli 仅允许官方 GitHub 插件的固定 GitHub API 注入形态', () => {
+ const valid = validateGhostManifest({
+ ...goodManifest(),
+ id: 'cindy-github',
+ slots: ['panel', 'network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub authentication',
+ source: 'gh-cli',
+ url: 'https://github.com/settings/tokens',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com'],
+ },
+ },
+ ],
+ },
+ });
+ expect(valid.ok, valid.ok ? '' : valid.reason).toBe(true);
+ if (valid.ok) {
+ const item = ghostPermissionItems(valid.manifest).find(
+ (entry) => entry.key === 'network:secret:github_pat',
+ );
+ expect(item?.labelKey).toBe('networkSecretGhCli');
+ expect(item?.detailKey).toBe('networkSecretGhCliDetail');
+
+ const prior = validateGhostManifest({
+ ...goodManifest(),
+ id: 'cindy-github',
+ slots: ['panel', 'network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub authentication',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.github.com'],
+ },
+ },
+ ],
+ },
+ });
+ expect(prior.ok).toBe(true);
+ if (prior.ok) {
+ expect(diffGhostPermissionItems(prior.manifest, valid.manifest).added).toEqual([]);
+ expect(ghostPermissionBaselineKey(prior.manifest)).toBe(
+ ghostPermissionBaselineKey(valid.manifest),
+ );
+ expect(
+ unreviewedGhostPermissionItems(
+ prior.manifest,
+ prior.manifest,
+ valid.manifest,
+ ),
+ ).toEqual([]);
+ }
+ }
+
+ for (const fixture of [
+ { id: 'github-helper' },
+ { header: 'X-GitHub-Token' },
+ { format: 'token {value}' },
+ { hosts: undefined },
+ { hosts: ['objects.githubusercontent.com'] },
+ {
+ exchange: {
+ url: 'https://api.github.com/token',
+ bodyFormat: '{"token":"{value}"}',
+ tokenPath: 'token',
+ },
+ },
+ ]) {
+ const id = 'id' in fixture ? fixture.id : 'cindy-github';
+ const result = validateGhostManifest({
+ ...goodManifest(),
+ id,
+ slots: ['panel', 'network'],
+ settingsHtml: 'settings.html',
+ network: {
+ hosts: ['api.github.com', 'objects.githubusercontent.com'],
+ secrets: [
+ {
+ key: 'github_pat',
+ label: 'GitHub authentication',
+ source: 'gh-cli',
+ inject: {
+ header: 'header' in fixture ? fixture.header : 'Authorization',
+ format: 'format' in fixture ? fixture.format : 'Bearer {value}',
+ ...('hosts' in fixture
+ ? fixture.hosts === undefined
+ ? {}
+ : { hosts: fixture.hosts }
+ : { hosts: ['api.github.com'] }),
+ },
+ ...('exchange' in fixture ? { exchange: fixture.exchange } : {}),
+ },
+ ],
+ },
+ });
+ expect(result.ok, JSON.stringify(fixture)).toBe(false);
+ }
+ });
+
it('权限清单:login-email 凭证用"将使用登录邮箱"分档文案,key 与 user 凭证同构', () => {
const r = validateGhostManifest(
withNet({
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 5bfcdcf021..652cf743ed 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -791,6 +791,9 @@ export const GHOST_OAUTH_BOUNCE_PATH_RE = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)
* 授权换来的 access token——用户在意识设置页填 client 凭证并点"连接账号",
* 主机跑授权流程并保管全部令牌,出网时现取新鲜 token 注入(见
* GhostSecretOauthDecl;必须同时声明 oauth 详单)。
+ * - 'gh-cli':仅供官方 cindy-github 使用。主机优先现读本机 GitHub CLI 的
+ * `gh auth token`,不可用时回落到同 key 经 /secrets 保存的 PAT。两种值都
+ * 只在 networkSlot 请求 GitHub API 时注入,不进入插件、Renderer、KV 或日志。
* - 'oidc-token':值 = Cindy 为当前企业 Membership 签发的短时 Connection
* JWT。只有当前组织的 Plugin Market organization 安装记录和 manifest digest
* 校验通过时,Host 才根据当前组织和插件 id 推导 audience;插件不能声明或读取。
@@ -800,7 +803,7 @@ export const GHOST_OAUTH_BOUNCE_PATH_RE = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)
* 改走 source:'oauth' + tokenBroker:'feishu';存量已装清单由内置意识播种器
* 按指纹覆盖自愈,未覆盖前该意识加载被拒属预期。)
*/
-export const GHOST_SECRET_SOURCES = ['user', 'login-email', 'oauth', 'oidc-token'] as const;
+export const GHOST_SECRET_SOURCES = ['user', 'login-email', 'oauth', 'gh-cli', 'oidc-token'] as const;
export type GhostSecretSource = (typeof GHOST_SECRET_SOURCES)[number];
/**
@@ -1438,7 +1441,10 @@ export interface InstalledGhost {
};
}
-/** 插件包的来源与审核等级;决定 UI 徽标,不改变运行时 slot 权限。 */
+/**
+ * 插件包的来源与审核等级;通常只决定 UI 徽标。保留的 gh-cli 凭证来源还会
+ * 要求 cindy-github 具备 cindy-official Host receipt,防止第三方仅自报 id。
+ */
export type GhostTrustLevel =
| 'cindy-official'
| 'reviewed'
@@ -1763,8 +1769,8 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
// 来源分档文案:登录邮箱派生 vs 用户自填(意识 settingsHtml 收单——宿主
// 凭证渲染已退役,user 凭证只剩这一档)。收单档文案不许说"意识代码无法
// 读取"这种过头话:录入瞬间明文经过意识页面,知情同意面要如实。
- // user/login-email/oauth 保持历史 key,不影响存量插件;企业身份是新的高风险
- // Host 托管来源,单独带 source 后缀,从其它来源切换时必须重新确认。
+ // user/login-email/oauth/gh-cli 保持历史 key,不影响存量插件;gh-cli
+ // 只改变 Host 来源文案,不把“自动复用 gh”误报成新增权限确认。
if (secret.source === 'oauth' && secret.oauth) {
// OAuth 凭证:展示授权域名 + scopes 全量如实列出(通用声明式的知情
// 同意面——平台不预设 provider,用户看到的就是全部授权事实)。detail
@@ -1797,6 +1803,16 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
});
continue;
}
+ if (secret.source === 'gh-cli') {
+ items.push({
+ key: `network:secret:${secret.key}`,
+ kind: 'network',
+ labelKey: 'networkSecretGhCli',
+ labelArgs: { name: secret.label },
+ detailKey: 'networkSecretGhCliDetail',
+ });
+ continue;
+ }
const identity = secret.source === 'login-email';
items.push({
key: `network:secret:${secret.key}`,
@@ -1993,11 +2009,27 @@ export interface GhostPermissionDiff {
* 形态),只看 key+detail 会把"说明/成本面变了"漏判成"权限面没变",更新时
* 用户看不到重新确认。
*/
+function permissionDetailKeyForFingerprint(item: GhostPermissionItem): string {
+ // cindy-github 从存量 PAT(source:user)升级为 Host 优先 gh-cli 时,凭证仍由
+ // Main 只注入同一个 network secret key 与同一组目标;变化的是设置页/权限
+ // 页对“凭证从哪里来”的说明,不是插件获得了新权限。两档共用历史 key 的
+ // 同时也必须共用审阅指纹,否则升级会被误判成扩权并要求存量用户重新确认。
+ // gh-cli 的 manifest 校验只允许官方 cindy-github,因此这个兼容等价不会
+ // 放宽其它插件;其它 detailKey/detailArgs 变化仍按新说明完整性规则复核。
+ if (
+ item.detailKey === 'networkSecretGhostInputDetail' ||
+ item.detailKey === 'networkSecretGhCliDetail'
+ ) {
+ return 'networkSecretGithubCredentialDetail';
+ }
+ return item.detailKey ?? '';
+}
+
function ghostPermissionItemFingerprint(item: GhostPermissionItem): string {
const args = item.detailArgs
? Object.entries(item.detailArgs).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
: [];
- return JSON.stringify([item.key, item.detail ?? '', item.detailKey ?? '', args]);
+ return JSON.stringify([item.key, item.detail ?? '', permissionDetailKeyForFingerprint(item), args]);
}
/**
@@ -3669,7 +3701,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
if (typeof s.label !== 'string' || s.label.trim().length === 0 || s.label.length > 64) {
return { ok: false, reason: 'network.secrets[].label 必须是 1–64 字符的非空字符串' };
}
- // 来源:缺省 'user';login-email / oauth / oidc-token 均由主机托管。
+ // 来源:缺省 'user';login-email / oauth / gh-cli / oidc-token 均由主机托管。
// 归一化:'user' 不落清单(与缺省同义,权限 diff 不 churn)。
let source: GhostSecretSource | undefined;
if (s.source !== undefined) {
@@ -3684,6 +3716,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
if (s.source === 'login-email') source = 'login-email';
if (s.source === 'oauth') source = 'oauth';
+ if (s.source === 'gh-cli') source = 'gh-cli';
if (s.source === 'oidc-token') source = 'oidc-token';
}
// 旧 input 字段已退役:Setup Runtime 直接从 Secret 声明生成 Host 表单,
@@ -3724,6 +3757,12 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
reason: `network.secrets[].source 为 ${source} 时不允许声明 exchange(登录态凭证不外送交换端点)`,
};
}
+ if (source === 'gh-cli' && s.exchange !== undefined) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].source 为 gh-cli 时不允许声明 exchange(GitHub token 只能直接注入 GitHub API)',
+ };
+ }
if (
s.hint !== undefined &&
(typeof s.hint !== 'string' || s.hint.trim().length === 0 || s.hint.length > 200)
@@ -3802,6 +3841,25 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
};
}
}
+ if (source === 'gh-cli') {
+ if (raw.id !== 'cindy-github') {
+ return {
+ ok: false,
+ reason: 'network.secrets[].source 为 gh-cli 时仅允许官方 cindy-github 插件使用',
+ };
+ }
+ if (
+ inj.header !== 'Authorization' ||
+ inj.format !== 'Bearer {value}' ||
+ injectHosts?.length !== 1 ||
+ injectHosts[0] !== 'api.github.com'
+ ) {
+ return {
+ ok: false,
+ reason: 'network.secrets[].source 为 gh-cli 时 inject 必须固定为 api.github.com 的 Authorization: Bearer {value}',
+ };
+ }
+ }
// oauth(source: 'oauth' 时必填):主机托管 OAuth 授权详单。授权页与
// token 端点域名都必须落在 hosts 白名单内——确认框展示的域名集合就是
// 全部出网面(clientSecret 只流向 tokenUrl,授权只发生在 authorizeUrl)。
@@ -4320,14 +4378,16 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
}
const secretByKey = new Map<
string,
- { hostDerivedSource: 'login-email' | 'oidc-token' | null }
+ { hostDerivedSource: 'login-email' | 'gh-cli' | 'oidc-token' | null }
>([
...(network?.secrets ?? []).map(
(s) => [
s.key,
{
hostDerivedSource:
- s.source === 'login-email' || s.source === 'oidc-token' ? s.source : null,
+ s.source === 'login-email' || s.source === 'gh-cli' || s.source === 'oidc-token'
+ ? s.source
+ : null,
},
] as const,
),
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index a55208acd4..fb3094ff5c 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -74,6 +74,12 @@
## 4. 网络、凭证与资源交接
- network 只允许 manifest 白名单域名;凭证由主机保险库注入,**无明文读回**给沙箱。
+- `source: "gh-cli"` 是只为官方 `cindy-github` 保留的宿主凭证来源:Host 优先读取
+ 本机 `gh auth token`,不可用时才回落到同 key 经 `/secrets` 保存的 PAT。两种 token
+ 均只在 Main 的 networkSlot 内存中注入 `api.github.com` 的
+ `Authorization: Bearer` 请求头,不得进入插件、Renderer、Agent、KV、日志或 Node
+ Worker。设置页只能读取 `hostAvailable` 布尔与备用 PAT 的 `saved/tail` 状态。该来源
+ 不允许 `exchange` 或 `setup.requires` 引用,第三方插件不得声明。
- `source: "oidc-token"` 是 Host 托管的短时 Cindy Connection JWT:只对当前企业
Membership 生效;只有当前组织的 Plugin Market organization 安装记录仍有效、且
安装目录 manifest digest 与记录一致时,Host 才会根据当前组织和插件 id 推导 audience。