Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 恢复 Forge 企业作者 OIDC 自测
fmfsaisai4f10f5cde757
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex f36a57bfc5..c049e13389 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -1023,7 +1023,7 @@ export class GhostManager {return this.receiptStore.rootDir();}- /** 新安装不再写来源;这里只识别旧 receipt,避免存量 Forge Broker 资格断裂。 */+ /** 只认显式 Forge 安装写入的来源;未知/手动来源一律按 manual。 */readEffectiveInstallOrigin(id: string): 'manual' | 'agent-forge' {this.ensureCurrentOwnerContextSync();try {@@ -2567,6 +2567,7 @@ export class GhostManager {initiallyEnabled?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;+ installOrigin?: 'agent-forge';},) {return this.runExclusiveMutation(() => this.installUnlocked(lizFilePath, opts));@@ -2578,6 +2579,7 @@ export class GhostManager {initiallyEnabled?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;+ installOrigin?: 'agent-forge';},): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {// 装入初始启用态由调用方决定;缺省 true 保持既有调用方语义不变。@@ -2684,6 +2686,7 @@ export class GhostManager {packageSha256,revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ ...(opts?.installOrigin ? { installOrigin: opts.installOrigin } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });let tombstoneClearPending = false;@@ -2781,6 +2784,7 @@ export class GhostManager {expectedInstalledApproval: string;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;+ installOrigin?: 'agent-forge';beforePackageCommit?: () => GhostPackageCommitPreparation | void;/** 目录换位完成后、任何通知或运行时收尾前触发。 */onPackagePlaced?: () => void;@@ -2795,6 +2799,7 @@ export class GhostManager {expectedInstalledApproval: string;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;+ installOrigin?: 'agent-forge';/** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */beforePackageCommit?: () => GhostPackageCommitPreparation | void;/** 目录换位完成后、任何通知或运行时收尾前触发。 */@@ -2844,11 +2849,9 @@ export class GhostManager {},};}- const legacyInstallOrigin =- approvalResult.state === 'approved' &&- effectiveInstallOrigin(approvalResult.receipt) === 'agent-forge'- ? 'agent-forge'- : undefined;+ // 来源描述的是本次明确选择的装入通道,而不是 id 的永久资格。手动更新+ // 不继承旧 Forge 来源,否则新增 OIDC host 可绕过 Forge 的窄确认。+ const installOrigin = opts.installOrigin;// 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时,重新安装仍采用原// `.disabled` 镜像;损坏 receipt 一律保持停用。const enabled =@@ -3023,7 +3026,7 @@ export class GhostManager {packageSha256,revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),- ...(legacyInstallOrigin ? { installOrigin: legacyInstallOrigin } : {}),+ ...(installOrigin ? { installOrigin } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });} catch (err) {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 83c1d444af..9ac67904f8 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -2268,6 +2268,25 @@ describe('GhostManager · update pre-rename recovery', () => {});describe('GhostManager · install', () => {+ it('only an explicitly tagged Forge install writes agent-forge origin', async () => {+ const manual = await manager.install(await makeCindy('manual.cindy', goodManifest('manual')));+ expect(manual).toHaveProperty('ghost');+ const manualReceipt = JSON.parse(+ await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'manual.json'), 'utf8'),+ ) as Record<string, unknown>;+ expect(manualReceipt).not.toHaveProperty('installOrigin');+ expect(manager.readEffectiveInstallOrigin('manual')).toBe('manual');++ const forged = await manager.install(+ await makeCindy('forge.cindy', goodManifest('acme-tool')),+ {+ installOrigin: 'agent-forge',+ },+ );+ expect(forged).toHaveProperty('ghost');+ expect(manager.readEffectiveInstallOrigin('acme-tool')).toBe('agent-forge');+ });+it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {const manifest = {...goodManifest(),@@ -4520,6 +4539,40 @@ describe('GhostManager · Unix file permissions', () => {});describe('GhostManager · update(原位换版)', () => {+ it('an explicit Forge update replaces a manual receipt origin', async () => {+ await manager.install(await makeCindy('manual-v1.cindy', goodManifest()));+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');+ const installed = manager.list().find((ghost) => ghost.manifest.id === 'hello');+ const result = await manager.update(+ await makeCindy('forge-v2.cindy', { ...goodManifest(), version: '2.0.0' }),+ {+ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),+ installOrigin: 'agent-forge',+ },+ );+ expect(result).toHaveProperty('ghost');+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('agent-forge');+ });++ it('a manual update clears an earlier Forge origin instead of inheriting privilege', async () => {+ await manager.install(await makeCindy('forge-v1.cindy', goodManifest()), {+ installOrigin: 'agent-forge',+ });+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('agent-forge');++ const installed = manager.list().find((ghost) => ghost.manifest.id === 'hello');+ const result = await manager.update(+ await makeCindy('manual-v2.cindy', { ...goodManifest(), version: '2.0.0' }),+ { expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval) },+ );+ expect(result).toHaveProperty('ghost');+ const receipt = JSON.parse(+ await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'hello.json'), 'utf8'),+ ) as Record<string, unknown>;+ expect(receipt).not.toHaveProperty('installOrigin');+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');+ });+it('happy path:版本替换、旧文件清干净、目录不变、onChanged 广播', async () => {await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));onChanged.mockClear();diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.tsindex c0257a4b38..5df12ada24 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts@@ -155,10 +155,14 @@ describe('installed Plugin Connection audience resolver', () => {).toBeNull();});- it('keeps legacy Forge OIDC for an approved current-organization prefix plugin', () => {+ it('resolves explicit Forge OIDC before a stale or foreign market row', () => {const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };const resolver = loadConnectionAudienceResolver({- ...resolverOptions(forgeManifest, null),+ ...resolverOptions(forgeManifest, {+ ...marketInstallation,+ installed: false,+ organizationId: 'org-other',+ }),readInstallOrigin: () => 'agent-forge',readApprovedPackageSha256: () => 'a'.repeat(64),lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),@@ -171,7 +175,7 @@ describe('installed Plugin Connection audience resolver', () => {});});- it('does not extend legacy Forge OIDC to a manual install or another prefix', () => {+ it('does not extend Forge OIDC to a manual install or another prefix', () => {const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };for (const options of [{ readInstallOrigin: () => 'manual' as const, pluginPrefix: 'acme' },diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.tsindex dbbb53202b..f00003fe1d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts@@ -17,6 +17,9 @@ describe('FORGE_GUIDE · Cindy Connection 凭证章节', () => {'identities','不允许 `*.example.com` 通配','POST / PUT / PATCH / DELETE',+ '显式调用 `ghost_forge_install` 安装',+ '要求用户手输相同 id',+ '手动导入不签发',]) {expect(FORGE_GUIDE).toContain(marker);}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.tsindex 54b7b3ab80..e726caf578 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts@@ -32,20 +32,23 @@ describe('FORGE_GUIDE · oauth 凭证章节', () => {expect(FORGE_GUIDE).toContain('`/secrets`、`/oauth`、`/wake`');});- it('redirectPort 与 tokenBroker 两路资格在场(§2 样例 + §4.7 说明 + 拒装原因)', () => {+ it('redirectPort 与 tokenBroker 三路资格在场(§2 样例 + §4.7 说明 + 拒装原因)', () => {for (const marker of ['"redirectPort"','"tokenBroker"','redirectPort 不是 1024–65535 整数','tokenBroker 没同时声明 redirectPort','或与 clientSecret 同时声明',- '两路资格',+ '三路资格','静态官方前缀照旧放行',- '服务端 organization market 包已安装',+ '当前组织的服务端',+ 'organization market 包已安装','organizationId 与当前组织一致','release sha256 与批准 receipt 的 packageSha256 相等',- '不接受本地装入、个人身份或别的组织前缀',- '只给 Broker 与 oidc-token,不给宿主原语',+ '企业作者通过 `ghost_forge_install` 明确安装',+ '手动导入不属于 Forge 路径',+ '只给 Broker',+ '不给宿主原语','总长不得超过 64 字符',]) {expect(FORGE_GUIDE).toContain(marker);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 02a17c7b98..b1f80c0647 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -1501,7 +1501,7 @@ describe('FORGE_GUIDE', () => {expect(FORGE_GUIDE).toContain("ghost_forge_install({ dir: '<绝对路径>' })");expect(FORGE_GUIDE).toContain('不要因为 scaffold 或 pack 成功就自动调用本工具');expect(FORGE_GUIDE).toContain('同版本也可覆盖');- expect(FORGE_GUIDE).toContain('两种入口走同一安装/更新事务');+ expect(FORGE_GUIDE).toContain('手动导入不会取得这项 Forge 作者资格');});it('开场白要求读完沙箱红线与打包测试两章', () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.tsnew file mode 100644index 0000000000..247f66902b--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest';++import type { GhostManifest } from '../../../shared/ghost';+import {+ ForgeOidcInstallConfirmBridge,+ forgeOidcInstallConfirmFacts,+ type ForgeOidcInstallConfirmPush,+} from '../forgeOidcInstallConfirmBridge';++function manifest(secrets: NonNullable<GhostManifest['network']>['secrets']): GhostManifest {+ return {+ schemaVersion: 2,+ id: 'acme-tool',+ name: 'Acme Tool',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['network'],+ network: { hosts: ['api.acme.test'], secrets },+ };+}++const OIDC = manifest([+ {+ key: 'identity',+ label: 'Identity',+ source: 'oidc-token',+ inject: { header: 'Authorization', format: 'Bearer {value}', hosts: ['api.acme.test'] },+ },+]);++describe('forgeOidcInstallConfirmFacts', () => {+ it('requires confirmation only for organization installs that declare oidc-token', () => {+ expect(forgeOidcInstallConfirmFacts(OIDC, 'org')).toEqual({+ ghostId: 'acme-tool',+ ghostName: 'Acme Tool',+ hosts: ['api.acme.test'],+ });+ expect(forgeOidcInstallConfirmFacts(OIDC, 'personal')).toBeNull();+ expect(+ forgeOidcInstallConfirmFacts(+ manifest([+ {+ key: 'oauth',+ label: 'OAuth',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.acme.test/authorize',+ tokenUrl: 'https://accounts.acme.test/token',+ clientId: 'client',+ redirectPort: 53684,+ tokenBroker: 'jira',+ },+ },+ ]),+ 'org',+ ),+ ).toBeNull();+ });+});++describe('ForgeOidcInstallConfirmBridge', () => {+ it('round-trips one answer and fails closed on duplicate or malformed replies', async () => {+ const sent: ForgeOidcInstallConfirmPush[] = [];+ const bridge = new ForgeOidcInstallConfirmBridge({+ sendToWindow: (payload) => {+ sent.push(payload);+ return true;+ },+ timeoutMs: 1_000,+ });+ const pending = bridge.request({+ ghostId: 'acme-tool',+ ghostName: 'Acme Tool',+ hosts: ['api.acme.test'],+ });+ expect(sent).toHaveLength(1);+ expect(bridge.resolve(sent[0].requestId, 'true')).toBe(true);+ expect(await pending).toBe(false);+ expect(bridge.resolve(sent[0].requestId, true)).toBe(false);+ });++ it('cancelAll releases every pending install as declined', async () => {+ const bridge = new ForgeOidcInstallConfirmBridge({+ sendToWindow: () => true,+ timeoutMs: 60_000,+ });+ const pending = bridge.request({+ ghostId: 'acme-tool',+ ghostName: 'Acme Tool',+ hosts: ['api.acme.test'],+ });+ bridge.cancelAll();+ await expect(pending).resolves.toBe(false);+ expect(bridge.pendingCount).toBe(0);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.tsnew file mode 100644index 0000000000..6a434235df--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts@@ -0,0 +1,40 @@+import fs from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++const source = fs.readFileSync(fileURLToPath(new URL('../index.ts', import.meta.url)), 'utf8');++function forgeInstallBody(): string {+ const start = source.indexOf('export async function installOrUpdateLocalGhostPackageFromForge');+ const end = source.indexOf('/**\n * Plugin 市场专用装入入口', start);+ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ return source.slice(start, end);+}++describe('Forge OIDC install entry wiring', () => {+ it('finishes the narrow confirmation before any install/update mutation begins', () => {+ const body = forgeInstallBody();+ const confirm = body.indexOf(+ 'await ensureForgeOidcInstallConfirmBridge().request(confirmFacts)',+ );+ const mutation = body.indexOf('return withGhostInstallLock');+ expect(confirm).toBeGreaterThanOrEqual(0);+ expect(mutation).toBeGreaterThan(confirm);+ expect(body).toContain("throwIpcError('MUTATION_CANCELLED'");+ });++ it('marks both new installs and in-place updates as explicit agent-forge', () => {+ const body = forgeInstallBody();+ expect(body).toContain("installOrigin: 'agent-forge'");+ expect(body).toContain("getActiveAppSession(),\n 'agent-forge',");+ });++ it('authorizes tokenBroker against Forge facts without making it trigger the OIDC dialog', () => {+ const body = forgeInstallBody();+ expect(body).toContain(+ "rejectUnauthorizedTokenBroker(inspected.manifest, { installOrigin: 'agent-forge' })",+ );+ expect(body).toContain('forgeOidcInstallConfirmFacts(');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.tsindex 41f459b5d8..1e81a3e15e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts@@ -200,6 +200,40 @@ describe('loadGhostFirstPartyFactsLoader', () => {});});+ it('keeps explicit Forge facts usable when the rebuildable market ledger cannot be read', () => {+ const loaded = loader({+ readInstallOrigin: () => 'agent-forge',+ readMarketInstallation: () => {+ throw new Error('EACCES');+ },+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),+ }).load('acme-tool', 'runtime', ORG_A);++ expect(loaded).toMatchObject({+ kind: 'ready',+ facts: {+ marketRecord: null,+ installOrigin: 'agent-forge',+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },+ },+ });+ });++ it('applies an install-time Forge origin before consulting a broken market ledger', () => {+ const loaded = loader({+ readInstallOrigin: () => 'manual',+ readMarketInstallation: () => {+ throw new Error('EACCES');+ },+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),+ }).load('acme-tool', 'install', ORG_A, { installOrigin: 'agent-forge' });++ expect(loaded).toMatchObject({+ kind: 'ready',+ facts: { installOrigin: 'agent-forge', marketRecord: null },+ });+ });+it('copies a confirmed ledger miss as marketRecord null when facts are otherwise ready', () => {const loaded = loader({readMarketInstallation: () => null,@@ -314,7 +348,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {});});- it('copies only the legacy Forge origin and fails closed when it cannot be read', () => {+ it('copies only the explicit Forge origin and fails closed when it cannot be read', () => {const forged = loader({readInstallOrigin: () => 'agent-forge',lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.tsindex a2f3972853..7f0d3157c9 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts@@ -314,7 +314,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {});});- it('keeps Broker only for a legacy Forge receipt under the current organization prefix', () => {+ it('grants Broker-only self-test to an explicit Forge install under the current organization prefix', () => {expect(resolveGhostFirstPartyPrivilege(facts({@@ -326,7 +326,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {).toEqual({brokerEligible: true,hostPrimitiveEligible: false,- basis: 'legacy-forge-current-org-prefix',+ basis: 'forge-current-org-prefix',});expect(resolveGhostFirstPartyPrivilege(@@ -353,6 +353,30 @@ describe('resolveGhostFirstPartyPrivilege', () => {).toBe(false);});+ it('lets explicit Forge self-test win over every stale or foreign market-row shape', () => {+ const rows = [+ market({ scope: 'organization', installed: false }),+ market({ scope: 'organization', organizationId: 'org-other' }),+ market({ scope: 'personal', organizationId: null, source: 'local-market' }),+ ];+ for (const marketRecord of rows) {+ expect(+ resolveGhostFirstPartyPrivilege(+ facts({+ ghostId: 'acme-feishu',+ marketRecord,+ currentOrganization: CURRENT_ORG,+ installOrigin: 'agent-forge',+ }),+ ),+ ).toEqual({+ brokerEligible: true,+ hostPrimitiveEligible: false,+ basis: 'forge-current-org-prefix',+ });+ }+ });+// 台账里有这条 id 但 installed 为 false 时,曾经会整段跳过市场分支、落到末尾那条// 「本地包 + 本组织前缀 → 放行」的兜底。于是同一条 `scope: 'personal'` 记录// (明确不可信)把 installed 从 true 改成 false,结论就从 deny 翻成 allow ——@@ -375,7 +399,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {basis: 'denied-unknown-origin',});}- // 作者自测:从未发布过的 id 没有台账行,本地装入仍然 deny。+ // 手动本地包不能借一个 installed=false 的市场行取得资格。});it('keeps official-prefix broker even when facts are unavailable, and asks the resolver otherwise', () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex 9392aa610c..1b7a64f220 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -229,7 +229,7 @@ describe('GhostInstallReceiptStore cleanup', () => {});});- it('preserves only the legacy Forge origin as an effective authorization fact', async () => {+ it('recognizes only the Host-owned Forge origin as an effective authorization fact', async () => {await store.write(createGhostInstallReceipt({...createSetupReceipt(),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.tsindex 5ab1974e5a..dbbf2ac736 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.ts@@ -3,10 +3,11 @@ import { describe, expect, it } from 'vitest';import { ghostTokenBrokerInstallError } from '../ghostTokenBrokerInstallError.js';describe('ghostTokenBrokerInstallError', () => {- it('returns the actionable local-install authorization error', () => {+ it('distinguishes manual import from the explicit Forge author path', () => {expect(ghostTokenBrokerInstallError()).toMatchObject({code: 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',- reason: expect.stringContaining('本地装入'),+ reason: expect.stringContaining('手动装入'),});+ expect(ghostTokenBrokerInstallError().reason).toContain('ghost_forge_install');});});diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.tsindex 936d477292..26551afc4a 100644--- a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts@@ -1,8 +1,7 @@/**- * Host-owned Connection audience resolution. New grants require an intact- * organization-scoped Plugin Market install; a bounded read-only fallback keeps- * legacy Forge receipts working. The Host derives the audience from the current- * organization and the installed plugin id.+ * Host-owned Connection audience resolution. Explicit Forge installs for the+ * current organization and intact organization-market installs are the two+ * dynamic bases. The Host derives the audience from current identity + plugin id.*/import { isValidGhostId, isValidGhostNetworkHostPattern } from '../../shared/ghost.js';import type { GhostManifest } from '../../shared/ghost.js';@@ -56,6 +55,18 @@ export function isConnectionSecretReady(return resolution !== null && injectHosts.some((host) => resolution.allowedHosts.includes(host));}+/** Exact non-wildcard hosts declared for Host-injected Connection JWTs. */+export function declaredOidcTokenHosts(manifest: GhostManifest): string[] {+ return [+ ...new Set(+ (manifest.network?.secrets ?? [])+ .filter((secret) => secret.source === 'oidc-token')+ .flatMap((secret) => secret.inject.hosts ?? [])+ .filter((host) => isValidGhostNetworkHostPattern(host) && !host.startsWith('*.')),+ ),+ ];+}+export interface LoadConnectionAudienceResolverOptions {readInstalledManifest(ghostId: string): GhostManifest | null;readInstalledManifestDigest(ghostId: string): string | null;@@ -97,14 +108,7 @@ export function loadConnectionAudienceResolver(}const finish = (manifest: GhostManifest): ConnectionAudienceResolution | null => {- const allowedHosts = [- ...new Set(- (manifest.network?.secrets ?? [])- .filter((secret) => secret.source === 'oidc-token')- .flatMap((secret) => secret.inject.hosts ?? [])- .filter((host) => isValidGhostNetworkHostPattern(host) && !host.startsWith('*.')),- ),- ];+ const allowedHosts = declaredOidcTokenHosts(manifest);if (allowedHosts.length === 0) return reject('oidc-host-declaration-missing');const audience = `${identity.orgSlug}:${ghostId}`;if (audience.length > 64) return reject('audience-too-long');@@ -128,9 +132,8 @@ export function loadConnectionAudienceResolver(}};- // 只读兼容升级前的 Forge receipt。新安装不再写 agent-forge;但旧插件的- // Connection JWT 资格不能因客户端升级中断。个人身份、缺失组织 slug、未知- // 前缀与缺失批准包哈希都已在进入此分支前后 fail closed。+ // 显式 ghost_forge_install 的企业作者自测分支,同时兼容升级前已有的+ // agent-forge receipt。个人身份、未知前缀与缺失批准包哈希均 fail closed。const forgeOrigin = options.readInstallOrigin?.(ghostId);if (forgeOrigin === 'agent-forge') {const prefixLookup = options.lookupOrganizationPrefix?.(identity.orgId);diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex fc1f4be01a..6febdcdc43 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1461,7 +1461,8 @@ ghost_forge_pack 校验并生成 .cindy 产物;需要发布时改用 publish i**安装与更新契约**:用户导入本地 \`.cindy\`、点击市场安装,或插件命中服务端 \`defaultInstall\`,都是明确的安装依据;-Cindy 校验真实包后直接安装并启用,不再追加能力确认弹窗。市场安装会绑定所选来源,+Cindy 校验真实包后直接安装并启用,不再追加整张能力确认弹窗。唯一的窄确认是:企业作者+用 \`ghost_forge_install\` 安装声明了 \`oidc-token\` 的包时,需核对 id 与注入域名。市场安装会绑定所选来源,此后的新版本由 Cindy 静默更新并保留当前启用状态;本地 \`.cindy\` 不自动猜测更新来源,需要用户再次导入新版包。插件自主 Host 能力仍必须完整声明,插件详情会如实展示,Host 运行时按声明强制守门;市场下载包若超出该版本市场清单声明的能力,会作为包内容不一致被拒绝。@@ -1835,7 +1836,7 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它"extraAuthorizeParams": { "access_type": "offline", "prompt": "consent" }, // 可选 ≤8 条:服务商特有授权参数(协议保留参数禁写)"identity": { "url": "https://api.example.com/userinfo", "labelPath": "email", "displayTemplate": "{team} · {user}", "avatarPath": "data.avatar_thumb" }, // 可选:授权后拉一次身份端点给账号打标签(设置页"已连接为 xxx";url 域名须命中 hosts)。labelPath 应指向**唯一且稳定**字段(如邮箱 / user_id)——它是重复授权时的同身份合并判定键,选 name 这类可重名可改名字段会误合并。displayTemplate 可选:人类可读展示名模板,\`{点分路径}\` 占位符从同一份身份响应取值(至少一个占位符,≤200 字符),任一占位符取不到值整体降级为空、回落显示 labelPath 的值——labelPath 的稳定字段不可读(如 Slack 的 user_id)时声明它,设置页与账号工具展示的就是渲染后的名字(邮箱这类本身可读的服务商不需要)。avatarPath 可选:头像 URL 在身份响应里的点分路径(如飞书的 "data.avatar_thumb")——主机取 https 地址后**不带凭证**下载小图(仅 png/jpeg/webp/gif、≤256KB)转 data URL 存库,\`/oauth\` 回查里以 account.avatarDataUrl 给你的 settingsHtml 展示(<img> 直接用)。**下载仅对第一方官方意识生效**(头像地址不受 hosts 白名单约束,第三方声明合法但恒降级 null)——所以页面必须能没头像也好看(如回落姓名首字圆片)"redirectPort": 53682, // 可选:loopback 回调固定端口(1024–65535);声明 tokenBroker 时必填。服务商要求回调 URI 与注册值精确匹配(如 Atlassian)时声明,回调恒为 http://127.0.0.1:<端口>/callback;非 broker 模式缺省 = 随机端口(Google 等允许任意 loopback 端口的服务商不用声明)- "tokenBroker": "jira", // 可选:两路资格:静态官方前缀照旧放行;或当前组织的服务端 organization market 包已安装、source 为 market、organizationId 与当前组织一致、id 命中本组织已登记前缀且 release sha256 与批准 receipt 的 packageSha256 相等。组织市场基座不接受本地装入、个人身份或别的组织前缀,且只给 Broker 与 oidc-token,不给宿主原语。声明时必须同时声明 redirectPort;code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client+ "tokenBroker": "jira", // 可选:三路资格:静态官方前缀照旧放行;当前组织的服务端 organization market 包满足来源/组织/前缀/整包 sha256 绑定;或企业作者用 ghost_forge_install 明确安装且 id 命中本组织已登记前缀。后两路只给 Broker 与 oidc-token,不给宿主原语;手动导入与个人身份不放行。声明时必须同时声明 redirectPort;code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client"brokerBounce": { "path": "/example/bounce", "callbackPath": "/example/callback" } // 可选:双地址弹跳回调(服务商后台只收 https redirect、不收 http loopback 时用)。必须与 tokenBroker、redirectPort 同时声明;报给服务商的 redirect_uri = broker 服务基地址 + path(主机运行时拼,清单不落域名),浏览器授权后由弹跳路由 302 回 http://127.0.0.1:<redirectPort><callbackPath>}}],@@ -2971,12 +2972,15 @@ PAT;页面可据此展示“已检测到 gh,可直接使用”,但不能\`Authorization: Bearer {value}\`,不允许 exchange,也不要放进 \`setup.requires\`。**Cindy 企业身份断言(source:"oidc-token",可选)**:适用于接入 Cindy Connection-Auth 的企业服务。主机只在当前登录账号属于组织 Membership、且该插件拥有当前组织的-Plugin Market organization 安装记录(source 必须是服务端 \`market\`)、安装 manifest-digest 未被篡改并声明了目标服务域名时,按需向 auth-server 换取短时 Connection JWT。+Auth 的企业服务。主机只在当前登录账号属于组织 Membership,且满足以下任一安装基座时+按需向 auth-server 换取短时 Connection JWT:①当前组织的 Plugin Market organization+安装记录(source 必须是服务端 \`market\`),且安装 manifest digest 与记录一致;②企业作者+显式调用 \`ghost_forge_install\` 安装,插件 id 命中当前组织已登记前缀,且批准 receipt+保有本次包的完整 sha256。两路都要求清单声明目标服务域名。audience 与组织身份由主机推导,插件清单和运行时代码都不能选择、读取或保存audience/token;audience 固定为 \`\${orgSlug}:\${ghostId}\`,总长不得超过 64 字符。-该组织市场基座不适用于个人身份或本地装入,只给 Broker 与 oidc-token、不给宿主原语。+个人身份与手动导入不签发;Forge 安装前会展示插件名、id 与精确域名,并要求手输相同 id+确认。市场与 Forge 两条组织基座都只给 Broker 与 oidc-token、不给宿主原语。该凭证必须固定声明\`"inject": { "header": "Authorization", "format": "Bearer {value}", "hosts": [...] }\`,且 \`hosts\` 必须是非空的显式子集,只允许把断言发给列出的企业服务域名。@@ -3059,11 +3063,12 @@ identity.displayTemplate 时,\`/oauth\` 回查与连接结果里 account.label即可;第一方官方内置意识会先自动结束占用进程并重试,第三方意识不享受此回收——请选一个不易撞车的端口)。声明 \`tokenBroker\` 时必须提供;非 broker 模式下,Google 这类允许任意 loopback 端口的服务商不用声明。-- \`tokenBroker\`:资格有两路:①静态官方前缀命中,照旧放行;②当前组织的服务端+- \`tokenBroker\`:资格有三路:①静态官方前缀命中,照旧放行;②当前组织的服务端organization market 包已安装、source 为 \`market\`、organizationId 与当前组织一致,id 命中本组织已登记前缀,且 release sha256 与批准 receipt 的 packageSha256 相等。- 组织市场基座不接受本地装入、个人身份或别的组织前缀,且只给 Broker 与- oidc-token,不给宿主原语。+ ③企业作者通过 \`ghost_forge_install\` 明确安装,且 id 命中当前组织已登记前缀;是否已有+ 同 id 市场记录不影响这条自测路径。后两路不接受个人身份或别的组织前缀,且只给 Broker+ 与 oidc-token,不给宿主原语;手动导入不属于 Forge 路径。code/refresh 交换改经 Cindy 服务端 broker 完成,client secret 由服务端持有、不随包分发,且要求用户已登录 Cindy。声明它时必须同时声明 redirectPort,并与 clientSecret互斥;PKCE 缺省开(verifier@@ -4373,7 +4378,9 @@ const opened = await cindy.iosSimulator.request({\`ghost_forge_install({ dir: '<绝对路径>' })\`。它会重新校验并打包当前源码,再把这次产生的确切包直接安装;首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、数据与面板位置,同版本也可覆盖。不要因为 scaffold 或 pack 成功就自动调用本工具。- 用户也可以自己导入上一步的 \`.cindy\`,两种入口走同一安装/更新事务;+ 企业身份下若清单声明 \`source:"oidc-token"\`,提交安装前会展示插件名、id 与精确注入+ 域名,并要求用户手输相同 id;取消不会安装。确认后的企业作者自测可签发 Connection JWT。+ 用户也可以自己导入上一步的 \`.cindy\`,但手动导入不会取得这项 Forge 作者资格;4. 安装后再让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。企业组织成员需要发布时,调用 \`ghost_forge_pack({ dir: '<绝对路径>', intent: 'publish' })\`。diff --git a/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.tsnew file mode 100644index 0000000000..a1dd3cb001--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.ts@@ -0,0 +1,103 @@+import { randomUUID } from 'node:crypto';++import type { GhostManifest } from '../../shared/ghost.js';+import { GHOST_CONFIRM_TIMEOUT_MS } from '../../shared/ghost.js';+import { declaredOidcTokenHosts } from './connectionAudienceResolver.js';++export interface ForgeOidcInstallConfirmPush {+ requestId: string;+ ghostId: string;+ ghostName: string;+ hosts: string[];+}++export interface ForgeOidcInstallConfirmFacts {+ ghostId: string;+ ghostName: string;+ hosts: string[];+}++/** 只有企业身份安装声明了 oidc-token 的 Forge 包才需要这扇窄确认窗。 */+export function forgeOidcInstallConfirmFacts(+ manifest: GhostManifest,+ membershipKind: 'personal' | 'org',+): ForgeOidcInstallConfirmFacts | null {+ if (membershipKind !== 'org') return null;+ const hosts = declaredOidcTokenHosts(manifest);+ return hosts.length > 0 ? { ghostId: manifest.id, ghostName: manifest.name, hosts } : null;+}++export interface ForgeOidcInstallConfirmBridgeDeps {+ sendToWindow(payload: ForgeOidcInstallConfirmPush): boolean;+ timeoutMs?: number;+ log?: { warn: (message: string, meta?: Record<string, unknown>) => void };+}++interface PendingConfirm {+ resolve: (confirmed: boolean) => void;+ timeoutId: ReturnType<typeof setTimeout>;+}++/**+ * Forge 企业身份自测确认的 main ↔ renderer 往返桥。只投一个 Cindy 窗口;+ * 无窗口、超时、畸形回包与边界切换都 fail closed。+ */+export class ForgeOidcInstallConfirmBridge {+ private readonly pending = new Map<string, PendingConfirm>();++ constructor(private readonly deps: ForgeOidcInstallConfirmBridgeDeps) {}++ request(facts: ForgeOidcInstallConfirmFacts): Promise<boolean> {+ const requestId = randomUUID();+ return new Promise<boolean>((resolve, reject) => {+ const timeoutId = setTimeout(() => {+ this.deps.log?.warn('forge OIDC install confirm timed out', {+ ghostId: facts.ghostId,+ requestId,+ });+ this.settle(requestId, false);+ }, this.deps.timeoutMs ?? GHOST_CONFIRM_TIMEOUT_MS);+ this.pending.set(requestId, { resolve, timeoutId });+ if (!this.deps.sendToWindow({ requestId, ...facts })) {+ this.pending.delete(requestId);+ clearTimeout(timeoutId);+ reject(new Error('没有可挂靠的宿主窗口'));+ }+ });+ }++ resolve(requestId: string, confirmed: unknown): boolean {+ if (!this.pending.has(requestId)) return false;+ this.settle(requestId, confirmed === true);+ return true;+ }++ cancelAll(): void {+ for (const requestId of Array.from(this.pending.keys())) this.settle(requestId, false);+ }++ get pendingCount(): number {+ return this.pending.size;+ }++ private settle(requestId: string, confirmed: boolean): void {+ const entry = this.pending.get(requestId);+ if (!entry) return;+ this.pending.delete(requestId);+ clearTimeout(entry.timeoutId);+ entry.resolve(confirmed);+ }+}++let bridgeSingleton: ForgeOidcInstallConfirmBridge | null = null;++export function initForgeOidcInstallConfirmBridge(+ deps: ForgeOidcInstallConfirmBridgeDeps,+): ForgeOidcInstallConfirmBridge {+ bridgeSingleton = new ForgeOidcInstallConfirmBridge(deps);+ return bridgeSingleton;+}++export function getForgeOidcInstallConfirmBridge(): ForgeOidcInstallConfirmBridge | null {+ return bridgeSingleton;+}diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.tsindex 2c0c97f4fc..9a39d77637 100644--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts@@ -54,6 +54,7 @@ export interface GhostFirstPartyFactsLoader {ghostId: string,purpose: GhostFirstPartyFactsPurpose,identity: GhostFirstPartyFactsIdentity,+ overrides?: GhostFirstPartyFactsOverrides,): GhostFirstPartyFactsLoad;}@@ -63,7 +64,7 @@ export interface LoadGhostFirstPartyFactsLoaderOptions {/** Missing or legacy package evidence must return null. */readApprovedPackageSha256(ghostId: string): string | null;lookupOrganizationPrefix(orgId: string): OrganizationPrefixLookup;- /** 新安装返回 manual;仅旧 receipt 会返回 agent-forge。 */+ /** 显式 ghost_forge_install 返回 agent-forge;其它入口返回 manual。 */readInstallOrigin(ghostId: string): 'manual' | 'agent-forge';}@@ -107,26 +108,11 @@ export type GhostFirstPartyFactsOverrides = {marketRecord?: GhostFirstPartyMarketRecord | null;};-export function applyGhostFirstPartyFactsOverrides(- load: GhostFirstPartyFactsLoad,- overrides?: GhostFirstPartyFactsOverrides,-): GhostFirstPartyFactsLoad {- if (!overrides || load.kind !== 'ready') return load;- return {- kind: 'ready',- facts: {- ...load.facts,- ...(overrides.installOrigin !== undefined ? { installOrigin: overrides.installOrigin } : {}),- ...(overrides.marketRecord !== undefined ? { marketRecord: overrides.marketRecord } : {}),- },- };-}-export function loadGhostFirstPartyFactsLoader(options: LoadGhostFirstPartyFactsLoaderOptions,): GhostFirstPartyFactsLoader {return {- load(ghostId, purpose, identity) {+ load(ghostId, purpose, identity, overrides) {const unavailable = (reason: GhostFirstPartyFactsUnavailableReason,): GhostFirstPartyFactsLoad => ({@@ -143,24 +129,34 @@ export function loadGhostFirstPartyFactsLoader(return unavailable('installed-list-read-failed');}- let marketRecord: GhostFirstPartyMarketRecord | null = null;- try {- const installation = options.readMarketInstallation(ghostId);- marketRecord = installation- ? toMarketRecord(installation, options.readApprovedPackageSha256(ghostId))- : null;- } catch {- // Builtin official plugins do not consult the ledger. A corrupt ledger- // must not take away xd-feishu / xd-atlassian broker eligibility.- if (!builtin) return unavailable('market-installation-read-failed');- marketRecord = null;+ let installOrigin: 'manual' | 'agent-forge' = 'manual';+ if (overrides?.installOrigin !== undefined) {+ installOrigin = overrides.installOrigin;+ } else {+ try {+ installOrigin = options.readInstallOrigin(ghostId);+ } catch {+ installOrigin = 'manual';+ }}- let installOrigin: 'manual' | 'agent-forge' = 'manual';- try {- installOrigin = options.readInstallOrigin(ghostId);- } catch {- installOrigin = 'manual';+ let marketRecord: GhostFirstPartyMarketRecord | null = null;+ if (overrides?.marketRecord !== undefined) {+ marketRecord = overrides.marketRecord;+ } else {+ try {+ const installation = options.readMarketInstallation(ghostId);+ marketRecord = installation+ ? toMarketRecord(installation, options.readApprovedPackageSha256(ghostId))+ : null;+ } catch {+ // Builtin official plugins and explicit Forge self-tests do not depend+ // on the ledger. A corrupt cache must not take either qualification away.+ if (!builtin && installOrigin !== 'agent-forge') {+ return unavailable('market-installation-read-failed');+ }+ marketRecord = null;+ }}if (identity.membershipKind !== 'org' || !identity.orgId) {diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.tsindex 9262ab0abf..aa84f4a718 100644--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts@@ -11,9 +11,10 @@** Input priority: first evaluable of* 1. builtin seed → static official table- * 2. plugin-market ledger (source + scope + organizationId + Release sha256)+ * 2. explicit agent-forge install + current organization prefix+ * 3. plugin-market ledger (source + scope + organizationId + Release sha256)* paired with the approved receipt packageSha256- * 3. neither → fail-closed, no privilege+ * 4. neither → fail-closed, no privilege** Discriminator is the combination of `source` and `scope`, not `scope`* alone. Custom / git market rows write `scope: 'public'` as a placeholder@@ -47,7 +48,7 @@ export type GhostFirstPartyBasis =| 'builtin-official'| 'market-public'| 'market-organization-current'- | 'legacy-forge-current-org-prefix'+ | 'forge-current-org-prefix'| 'denied-alias'| 'denied-foreign-org'| 'denied-unknown-origin';@@ -80,7 +81,7 @@ export interface GhostFirstPartyFacts {builtin: boolean;marketRecord: GhostFirstPartyMarketRecord | null;currentOrganization: GhostFirstPartyCurrentOrganization | null;- /** 仅来自升级前 receipt;新安装恒为 manual。 */+ /** 仅显式 ghost_forge_install 写入 agent-forge;其它入口均为 manual。 */installOrigin: 'manual' | 'agent-forge';}@@ -147,20 +148,21 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Ghreturn deny('denied-alias');}+ // 企业作者的显式 Forge 自测资格来自本次安装来源与当前组织前缀,和市场账本+ // 是否已有同 id、是否仍标记 installed 无关。它只开放 Broker / oidc-token,+ // 宿主原语仍保持拒绝。+ if (+ facts.installOrigin === 'agent-forge' &&+ matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)+ ) {+ return allow('forge-current-org-prefix', false);+ }+const record = facts.marketRecord;if (record !== null) {if (!record.installed) {- // A ledger row that exists but is not installed must not fall through to- // the local-package tail below. Two reasons, both mattering:- // 1. Fail-open direction. `{scope: 'personal', installed: true}` is- // denied here; flipping `installed` to false would have turned that- // same row into an allow via the tail. A security predicate must- // never grant more when one of its fields is false.- // 2. It is the impersonation case, not the self-test case. Once an id- // appears in the market ledger, a hand-built local package carrying- // that same id is impersonating it. Author self-test is unaffected:- // a never-published id has no ledger row at all (`marketRecord`- // is null) and still reaches the tail.+ // Uninstalled ledger rows stay denied. Explicit Forge self-test is+ // decided above from origin + org prefix, before this market branch.return deny('denied-unknown-origin');}if (record.scope === 'public' && record.source === 'market') {@@ -188,23 +190,9 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Gh}return allow('market-organization-current', false);}- if (- facts.installOrigin === 'agent-forge' &&- (record.source === 'git-market' || record.source === 'local-market') &&- matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)- ) {- return allow('legacy-forge-current-org-prefix', false);- }return deny('denied-unknown-origin');}- if (- facts.installOrigin === 'agent-forge' &&- matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)- ) {- return allow('legacy-forge-current-org-prefix', false);- }-return deny('denied-unknown-origin');}diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 73f8f505de..798605e257 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -66,8 +66,8 @@ export interface GhostInstallReceipt {*/packageSha256?: string;/**- * 旧版 Forge 安装写入的来源标记。新安装不再写入;保留只读是为了让升级前- * 已获 Broker 资格的存量插件不会在客户端升级后突然失效。+ * 显式 `ghost_forge_install` 写入的来源标记。手动导入等其它入口不写;旧版+ * receipt 中的同名值继续有效,避免升级后丢失既有企业作者自测资格。*/installOrigin?: string;/**@@ -1060,7 +1060,7 @@ function isPersistableInstallOrigin(value: string): boolean {);}-/** 旧 receipt 的授权视图:只有历史 agent-forge 值有效,其余一律降级。 */+/** 来源授权视图:只有 Host 写入的 agent-forge 值有效,其余一律降级。 */export function effectiveInstallOrigin(receipt: Pick<GhostInstallReceipt, 'installOrigin'>,): 'manual' | 'agent-forge' {diff --git a/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.ts b/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.tsindex 001ec1a6e2..18447d2ef4 100644--- a/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.ts+++ b/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.ts@@ -12,6 +12,7 @@ export interface GhostTokenBrokerInstallError {export function ghostTokenBrokerInstallError(): GhostTokenBrokerInstallError {return {code: 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',- reason: '本地装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装',+ reason:+ '手动装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装,或由企业作者使用 ghost_forge_install 安装自测',};}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 924dc001eb..8ea88b9f00 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -268,6 +268,11 @@ import {getGhostConfirmDialogBridge,initGhostConfirmDialogBridge,} from './ghostConfirmDialogBridge.js';+import {+ forgeOidcInstallConfirmFacts,+ getForgeOidcInstallConfirmBridge,+ initForgeOidcInstallConfirmBridge,+} from './forgeOidcInstallConfirmBridge.js';import { GhostNetworkSlot } from './networkSlot.js';import {type ConnectionAudienceResolution,@@ -277,7 +282,6 @@ import {type ConnectionAudienceResolver,} from './connectionAudienceResolver.js';import {- applyGhostFirstPartyFactsOverrides,bindPendingMarketRecordToInspectedPackage,loadGhostFirstPartyFactsLoader,type GhostFirstPartyFactsLoader,@@ -975,6 +979,7 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {getGhostSetupInteractionBridge()?.cleanupAll('session_aborted');getGhostGrantConfirmBridge()?.cleanupAll('session_aborted');getGhostConfirmDialogBridge()?.cancelAll();+ getForgeOidcInstallConfirmBridge()?.cancelAll();runtimeSingleton?.destroyAll();resetNodeRuntimeBrokerForAccountBoundary();// Library 会话一并作废:关 db worker + 作废 handle——在途写入已在串行链上@@ -2557,7 +2562,7 @@ function readInstalledGhostManifestDigest(ghostId: string): string | null {return digests[0] ?? null;}-/** Resolve Connection metadata from trusted organization installs or legacy Forge receipts. */+/** Resolve Connection metadata from trusted organization installs or explicit Forge receipts. */function getConnectionAudienceResolver(): ConnectionAudienceResolver {if (!connectionAudienceResolverSingleton) {connectionAudienceResolverSingleton = loadConnectionAudienceResolver({@@ -2629,11 +2634,13 @@ export function loadGhostFirstPartyFactsForGhost(): GhostFirstPartyFactsLoad {const state = getAuthState();const user = state.isAuthenticated ? state.user : null;- return applyGhostFirstPartyFactsOverrides(- getGhostFirstPartyFactsLoader().load(ghostId, purpose, {+ return getGhostFirstPartyFactsLoader().load(+ ghostId,+ purpose,+ {membershipKind: user?.membershipKind ?? 'personal',orgId: user?.orgId ?? null,- }),+ },overrides,);}@@ -2930,6 +2937,33 @@ let confirmSlotSingleton: GhostConfirmSlot | null = null;/** 意识确认弹窗通道(main → **单个**窗口;renderer 用主机同款 ConfirmDialog 渲染)。 */export const GHOST_CONFIRM_CHANNEL = 'ghosts:confirm-request';+export const FORGE_OIDC_INSTALL_CONFIRM_CHANNEL = 'forge-oidc-install:confirm-request';++function pickTrustedAppWindow(): Electron.BrowserWindow | undefined {+ const focused = BrowserWindow.getFocusedWindow();+ if (focused && !focused.isDestroyed() && isTrustedAppRendererWindow(focused)) return focused;+ return BrowserWindow.getAllWindows().find(+ (candidate) => !candidate.isDestroyed() && isTrustedAppRendererWindow(candidate),+ );+}++function sendTrustedGhostWindowPush(channel: string, payload: unknown): boolean {+ const win = pickTrustedAppWindow();+ if (!win) return false;+ sendGhostWindowPush(win, channel, payload);+ return true;+}++function ensureForgeOidcInstallConfirmBridge() {+ return (+ getForgeOidcInstallConfirmBridge() ??+ initForgeOidcInstallConfirmBridge({+ sendToWindow: (payload) =>+ sendTrustedGhostWindowPush(FORGE_OIDC_INSTALL_CONFIRM_CHANNEL, payload),+ log,+ })+ );+}/*** 确认弹窗槽单例(confirm):资格审/净化/限速/单飞在 GhostConfirmSlot,往返与@@ -5347,6 +5381,7 @@ async function installAndDockLocked(enable?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;+ installOrigin?: 'agent-forge';},): Promise<InstalledGhost> {// 初始启用态由入口显式传入;当前用户导入与市场首装都传 true,覆盖更新@@ -5357,6 +5392,7 @@ async function installAndDockLocked(? { expectedPackageSha256: opts.expectedPackageSha256 }: {}),...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),+ ...(opts.installOrigin ? { installOrigin: opts.installOrigin } : {}),});if ('rejection' in result) throwInstallError(result.rejection);// 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。@@ -5406,6 +5442,7 @@ async function updateLocalGhostPackageLocked(expectedPackageSha256: string,expectedInstalledApproval: string,mutationOwner: ActiveAppSession,+ installOrigin?: 'agent-forge',): Promise<InstalledGhost> {const runtime = getGhostRuntime();const marketLedger = getPluginMarketLedger().bind(@@ -5484,6 +5521,7 @@ async function updateLocalGhostPackageLocked(manager.update(cindyFilePath, {expectedPackageSha256,expectedInstalledApproval,+ ...(installOrigin ? { installOrigin } : {}),...(previousGhost? {beforePackageCommit: () =>@@ -5555,7 +5593,25 @@ export async function installOrUpdateLocalGhostPackageFromForge(}rejectReservedGhostId(inspected.manifest.id);rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);- rejectUnauthorizedTokenBroker(inspected.manifest);+ rejectUnauthorizedTokenBroker(inspected.manifest, { installOrigin: 'agent-forge' });++ const authState = getAuthState();+ const user = authState.isAuthenticated ? authState.user : null;+ const confirmFacts = forgeOidcInstallConfirmFacts(+ inspected.manifest,+ user?.membershipKind ?? 'personal',+ );+ if (confirmFacts) {+ let confirmed = false;+ try {+ confirmed = await ensureForgeOidcInstallConfirmBridge().request(confirmFacts);+ } catch {+ throwIpcError('PRECONDITION_FAILED', '当前无法显示企业身份使用确认,请稍后重试');+ }+ if (!confirmed) {+ throwIpcError('MUTATION_CANCELLED', '用户取消了企业身份插件安装');+ }+ }return withGhostInstallLock(inspected.manifest.id, async () => {const installed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);@@ -5565,6 +5621,7 @@ export async function installOrUpdateLocalGhostPackageFromForge(ghostId: inspected.manifest.id,enable: true,expectedPackageSha256: expected.packageSha256,+ installOrigin: 'agent-forge',}),action: 'installed',};@@ -5577,6 +5634,7 @@ export async function installOrUpdateLocalGhostPackageFromForge(expected.packageSha256,ghostInstallApprovalToken(installed.approval),getActiveAppSession(),+ 'agent-forge',),action: 'updated',};@@ -6634,6 +6692,23 @@ export function registerGhostIpc(): void {return { handled: bridge.resolve(p.requestId, p.confirmed) };});+ ipcMain.handle('forge-oidc-install:resolve-confirm', async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ const p = raw as { requestId?: unknown; confirmed?: unknown } | null;+ if (+ !p ||+ typeof p.requestId !== 'string' ||+ p.requestId.length === 0 ||+ p.requestId.length > 128 ||+ typeof p.confirmed !== 'boolean'+ ) {+ throwIpcError('INVALID_PARAMS', 'invalid Forge OIDC install confirmation');+ }+ const bridge = getForgeOidcInstallConfirmBridge();+ if (!bridge) return { handled: false };+ return { handled: bridge.resolve(p.requestId, p.confirmed) };+ });+// ── 意识聊天卡片取件(卡槽③;宿主 renderer 历史回放用)──────────────// 查询型 handler:无卡返回 { card: null },renderer 据此降级为通用媒体// 渲染(远程会话/被 GC 的历史卡都走这条),不抛 NOT_FOUND——规则 13 的diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex bc10e80208..58224d741f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -611,6 +611,7 @@ const fanOutGhostUnreadSnapshot = createIpcFanOut('ghosts:unread-snapshot');// 意识确认弹窗(confirm 槽:renderer 用主机同款 ConfirmDialog 弹,答案回 main)。// main 只投单个窗口(不广播),所以这里落地的窗口就是该弹框的唯一归属。const fanOutGhostConfirmRequest = createIpcFanOut('ghosts:confirm-request');+const fanOutForgeOidcInstallConfirmRequest = createIpcFanOut('forge-oidc-install:confirm-request');// 插件预览开页(preview 槽:renderer 在右侧栏开 web-browser 标签)。const fanOutGhostPreviewOpen = createIpcFanOut('ghosts:preview-open');// 插件自动化草稿(agent 槽 schedule 加档:renderer 开自动化创建面板并预填)。@@ -1258,6 +1259,12 @@ contextBridge.exposeInMainWorld('electronAPI', {// 管子请求。requestId 是 main 铸的,陌生/重复 id 由桥忽略。resolveConfirm: (requestId: string, confirmed: boolean): Promise<{ handled: boolean }> =>ipcRenderer.invoke('ghosts:confirm:resolve', { requestId, confirmed }),+ onForgeOidcInstallConfirmRequest: fanOutForgeOidcInstallConfirmRequest,+ resolveForgeOidcInstallConfirm: (+ requestId: string,+ confirmed: boolean,+ ): Promise<{ handled: boolean }> =>+ ipcRenderer.invoke('forge-oidc-install:resolve-confirm', { requestId, confirmed }),onPreviewOpen: fanOutGhostPreviewOpen,onScheduleDraft: fanOutGhostScheduleDraft,getCard: (diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex c2e2b5e9e9..34af384c3f 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -27,6 +27,7 @@ import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';+import { ForgeOidcInstallConfirmHost } from '@/cindy-brain/ForgeOidcInstallConfirmHost';import { PluginPublisherConfirmHost } from '@/features/plugin/PluginPublisherConfirmHost';import { makerChatStore } from '@/lib/makerChatStore';import {@@ -372,6 +373,7 @@ export function App() {内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口都挂、谁收到谁弹,不按窗口类型 gate。 */}<GhostConfirmDialogHost />+ <ForgeOidcInstallConfirmHost /><PluginPublisherConfirmHost /><OwnerScopedRouter /></EnvCheckGuard>diff --git a/apps/desktop/src/renderer/cindy-brain/ForgeOidcInstallConfirmHost.tsx b/apps/desktop/src/renderer/cindy-brain/ForgeOidcInstallConfirmHost.tsxnew file mode 100644index 0000000000..9106957b62--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/ForgeOidcInstallConfirmHost.tsx@@ -0,0 +1,86 @@+import { useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';++/** 企业作者显式 Forge 安装时的 OIDC 窄确认;不承载通用能力审核。 */+export function ForgeOidcInstallConfirmHost() {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();++ useEffect(() => {+ return window.electronAPI.ghosts.onForgeOidcInstallConfirmRequest((payload) => {+ if (+ !payload ||+ typeof payload.requestId !== 'string' ||+ typeof payload.ghostId !== 'string' ||+ typeof payload.ghostName !== 'string' ||+ !Array.isArray(payload.hosts) ||+ !payload.hosts.every((host) => typeof host === 'string')+ ) {+ return;+ }+ void (async () => {+ let confirmed = false;+ try {+ confirmed = await confirm({+ title: t('settings.ghosts.forgeOidcInstallConfirm.title'),+ description: t('settings.ghosts.forgeOidcInstallConfirm.description'),+ content: (+ <dl className="space-y-3 text-13 text-[var(--confirm-desc)]">+ <div>+ <dt className="text-[var(--text-tertiary)]">+ {t('settings.ghosts.forgeOidcInstallConfirm.pluginNameLabel')}+ </dt>+ <dd className="mt-0.5 font-medium text-[var(--confirm-title)]">+ {payload.ghostName}+ </dd>+ </div>+ <div>+ <dt className="text-[var(--text-tertiary)]">+ {t('settings.ghosts.forgeOidcInstallConfirm.pluginIdLabel')}+ </dt>+ <dd className="mt-0.5 font-mono text-[var(--confirm-title)]">+ {payload.ghostId}+ </dd>+ </div>+ <div>+ <dt className="text-[var(--text-tertiary)]">+ {t('settings.ghosts.forgeOidcInstallConfirm.hostsLabel')}+ </dt>+ <dd className="mt-0.5 space-y-0.5 font-mono text-[var(--confirm-title)]">+ {payload.hosts.map((host) => (+ <div key={host}>{host}</div>+ ))}+ </dd>+ </div>+ </dl>+ ),+ maxWidth: 460,+ contentSelectable: true,+ describeContent: true,+ requireTypedConfirmation: {+ expected: payload.ghostId,+ label: t('settings.ghosts.forgeOidcInstallConfirm.typedIdLabel', {+ id: payload.ghostId,+ }),+ },+ confirmText: t('settings.ghosts.forgeOidcInstallConfirm.confirm'),+ cancelText: t('settings.ghosts.forgeOidcInstallConfirm.cancel'),+ });+ } finally {+ try {+ await window.electronAPI.ghosts.resolveForgeOidcInstallConfirm(+ payload.requestId,+ confirmed,+ );+ } catch {+ // main 侧超时或 owner boundary 会按未确认收口。+ }+ }+ })();+ });+ }, [confirm, t]);++ return null;+}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ForgeOidcInstallConfirmHost.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ForgeOidcInstallConfirmHost.test.tsxnew file mode 100644index 0000000000..0a21976197--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ForgeOidcInstallConfirmHost.test.tsx@@ -0,0 +1,81 @@+// @vitest-environment jsdom+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ReactNode } from 'react';++import { ForgeOidcInstallConfirmHost } from '../ForgeOidcInstallConfirmHost';++const mocks = vi.hoisted(() => ({ confirm: vi.fn() }));++vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm: mocks.confirm }),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { id?: string }) => (options?.id ? `${key}:${options.id}` : key),+ }),+}));++describe('ForgeOidcInstallConfirmHost', () => {+ let push:+ | ((payload: {+ requestId: string;+ ghostId: string;+ ghostName: string;+ hosts: string[];+ }) => void)+ | undefined;+ const resolveConfirm = vi.fn();++ beforeEach(() => {+ mocks.confirm.mockReset().mockResolvedValue(true);+ resolveConfirm.mockReset().mockResolvedValue({ handled: true });+ (window as unknown as { electronAPI: unknown }).electronAPI = {+ ghosts: {+ onForgeOidcInstallConfirmRequest: (callback: typeof push) => {+ push = callback;+ return () => {};+ },+ resolveForgeOidcInstallConfirm: resolveConfirm,+ },+ };+ });++ afterEach(() => {+ cleanup();+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;+ });++ it('passes exact typed-id and selectable facts without adding a copy action', async () => {+ render(<ForgeOidcInstallConfirmHost />);+ await act(async () => {+ push?.({+ requestId: 'request-1',+ ghostId: 'acme-tool',+ ghostName: 'Acme Tool',+ hosts: ['api.acme.test', 'files.acme.test'],+ });+ });++ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));+ const options = mocks.confirm.mock.calls[0][0] as {+ content: ReactNode;+ contentSelectable: boolean;+ requireTypedConfirmation: { expected: string; label: string };+ };+ expect(options.contentSelectable).toBe(true);+ expect(options.requireTypedConfirmation).toEqual({+ expected: 'acme-tool',+ label: 'settings.ghosts.forgeOidcInstallConfirm.typedIdLabel:acme-tool',+ });++ render(<>{options.content}</>);+ expect(screen.getByText('Acme Tool')).toBeTruthy();+ expect(screen.getByText('acme-tool')).toBeTruthy();+ expect(screen.getByText('api.acme.test')).toBeTruthy();+ expect(screen.getByText('files.acme.test')).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();+ expect(resolveConfirm).toHaveBeenCalledWith('request-1', true);+ });+});diff --git a/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx b/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsxindex ce8cb7b2f8..e86c3aabec 100644--- a/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx+++ b/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx@@ -158,4 +158,54 @@ describe('ConfirmDialog 长内容布局', () => {expect(dialog.querySelectorAll('.overflow-y-auto').length).toBe(0);expect(flashScrollbar).not.toHaveBeenCalled();});++ it('手输确认逐字匹配且正文可选择,前后空格不能绕过 id 核对', () => {+ const onConfirm = vi.fn();+ render(+ <ConfirmDialog+ open+ onOpenChange={() => {}}+ title="企业身份自测"+ description="确认域名"+ content={<div>api.acme.test</div>}+ contentSelectable+ confirmText="安装"+ requireTypedConfirmation={{ expected: 'acme-tool', label: '输入插件 id' }}+ onConfirm={onConfirm}+ />,+ );+ const input = screen.getByLabelText('输入插件 id');+ const confirmButton = screen.getByRole('button', { name: '安装' });+ expect(screen.getByRole('alertdialog').querySelector('.overflow-y-auto')?.className).toContain(+ 'select-text',+ );++ fireEvent.change(input, { target: { value: ' acme-tool ' } });+ expect((confirmButton as HTMLButtonElement).disabled).toBe(true);+ fireEvent.change(input, { target: { value: 'acme-tool' } });+ expect((confirmButton as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(confirmButton);+ expect(onConfirm).toHaveBeenCalledTimes(1);+ });++ it('手输匹配后按 Enter 仍服从调用方的额外禁用条件', () => {+ const onConfirm = vi.fn();+ render(+ <ConfirmDialog+ open+ onOpenChange={() => {}}+ title="企业身份自测"+ confirmText="安装"+ confirmDisabled+ requireTypedConfirmation={{ expected: 'acme-tool', label: '输入插件 id' }}+ onConfirm={onConfirm}+ />,+ );++ const input = screen.getByLabelText('输入插件 id');+ fireEvent.change(input, { target: { value: 'acme-tool' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect((screen.getByRole('button', { name: '安装' }) as HTMLButtonElement).disabled).toBe(true);+ expect(onConfirm).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsxindex f4321b2fd6..1e7fecdd3d 100644--- a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx@@ -35,6 +35,14 @@ export interface ConfirmOptions {* 破坏性确认(删除/重置等)请保持默认。*/autoFocusConfirm?: boolean;+ /** 逐字输入 expected 才可确认;由 ConfirmDialog 持有本轮输入状态。 */+ requireTypedConfirmation?: {+ expected: string;+ label: string;+ placeholder?: string;+ };+ /** 允许确认正文与富内容被框选复制。 */+ contentSelectable?: boolean;}const DONT_SHOW_AGAIN_PREFIX = 'confirm-dialog.skip:';@@ -282,6 +290,8 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {showCancel={currentItem.options.showCancel}tertiaryText={currentItem.options.tertiaryText}autoFocusConfirm={currentItem.options.autoFocusConfirm}+ requireTypedConfirmation={currentItem.options.requireTypedConfirmation}+ contentSelectable={currentItem.options.contentSelectable}dontShowAgainLabel={currentItem.options.dontShowAgainKey? currentItem.options.dontShowAgainLabel ?? '下次不再提示'diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsxindex d6aa561a76..5eba5db1df 100644--- a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx@@ -49,6 +49,14 @@ export interface ConfirmDialogProps {autoFocusConfirm?: boolean;/** Disable the primary action until caller-owned validation has passed. */confirmDisabled?: boolean;+ /** 要求逐字输入 expected 才能确认;匹配不做 trim 或大小写折叠。 */+ requireTypedConfirmation?: {+ expected: string;+ label: string;+ placeholder?: string;+ };+ /** 允许正文和富内容被框选复制;缺省保持普通确认框的防误选行为。 */+ contentSelectable?: boolean;/** 嵌套在其它 Dialog 内时提升层级;普通确认继续使用默认层级。 */zIndex?: number;/** Destructive actions use the semantic destructive theme tokens. */@@ -95,6 +103,8 @@ export function ConfirmDialog({checkboxDefaultChecked = false,autoFocusConfirm,confirmDisabled = false,+ requireTypedConfirmation,+ contentSelectable = false,confirmVariant = 'default',confirmIcon,describeContent = false,@@ -114,7 +124,15 @@ export function ConfirmDialog({useEffect(() => {if (open) setDontShowAgain(checkboxDefaultChecked);}, [open, checkboxDefaultChecked]);+ const [typedConfirmation, setTypedConfirmation] = useState('');+ useEffect(() => {+ if (open) setTypedConfirmation('');+ }, [open]);+ const typedConfirmationSatisfied =+ !requireTypedConfirmation || typedConfirmation === requireTypedConfirmation.expected;+ const confirmBlocked = loading || confirmDisabled || !typedConfirmationSatisfied;const confirmBtnRef = useRef<HTMLButtonElement>(null);+ const typedConfirmationRef = useRef<HTMLInputElement>(null);const scrollRef = useRef<HTMLDivElement>(null);// 滚动条 thumb 默认透明(globals.css),不滚不 hover 就看不见"下面还有内容"。// 授权确认场景里这不是观感问题:权限清单被折在视口下面而用户不知道,等于@@ -184,11 +202,15 @@ export function ConfirmDialog({if (loading) e.preventDefault();}}onOpenAutoFocus={- autoFocusConfirm+ requireTypedConfirmation || autoFocusConfirm? (e) => {+ e.preventDefault();+ if (requireTypedConfirmation) {+ typedConfirmationRef.current?.focus();+ return;+ }// Radix 默认聚焦第一个可聚焦元素 / Cancel —— 这里覆盖,// 把焦点交给主按钮,避免"取消"天然带 focus ring。- e.preventDefault();confirmBtnRef.current?.focus();}: undefined@@ -214,6 +236,7 @@ export function ConfirmDialog({onClickCapture={revealScrollbar}className={cn('min-h-0 flex-1 overflow-y-auto overscroll-contain',+ contentSelectable && 'select-text',// 保持旧间距:有 description 时紧跟标题 mt-2;仅富内容(无正文)// 时沿用原 content 的 mt-3,避免 content-only 弹窗间距变化。description ? 'mt-2' : 'mt-3',@@ -245,11 +268,48 @@ export function ConfirmDialog({{dontShowAgainLabel}</label>)}+ {requireTypedConfirmation && (+ <div className="mt-4 shrink-0">+ <label+ htmlFor={`${bodyId}-typed`}+ className="block text-13 leading-[1.5] text-[var(--confirm-desc)]"+ >+ {requireTypedConfirmation.label}+ </label>+ <input+ ref={typedConfirmationRef}+ id={`${bodyId}-typed`}+ type="text"+ autoComplete="off"+ autoCorrect="off"+ autoCapitalize="off"+ spellCheck={false}+ value={typedConfirmation}+ disabled={loading}+ onChange={(e) => setTypedConfirmation(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !confirmBlocked) {+ e.preventDefault();+ onConfirm?.({ dontShowAgain });+ }+ }}+ placeholder={+ requireTypedConfirmation.placeholder ?? requireTypedConfirmation.expected+ }+ className={cn(+ 'mt-1.5 h-9 w-full rounded-lg border px-3 text-13',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',+ 'text-[var(--settings-input-text)] placeholder:text-[var(--text-placeholder)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ />+ </div>+ )}<div className="mt-6 flex shrink-0 justify-end gap-2.5"><AlertDialog.Action asChild><buttonref={confirmBtnRef}- disabled={loading || confirmDisabled}+ disabled={confirmBlocked}aria-busy={loading || undefined}aria-label={resolvedConfirmText}onClick={() => onConfirm?.({ dontShowAgain })}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 16202c7bbb..bd9a8de2cb 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4337,6 +4337,16 @@"expandDescription": "Show Full Description","collapseDescription": "Hide Full Description"},+ "forgeOidcInstallConfirm": {+ "title": "Confirm organization identity testing",+ "description": "After installation, this plugin can use your current organization identity to request Connection JWTs for the hosts below. Confirm that this is the plugin you just built.",+ "pluginNameLabel": "Plugin",+ "pluginIdLabel": "Plugin id",+ "hostsLabel": "Organization identity injection hosts",+ "typedIdLabel": "Enter the plugin id “{{id}}” to confirm",+ "confirm": "Install and allow testing",+ "cancel": "Cancel"+ },"trust": {"official": "Official Cindy plugin","officialDetail": "Bundled with Cindy.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 4668ef542f..9622d91c26 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4336,6 +4336,16 @@"expandDescription": "紹介全文を表示","collapseDescription": "紹介を折りたたむ"},+ "forgeOidcInstallConfirm": {+ "title": "組織 ID のセルフテストを確認",+ "description": "インストール後、このプラグインは現在の組織 ID を使用して、以下のホスト向けの Connection JWT をリクエストできます。今ビルドしたプラグインであることを確認してください。",+ "pluginNameLabel": "プラグイン",+ "pluginIdLabel": "プラグイン id",+ "hostsLabel": "組織 ID の注入先ホスト",+ "typedIdLabel": "確認するにはプラグイン id「{{id}}」を入力",+ "confirm": "インストールしてテストを許可",+ "cancel": "キャンセル"+ },"trust": {"official": "Cindy 公式プラグイン","officialDetail": "Cindy に同梱されています。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5093449c03..c3c2a4164e 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4336,6 +4336,16 @@"expandDescription": "전체 소개 보기","collapseDescription": "소개 접기"},+ "forgeOidcInstallConfirm": {+ "title": "조직 ID 자체 테스트 확인",+ "description": "설치 후 이 플러그인은 현재 조직 ID를 사용하여 아래 호스트용 Connection JWT를 요청할 수 있습니다. 방금 빌드한 플러그인이 맞는지 확인하세요.",+ "pluginNameLabel": "플러그인",+ "pluginIdLabel": "플러그인 id",+ "hostsLabel": "조직 ID 삽입 호스트",+ "typedIdLabel": "확인하려면 플러그인 id “{{id}}” 입력",+ "confirm": "설치 및 테스트 허용",+ "cancel": "취소"+ },"trust": {"official": "Cindy 공식 플러그인","officialDetail": "Cindy에 함께 제공됩니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 38119ef2f2..dc06b8e312 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4328,6 +4328,16 @@"expandDescription": "展开完整介绍","collapseDescription": "收起介绍"},+ "forgeOidcInstallConfirm": {+ "title": "确认企业身份自测",+ "description": "安装后,这个插件可以使用你当前的企业身份,向下列域名请求 Connection JWT。请确认这是你刚刚构建的插件。",+ "pluginNameLabel": "插件",+ "pluginIdLabel": "插件 id",+ "hostsLabel": "企业身份注入域名",+ "typedIdLabel": "输入插件 id“{{id}}”以确认",+ "confirm": "安装并允许自测",+ "cancel": "取消"+ },"trust": {"official": "Cindy 官方插件","officialDetail": "由 Cindy 随应用提供。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 64d76b0123..22749cbeae 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4328,6 +4328,16 @@"expandDescription": "展開完整介紹","collapseDescription": "收起介紹"},+ "forgeOidcInstallConfirm": {+ "title": "確認企業身份自測",+ "description": "安裝後,這個插件可以使用你目前的企業身份,向下列網域請求 Connection JWT。請確認這是你剛剛建置的插件。",+ "pluginNameLabel": "插件",+ "pluginIdLabel": "插件 id",+ "hostsLabel": "企業身份注入網域",+ "typedIdLabel": "輸入插件 id「{{id}}」以確認",+ "confirm": "安裝並允許自測",+ "cancel": "取消"+ },"trust": {"official": "Cindy 官方插件","officialDetail": "由 Cindy 隨應用提供。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8ff8262b85..f1c596b601 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1227,6 +1227,18 @@ interface ElectronAPI {ghosts: {/** 首帧同步拉取已装清单(规则 7:意识面板与内置面板同帧注册,无跳变)。 */listSync: () => { ghosts: import('../shared/ghost').InstalledGhost[] };+ onForgeOidcInstallConfirmRequest: (+ callback: (payload: {+ requestId: string;+ ghostId: string;+ ghostName: string;+ hosts: string[];+ }) => void,+ ) => () => void;+ resolveForgeOidcInstallConfirm: (+ requestId: string,+ confirmed: boolean,+ ) => Promise<{ handled: boolean }>;/** Plugin 快捷行最近使用顺序(最新在前,首帧同步读取避免排序跳变)。 */recentUsageSync: () => { ids: string[] };/** 成功发送一次 Plugin 指令后记录最近使用。 */diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 5efb0f38d0..3f90df1d01 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -867,8 +867,8 @@ export const GHOST_OAUTH_BOUNCE_PATH_RE = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)* `gh auth token`,不可用时回落到同 key 经 /secrets 保存的 PAT。两种值都* 只在 networkSlot 请求 GitHub API 时注入,不进入插件、Renderer、KV 或日志。* - 'oidc-token':值 = Cindy 为当前企业 Membership 签发的短时 Connection- * JWT。新授权只有当前组织的 Plugin Market organization 安装记录和 manifest- * digest 校验通过时才会签发;升级前已有的 agent-forge receipt 保留只读兼容。+ * JWT。当前组织的可信市场安装,或企业作者通过 ghost_forge_install 明确安装且+ * id 命中本组织登记前缀时可签发;手动导入不取得该资格。* Host 根据当前组织和插件 id 推导 audience,插件不能声明或读取。* 令牌只在 networkSlot 发请求时注入,且永不进入 Node Worker。*diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 4b523ddf9a..6e86dc6255 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -228,8 +228,10 @@Worker。设置页只能读取 `hostAvailable` 布尔与备用 PAT 的 `saved/tail` 状态。该来源不允许 `exchange` 或 `setup.requires` 引用,第三方插件不得声明。- `source: "oidc-token"` 是 Host 托管的短时 Cindy Connection JWT:只对当前企业- Membership 生效;只有当前组织的 Plugin Market organization 安装记录仍有效、且- 安装目录 manifest digest 与记录一致时,Host 才会根据当前组织和插件 id 推导 audience。+ Membership 生效。资格有两条:当前组织的 Plugin Market organization 安装记录仍有效、+ 且安装目录 manifest digest 与记录一致;或企业作者显式使用 `ghost_forge_install`+ 安装、在提交前核对插件 id 与精确注入域名,且插件 id 命中当前组织前缀。手动导入不取得+ Forge 作者资格。Host 根据当前组织和插件 id 推导 audience。插件和 Node Worker 都不能读取或保存令牌。声明必须固定使用`Authorization: Bearer {value}` 并显式列出非空 `inject.hosts`;其中只允许精确域名,不允许通配。实际目标必须精确命中这份可信 manifest 声明的服务域名才会签发和注入。它没有用户输入、`url`、`exchange` 或