Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add host-managed connection auth
chenhongdc35ae564829
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.tsnew file mode 100644index 0000000000..4589b02217--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts@@ -0,0 +1,133 @@+import { describe, expect, it } from 'vitest';+import {+ loadDevConnectionAudienceResolver,+ parseDevConnectionTrustFile,+} from '../connectionAudienceResolver.js';++const TRUST_FILE = JSON.stringify({+ schemaVersion: 1,+ plugins: [+ {+ ghostId: 'plugin-a',+ orgSlug: 'org-example',+ pluginSlug: 'plugin-a',+ hosts: ['service-a.x.test'],+ },+ {+ ghostId: 'plugin-b',+ orgSlug: 'org-example',+ pluginSlug: 'plugin-b',+ hosts: ['service-b.x.test'],+ },+ ],+});++describe('development Connection audience resolver', () => {+ it('derives audience only from the trusted ghost/org mapping', () => {+ const resolver = loadDevConnectionAudienceResolver({+ trustFilePath: '/tmp/connection-trust.json',+ isPackaged: false,+ desktopDevMode: 'local',+ readFile: () => TRUST_FILE,+ });+ expect(+ resolver.resolve('plugin-a', {+ membershipId: 'membership-1',+ membershipKind: 'org',+ orgSlug: 'org-example',+ }),+ ).toEqual({+ membershipId: 'membership-1',+ audience: 'org-example:plugin-a',+ pluginSlug: 'plugin-a',+ allowedHosts: ['service-a.x.test'],+ });+ expect(+ resolver.resolve('plugin-b', {+ membershipId: 'membership-1',+ membershipKind: 'org',+ orgSlug: 'org-example',+ })?.audience,+ ).toBe('org-example:plugin-b');+ expect(+ resolver.resolve('plugin-a', {+ membershipId: 'membership-1',+ membershipKind: 'personal',+ orgSlug: null,+ }),+ ).toBeNull();+ expect(+ resolver.resolve('plugin-a', {+ membershipId: 'membership-1',+ membershipKind: 'org',+ orgSlug: 'org-other',+ }),+ ).toBeNull();+ expect(+ resolver.resolve('unknown', {+ membershipId: 'membership-1',+ membershipKind: 'org',+ orgSlug: 'org-example',+ }),+ ).toBeNull();+ });++ it('fails closed for packaged/non-local/relative-path overrides', () => {+ const base = {+ trustFilePath: '/tmp/connection-trust.json',+ desktopDevMode: 'local',+ readFile: () => TRUST_FILE,+ };+ expect(() => loadDevConnectionAudienceResolver({ ...base, isPackaged: true })).toThrow(+ /forbidden/,+ );+ expect(() =>+ loadDevConnectionAudienceResolver({+ ...base,+ isPackaged: false,+ desktopDevMode: 'remote',+ }),+ ).toThrow(/local mode/);+ expect(() =>+ loadDevConnectionAudienceResolver({+ ...base,+ trustFilePath: 'relative.json',+ isPackaged: false,+ }),+ ).toThrow(/absolute/);+ });++ it.each([+ '{}',+ JSON.stringify({ schemaVersion: 2, plugins: [] }),+ JSON.stringify({ schemaVersion: 1, plugins: [] }),+ JSON.stringify({ schemaVersion: 1, plugins: [{ ghostId: 'Bad_ID', orgSlug: 'org-example', pluginSlug: 'plugin-a' }] }),+ JSON.stringify({ schemaVersion: 1, plugins: [{ ghostId: 'plugin-a', orgSlug: 'org-example', pluginSlug: 'Plugin-A' }] }),+ JSON.stringify({+ schemaVersion: 1,+ plugins: [{ ghostId: 'plugin-a', orgSlug: 'org-example', pluginSlug: 'plugin-a', hosts: [] }],+ }),+ JSON.stringify({+ schemaVersion: 1,+ plugins: [{ ghostId: 'plugin-a', orgSlug: 'org-example', pluginSlug: 'plugin-a', hosts: ['*.x.test'] }],+ }),+ JSON.stringify({+ schemaVersion: 1,+ plugins: [{+ ghostId: 'plugin-a',+ orgSlug: 'org-example',+ pluginSlug: 'plugin-a',+ hosts: ['service-a.x.test', 'service-a.x.test'],+ }],+ }),+ JSON.stringify({+ schemaVersion: 1,+ plugins: [+ { ghostId: 'plugin-a', orgSlug: 'org-example', pluginSlug: 'plugin-a', hosts: ['service-a.x.test'] },+ { ghostId: 'plugin-a', orgSlug: 'org-example', pluginSlug: 'plugin-b', hosts: ['service-b.x.test'] },+ ],+ }),+ ])('rejects malformed trust input', (raw) => {+ expect(() => parseDevConnectionTrustFile(raw)).toThrow();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionTokenProvider.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionTokenProvider.test.tsnew file mode 100644index 0000000000..76bfad5978--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionTokenProvider.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it, vi } from 'vitest';+import { ConnectionTokenProvider } from '../connectionTokenProvider.js';++describe('ConnectionTokenProvider', () => {+ it('caches per membership/audience and single-flights concurrent issuance', async () => {+ let now = 1_000_000;+ const issue = vi.fn(async (audience: string) => ({+ token: `token-for-${audience}`,+ expiresIn: 1_800,+ audience,+ }));+ const provider = new ConnectionTokenProvider({ issue, now: () => now });+ const input = { membershipId: 'membership-1', audience: 'org-example:plugin-a' };++ const tokens = await Promise.all([+ provider.getToken(input),+ provider.getToken(input),+ provider.getToken(input),+ ]);+ expect(tokens).toEqual(Array(3).fill('token-for-org-example:plugin-a'));+ expect(issue).toHaveBeenCalledTimes(1);+ await provider.getToken(input);+ expect(issue).toHaveBeenCalledTimes(1);++ await provider.getToken({ ...input, audience: 'org-example:plugin-b' });+ await provider.getToken({ ...input, membershipId: 'membership-2' });+ expect(issue).toHaveBeenCalledTimes(3);++ now += 1_741_000;+ await provider.getToken(input);+ expect(issue).toHaveBeenCalledTimes(4);+ });++ it('invalidate and clearAll force re-issuance without persisting tokens', async () => {+ let serial = 0;+ const provider = new ConnectionTokenProvider({+ issue: async (audience) => ({ token: `token-${++serial}`, expiresIn: 1_800, audience }),+ });+ const a = { membershipId: 'membership-1', audience: 'org-example:plugin-a' };+ const b = { membershipId: 'membership-1', audience: 'org-example:plugin-b' };+ expect(await provider.getToken(a)).toBe('token-1');+ expect(await provider.getToken(b)).toBe('token-2');+ provider.invalidate(a);+ expect(await provider.getToken(a)).toBe('token-3');+ provider.clearAll();+ expect(await provider.getToken(a)).toBe('token-4');+ expect(await provider.getToken(b)).toBe('token-5');+ });++ it('rejects malformed issuer responses and does not cache them', async () => {+ const issue = vi+ .fn()+ .mockResolvedValueOnce({ token: '', expiresIn: 1_800, audience: 'org-example:plugin-a' })+ .mockResolvedValue({ token: 'valid', expiresIn: 1_800, audience: 'org-example:plugin-a' });+ const provider = new ConnectionTokenProvider({ issue });+ const input = { membershipId: 'membership-1', audience: 'org-example:plugin-a' };+ await expect(provider.getToken(input)).rejects.toThrow(/invalid response/);+ await expect(provider.getToken(input)).resolves.toBe('valid');+ expect(issue).toHaveBeenCalledTimes(2);+ });++ it('rejects an old in-flight result after an account boundary', async () => {+ let resolveFirst!: (value: {+ token: string;+ expiresIn: number;+ audience: string;+ }) => void;+ const issue = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ )+ .mockImplementation(async (audience: string) => ({+ token: 'new-token',+ expiresIn: 1_800,+ audience,+ }));+ const provider = new ConnectionTokenProvider({ issue });+ const input = { membershipId: 'membership-1', audience: 'org-example:plugin-a' };++ const stale = provider.getToken(input);+ provider.clearAll();+ await expect(provider.getToken(input)).resolves.toBe('new-token');+ resolveFirst({ token: 'old-token', expiresIn: 1_800, audience: input.audience });+ await expect(stale).rejects.toThrow(/account change/);+ await expect(provider.getToken(input)).resolves.toBe('new-token');+ expect(issue).toHaveBeenCalledTimes(2);+ });+});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.tsnew file mode 100644index 0000000000..dbbb53202b--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.connection.test.ts@@ -0,0 +1,24 @@+/**+ * FORGE_GUIDE · Cindy Connection 凭证章节存在性。+ * source:'oidc-token' 是插件作者可见的 manifest 契约,手册必须与校验器同步。+ */+import { describe, expect, it } from 'vitest';++import { FORGE_GUIDE } from '../forge.js';++describe('FORGE_GUIDE · Cindy Connection 凭证章节', () => {+ it('说明 oidc-token 的 Host 托管、注入限制和不可读边界', () => {+ for (const marker of [+ '"oidc-token"',+ 'Cindy 企业身份断言',+ 'Connection JWT',+ 'Authorization: Bearer {value}',+ 'setup.requires',+ 'identities',+ '不允许 `*.example.com` 通配',+ 'POST / PUT / PATCH / DELETE',+ ]) {+ expect(FORGE_GUIDE).toContain(marker);+ }+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.tsnew file mode 100644index 0000000000..a18d0ed7c5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostDevRuntimeContract.test.ts@@ -0,0 +1,26 @@+import fs from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++describe('dev-only plugin QA call boundary', () => {+ it('保持 packaged 隔离、可信 Renderer 校验和固定 preload 方法', () => {+ const main = fs.readFileSync(+ path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),+ 'utf8',+ );+ const preload = fs.readFileSync(path.resolve(process.cwd(), 'src/preload/preload.ts'), 'utf8');+ const devOnlyStart = main.indexOf("if (!app.isPackaged) {");+ const handlerStart = main.indexOf("ipcMain.handle('ghosts:dev-runtime'", devOnlyStart);+ const handlerEnd = main.indexOf("\n });", handlerStart);+ const handler = main.slice(handlerStart, handlerEnd);++ expect(devOnlyStart).toBeGreaterThanOrEqual(0);+ expect(handlerStart).toBeGreaterThan(devOnlyStart);+ expect(handler).toContain('assertTrustedAppRendererEvent(event)');+ expect(handler).toContain("case 'call'");+ expect(handler).toContain('getGhostPipeDispatcher().callGhostTool');+ expect(preload).toContain("ipcRenderer.invoke('ghosts:dev-runtime', 'call', id, { tool, args })");+ expect(preload).not.toContain("devCall: (channel:");+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.tsindex e44619eac5..7ff1023375 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'): GhostManifest {+function manifest(source?: 'user' | 'oauth' | 'login-email' | '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('oidc-token') },]) {const storeSecret = vi.fn(() => true);const result = executeGhostSetupInlineSubmission(diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.tsindex bde587f8c0..67eac9cdd8 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupStatus.test.ts@@ -62,6 +62,32 @@ describe('evaluateGhostSetup · 启发式回落(无 setup 声明)', () => {expect(evaluateGhostSetup(m, probes()).ready).toBe(true);});+ it('仅 oidc-token 凭证的插件不被误判为需要填写 Secret', () => {+ const m = manifest({+ slots: ['tool', 'network'],+ tools: [{ name: 'whoami', description: '查看企业身份' }],+ network: {+ hosts: ['service-a.x.test'],+ secrets: [+ {+ key: 'cindy_identity',+ label: 'Cindy 企业身份',+ source: 'oidc-token',+ inject: {+ ...INJECT,+ hosts: ['service-a.x.test'],+ },+ },+ ],+ },+ });+ expect(evaluateGhostSetup(m, probes())).toEqual({+ ready: true,+ missingGroups: [],+ reauth: [],+ });+ });+it('双 key 任一已保存即就绪(Web Search 形态)', () => {const m = manifest({slots: ['tool', 'network'],diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.tsnew file mode 100644index 0000000000..7b53faa083--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts@@ -0,0 +1,225 @@+import { describe, expect, it, vi } from 'vitest';++import type { GhostNetworkNeeds, InstalledGhost } from '../../../shared/ghost.js';+import { GhostNetworkSlot, type NetworkSlotDeps } from '../networkSlot.js';++const URL = 'https://service-a.x.test/whoami';+const INPUT = {+ membershipId: 'membership-1',+ audience: 'org-example:plugin-a',+ allowedHosts: ['service-a.x.test'],+};+const TOKEN_INPUT = { membershipId: INPUT.membershipId, audience: INPUT.audience };++function ghost(+ hosts: string[] = ['service-a.x.test'],+ injectHosts: string[] = ['service-a.x.test'],+): InstalledGhost {+ const network: GhostNetworkNeeds = {+ hosts,+ secrets: [+ {+ key: 'cindy_identity',+ label: 'Cindy Enterprise Identity',+ source: 'oidc-token',+ inject: {+ header: 'Authorization',+ format: 'Bearer {value}',+ hosts: injectHosts,+ },+ },+ ],+ };+ return {+ manifest: {+ schemaVersion: 2,+ id: 'plugin-a',+ name: 'Plugin A',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool', 'network'],+ tools: [{ name: 'whoami_a', description: 'Show identity' }],+ network,+ },+ dir: '/fake/plugin-a',+ enabled: true,+ };+}++function response(status = 200): Response {+ return new Response(JSON.stringify({ service: 'a', ok: status === 200 }), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++function makeSlot(overrides: Partial<NetworkSlotDeps> = {}) {+ const fetchImpl = vi.fn<NetworkSlotDeps['fetchImpl']>(async () => response());+ const resolve = vi.fn(() => INPUT);+ const getToken = vi.fn(async () => 'connection.jwt.value');+ const invalidate = vi.fn();+ const deps: NetworkSlotDeps = {+ getGhost: () => ghost(),+ readSecret: () => null,+ getLoginEmail: () => null,+ fetchImpl,+ readGhostMedia: async () => null,+ takeDirDeposit: () => null,+ writeSaveDeposit: async () => null,+ saveGhostMedia: async () => ({ url: '', hash: '', ext: '' }),+ isSupportedMediaMime: () => false,+ connectionTokens: { resolve, getToken, invalidate },+ ...overrides,+ };+ return {+ slot: new GhostNetworkSlot(deps),+ fetchImpl,+ resolve,+ getToken,+ invalidate,+ };+}++describe('networkSlot Connection identity', () => {+ it('replaces a plugin-supplied Authorization header and never returns the token', async () => {+ const h = makeSlot();+ const result = await h.slot.handleFetchRequest('plugin-a', {+ url: URL,+ headers: { Authorization: 'Bearer forged-by-plugin' },+ });++ expect(result.ok).toBe(true);+ expect(h.getToken).toHaveBeenCalledWith(TOKEN_INPUT);+ expect(h.fetchImpl.mock.calls[0]?.[1].headers).toMatchObject({+ Authorization: 'Bearer connection.jwt.value',+ });+ expect(JSON.stringify(result)).not.toContain('connection.jwt.value');+ expect(JSON.stringify(result)).not.toContain('forged-by-plugin');+ });++ it('fails closed when Host provenance does not authorize the plugin', async () => {+ const h = makeSlot({+ connectionTokens: {+ resolve: () => null,+ getToken: vi.fn(async () => {+ throw new Error('must not issue');+ }),+ invalidate: vi.fn(),+ },+ });+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(result.ok).toBe(false);+ expect(h.fetchImpl).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).not.toContain('org-example');+ });++ it('fails closed before issuance when the target host is absent from Host provenance', async () => {+ const h = makeSlot({+ connectionTokens: {+ resolve: () => ({ ...INPUT, allowedHosts: ['other.x.test'] }),+ getToken: vi.fn(async () => {+ throw new Error('must not issue');+ }),+ invalidate: vi.fn(),+ },+ });+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(result.ok).toBe(false);+ expect(h.fetchImpl).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).not.toContain(INPUT.audience);+ });++ it('blocks a redirect before the second request when its host is not in Host provenance', async () => {+ const h = makeSlot({+ getGhost: () =>+ ghost(+ ['service-a.x.test', 'service-b.x.test'],+ ['service-a.x.test', 'service-b.x.test'],+ ),+ });+ h.fetchImpl.mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { location: 'https://service-b.x.test/whoami' },+ }),+ );++ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(result.ok).toBe(false);+ expect(h.fetchImpl).toHaveBeenCalledTimes(1);+ expect(h.getToken).toHaveBeenCalledTimes(1);+ });++ it('invalidates, reissues, and replays exactly once after a 401', async () => {+ const h = makeSlot();+ h.fetchImpl.mockResolvedValueOnce(response(401)).mockResolvedValueOnce(response(200));+ h.getToken.mockResolvedValueOnce('connection.jwt.1').mockResolvedValueOnce('connection.jwt.2');++ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(result.ok).toBe(true);+ expect(h.fetchImpl).toHaveBeenCalledTimes(2);+ expect(h.getToken).toHaveBeenCalledTimes(2);+ expect(h.invalidate).toHaveBeenCalledTimes(1);+ expect(h.invalidate).toHaveBeenCalledWith(TOKEN_INPUT);+ expect(h.fetchImpl.mock.calls.map((call) => call[1].headers.Authorization)).toEqual([+ 'Bearer connection.jwt.1',+ 'Bearer connection.jwt.2',+ ]);+ });++ it('invalidates but does not replay a non-idempotent request after a 401', async () => {+ const h = makeSlot();+ h.fetchImpl.mockResolvedValue(response(401));++ const result = await h.slot.handleFetchRequest('plugin-a', {+ url: URL,+ method: 'POST',+ body: '{"action":"create"}',+ });++ expect(result).toMatchObject({ ok: true, status: 401 });+ expect(h.fetchImpl).toHaveBeenCalledTimes(1);+ expect(h.getToken).toHaveBeenCalledTimes(1);+ expect(h.invalidate).toHaveBeenCalledTimes(1);+ expect(h.invalidate).toHaveBeenCalledWith(TOKEN_INPUT);+ });++ it('does not retry 403 and never retries a second 401', async () => {+ const forbidden = makeSlot();+ forbidden.fetchImpl.mockResolvedValue(response(403));+ const forbiddenResult = await forbidden.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(forbiddenResult).toMatchObject({ ok: true, status: 403 });+ expect(forbidden.fetchImpl).toHaveBeenCalledTimes(1);+ expect(forbidden.invalidate).not.toHaveBeenCalled();++ const unauthorized = makeSlot();+ unauthorized.fetchImpl.mockResolvedValue(response(401));+ const unauthorizedResult = await unauthorized.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(unauthorizedResult).toMatchObject({ ok: true, status: 401 });+ expect(unauthorized.fetchImpl).toHaveBeenCalledTimes(2);+ expect(unauthorized.invalidate).toHaveBeenCalledTimes(1);+ });++ it('cancels before fetch when the active Membership changes after issuance', async () => {+ const h = makeSlot();+ h.resolve+ .mockReturnValueOnce(INPUT)+ .mockReturnValueOnce({ ...INPUT, membershipId: 'membership-2' });+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(result.ok).toBe(false);+ expect(h.fetchImpl).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).not.toContain('connection.jwt.value');+ });++ it('cancels before fetch when Host provenance no longer authorizes the injected hostname', async () => {+ const h = makeSlot();+ h.resolve+ .mockReturnValueOnce(INPUT)+ .mockReturnValueOnce({ ...INPUT, allowedHosts: ['other.x.test'] });+ const result = await h.slot.handleFetchRequest('plugin-a', { url: URL });+ expect(result.ok).toBe(false);+ expect(h.fetchImpl).not.toHaveBeenCalled();+ expect(JSON.stringify(result)).not.toContain('connection.jwt.value');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.tsindex 4809cd0b0f..7371e18e44 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts@@ -35,6 +35,10 @@ interface Harness {runtimeStateOf: ReturnType<typeof vi.fn>;spawn: ReturnType<typeof vi.fn>;sendToGhost: ReturnType<typeof vi.fn>;+ log: {+ info: ReturnType<typeof vi.fn>;+ warn: ReturnType<typeof vi.fn>;+ };};sent: GhostPipeToolCall[];}@@ -53,6 +57,10 @@ function makeHarness(opts: {sent.push(payload);return true;}),+ log: {+ info: vi.fn(),+ warn: vi.fn(),+ },};const dispatcher = new GhostPipeDispatcher({...deps,@@ -189,6 +197,37 @@ describe('配对交卷', () => {expect(h.dispatcher.pendingCount()).toBe(0);});+ it('完成日志只含元数据,不记录参数或返回内容', async () => {+ const h = makeHarness();+ const secretArg = 'must-not-log-argument';+ const secretResult = 'must-not-log-result';+ const p = h.dispatcher.callGhostTool({+ ...CALL,+ args: { prompt: secretArg },+ callId: 'observable-call',+ });+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));+ h.dispatcher.handleToolResult('art', {+ type: 'tool-result',+ callId: 'observable-call',+ ok: true,+ result: { value: secretResult },+ });+ await expect(p).resolves.toMatchObject({ ok: true });++ expect(h.deps.log.info).toHaveBeenCalledTimes(1);+ expect(h.deps.log.info).toHaveBeenCalledWith('ghost tool call completed', {+ ghostId: 'art',+ tool: 'gen_image',+ callId: 'observable-call',+ ok: true,+ totalMs: expect.any(Number),+ });+ const logs = JSON.stringify(h.deps.log.info.mock.calls);+ expect(logs).not.toContain(secretArg);+ expect(logs).not.toContain(secretResult);+ });+it('意识侧报错 → INTERNAL 透传 message', async () => {const h = makeHarness();const p = h.dispatcher.callGhostTool(CALL);diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.tsnew file mode 100644index 0000000000..4190b29a04--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts@@ -0,0 +1,219 @@+/**+ * Host-owned Connection audience resolver. The development implementation+ * replaces Plugin Market provenance with an explicit local trust file; plugin+ * manifests and runtime messages never provide an audience.+ */+import path from 'node:path';+import {+ GHOST_NETWORK_MAX_HOSTS,+ isValidGhostId,+ isValidGhostNetworkHostPattern,+} from '../../shared/ghost.js';++export interface ConnectionAudienceIdentity {+ membershipId: string;+ membershipKind: 'personal' | 'org';+ orgSlug: string | null;+}++export interface ConnectionAudienceResolution {+ membershipId: string;+ audience: string;+ pluginSlug: string;+ allowedHosts: readonly string[];+}++export interface ConnectionAudienceResolver {+ resolve(+ ghostId: string,+ identity: ConnectionAudienceIdentity,+ ): ConnectionAudienceResolution | null;+}++interface DevTrustRecord {+ ghostId: string;+ orgSlug: string;+ pluginSlug: string;+ hosts: string[];+}++const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;+const PLUGIN_SLUG_RE = /^[a-z][a-z0-9-]{0,31}$/;+const MAX_TRUST_FILE_BYTES = 64 * 1024;+const MAX_TRUST_RECORDS = 64;++function exactKeys(value: Record<string, unknown>, expected: readonly string[]): boolean {+ const actual = Object.keys(value).sort();+ return (+ actual.length === expected.length &&+ actual.every((key, index) => key === [...expected].sort()[index])+ );+}++export function parseDevConnectionTrustFile(raw: string): DevTrustRecord[] {+ if (Buffer.byteLength(raw, 'utf8') > MAX_TRUST_FILE_BYTES) {+ throw new Error('Connection development trust file is too large');+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ throw new Error('Connection development trust file is not valid JSON');+ }+ if (+ typeof parsed !== 'object' ||+ parsed === null ||+ Array.isArray(parsed) ||+ !exactKeys(parsed as Record<string, unknown>, ['plugins', 'schemaVersion'])+ ) {+ throw new Error('Connection development trust file has an invalid root object');+ }+ const root = parsed as { schemaVersion?: unknown; plugins?: unknown };+ if (root.schemaVersion !== 1) {+ throw new Error('Connection development trust file schemaVersion must be 1');+ }+ if (+ !Array.isArray(root.plugins) ||+ root.plugins.length === 0 ||+ root.plugins.length > MAX_TRUST_RECORDS+ ) {+ throw new Error('Connection development trust file plugins must be a non-empty bounded array');+ }++ const seenGhostIds = new Set<string>();+ return root.plugins.map((record, index) => {+ if (+ typeof record !== 'object' ||+ record === null ||+ Array.isArray(record) ||+ !exactKeys(record as Record<string, unknown>, ['ghostId', 'hosts', 'orgSlug', 'pluginSlug'])+ ) {+ throw new Error(`Connection development trust record ${index} is invalid`);+ }+ const { ghostId, orgSlug, pluginSlug, hosts } = record as Record<string, unknown>;+ if (typeof ghostId !== 'string' || !isValidGhostId(ghostId)) {+ throw new Error(`Connection development trust record ${index} has an invalid ghostId`);+ }+ if (typeof orgSlug !== 'string' || !SLUG_RE.test(orgSlug)) {+ throw new Error(`Connection development trust record ${index} has an invalid orgSlug`);+ }+ if (typeof pluginSlug !== 'string' || !PLUGIN_SLUG_RE.test(pluginSlug)) {+ throw new Error(`Connection development trust record ${index} has an invalid pluginSlug`);+ }+ if (`${orgSlug}:${pluginSlug}`.length > 64) {+ throw new Error(`Connection development trust record ${index} has an oversized audience`);+ }+ if (!Array.isArray(hosts) || hosts.length === 0 || hosts.length > GHOST_NETWORK_MAX_HOSTS) {+ throw new Error(`Connection development trust record ${index} has invalid hosts`);+ }+ const normalizedHosts: string[] = [];+ for (const host of hosts) {+ const normalized = typeof host === 'string' ? host.trim().toLowerCase() : '';+ if (+ !isValidGhostNetworkHostPattern(normalized) ||+ normalized.startsWith('*.') ||+ normalizedHosts.includes(normalized)+ ) {+ throw new Error(`Connection development trust record ${index} has an invalid host`);+ }+ normalizedHosts.push(normalized);+ }+ if (seenGhostIds.has(ghostId)) {+ throw new Error(`Connection development trust file repeats ghostId ${ghostId}`);+ }+ seenGhostIds.add(ghostId);+ return { ghostId, orgSlug, pluginSlug, hosts: normalizedHosts };+ });+}++export interface LoadDevConnectionAudienceResolverOptions {+ trustFilePath?: string;+ isPackaged: boolean;+ desktopDevMode?: string;+ readFile(pathname: string): string;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+}++const NO_CONNECTION_AUDIENCE_RESOLVER: ConnectionAudienceResolver = {+ resolve: () => null,+};++export function loadDevConnectionAudienceResolver(+ options: LoadDevConnectionAudienceResolverOptions,+): ConnectionAudienceResolver {+ const trustFilePath = options.trustFilePath?.trim();+ if (!trustFilePath) {+ options.log?.warn('ghost Connection development trust file is not configured', {+ isPackaged: options.isPackaged,+ desktopDevMode: options.desktopDevMode ?? null,+ });+ return NO_CONNECTION_AUDIENCE_RESOLVER;+ }+ if (options.isPackaged) {+ throw new Error('Connection development trust override is forbidden in packaged builds');+ }+ if (options.desktopDevMode !== 'local') {+ throw new Error('Connection development trust override requires Desktop local mode');+ }+ if (!path.isAbsolute(trustFilePath)) {+ throw new Error('Connection development trust file path must be absolute');+ }++ let raw: string;+ try {+ raw = options.readFile(trustFilePath);+ } catch {+ // Do not echo the local absolute path into logs or plugin-visible errors.+ options.log?.warn('ghost Connection development trust file read failed');+ throw new Error('Connection development trust file cannot be read');+ }+ let records: DevTrustRecord[];+ try {+ records = parseDevConnectionTrustFile(raw);+ } catch (error) {+ options.log?.warn('ghost Connection development trust file parse failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ const byGhostId = new Map(records.map((record) => [record.ghostId, record] as const));+ options.log?.info('ghost Connection development trust loaded', {+ recordCount: records.length,+ });+ return {+ resolve(ghostId, identity) {+ const record = byGhostId.get(ghostId);+ if (!record) {+ options.log?.warn('ghost Connection audience resolution rejected', {+ ghostId,+ reason: 'ghost-not-trusted',+ });+ return null;+ }+ const reason =+ identity.membershipKind !== 'org'+ ? 'membership-not-org'+ : identity.membershipId.length === 0+ ? 'membership-id-empty'+ : identity.orgSlug !== record.orgSlug+ ? 'org-mismatch'+ : null;+ if (reason) {+ options.log?.warn('ghost Connection audience resolution rejected', {+ ghostId,+ reason,+ });+ return null;+ }+ return {+ membershipId: identity.membershipId,+ audience: `${record.orgSlug}:${record.pluginSlug}`,+ pluginSlug: record.pluginSlug,+ allowedHosts: record.hosts,+ };+ },+ };+}diff --git a/apps/desktop/src/main/cindy-brain/connectionTokenProvider.ts b/apps/desktop/src/main/cindy-brain/connectionTokenProvider.tsnew file mode 100644index 0000000000..7b774bc271--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/connectionTokenProvider.ts@@ -0,0 +1,95 @@+/**+ * Main-process-only Connection JWT cache. Tokens never persist and concurrent+ * requests for the same Membership/audience share one issuance operation.+ */+export interface IssuedConnectionToken {+ token: string;+ expiresIn: number;+ audience: string;+}++export interface ConnectionTokenProviderDeps {+ issue(audience: string): Promise<IssuedConnectionToken>;+ now?: () => number;+}++interface CachedConnectionToken {+ token: string;+ usableUntil: number;+}++const EXPIRY_MARGIN_MS = 60_000;+const MAX_TOKEN_CHARS = 32 * 1024;+const MAX_EXPIRES_IN_SECONDS = 1_800;++function cacheKey(membershipId: string, audience: string): string {+ return `${membershipId}\u0000${audience}`;+}++export class ConnectionTokenProvider {+ private readonly cache = new Map<string, CachedConnectionToken>();+ private readonly inflight = new Map<string, { generation: number; promise: Promise<string> }>();+ private readonly now: () => number;+ /**+ * Account-boundary generation. A late issuance from an old Membership must+ * neither re-enter the cache nor continue to an enterprise request.+ */+ private generation = 0;++ constructor(private readonly deps: ConnectionTokenProviderDeps) {+ this.now = deps.now ?? Date.now;+ }++ async getToken(input: { membershipId: string; audience: string }): Promise<string> {+ const key = cacheKey(input.membershipId, input.audience);+ const cached = this.cache.get(key);+ if (cached && this.now() < cached.usableUntil) return cached.token;+ if (cached) this.cache.delete(key);++ const generation = this.generation;+ let entry = this.inflight.get(key);+ if (!entry || entry.generation !== generation) {+ const promise = this.issueAndCache(key, input.audience, generation).finally(() => {+ if (this.inflight.get(key)?.promise === promise) this.inflight.delete(key);+ });+ entry = { generation, promise };+ this.inflight.set(key, entry);+ }+ return entry.promise;+ }++ invalidate(input: { membershipId: string; audience: string }): void {+ this.cache.delete(cacheKey(input.membershipId, input.audience));+ }++ clearAll(): void {+ this.generation += 1;+ this.cache.clear();+ // The underlying HTTP call is not cancellable here, but new callers must+ // never join an issuance that started before the account boundary.+ this.inflight.clear();+ }++ private async issueAndCache(key: string, audience: string, generation: number): Promise<string> {+ const issued = await this.deps.issue(audience);+ if (+ typeof issued.token !== 'string' ||+ issued.token.length === 0 ||+ issued.token.length > MAX_TOKEN_CHARS ||+ issued.audience !== audience ||+ !Number.isSafeInteger(issued.expiresIn) ||+ issued.expiresIn <= 0 ||+ issued.expiresIn > MAX_EXPIRES_IN_SECONDS+ ) {+ throw new Error('Connection token issuer returned an invalid response');+ }+ if (generation !== this.generation) {+ throw new Error('Connection token request was superseded by an account change');+ }+ this.cache.set(key, {+ token: issued.token,+ usableUntil: this.now() + Math.max(0, issued.expiresIn * 1_000 - EXPIRY_MARGIN_MS),+ });+ return issued.token;+ }+}diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex f0d484f14b..f2f3bc4158 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1149,7 +1149,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 字段)+ "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)"hint": "在控制台生成后粘贴", // 可选提示(主机 Setup 卡与 settingsHtml 都会用到)"url": "https://example.com/settings/keys", // 可选:控制台/申请地址(仅 https)。调用前缺凭证时,主机 Setup 卡会在输入框旁展示本地化的「获取凭证」入口;settingsHtml 也可用 <a href> 逐字引用它,点击经主机转系统浏览器打开(见 §4.8「外链」)"inject": { // 必填:这条凭证怎么进请求@@ -1985,6 +1985,20 @@ BroadcastChannel、日志或任何自存路径(review 必查)。凭证只会注照"请重新登录"画)——确认框已如实披露,除展示外别拿它做别的;对该 key 的PUT/DELETE 一律 405(派生身份不可配置)。+**Cindy 企业身份断言(source:"oidc-token",可选)**:适用于接入 Cindy Connection+Auth 的企业服务。主机只在当前登录账号属于组织 Membership、且该插件存在受信安装映射时,+按需向 auth-server 换取短时 Connection JWT;audience 与组织身份由主机推导,插件清单和+运行时代码都不能选择、读取或保存 audience/token。该凭证必须固定声明+\`"inject": { "header": "Authorization", "format": "Bearer {value}", "hosts": [...] }\`,+且 \`hosts\` 必须是非空的显式子集,只允许把断言发给列出的企业服务域名。+\`oidc-token\` 的 \`inject.hosts\` 只接受精确域名,不允许 \`*.example.com\` 通配;Host+还会用受信安装记录里的服务域名做第二层精确校验,两边都匹配才会签发并注入。+它没有用户输入、\`url\`、\`exchange\` 或 \`oauth\` 详单,也不要放进 \`setup.requires\`;没有企业+身份时 cindy.fetch 会 fail-closed 并返回结构化错误。企业服务应使用 Connection JWT+中的 \`sub\`、\`email\` 或 \`identities\` 等声明自行选择业务身份,不要要求 Cindy 客户端先把+令牌交给插件代码。上游返回 401 时,Host 只对 GET / HEAD / OPTIONS 自动换令牌重试一次;+POST / PUT / PATCH / DELETE 和上传请求只作废令牌缓存、不自动重放,避免重复业务写入。+**key 换令牌二段式(exchange,可选)**:有些服务的 API key 不直接当请求凭证,要先POST 一个交换端点换临时令牌(令牌才进 Authorization)。在凭证上声明 \`exchange\`(字段见 §2),主机就照单代办整个流程:换取 → 按 ttlSeconds 缓存 → \`inject.format\`@@ -3105,8 +3119,8 @@ 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"、- source:"login-email" 还声明了 url 或 exchange、+ secret.source 不是 "user"/"login-email"/"oauth"/"oidc-token"、+ source:"login-email" 或 source:"oidc-token" 声明了 url 或 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.tsindex e838b90bcf..bf12a5e24d 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInlineExecutor.ts@@ -74,7 +74,8 @@ export function executeGhostSetupInlineSubmission((secret) =>secret.key === secretKey &&secret.source !== 'oauth' &&- secret.source !== 'login-email',+ secret.source !== 'login-email' &&+ secret.source !== 'oidc-token',);const nodeDecl = manifest.node?.secretBindings?.find((secret) => secret.key === secretKey);const decl = networkDecl ?? nodeDecl;diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.tsindex 3906873d7d..0e64cb6230 100644--- a/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSetupStatus.ts@@ -14,8 +14,8 @@* - user 源凭证:保险库已保存(等价 /secrets GET 的 saved);* - oauth 源凭证:client 可用(自填或内置)且 ≥1 个 connected 账号;* 账号存在但全部 expired 时归入 reauth(弹窗文案区分「重新连接」);- * - login-email 源凭证:恒就绪(登录派生,无配置动作;校验层已禁止- * setup 引用,启发式也不将其计入需求);+ * - login-email / oidc-token 源凭证:Host 派生,没有用户配置动作;校验层+ * 禁止 setup 引用,启发式也不把它们伪装成待填写 Secret;* - 连接:该声明键下至少一条连接;* - kv 参数:意识 /kv 文件顶层键非空(undefined / null / 空白字符串算* 未配置;false / 0 等有值形态算已配置——存在性检查,不做语义校验)。@@ -102,7 +102,7 @@ function deriveRequirementGroups(manifest: GhostManifest): GhostSetupRequirement}const implicit: GhostSetupRequirement[] = [];for (const s of manifest.network?.secrets ?? []) {- if (s.source === 'login-email') continue; // 登录派生恒就绪,不构成配置需求+ if (s.source === 'login-email' || s.source === 'oidc-token') continue;implicit.push({ kind: 'secret', key: s.key });}for (const s of manifest.node?.secretBindings ?? []) {@@ -227,10 +227,10 @@ function verdictOf(}if (nodeDecl) return probes.secretSaved(req.key) ? 'satisfied' : 'missing';if (!decl) return 'satisfied';- if (decl.source === 'login-email') {+ if (decl.source === 'login-email' || decl.source === 'oidc-token') {if (strict) {throw new GhostSetupAssessmentError(- `setup requirement ${requirementRef(req)} cannot use login-email`,+ `setup requirement ${requirementRef(req)} cannot use a Host-derived secret`,);}return 'satisfied';diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex cc2b6760bc..db3abd2f80 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -176,6 +176,15 @@ import {initGhostConfirmDialogBridge,} from './ghostConfirmDialogBridge.js';import { GhostNetworkSlot } from './networkSlot.js';+import {+ type ConnectionAudienceResolution,+ loadDevConnectionAudienceResolver,+ type ConnectionAudienceResolver,+} from './connectionAudienceResolver.js';+import {+ ConnectionTokenProvider,+ type IssuedConnectionToken,+} from './connectionTokenProvider.js';import { GhostFsSlot } from './fsSlot.js';import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';@@ -1639,6 +1648,52 @@ export function noteGhostSessionFocused(sessionId: string | null): void {let cindySlotSingleton: GhostCindySlot | null = null;let networkSlotSingleton: GhostNetworkSlot | null = null;let notifySlotSingleton: GhostNotifySlot | null = null;+let connectionAudienceResolverSingleton: ConnectionAudienceResolver | null = null;+let connectionTokenProviderSingleton: ConnectionTokenProvider | null = null;++/** Development-only provenance source; production will replace this resolver with Market records. */+function getConnectionAudienceResolver(): ConnectionAudienceResolver {+ if (!connectionAudienceResolverSingleton) {+ connectionAudienceResolverSingleton = loadDevConnectionAudienceResolver({+ trustFilePath: process.env.XDT_CONNECTION_DEV_TRUST_FILE,+ isPackaged: app.isPackaged,+ desktopDevMode: process.env.XDT_DESKTOP_DEV_MODE,+ readFile: (pathname) => fs.readFileSync(pathname, 'utf8'),+ log,+ });+ }+ return connectionAudienceResolverSingleton;+}++function resolveConnectionAudienceForGhost(+ ghostId: string,+): ConnectionAudienceResolution | null {+ const state = getAuthState();+ const user = state.isAuthenticated ? state.user : null;+ if (!user) return null;+ return getConnectionAudienceResolver().resolve(ghostId, {+ membershipId: user.id,+ membershipKind: user.membershipKind,+ orgSlug: user.orgSlug,+ });+}++/** Main-memory-only Connection token issuer/cache. */+function getConnectionTokenProvider(): ConnectionTokenProvider {+ if (!connectionTokenProviderSingleton) {+ connectionTokenProviderSingleton = new ConnectionTokenProvider({+ issue: (audience) =>+ serverApiFetch<IssuedConnectionToken>('/api/auth/connections/token', {+ method: 'POST',+ body: { audience },+ baseUrl: () => getClientEndpoint('authApiBaseUrl'),+ timeoutMs: 15_000,+ redactErrorDetails: true,+ }),+ });+ }+ return connectionTokenProviderSingleton;+}/** 意识系统提示通道(main → 全窗口 renderer;宿主 Toast 渲染,带意识身份头)。 */export const GHOST_NOTIFY_CHANNEL = 'ghosts:notify';@@ -2955,6 +3010,13 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {invalidateAccessToken: (ghostId, secretKey, accountId) =>getGhostOauthAccountManager().invalidateAccessToken(ghostId, secretKey, accountId),},+ // Cindy Connection JWT:audience 只由 Host 的可信映射推导,令牌只留在+ // Main 内存并由 networkSlot 直接注入,插件与 Node Worker 都拿不到。+ connectionTokens: {+ resolve: resolveConnectionAudienceForGhost,+ getToken: (input) => getConnectionTokenProvider().getToken(input),+ invalidate: (input) => getConnectionTokenProvider().invalidate(input),+ },// 多连接凭证(network.connections):按在装清单逐 decl 查连接管理器——// 用户添加的地址并入动态白名单(hostsFor),出网时按 hostname 精确// 匹配注入那条连接自己的 token(tokenFor;同一 hostname 命中多个 decl@@ -3514,9 +3576,14 @@ export function registerGhostIpc(): void {const networkSecretDecls = ghost.manifest.network?.secrets ?? [];const nodeSecretDecls = ghost.manifest.node?.secretBindings ?? [];const userSecretKeys = networkSecretDecls- // login-email(派生)与 oauth(主机托管授权)都没有"用户填值"这回事,+ // Host 派生与 oauth(主机托管授权)都没有"用户填值"这回事,// 不进 /secrets 收单键集(oauth 的 client 凭证走 /oauth 端点)。- .filter((s) => s.source !== 'login-email' && s.source !== 'oauth')+ .filter(+ (s) =>+ s.source !== 'login-email'+ && s.source !== 'oauth'+ && s.source !== 'oidc-token',+ ).map((s) => s.key).concat(nodeSecretDecls.map((s) => s.key));// login-email 派生身份:GET 状态回查附 identity(= 当前登录邮箱,设置页@@ -3525,12 +3592,30 @@ export function registerGhostIpc(): void {const identitySecretKeys = networkSecretDecls.filter((s) => s.source === 'login-email').map((s) => s.key);+ const managedSecretDecls = networkSecretDecls.filter(+ (s) => s.source === 'oidc-token',+ );+ const connectionIdentityReady =+ managedSecretDecls.length > 0+ ? (() => {+ try {+ return resolveConnectionAudienceForGhost(ghostId) !== null;+ } catch {+ return false;+ }+ })()+ : false;+ const managedSecretStates = managedSecretDecls.map((s) => ({+ key: s.key,+ saved: connectionIdentityReady,+ }));return handleGhostSecretsRequest({method,pathname,readBodyText,userSecretKeys,identitySecretKeys,+ managedSecretStates,getLoginEmail: () => getAuthState().user?.email ?? null,ghostId,vault: {@@ -3871,6 +3956,10 @@ export function registerGhostIpc(): void {activateGhostsAndMigrateLegacyAccounts,);onAuthStateChange(() => {+ // Login/logout, Membership switches, and refresh integration all cross+ // an auth notification boundary. Discard every short-lived Connection+ // assertion so a late request can never reuse the previous identity.+ connectionTokenProviderSingleton?.clearAll();if (!getAppCapabilities().canUseCindyAccountServices) suspendCindyAccountGhosts();// Even when provisioning itself is a no-op, the renderer and agent// roster must immediately reflect the new session capability set.@@ -4633,7 +4722,8 @@ export function registerGhostIpc(): void {// dev-only 运行时控制通道(QA:能起 / 能停 / 能崩 / 能看状态)。// packaged 版不注册;正式的按需拉起 / 闲置熄灯由上层自动策略负责。if (!app.isPackaged) {- ipcMain.handle('ghosts:dev-runtime', async (_event, action: unknown, id: unknown) => {+ ipcMain.handle('ghosts:dev-runtime', async (event, action: unknown, id: unknown, payload: unknown) => {+ assertTrustedAppRendererEvent(event);if (action === 'status') return { states: runtime.listStates() };if (typeof id !== 'string' || id.trim().length === 0) {throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');@@ -4654,6 +4744,37 @@ export function registerGhostIpc(): void {case 'crash':if (!runtime.crashForTest(id)) throwIpcError('INVALID_PARAMS', `意识 ${id} 不在运行中`);return { state: runtime.stateOf(id) };+ case 'call': {+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {+ throwIpcError('INVALID_PARAMS', 'call payload must be an object');+ }+ const request = payload as { tool?: unknown; args?: unknown };+ if (+ typeof request.tool !== 'string' ||+ !/^[a-z][a-z0-9_-]{0,63}$/.test(request.tool)+ ) {+ throwIpcError('INVALID_PARAMS', 'tool must be a valid plugin tool name');+ }+ const args = request.args ?? {};+ if (!args || typeof args !== 'object' || Array.isArray(args)) {+ throwIpcError('INVALID_PARAMS', 'args must be an object');+ }+ let encodedArgs: string;+ try {+ encodedArgs = JSON.stringify(args);+ } catch {+ throwIpcError('INVALID_PARAMS', 'args must be JSON serializable');+ }+ if (encodedArgs.length > 256 * 1024) {+ throwIpcError('INVALID_PARAMS', 'args are too large');+ }+ requireGhostAvailableForActiveSession(id);+ return getGhostPipeDispatcher().callGhostTool({+ ghostId: id,+ tool: request.tool,+ args: args as Record<string, unknown>,+ });+ }default:throwIpcError('INVALID_PARAMS', `未知 action ${JSON.stringify(action)}`);}diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.tsindex fe2dba4b66..c8e5d5719a 100644--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts@@ -151,6 +151,19 @@ export interface NetworkSlotDeps {>;invalidateAccessToken(ghostId: string, secretKey: string, accountId: string): void;};+ /**+ * Cindy organization identity assertions (`source: 'oidc-token'`). Audience+ * resolution is Host-owned; manifests and runtime messages cannot choose it.+ */+ connectionTokens?: {+ resolve(ghostId: string): {+ membershipId: string;+ audience: string;+ allowedHosts: readonly string[];+ } | null;+ getToken(input: { membershipId: string; audience: string }): Promise<string>;+ invalidate(input: { membershipId: string; audience: string }): void;+ };/*** 多连接凭证通道(network.connections;生产由 index.ts 注入闭包,内部按* manifest.network.connections 逐 decl 查 GhostConnectionManager)。@@ -182,6 +195,9 @@ const MAX_HEADER_VALUE_LEN = 2048;/** 重定向最大跳数(逐跳重验白名单;超出按失败收)。 */const MAX_REDIRECTS = 3;+/** Only these methods may be automatically replayed after a Connection JWT 401. */+const CONNECTION_RETRYABLE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);+/*** 意识自带请求头的剥除名单(小写):协议关键头由 HTTP 栈管,凭证类头由* 保险库注入独占——意识写了也不生效(消毒后静默丢弃,不算错误,保持@@ -1021,6 +1037,8 @@ export class GhostNetworkSlot {if (inject0.error) return { ok: false, message: inject0.error };let usedExchange = inject0.usedExchange;const oauthInjected = new Map(inject0.oauthInjected);+ const connectionInjected = new Map(inject0.connectionInjected);+ let initialConnectionInjected = new Map(inject0.connectionInjected);// ── 在途并发闸(常量硬顶,防死循环刷单;不是配额)──────────────────const inflight = this.inflight.get(ghostId) ?? 0;@@ -1071,7 +1089,7 @@ export class GhostNetworkSlot {}// ── 执行(重定向逐跳手动跟,每跳重验白名单 + 重算凭证注入)────────- // 外层 attempt 循环只为交换型 / oauth 凭证的 401 兜底:令牌可能被+ // 外层 attempt 循环只为交换型 / oauth / Connection 凭证的 401 兜底:令牌可能被// 服务端提前作废,作废本地缓存重换/重刷一次再整链重试;第二次仍// 401 就原样回给意识。let response: Response | null = null;@@ -1081,9 +1099,17 @@ export class GhostNetworkSlot {for (const [secretKey, accountId] of oauthInjected) {this.deps.oauthTokens?.invalidateAccessToken(ghostId, secretKey, accountId);}+ for (const input of connectionInjected.values()) {+ this.deps.connectionTokens?.invalidate({+ membershipId: input.membershipId,+ audience: input.audience,+ });+ }const reInject = await this.injectSecrets(ghostId, net.secrets ?? [], connectionDecls, url.hostname, net.hosts, requestHeaders, authAccount);if (reInject.error) return { ok: false, message: reInject.error };+ initialConnectionInjected = new Map(reInject.connectionInjected);for (const [k, v] of reInject.oauthInjected) oauthInjected.set(k, v);+ for (const [k, v] of reInject.connectionInjected) connectionInjected.set(k, v);this.deps.log?.info('ghost fetch-request 401 → re-auth retry', {ghostId, callId, host: url.hostname,});@@ -1092,7 +1118,10 @@ export class GhostNetworkSlot {let currentMethod: string = method;let currentBody = body;let bodyDropped = false;+ let responseConnectionInjected = new Map(initialConnectionInjected);+ let responseMethod = currentMethod;response = null;+ let currentConnectionInjected = initialConnectionInjected;for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {const hopHeaders = { ...requestHeaders };// 降级丢 body 后 Content-Type 也要跟着剥(fetch 规范的 request-body-@@ -1103,8 +1132,37 @@ export class GhostNetworkSlot {// (injectSecrets 开头会先把所有声明凭证头的大小写变体删干净)。const hopInject = await this.injectSecrets(ghostId, net.secrets ?? [], connectionDecls, currentUrl.hostname, net.hosts, hopHeaders, authAccount);if (hopInject.error) return { ok: false, message: hopInject.error };+ currentConnectionInjected = hopInject.connectionInjected;usedExchange ||= hopInject.usedExchange;for (const [k, v] of hopInject.oauthInjected) oauthInjected.set(k, v);+ for (const [k, v] of hopInject.connectionInjected) connectionInjected.set(k, v);+ }+ if (currentConnectionInjected.size > 0) {+ let current: {+ membershipId: string;+ audience: string;+ allowedHosts: readonly string[];+ } | null = null;+ try {+ current = this.deps.connectionTokens?.resolve(ghostId) ?? null;+ } catch {+ current = null;+ }+ const stillCurrent =+ current !== null+ && [...currentConnectionInjected.values()].every(+ (input) =>+ input.membershipId === current.membershipId+ && input.audience === current.audience+ && input.hostname === currentUrl.hostname+ && current.allowedHosts.includes(input.hostname),+ );+ if (!stillCurrent) {+ return {+ ok: false,+ message: 'Cindy 企业账号已切换,本次请求已取消,请重试',+ };+ }}response = await this.deps.fetchImpl(currentUrl.toString(), {method: currentMethod,@@ -1113,6 +1171,8 @@ export class GhostNetworkSlot {signal: controller.signal,redirect: 'manual',});+ responseConnectionInjected = currentConnectionInjected;+ responseMethod = currentMethod;if (![301, 302, 303, 307, 308].includes(response.status)) break;const location = response.headers.get('location');if (!location) break; // 3xx 无 Location:按普通响应回给意识@@ -1141,7 +1201,27 @@ export class GhostNetworkSlot {currentUrl = nextUrl;}if (!response) break;- if (response.status === 401 && (usedExchange || oauthInjected.size > 0) && attempt === 0) {+ if (+ response.status === 401+ && responseConnectionInjected.size > 0+ && !CONNECTION_RETRYABLE_METHODS.has(responseMethod)+ ) {+ for (const input of responseConnectionInjected.values()) {+ this.deps.connectionTokens?.invalidate({+ membershipId: input.membershipId,+ audience: input.audience,+ });+ }+ this.deps.log?.info('ghost fetch-request Connection 401 cache invalidated without replay', {+ ghostId, callId, method: responseMethod, host: url.hostname,+ });+ break;+ }+ if (+ response.status === 401+ && (usedExchange || oauthInjected.size > 0 || responseConnectionInjected.size > 0)+ && attempt === 0+ ) {// 丢弃本次响应体(best-effort),换新令牌整链重试一次。try {await (response as { body?: ReadableStream<Uint8Array> | null }).body?.cancel();@@ -1381,6 +1461,11 @@ export class GhostNetworkSlot {usedExchange: boolean;/** 本次注入过的 oauth 凭证(secretKey → 实际用的账号 id;401 作废用)。 */oauthInjected: Map<string, string>;+ /** 本次注入过的 Connection 凭证(secretKey → 缓存键;401 作废用)。 */+ connectionInjected: Map<+ string,+ { membershipId: string; audience: string; hostname: string }+ >;}> {// 声明的凭证头一律主机独占:先把意识自带(或上一跳残留)的任何大小写// 变体删干净,再按本 host 注入——不管这条凭证这一跳注不注入都要删,@@ -1395,13 +1480,22 @@ export class GhostNetworkSlot {}let usedExchange = false;const oauthInjected = new Map<string, string>();+ const connectionInjected = new Map<+ string,+ { membershipId: string; audience: string; hostname: string }+ >();for (const secret of secrets) {const scope = secret.inject.hosts ?? allHosts;if (!scope.some((pattern) => ghostNetworkHostMatches(pattern, hostname))) continue;- const resolved = await this.resolveSecretValue(ghostId, secret, authAccount);- if ('error' in resolved) return { error: resolved.error, usedExchange, oauthInjected };+ const resolved = await this.resolveSecretValue(ghostId, secret, hostname, authAccount);+ if ('error' in resolved) {+ return { error: resolved.error, usedExchange, oauthInjected, connectionInjected };+ }if (secret.exchange !== undefined) usedExchange = true;if (resolved.oauthAccountId !== undefined) oauthInjected.set(secret.key, resolved.oauthAccountId);+ if (resolved.connectionTokenKey !== undefined) {+ connectionInjected.set(secret.key, resolved.connectionTokenKey);+ }// 函数式替换同 performExchange:凭证/令牌含 $ 不得触发特殊序列解释。headers[secret.inject.header] = secret.inject.format.replace('{value}', () => resolved.value);}@@ -1418,13 +1512,14 @@ export class GhostNetworkSlot {error: `连接地址 ${hostname} 的凭证读取失败——请到主界面侧边栏「插件」的本插件详情页重新添加该连接`,usedExchange,oauthInjected,+ connectionInjected,};}deleteHeaderVariants(headers, tok.header);headers[tok.header] = tok.format.replace('{value}', () => tok.value);}}- return { error: null, usedExchange, oauthInjected };+ return { error: null, usedExchange, oauthInjected, connectionInjected };}/**@@ -1436,8 +1531,65 @@ export class GhostNetworkSlot {private async resolveSecretValue(ghostId: string,secret: GhostSecretDecl,+ hostname: string,authAccount?: string,- ): Promise<{ value: string; oauthAccountId?: string } | { error: string }> {+ ): Promise<+ | {+ value: string;+ oauthAccountId?: string;+ connectionTokenKey?: { membershipId: string; audience: string; hostname: string };+ }+ | { error: string }+ > {+ if (secret.source === 'oidc-token') {+ const manager = this.deps.connectionTokens;+ if (!manager) {+ return { error: 'Cindy 企业身份通道未就绪,请升级应用或反馈' };+ }+ let resolution: {+ membershipId: string;+ audience: string;+ allowedHosts: readonly string[];+ } | null;+ try {+ resolution = manager.resolve(ghostId);+ } catch {+ this.deps.log?.warn('ghost Connection audience resolver unavailable', { ghostId });+ return { error: 'Cindy 企业身份暂时不可用,请稍后重试或反馈' };+ }+ if (!resolution) {+ this.deps.log?.warn('ghost Connection audience resolution returned no result', {+ ghostId,+ host: hostname,+ });+ return { error: '当前 Cindy 企业身份不可用于此插件,请确认已登录正确的企业账号' };+ }+ if (!resolution.allowedHosts.includes(hostname)) {+ this.deps.log?.warn('ghost Connection audience host rejected', {+ ghostId,+ host: hostname,+ });+ return { error: '当前 Cindy 企业身份不可用于此服务地址' };+ }+ const tokenInput = {+ membershipId: resolution.membershipId,+ audience: resolution.audience,+ };+ try {+ const token = await manager.getToken(tokenInput);+ return {+ value: token,+ connectionTokenKey: { ...tokenInput, hostname },+ };+ } catch (error) {+ this.deps.log?.warn('ghost Connection token issuance failed', {+ ghostId,+ host: hostname,+ error: error instanceof Error ? error.message : String(error),+ });+ return { error: '暂时无法获取 Cindy 企业身份,请检查网络后重试' };+ }+ }// source:'oauth':令牌管理器现取新鲜 access token(缓存 + 单飞刷新在// 管理器内);错误折叠成人话(不含任何令牌字节),可自愈的引导去设置页。if (secret.source === 'oauth') {diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.tsindex 436e33a7ac..ab3cdb3571 100644--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts@@ -337,6 +337,14 @@ export class GhostPipeDispatcher {if (!entry) return;this.pending.delete(callId);(this.deps.clearTimeoutFn ?? clearTimeout)(entry.timer);+ this.deps.log?.info('ghost tool call completed', {+ ghostId: entry.ghostId,+ tool: entry.tool,+ callId,+ ok: result.ok,+ ...(result.ok ? {} : { errorCode: result.errorCode }),+ totalMs: Date.now() - entry.startedAt,+ });entry.resolve(result);}}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.tsindex 3803c6fd83..7471fbc688 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@@ -111,7 +111,7 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收});it('login-email 键不可配置:PUT/POST/DELETE 一律 405', async () => {- for (const method of ['PUT', 'POST', 'DELETE']) {+ for (const method of ['GET', 'PUT', 'POST', 'DELETE']) {const out = await handleGhostSecretsRequest({method,pathname: '/secrets/pages_token',@@ -126,6 +126,34 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收}});+ it('oidc-token 只回 Host 托管就绪状态,不回 token/audience/身份资料且不可写删', async () => {+ const base = {+ readBodyText: () => Promise.resolve('{"value":"forged"}'),+ userSecretKeys: [] as string[],+ managedSecretStates: [{ key: 'cindy_identity', saved: true }],+ vault: memVault(),+ ghostId: 'demo',+ };+ const list = await handleGhostSecretsRequest({+ ...base,+ method: 'GET',+ pathname: '/secrets',+ });+ expect(JSON.parse(list.body ?? '')).toEqual([+ { key: 'cindy_identity', saved: true, managed: true },+ ]);+ expect(list.body).not.toMatch(/token|audience|membership|org-example/i);++ for (const method of ['GET', 'PUT', 'POST', 'DELETE']) {+ const out = await handleGhostSecretsRequest({+ ...base,+ method,+ pathname: '/secrets/cindy_identity',+ });+ expect(out.status, method).toBe(405);+ }+ });+it('PUT /secrets/<key> 合法值 → 204 且 trim 后入库;POST 等价', async () => {for (const method of ['PUT', 'POST']) {const vault = memVault();diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.tsindex e0d6ed0067..de1c4e5df0 100644--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts@@ -17,7 +17,7 @@* 未登录/登录态缺邮箱 → saved:false 无 identity,页面照"请重新登录"画);* - PUT /secrets/<key> → body {"value":"..."} 存入主机保险库,204;* - DELETE /secrets/<key> → 清除,204(幂等);- * - login-email 键的 PUT/POST/DELETE → 405(派生身份不可配置);+ * - login-email / Host 托管凭证键的任意单键操作 → 405(派生身份不可配置);* - 未声明的 key → 404;坏 body / 空值 → 400;* 值超长 → 413;其它 method → 405;保险库写失败 → 500(不外泄细节)。*@@ -68,6 +68,8 @@ export async function handleGhostSecretsRequest(args: {identitySecretKeys?: string[];/** 现读当前登录邮箱(identity 条目的值来源);未登录/缺邮箱返回 null。 */getLoginEmail?: () => string | null;+ /** Host 托管凭证(source:'oidc-token')的就绪状态;值不进入意识可见接口。 */+ managedSecretStates?: Array<{ key: string; saved: boolean }>;vault: GhostSecretsVault;ghostId: string;/**@@ -80,6 +82,8 @@ export async function handleGhostSecretsRequest(args: {}): Promise<GhostSecretsRequestOutcome> {const { method, pathname, readBodyText, userSecretKeys, vault, ghostId, log } = args;const identityKeys = args.identitySecretKeys ?? [];+ const managedStates = args.managedSecretStates ?? [];+ const managedKeys = managedStates.map(({ key }) => key);if (pathname === '/secrets') {if (method !== 'GET') return { status: 405 };@@ -95,7 +99,12 @@ export async function handleGhostSecretsRequest(args: {const identityList = identityKeys.map((key) =>email ? { key, saved: true, identity: email } : { key, saved: false },);- return { status: 200, body: JSON.stringify([...userList, ...identityList]) };+ const managedList = managedStates.map(({ key, saved }) => ({+ key,+ saved,+ managed: true,+ }));+ return { status: 200, body: JSON.stringify([...userList, ...identityList, ...managedList]) };} catch (err) {log?.warn('ghost secrets 状态回查失败', { ghostId, err: String(err) });return { status: 500 };@@ -106,7 +115,7 @@ export async function handleGhostSecretsRequest(args: {const secretKey = pathname.slice('/secrets/'.length);if (!secretKey || secretKey.includes('/')) return { status: 404 };// 身份凭证不可配置:任何写/删/读单条的动作统一 405(派生值随登录态走)。- if (identityKeys.includes(secretKey)) return { status: 405 };+ if (identityKeys.includes(secretKey) || managedKeys.includes(secretKey)) return { status: 405 };// 只认当前清单里 user 来源的键——未声明/已下线的键统一 404,不给沙箱区分面。if (!userSecretKeys.includes(secretKey)) return { status: 404 };@@ -140,7 +149,11 @@ export async function handleGhostSecretsRequest(args: {try {args.onStored?.(secretKey);} catch (err) {- log?.warn('ghost secret onStored 通知失败(不影响入库结果)', { ghostId, secretKey, err: String(err) });+ log?.warn('ghost secret onStored 通知失败(不影响入库结果)', {+ ghostId,+ secretKey,+ err: String(err),+ });}return { status: 204 };}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e5a2a54038..b38bcfe43f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1055,6 +1055,8 @@ contextBridge.exposeInMainWorld('electronAPI', {// dev-only 运行时控制(packaged 版 main 侧不注册该 channel)。devRuntime: (action: 'status' | 'spawn' | 'stop' | 'crash', id?: string): Promise<unknown> =>ipcRenderer.invoke('ghosts:dev-runtime', action, id),+ devCall: (id: string, tool: string, args: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghosts:dev-runtime', 'call', id, { tool, args }),},pluginMarket: {diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex e8ba4fc94f..ed11267e18 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 === 'networkSecretOrganizationIdentity' ||item.labelKey === 'nodeSecret')return KeyRound;diff --git a/apps/desktop/src/renderer/cindy-brain/ghostDevTools.ts b/apps/desktop/src/renderer/cindy-brain/ghostDevTools.tsindex 8102074886..511349f8f1 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostDevTools.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostDevTools.ts@@ -14,6 +14,7 @@ import type { InstalledGhost } from '../../shared/ghost';* await __cindyGhosts.spawn('<id>') 拉起沙箱(off/crashed → running)* await __cindyGhosts.stopRun('<id>') 熄灯(→ off)* await __cindyGhosts.crash('<id>') 强崩沙箱进程(验证崩溃隔离与熔断)+ * await __cindyGhosts.call('<id>', '<tool>', {}) 经正式派发链调用工具** 生产构建(import.meta.env.DEV = false)完全不挂载,零暴露。* 读写全部走 electronAPI.ghosts(main 侧 GhostManager 严格校验),@@ -28,6 +29,7 @@ interface GhostDevToolsApi {spawn: (id: string) => Promise<string>;stopRun: (id: string) => Promise<string>;crash: (id: string) => Promise<string>;+ call: (id: string, tool: string, args?: Record<string, unknown>) => Promise<unknown>;}declare global {@@ -70,5 +72,7 @@ export function installGhostDevTools(): void {await window.electronAPI.ghosts.devRuntime('crash', id);return `已强崩 ${id} 的沙箱进程;稍后用 runtime() 查看 crashed/fused 状态`;},+ call: (id: string, tool: string, args: Record<string, unknown> = {}) =>+ window.electronAPI.ghosts.devCall(id, tool, args),};}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 2196c93320..55f62843f2 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3404,6 +3404,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.",+ "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}})","networkSecretOauthDetail": "The authorization flow and all tokens are managed by the host and can never be read by the plugin code; you provide the client credentials on the plugin detail page. The requested permission scopes are listed verbatim below — review them before approving.","networkConnections": "Can connect to {{label}} addresses you add",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex da5669ccb6..dbefe1c057 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3403,6 +3403,8 @@"networkSecretGhostInputDetail": "この資格情報はプラグイン自身の設定画面で入力を受け付けるため、入力時にはプラグインのページを経由します。その後ホストへ一度だけ渡されて暗号化保存され、保存後はプラグインから読み出せません。注入は宣言されたドメインへのリクエスト時のみホストが行います。","networkSecretIdentity": "ログインメールアドレスを認証情報「{{name}}」として使用します","networkSecretIdentityDetail": "値はログイン中のアカウントのメールアドレスから取得され、リクエスト時にホストが自動的に導出・注入します。入力は不要です。プラグインは設定画面に現在の身元を表示する目的で、このメールアドレスを読み取れます。",+ "networkSecretOrganizationIdentity": "Cindy の組織ユーザー ID を認証情報「{{name}}」として使用します",+ "networkSecretOrganizationIdentityDetail": "Cindy は必要なときに短時間有効な ID アサーションを発行し、ホストだけが明示されたサービスホストへ送信します。プラグインのコードはトークンを読み取ったり保存したりできません。","networkSecretOauth": "{{host}} で OAuth 認可を行うよう案内します({{name}})","networkSecretOauthDetail": "認可フローとすべてのトークンはホストが管理し、プラグインのコードからは読み取れません。クライアント資格情報はこのプラグインの詳細ページで入力します。以下は要求される権限スコープの原文です。確認のうえ許可してください。","networkConnections": "あなたが追加した{{label}}に接続可能",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6f8e007738..cb12708e14 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3403,6 +3403,8 @@"networkSecretGhostInputDetail": "이 자격 증명은 플러그인 자체 설정 화면에서 입력받으므로 입력 시점에 플러그인 페이지를 거칩니다. 이후 호스트에 한 번만 전달되어 암호화 저장되며, 저장 후에는 플러그인이 다시 읽을 수 없습니다. 주입은 선언된 도메인 요청 시에만 호스트가 수행합니다.","networkSecretIdentity": "로그인 이메일을 자격 증명 \"{{name}}\"(으)로 사용합니다","networkSecretIdentityDetail": "값은 로그인된 계정의 이메일에서 가져오며, 요청 시 호스트가 자동으로 파생하여 주입합니다. 입력할 필요가 없으며, 플러그인은 설정 화면에 현재 신원을 표시하기 위해 이 이메일을 읽을 수 있습니다.",+ "networkSecretOrganizationIdentity": "Cindy 조직 사용자 신원을 자격 증명 \"{{name}}\"(으)로 사용합니다",+ "networkSecretOrganizationIdentityDetail": "Cindy가 필요할 때 단기 신원 어설션을 발급하며, 호스트만 명시된 서비스 호스트로 전송합니다. 플러그인 코드는 토큰을 읽거나 저장할 수 없습니다.","networkSecretOauth": "{{host}}에서 OAuth 인증을 진행하도록 안내합니다({{name}})","networkSecretOauthDetail": "인증 흐름과 모든 토큰은 호스트가 관리하며 플러그인 코드는 읽을 수 없습니다. 클라이언트 자격 증명은 이 플러그인의 상세 페이지에서 직접 입력합니다. 아래는 요청되는 권한 범위(scopes) 원문이니 확인 후 허용하세요.","networkConnections": "내가 추가한 {{label}}에 연결 가능",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e08642851f..9dec83437b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3403,6 +3403,8 @@"networkSecretGhostInputDetail": "凭证由这个插件自己的设置界面收集,录入时会经过插件页面;随后一次性交给主机加密保管,存入后插件无法读回,主机只在请求它声明的域名时注入。","networkSecretIdentity": "将使用你的登录邮箱作为凭证「{{name}}」","networkSecretIdentityDetail": "值取自当前登录账号的邮箱,请求时由主机自动派生注入;无需填写。插件可读取该邮箱,用于在它的设置界面里展示当前身份。",+ "networkSecretOrganizationIdentity": "将使用你的 Cindy 企业身份作为凭证「{{name}}」",+ "networkSecretOrganizationIdentityDetail": "Cindy 会按需签发短时身份断言,仅由主机发送给明确列出的服务域名;插件代码无法读取或保存令牌。","networkSecretOauth": "将引导你在 {{host}} 完成 OAuth 授权({{name}})","networkSecretOauthDetail": "授权流程与全部令牌由主机代管,插件代码无法读取;客户端凭证由你在本插件详情页自填。下方为其申请的权限范围(scopes)原文,请确认后再放行。","networkConnections": "可连接你添加的 {{label}}",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1e65c30c0d..964ffc9227 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1383,6 +1383,12 @@ interface ElectronAPI {action: 'status' | 'spawn' | 'stop' | 'crash',id?: string,) => Promise<{ states?: Record<string, string>; state?: string }>;+ /** dev-only:经正式插件派发/权限链调用一个已声明工具。 */+ devCall: (+ id: string,+ tool: string,+ args: Record<string, unknown>,+ ) => Promise<unknown>;};/** Plugin Protocol v2 市场;网络、下载与安装全部在 main 进程完成。 */diff --git a/apps/desktop/src/shared/__tests__/ghost.oidc-token.test.ts b/apps/desktop/src/shared/__tests__/ghost.oidc-token.test.tsnew file mode 100644index 0000000000..6e4426e3b4--- /dev/null+++ b/apps/desktop/src/shared/__tests__/ghost.oidc-token.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest';++import { ghostPermissionItems, validateGhostManifest } from '../ghost.js';++function manifest(secret: Record<string, unknown>, extra: Record<string, unknown> = {}) {+ return {+ schemaVersion: 2,+ id: 'plugin-a',+ name: 'Plugin A',+ version: '1.0.0',+ entry: 'main.js',+ slots: ['tool', 'network'],+ tools: [{ name: 'whoami_a', description: 'Show the current enterprise identity' }],+ network: {+ hosts: ['service-a.x.test', 'other.x.test'],+ secrets: [+ {+ key: 'cindy_identity',+ label: 'Cindy Enterprise Identity',+ source: 'oidc-token',+ inject: {+ header: 'Authorization',+ format: 'Bearer {value}',+ hosts: ['service-a.x.test'],+ },+ ...secret,+ },+ ],+ },+ ...extra,+ };+}++describe('ghost manifest oidc-token source', () => {+ it('accepts the fixed Host-managed form without settingsHtml', () => {+ const result = validateGhostManifest(manifest({}));+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.manifest.network?.secrets?.[0]).toMatchObject({+ source: 'oidc-token',+ inject: {+ header: 'Authorization',+ format: 'Bearer {value}',+ hosts: ['service-a.x.test'],+ },+ });+ expect(ghostPermissionItems(result.manifest)).toContainEqual(+ expect.objectContaining({+ key: 'network:secret:cindy_identity',+ labelKey: 'networkSecretOrganizationIdentity',+ }),+ );+ });++ it.each([+ [{ inject: { header: 'Authorization', format: 'Bearer {value}' } }, 'inject.hosts'],+ [{ inject: { header: 'Authorization', format: 'Bearer {value}', hosts: [] } }, 'inject.hosts'],+ [{ inject: { header: 'X-Identity', format: 'Bearer {value}', hosts: ['service-a.x.test'] } }, 'Authorization'],+ [{ inject: { header: 'Authorization', format: '{value}', hosts: ['service-a.x.test'] } }, 'Bearer'],+ [{ url: 'https://service-a.x.test/settings' }, 'url'],+ [{ input: 'ghost' }, 'input'],+ [+ {+ exchange: {+ url: 'https://service-a.x.test/token',+ bodyFormat: '{"token":"{value}"}',+ tokenPath: 'token',+ },+ },+ 'exchange',+ ],+ [+ {+ oauth: {+ authorizeUrl: 'https://service-a.x.test/authorize',+ tokenUrl: 'https://service-a.x.test/token',+ },+ },+ 'oauth',+ ],+ ])('rejects an unsafe or ambiguous declaration', (secret, reason) => {+ const result = validateGhostManifest(manifest(secret));+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.reason).toContain(reason);+ });++ it('rejects setup references because there is no user configuration action', () => {+ const result = validateGhostManifest(+ manifest({}, { setup: { requires: [{ anyOf: ['secret:cindy_identity'] }] } }),+ );+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.reason).toContain('oidc-token');+ });++ it('rejects wildcard injection hosts for Connection JWTs', () => {+ const raw = manifest({}) as ReturnType<typeof manifest> & {+ network: {+ hosts: string[];+ secrets: Array<{ inject: { hosts: string[] } }>;+ };+ };+ raw.network.hosts = ['*.x.test'];+ raw.network.secrets[0]!.inject.hosts = ['*.x.test'];++ const result = validateGhostManifest(raw);+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.reason).toContain('不允许通配');+ });+});diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 6fd9def267..d106d3ecd0 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -711,12 +711,15 @@ export const GHOST_OAUTH_BOUNCE_PATH_RE = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)* 授权换来的 access token——用户在意识设置页填 client 凭证并点"连接账号",* 主机跑授权流程并保管全部令牌,出网时现取新鲜 token 注入(见* GhostSecretOauthDecl;必须同时声明 oauth 详单)。+ * - 'oidc-token':值 = Cindy 为当前企业 Membership 签发的短时 Connection+ * JWT。audience 由 Host 的可信安装记录推导,插件不能声明或读取;令牌+ * 只在 networkSlot 发请求时注入,且永不进入 Node Worker。** ('login-feishu-token' 已于 2026-07-17 随飞书登录整体下线退役——xd-feishu* 改走 source:'oauth' + tokenBroker:'feishu';存量已装清单由内置意识播种器* 按指纹覆盖自愈,未覆盖前该意识加载被拒属预期。)*/-export const GHOST_SECRET_SOURCES = ['user', 'login-email', 'oauth'] as const;+export const GHOST_SECRET_SOURCES = ['user', 'login-email', 'oauth', 'oidc-token'] as const;export type GhostSecretSource = (typeof GHOST_SECRET_SOURCES)[number];/**@@ -735,7 +738,7 @@ export interface GhostSecretDecl {key: string;/** 给用户看的名称(装入确认框展示)。 */label: string;- /** 凭证值来源;缺省 'user'(校验归一化:'user' 不落清单,只保留 'login-email')。 */+ /** 凭证值来源;缺省 'user'(校验归一化:'user' 不落清单)。 */source?: GhostSecretSource;/** 可选提示(如"在 example.com/settings 生成")。 */hint?: string;@@ -1627,6 +1630,16 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt});continue;}+ if (secret.source === 'oidc-token') {+ items.push({+ key: `network:secret:${secret.key}`,+ kind: 'network',+ labelKey: 'networkSecretOrganizationIdentity',+ labelArgs: { name: secret.label },+ detailKey: 'networkSecretOrganizationIdentityDetail',+ });+ continue;+ }const identity = secret.source === 'login-email';items.push({key: `network:secret:${secret.key}`,@@ -3424,7 +3437,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' = 主机登录邮箱派生(用户不填值)。+ // 来源:缺省 'user';login-email / oauth / oidc-token 均由主机托管。// 归一化:'user' 不落清单(与缺省同义,权限 diff 不 churn)。let source: GhostSecretSource | undefined;if (s.source !== undefined) {@@ -3439,6 +3452,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}if (s.source === 'login-email') source = 'login-email';if (s.source === 'oauth') source = 'oauth';+ if (s.source === 'oidc-token') source = 'oidc-token';}// 旧 input 字段已退役:Setup Runtime 直接从 Secret 声明生成 Host 表单,// settingsHtml 继续提供详情页管理。遗留 `input: "ghost"` 接受并忽略@@ -3451,26 +3465,26 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {}// login-email:值取自主机登录态派生,用户不填、没有输入面,// 禁 url / exchange,settingsHtml 豁免。- const loginDerived = source === 'login-email';- if (s.input === 'ghost' && loginDerived) {+ const hostDerived = source === 'login-email' || source === 'oidc-token';+ if (s.input === 'ghost' && hostDerived) {return {ok: false,reason: `source: ${source} 的凭证不允许标注 input: ghost(派生凭证没有输入,谈不上谁收单)`,};}- if (!loginDerived && raw.settingsHtml === undefined) {+ if (!hostDerived && raw.settingsHtml === undefined) {return {ok: false,reason: 'network.secrets 声明了用户填写的凭证时必须同时声明 settingsHtml(调用前可由 Host Setup 卡收单,settingsHtml 仍是长期管理/替换/清除入口)',};}- if (loginDerived && s.url !== undefined) {+ if (hostDerived && s.url !== undefined) {return {ok: false,reason: `network.secrets[].source 为 ${source} 时不允许声明 url(值取自主机登录态,没有"前往控制台"可去)`,};}- if (loginDerived && s.exchange !== undefined) {+ if (hostDerived && s.exchange !== undefined) {// 组合会把登录态凭证作为原始值 POST 给交换端点,而确认框文案只// 承诺"派生注入请求头"——语义盖不住,结构上禁掉(有真实场景再议)。return {@@ -3536,6 +3550,26 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {injectHosts.push(ihNorm);}}+ if (source === 'oidc-token') {+ if (inj.header !== 'Authorization' || inj.format !== 'Bearer {value}') {+ return {+ ok: false,+ reason: 'network.secrets[].source 为 oidc-token 时 inject 必须是 Authorization: Bearer {value}',+ };+ }+ if (injectHosts === undefined) {+ return {+ ok: false,+ reason: 'network.secrets[].source 为 oidc-token 时必须显式声明非空 inject.hosts,限制企业身份令牌的流向',+ };+ }+ if (injectHosts.some((host) => host.startsWith('*.'))) {+ return {+ ok: false,+ reason: 'network.secrets[].source 为 oidc-token 时 inject.hosts 只允许精确域名,不允许通配',+ };+ }+ }// oauth(source: 'oauth' 时必填):主机托管 OAuth 授权详单。授权页与// token 端点域名都必须落在 hosts 白名单内——确认框展示的域名集合就是// 全部出网面(clientSecret 只流向 tokenUrl,授权只发生在 authorizeUrl)。@@ -4040,7 +4074,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// setup 就绪声明:引用必须指向已声明的凭证/连接(悬空引用在装包期拒,// 不留到运行期才发现作者写错);kv 引用要求 settingsHtml(没有设置页- // 没人填参数);login-email 源恒就绪,引用它属结构性误解,直接拒装。+ // 没人填参数);Host 派生源没有用户配置动作,引用它属结构性误解,直接拒装。let setup: GhostSetupDecl | undefined;if (raw.setup !== undefined) {if (!isPlainObject(raw.setup)) {@@ -4052,12 +4086,21 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (!Array.isArray(su.requires) || su.requires.length > GHOST_SETUP_MAX_GROUPS) {return { ok: false, reason: `setup.requires 必须是 0–${GHOST_SETUP_MAX_GROUPS} 组的数组(空数组 = 显式声明无使用前置需求)` };}- const secretByKey = new Map<string, { loginDerived: boolean }>([+ const secretByKey = new Map<+ string,+ { hostDerivedSource: 'login-email' | 'oidc-token' | null }+ >([...(network?.secrets ?? []).map(- (s) => [s.key, { loginDerived: s.source === 'login-email' }] as const,+ (s) => [+ s.key,+ {+ hostDerivedSource:+ s.source === 'login-email' || s.source === 'oidc-token' ? s.source : null,+ },+ ] as const,),...(node?.secretBindings ?? []).map(- (s) => [s.key, { loginDerived: false }] as const,+ (s) => [s.key, { hostDerivedSource: null }] as const,),]);const connectionKeys = new Set((network?.connections ?? []).map((c) => c.key));@@ -4081,8 +4124,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (!decl) {return { ok: false, reason: `setup 引用了未声明的凭证 ${JSON.stringify(refKey)}(必须逐字取自 network.secrets[].key 或 node.secretBindings[].key)` };}- if (decl.loginDerived) {- return { ok: false, reason: `setup 不允许引用 login-email 源凭证 ${JSON.stringify(refKey)}(登录派生身份恒就绪,无配置动作可引导)` };+ if (decl.hostDerivedSource) {+ return { ok: false, reason: `setup 不允许引用 ${decl.hostDerivedSource} 源凭证 ${JSON.stringify(refKey)}(Host 派生身份没有用户配置动作可引导)` };}item = { kind: 'secret', key: refKey };} else {diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex bcc6c6875b..3ee9729c2f 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -74,6 +74,13 @@## 4. 网络、凭证与资源交接- network 只允许 manifest 白名单域名;凭证由主机保险库注入,**无明文读回**给沙箱。+- `source: "oidc-token"` 是 Host 托管的短时 Cindy Connection JWT:只对当前企业+ Membership 生效,audience 由 Host 的受信插件映射推导,插件和 Node Worker 都不能读取或+ 保存令牌。声明必须固定使用 `Authorization: Bearer {value}` 并显式列出非空+ `inject.hosts`;其中只允许精确域名,不允许通配。实际目标还必须精确命中 Host 受信安装+ 映射里的服务域名,两层同时通过才签发和注入。它没有用户输入、`url`、`exchange` 或+ `setup.requires` 配置动作。Connection JWT 请求遇到 401 时,仅 GET / HEAD / OPTIONS+ 可自动换令牌重试一次;非幂等请求只作废缓存,不自动重放。- 插件 setup 的完成状态只由 Host 读取真实持久化状态后判定。简单的`source: "user"` Secret 可由 Host 在聊天 Setup 卡中生成 `inline_form` 并直接写入保险库;插件详情页的 `settings.js` 仍可通过 `/oauth`、`/kv`、`/secrets`、