Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 组织插件按装入来源与组织事实拿 Broker 与 oidc-token

fmfsaisai12f78393437e
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index ff253a4eee..48c2e77b2d 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -45,6 +45,7 @@ import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
import { checkSkillMdConsistency } from './skillSlot.js';
import {
createGhostInstallReceipt,
+ effectiveInstallOrigin,
GhostInstallReceiptStore,
hashApprovedSkillContent,
readLegacyInstallTrust,
@@ -194,6 +195,11 @@ export interface GhostManagerOptions {
* 该入口不经用户确认就铸出批准,因此 id 与 source 都必须由生产接线明确放行。
*/
isTrustedBundledId?: (id: string) => boolean;
+ /**
+ * tokenBroker 装入闸。缺省只认静态官方前缀(测试夹具)。生产接线问
+ * first-party 判据,官方前缀命中仍走静态表。
+ */
+ isTokenBrokerAuthorized?: (manifest: GhostManifest) => boolean;
/** sourceDir 是否就是该 id 的随包只读种子目录,而非任意本机可变目录。 */
isTrustedBundledSource?: (id: string, sourceDir: string) => boolean;
/** Persist the user's builtin-uninstall intent before approval/content removal. */
@@ -1049,6 +1055,21 @@ export class GhostManager {
return this.receiptStore.rootDir();
}
+ /**
+ * Authorization-time install origin. Missing / unreadable receipts are
+ * `manual` — same fail-closed as today, never a privilege upgrade.
+ */
+ readEffectiveInstallOrigin(id: string): 'manual' | 'agent-forge' {
+ this.ensureCurrentOwnerContextSync();
+ try {
+ const approval = this.readApproval(id);
+ if (approval.state !== 'approved') return 'manual';
+ return effectiveInstallOrigin(approval.receipt);
+ } catch {
+ return 'manual';
+ }
+ }
+
/**
* Host-owned evidence for reconnecting an installation to retained source metadata.
* A pending package mutation or an invalid approval fails closed. Legacy provenance
@@ -1854,16 +1875,18 @@ export class GhostManager {
if (validated.manifest.id !== id) {
return { rejection: { code: 'file-invalid', reason: '清单 id 与安装目录不一致' } };
}
- // tokenBroker 门控与装入侧同一条规则(XDT 授权 broker 仅第一方官方插件可用,
- // 不区分 dev/packaged):走已装目录重新确认的都不是随包插件,声明即拒。
+ // tokenBroker 门控与装入侧同一条规则。官方前缀命中照旧放行;其余问
+ // 生产接线的 first-party 判据(含 receipt 装入来源)。
+ const brokerAuthorized =
+ this.options.isTokenBrokerAuthorized?.(validated.manifest) ?? isBrokerEligibleGhostId(id);
if (
- !isBrokerEligibleGhostId(id) &&
+ !brokerAuthorized &&
(validated.manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined)
) {
return {
rejection: {
code: 'file-invalid',
- reason: `id "${id}" 声明了 oauth.tokenBroker——XDT 授权 broker 仅第一方官方插件可用`,
+ reason: `id "${id}" 声明了 oauth.tokenBroker——当前安装来源或组织身份无权使用授权 broker`,
},
};
}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
index d1d11661b1..f09ffd4262 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
@@ -156,6 +156,59 @@ describe('installed Plugin Connection audience resolver', () => {
).toBeNull();
});
+ it('resolves a forge-installed org-prefix plugin before consulting the market ledger', () => {
+ const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };
+ const resolver = loadConnectionAudienceResolver({
+ ...resolverOptions(forgeManifest, null),
+ readInstallOrigin: () => 'agent-forge',
+ readApprovedPackageSha256: () => 'a'.repeat(64),
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ });
+ expect(resolver.resolve('acme-tool', identity)).toEqual({
+ membershipId: 'membership-1',
+ audience: 'org-example:acme-tool',
+ pluginSlug: 'acme-tool',
+ allowedHosts: ['service-a.x.test'],
+ });
+ });
+
+ it('does not give forge OIDC to a personal identity or a missing orgSlug', () => {
+ const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };
+ const resolver = loadConnectionAudienceResolver({
+ ...resolverOptions(forgeManifest, null),
+ readInstallOrigin: () => 'agent-forge',
+ readApprovedPackageSha256: () => 'a'.repeat(64),
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ });
+ expect(
+ resolver.resolve('acme-tool', {
+ membershipId: 'membership-1',
+ membershipKind: 'personal',
+ orgId: null,
+ orgSlug: null,
+ }),
+ ).toBeNull();
+ expect(
+ resolver.resolve('acme-tool', {
+ membershipId: 'membership-1',
+ membershipKind: 'org',
+ orgId: 'org-id-1',
+ orgSlug: null,
+ }),
+ ).toBeNull();
+ });
+
+ it('does not give forge OIDC to a manual install of the same org-prefix id', () => {
+ const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };
+ const resolver = loadConnectionAudienceResolver({
+ ...resolverOptions(forgeManifest, null),
+ readInstallOrigin: () => 'manual',
+ readApprovedPackageSha256: () => 'a'.repeat(64),
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ });
+ expect(resolver.resolve('acme-tool', identity)).toBeNull();
+ });
+
it('requires the managed secret target to match a declared exact host', () => {
const resolver = loadConnectionAudienceResolver({
...resolverOptions(),
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.ts
index a85f42d668..c5c189c281 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,13 +32,21 @@ 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 与 clientSecret 同时声明',
- '仅第一方官方意识可用',
+ '三路资格',
+ '静态官方前缀照旧放行',
+ '服务端 organization market 包已安装',
+ 'organizationId 与当前组织一致',
+ 'installOrigin 为 `agent-forge`',
+ '不接受手动装入、个人身份或别的组织前缀',
+ '只给 Broker 与 oidc-token,不给宿主原语',
+ 'packageSha256 来源指纹',
+ '总长不得超过 64 字符',
]) {
expect(FORGE_GUIDE).toContain(marker);
}
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts
index 037ece6033..8f5770810d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts
@@ -54,6 +54,7 @@ function loader(overrides: Partial<LoadGhostFirstPartyFactsLoaderOptions> = {})
readInstalledBuiltin: () => false,
readMarketInstallation: () => null,
lookupOrganizationPrefix: () => ({ kind: 'absent' }),
+ readInstallOrigin: () => 'manual',
...overrides,
});
}
@@ -76,6 +77,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
builtin: true,
marketRecord: null,
currentOrganization: null,
+ installOrigin: 'manual',
});
expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({
brokerEligible: true,
@@ -157,6 +159,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
builtin: false,
marketRecord: null,
currentOrganization: null,
+ installOrigin: 'manual',
},
});
});
@@ -204,6 +207,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {
builtin: false,
marketRecord: null,
currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },
+ installOrigin: 'manual',
},
});
});
@@ -226,7 +230,45 @@ describe('loadGhostFirstPartyFactsLoader', () => {
installed: true,
},
currentOrganization: { organizationId: 'org-a', pluginPrefix: null },
+ installOrigin: 'manual',
},
});
});
+
+ it('treats a missing receipt as manual so builtin official plugins stay unchanged', () => {
+ const loaded = loader({
+ readInstalledBuiltin: (ghostId) => ghostId === 'xd-feishu',
+ readInstallOrigin: () => 'manual',
+ }).load('xd-feishu', 'runtime', PERSONAL);
+ expect(loaded.kind).toBe('ready');
+ if (loaded.kind !== 'ready') return;
+ expect(loaded.facts.installOrigin).toBe('manual');
+ expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({
+ brokerEligible: true,
+ hostPrimitiveEligible: true,
+ basis: 'builtin-official',
+ });
+ });
+
+ it('copies installOrigin from the receipt reader and treats a read failure as manual', () => {
+ const forged = loader({
+ readInstallOrigin: () => 'agent-forge',
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ }).load('acme-feishu', 'runtime', ORG_A);
+ expect(forged).toMatchObject({
+ kind: 'ready',
+ facts: { installOrigin: 'agent-forge' },
+ });
+
+ const unread = loader({
+ readInstallOrigin: () => {
+ throw new Error('EACCES');
+ },
+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),
+ }).load('acme-feishu', 'runtime', ORG_A);
+ expect(unread).toMatchObject({
+ kind: 'ready',
+ facts: { installOrigin: 'manual' },
+ });
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts
index f4e6edd438..2724ba5255 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
FIRST_PARTY_ALIAS_GHOST_IDS,
+ authorizeGhostTokenBroker,
resolveGhostFirstPartyPrivilege,
type GhostFirstPartyFacts,
type GhostFirstPartyMarketRecord,
@@ -29,6 +30,7 @@ function facts(partial: Partial<GhostFirstPartyFacts> & Pick<GhostFirstPartyFact
builtin: false,
marketRecord: null,
currentOrganization: null,
+ installOrigin: 'manual',
...partial,
};
}
@@ -45,9 +47,10 @@ function market(
}
describe('resolveGhostFirstPartyPrivilege', () => {
- // 存量兼容红线(P0):随包的 xd-feishu / xd-atlassian 是全仓唯一声明 oauth.tokenBroker
- // 的两个插件。用户切成个人身份、或从未打开过市场页(无台账)时,它们必须照旧拿到
- // Broker 与宿主原语——退化了就是已装插件在升级后失效。
+ // 纯函数分支测试:用 xd-feishu / xd-atlassian 作为代表性官方前缀 id,验证
+ // builtin + 官方前缀会同时得到 Broker 与宿主原语;这不表示它们随发行包分发。
+ // 静态官方前缀的存量兼容由后面的 authorizeGhostTokenBroker(...,
+ // { kind: 'unavailable' }) 对照用例锁定。
// `currentOrganization: null` 与 `marketRecord: null` 在这里**显式写出**,不吃
// `facts()` 的默认值:否则将来有人为省事把默认改成"有组织",这条依然会通过
// (优先级 1 本就不看 org),但"个人身份"这个场景就悄悄没人守了。
@@ -247,35 +250,45 @@ describe('resolveGhostFirstPartyPrivilege', () => {
});
});
- it('gives local / custom-market packages broker when the id matches the current org prefix', () => {
+ it('gives a forge-built local package broker when the id matches the current org prefix, not a manual install', () => {
+ const shared = {
+ ghostId: 'acme-feishu',
+ currentOrganization: CURRENT_ORG,
+ } as const;
expect(
- resolveGhostFirstPartyPrivilege(
- facts({
- ghostId: 'acme-feishu',
- marketRecord: market({
- scope: 'personal',
- organizationId: null,
- source: 'local-market',
- }),
- currentOrganization: CURRENT_ORG,
- }),
- ),
+ resolveGhostFirstPartyPrivilege(facts({ ...shared, installOrigin: 'agent-forge' })),
).toEqual({
brokerEligible: true,
hostPrimitiveEligible: false,
basis: 'local-current-org-prefix',
});
+ expect(
+ resolveGhostFirstPartyPrivilege(facts({ ...shared, installOrigin: 'manual' })),
+ ).toEqual({
+ brokerEligible: false,
+ hostPrimitiveEligible: false,
+ basis: 'denied-unknown-origin',
+ });
+ });
+
+ it('does not raise a custom-market package to broker unless it was forge-installed', () => {
expect(
resolveGhostFirstPartyPrivilege(
facts({
ghostId: 'acme-feishu',
+ marketRecord: market({
+ scope: 'personal',
+ organizationId: null,
+ source: 'local-market',
+ }),
currentOrganization: CURRENT_ORG,
+ installOrigin: 'manual',
}),
),
).toEqual({
- brokerEligible: true,
+ brokerEligible: false,
hostPrimitiveEligible: false,
- basis: 'local-current-org-prefix',
+ basis: 'denied-unknown-origin',
});
});
@@ -301,8 +314,68 @@ describe('resolveGhostFirstPartyPrivilege', () => {
basis: 'denied-unknown-origin',
});
}
- // 作者自测不受影响:从未发布过的 id 压根没有台账行(marketRecord 为 null),
- // 照旧走到兜底并放行——这条在上面「local / custom-market」那条用例里钉着。
+ // 作者自测:从未发布过的 id 没有台账行。手动装仍 deny;只有 forge 装入
+ // 才走兜底放 Broker(见「forge-built local package」那条对照用例)。
+ });
+
+ it('keeps official-prefix broker even when facts are unavailable, and asks the resolver otherwise', () => {
+ expect(
+ authorizeGhostTokenBroker('xd-feishu', { kind: 'unavailable' }),
+ ).toBe(true);
+ expect(
+ authorizeGhostTokenBroker('acme-feishu', { kind: 'unavailable' }),
+ ).toBe(false);
+ expect(
+ authorizeGhostTokenBroker(
+ 'acme-feishu',
+ {
+ kind: 'ready',
+ facts: facts({
+ ghostId: 'acme-feishu',
+ currentOrganization: CURRENT_ORG,
+ installOrigin: 'agent-forge',
+ }),
+ },
+ ),
+ ).toBe(true);
+ expect(
+ authorizeGhostTokenBroker(
+ 'acme-feishu',
+ {
+ kind: 'ready',
+ facts: facts({
+ ghostId: 'acme-feishu',
+ currentOrganization: CURRENT_ORG,
+ installOrigin: 'manual',
+ }),
+ },
+ ),
+ ).toBe(false);
+ });
+
+ it('uses pending org-market facts only for non-official ids; official prefix never consults them', () => {
+ const pendingOrgMarket = facts({
+ ghostId: 'acme-feishu',
+ marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),
+ currentOrganization: CURRENT_ORG,
+ installOrigin: 'manual',
+ });
+ expect(authorizeGhostTokenBroker('acme-feishu', { kind: 'ready', facts: pendingOrgMarket })).toBe(
+ true,
+ );
+ expect(
+ authorizeGhostTokenBroker('cindy-art', {
+ kind: 'ready',
+ facts: facts({
+ ghostId: 'cindy-art',
+ builtin: false,
+ marketRecord: null,
+ currentOrganization: null,
+ installOrigin: 'manual',
+ }),
+ }),
+ ).toBe(true);
+ expect(authorizeGhostTokenBroker('cindy-art', { kind: 'unavailable' })).toBe(true);
});
// `legacy-adopted` 是市场列表成功后为「早于市场就已装在本机的官方前缀插件」合成的
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
index 51a788d5fa..f2e8b81f0f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@ -1839,6 +1839,39 @@ describe('tokenBroker 模式', () => {
expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBeNull();
expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
});
+
+ it('getFreshAccessToken refuses a cached broker token after eligibility is withdrawn', async () => {
+ let authorized = true;
+ const vault = seededVault();
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ broker: {
+ exchange: vi.fn(),
+ refresh: vi.fn(async () => ({
+ ok: true as const,
+ bundle: {
+ accessToken: 'at-cached',
+ refreshToken: 'rt-seed',
+ expiresAt: Date.now() + 60_000,
+ grantedScope: null,
+ },
+ })),
+ },
+ sleep: instantSleep,
+ isTokenBrokerAuthorized: () => authorized,
+ });
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, BROKER_DECL)).resolves.toMatchObject({
+ ok: true,
+ accessToken: 'at-cached',
+ });
+ authorized = false;
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, BROKER_DECL)).resolves.toMatchObject({
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ });
+ });
});
describe('brokerBounce(双地址弹跳回调)', () => {
diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
index 03cf9276c1..5ad8544154 100644
--- a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
@@ -7,6 +7,7 @@ import { isValidGhostId, isValidGhostNetworkHostPattern } from '../../shared/gho
import type { GhostManifest } from '../../shared/ghost.js';
import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID } from '../plugin-publisher/types.js';
+import { PLUGIN_PREFIX_PATTERN } from '@cindy/plugin-protocol';
export interface ConnectionAudienceIdentity {
membershipId: string;
@@ -58,6 +59,11 @@ export interface LoadConnectionAudienceResolverOptions {
readInstalledManifest(ghostId: string): GhostManifest | null;
readInstalledManifestDigest(ghostId: string): string | null;
readMarketInstallation(ghostId: string): PluginMarketInstallationRecord | null;
+ readApprovedPackageSha256?(ghostId: string): string | null;
+ readInstallOrigin?(ghostId: string): 'manual' | 'agent-forge';
+ lookupOrganizationPrefix?(
+ orgId: string,
+ ): { kind: 'known'; pluginPrefix: string | null } | { kind: 'absent' } | { kind: 'unavailable' };
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
warn: (msg: string, meta?: Record<string, unknown>) => void;
@@ -89,6 +95,63 @@ export function loadConnectionAudienceResolver(
return reject('org-slug-unavailable');
}
+ 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('*.')),
+ ),
+ ];
+ if (allowedHosts.length === 0) return reject('oidc-host-declaration-missing');
+ const audience = `${identity.orgSlug}:${ghostId}`;
+ if (audience.length > 64) return reject('audience-too-long');
+ options.log?.info('ghost Connection audience resolved', {
+ ghostId,
+ allowedHostCount: allowedHosts.length,
+ });
+ return {
+ membershipId: identity.membershipId,
+ audience,
+ pluginSlug: ghostId,
+ allowedHosts,
+ };
+ };
+
+ const readManifest = (): GhostManifest | null => {
+ try {
+ return options.readInstalledManifest(ghostId);
+ } catch {
+ return null;
+ }
+ };
+
+ // Forge branch before market-record: a forge package has no ledger row.
+ // Personal identity / missing orgSlug already rejected above.
+ const forgeOrigin = options.readInstallOrigin?.(ghostId);
+ if (forgeOrigin === 'agent-forge') {
+ const prefixLookup = identity.orgId
+ ? options.lookupOrganizationPrefix?.(identity.orgId)
+ : undefined;
+ const prefix =
+ prefixLookup && prefixLookup.kind === 'known' ? prefixLookup.pluginPrefix : null;
+ if (
+ prefix &&
+ PLUGIN_PREFIX_PATTERN.test(prefix) &&
+ ghostId.startsWith(`${prefix}-`)
+ ) {
+ const approvedSha = options.readApprovedPackageSha256?.(ghostId) ?? null;
+ if (!approvedSha || !/^[a-f0-9]{64}$/.test(approvedSha)) {
+ return reject('forge-package-sha-missing');
+ }
+ const manifest = readManifest();
+ if (!manifest) return reject('plugin-not-installed');
+ if (manifest.id !== ghostId) return reject('plugin-id-mismatch');
+ return finish(manifest);
+ }
+ }
+
let installation: PluginMarketInstallationRecord | null = null;
try {
installation = options.readMarketInstallation(ghostId);
@@ -126,29 +189,7 @@ export function loadConnectionAudienceResolver(
if (installedManifestDigest !== installation.manifestDigest) {
return reject('installed-manifest-digest-mismatch');
}
-
- const allowedHosts = [
- ...new Set(
- (manifest.network?.secrets ?? [])
- .filter((secret) => secret.source === 'oidc-token')
- .flatMap((secret) => secret.inject.hosts ?? [])
- .filter((host) => isValidGhostNetworkHostPattern(host) && !host.startsWith('*.')),
- ),
- ];
- if (allowedHosts.length === 0) return reject('oidc-host-declaration-missing');
-
- const audience = `${identity.orgSlug}:${ghostId}`;
- if (audience.length > 64) return reject('audience-too-long');
- options.log?.info('ghost Connection audience resolved', {
- ghostId,
- allowedHostCount: allowedHosts.length,
- });
- return {
- membershipId: identity.membershipId,
- audience,
- pluginSlug: ghostId,
- allowedHosts,
- };
+ return finish(manifest);
},
};
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 6893408b1e..f8618f6eb2 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1746,7 +1746,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)。服务商要求回调 URI 与注册值精确匹配(如 Atlassian)时声明,回调恒为 http://127.0.0.1:<端口>/callback;缺省 = 随机端口(Google 等允许任意 loopback 端口的服务商不用声明)
- "tokenBroker": "jira", // 可选:仅第一方官方意识可用(第三方声明拒装)。声明后 code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client
+ "tokenBroker": "jira", // 可选:三路资格:静态官方前缀照旧放行;当前组织的服务端 organization market 包已安装、source 为 market、organizationId 与当前组织一致且 id 命中本组织已登记前缀;或当前组织身份下经 ghost forge 装入(receipt.installOrigin 为 agent-forge)且 id 命中本组织已登记前缀。后两条新增基座不接受手动装入、个人身份或别的组织前缀,且只给 Broker 与 oidc-token,不给宿主原语。声明后 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>
}
}],
@@ -2855,14 +2855,20 @@ PAT;页面可据此展示“已检测到 gh,可直接使用”,但不能
\`Authorization: Bearer {value}\`,不允许 exchange,也不要放进 \`setup.requires\`。
**Cindy 企业身份断言(source:"oidc-token",可选)**:适用于接入 Cindy Connection
-Auth 的企业服务。主机只在当前登录账号属于组织 Membership、且该插件拥有当前组织的
-Plugin Market organization 安装记录、安装 manifest digest 未被篡改并声明了目标服务域名时,
-按需向 auth-server 换取短时 Connection JWT;audience 与组织身份由主机推导,插件清单和
-运行时代码都不能选择、读取或保存 audience/token。该凭证必须固定声明
+Auth 的企业服务。主机只在当前登录账号属于组织 Membership,并且满足下面两条基座
+之一时,按需向 auth-server 换取短时 Connection JWT:
+1. 当前组织的 Plugin Market organization 安装记录(source 必须是服务端 \`market\`),
+ 安装 manifest digest 未被篡改,并声明了目标服务域名;或
+2. **组织身份 + 本组织已登记前缀 + 插件 id 命中 \`<前缀>-\` + 经 ghost forge 装入
+ (receipt 为 agent-forge) + 批准记录中保有有效的 packageSha256 来源指纹**。
+audience 与组织身份由主机推导,插件清单和运行时代码都不能选择、读取或保存
+audience/token;audience 固定为 \`\${orgSlug}:\${ghostId}\`,总长不得超过 64 字符。
+这两条组织基座都不适用于个人身份或手动装入;其中 forge 基座还要求命中当前组织
+前缀。它们只给 Broker 与 oidc-token,不给宿主原语。该凭证必须固定声明
\`"inject": { "header": "Authorization", "format": "Bearer {value}", "hosts": [...] }\`,
且 \`hosts\` 必须是非空的显式子集,只允许把断言发给列出的企业服务域名。
\`oidc-token\` 的 \`inject.hosts\` 只接受精确域名,不允许 \`*.example.com\` 通配;Host
-会从通过 digest 校验的市场 manifest 读取这些声明,目标请求必须精确命中声明域名才会签发并注入。
+会从已批准的安装事实读取这些声明,目标请求必须精确命中声明域名才会签发并注入。
它没有用户输入、\`url\`、\`exchange\` 或 \`oauth\` 详单,也不要放进 \`setup.requires\`;没有企业
身份时 cindy.fetch 会 fail-closed 并返回结构化错误。企业服务应使用 Connection JWT
中的 \`sub\`、\`email\` 或 \`identities\` 等声明自行选择业务身份,不要要求 Cindy 客户端先把
@@ -2940,13 +2946,17 @@ identity.displayTemplate 时,\`/oauth\` 回查与连接结果里 account.label
即可;第一方官方内置意识会先自动结束占用进程并重试,第三方意识不享受此回收
——请选一个不易撞车的端口)。Google 这类允许任意 loopback 端口的服务商不用
声明。
-- \`tokenBroker\`:**仅第一方官方意识可用**(第三方声明直接拒装)——code/refresh
- 交换改经 Cindy 服务端 broker 完成,client secret 由服务端持有、不随包分发,
- 且要求用户已登录 Cindy。声明它时与 clientSecret 互斥;PKCE 缺省开(verifier
+- \`tokenBroker\`:资格有三路:①静态官方前缀命中,照旧放行;②当前组织的服务端
+ organization market 包已安装、source 为 \`market\`、organizationId 与当前组织一致,
+ 且 id 命中本组织已登记前缀;③当前组织身份下经 ghost forge 装入(receipt 的
+ installOrigin 为 \`agent-forge\`),且 id 命中本组织已登记前缀。第 2、3 条新增基座
+ 不接受手动装入、个人身份或别的组织前缀,且只给 Broker 与 oidc-token,不给宿主原语。
+ code/refresh 交换改经 Cindy 服务端 broker 完成,client secret 由服务端持有、不随包
+ 分发,且要求用户已登录 Cindy。声明它时与 clientSecret 互斥;PKCE 缺省开(verifier
经 broker exchange 透传服务端),不吃 PKCE 的服务商显式 \`"pkce": false\`;
设置页的 \`/oauth/<key>/client\` 自填通道返回 405(settingsHtml 不要再画
client 输入区)。
-- \`brokerBounce\`:双地址弹跳回调(随 tokenBroker,同样仅第一方)。部分
+- \`brokerBounce\`:双地址弹跳回调(随 tokenBroker,资格与 tokenBroker 相同)。部分
服务商后台只收 https redirect、不收 http loopback——声明后报给服务商的
redirect_uri 是「broker 服务的 https 弹跳路由」(主机用 broker 基地址 + \`path\`
运行时拼出),浏览器授权后弹跳路由 302 回本机
@@ -4276,7 +4286,7 @@ const opened = await cindy.iosSimulator.request({
extraAuthorizeParams 覆写保留参数(client_id/redirect_uri/state/code_challenge 等)、
redirectPort 不是 1024–65535 整数、tokenBroker 与 clientSecret 同时声明、
clientIdAlternatives 没与 clientId + tokenBroker 成套或包含重复/非法 ID、
- 非官方前缀 id 声明了 tokenBroker(仅第一方可用)、brokerBounce 没和 tokenBroker +
+ 当前安装来源或组织身份无权使用 tokenBroker、brokerBounce 没和 tokenBroker +
redirectPort 成套声明或路径不是 / 开头的站内绝对路径)
- connections 声明格式错(超 2 条、key 撞 secrets 的 key 或声明内重复、label 缺失/超 64 字、
inject 缺失/format 没有 {value}/header 用了协议关键头、**声明了 inject.hosts**(连接
diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts
index 5c9a6ae01b..15753e4129 100644
--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts
@@ -1,9 +1,7 @@
/**
* Assembles `GhostFirstPartyFacts` for `resolveGhostFirstPartyPrivilege`.
*
- * This loader only collects facts. It does not grant or refuse privileges, and
- * existing `isBrokerEligibleGhostId` / `isFirstPartyHostPrivilegeGhostId` call
- * sites stay unwired.
+ * This loader only collects facts. It does not grant or refuse privileges.
*
* Do not return a bare `GhostFirstPartyFacts` object: callers must be able to
* tell "facts are complete" from "a required fact could not be obtained".
@@ -63,6 +61,8 @@ export interface LoadGhostFirstPartyFactsLoaderOptions {
readInstalledBuiltin(ghostId: string): boolean;
readMarketInstallation(ghostId: string): PluginMarketInstallationRecord | null;
lookupOrganizationPrefix(orgId: string): OrganizationPrefixLookup;
+ /** Missing / unreadable receipts must return `manual`. */
+ readInstallOrigin(ghostId: string): 'manual' | 'agent-forge';
}
function actionFor(purpose: GhostFirstPartyFactsPurpose): GhostFirstPartyFactsUnavailableAction {
@@ -80,6 +80,26 @@ function toMarketRecord(
};
}
+export type GhostFirstPartyFactsOverrides = {
+ installOrigin?: 'manual' | 'agent-forge';
+ 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 {
@@ -112,6 +132,13 @@ export function loadGhostFirstPartyFactsLoader(
marketRecord = null;
}
+ let installOrigin: 'manual' | 'agent-forge' = 'manual';
+ try {
+ installOrigin = options.readInstallOrigin(ghostId);
+ } catch {
+ installOrigin = 'manual';
+ }
+
if (identity.membershipKind !== 'org' || !identity.orgId) {
return {
kind: 'ready',
@@ -120,6 +147,7 @@ export function loadGhostFirstPartyFactsLoader(
builtin,
marketRecord,
currentOrganization: null,
+ installOrigin,
},
};
}
@@ -141,7 +169,7 @@ export function loadGhostFirstPartyFactsLoader(
*/
const builtinOnlyFacts = (): GhostFirstPartyFactsLoad => ({
kind: 'ready',
- facts: { ghostId, builtin, marketRecord, currentOrganization: null },
+ facts: { ghostId, builtin, marketRecord, currentOrganization: null, installOrigin },
});
let lookup: OrganizationPrefixLookup;
@@ -163,6 +191,7 @@ export function loadGhostFirstPartyFactsLoader(
organizationId: identity.orgId,
pluginPrefix: lookup.pluginPrefix,
},
+ installOrigin,
},
};
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts
index 9e7055d7b7..5f0c6d3507 100644
--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts
@@ -5,9 +5,9 @@
* conclusion. Callers decide whether to refuse install or only withhold
* privileges; this module does not refuse loading.
*
- * Not wired yet. Existing `isBrokerEligibleGhostId` /
- * `isFirstPartyHostPrivilegeGhostId` call sites stay on the static prefix
- * predicates until the next step.
+ * Call sites that previously used only `isBrokerEligibleGhostId` now ask this
+ * resolver **after** the static official-prefix hit (`cindy-` / `filo-` / `xd-`).
+ * Official-prefix plugins keep today's grant. Everything else is decided here.
*
* Input priority: first evaluable of
* 1. builtin seed → static official table
@@ -31,7 +31,7 @@
*/
import { PLUGIN_PREFIX_PATTERN, type PluginScope } from '@cindy/plugin-protocol';
-import { isOfficialGhostId } from '../../shared/ghost.js';
+import { isBrokerEligibleGhostId, isOfficialGhostId } from '../../shared/ghost.js';
/**
* Ghost ids that share Host credential aliases (`GHOST_SECRET_STORAGE_ALIASES`).
@@ -73,6 +73,12 @@ export interface GhostFirstPartyFacts {
builtin: boolean;
marketRecord: GhostFirstPartyMarketRecord | null;
currentOrganization: GhostFirstPartyCurrentOrganization | null;
+ /**
+ * Authorization-time install origin from `effectiveInstallOrigin(receipt)`.
+ * Missing / unreadable receipts are `manual` (fail-closed, equals today).
+ * Local org-prefix packages only receive Broker when this is `agent-forge`.
+ */
+ installOrigin: 'manual' | 'agent-forge';
}
function matchesCurrentOrgPrefix(
@@ -160,14 +166,35 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Gh
(record.source === 'git-market' || record.source === 'local-market') &&
matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)
) {
- return allow('local-current-org-prefix', false);
+ // Custom-market rows are not a forge install. Granting Broker here would
+ // silently raise privilege for packages that today's install gate rejects.
+ return facts.installOrigin === 'agent-forge'
+ ? allow('local-current-org-prefix', false)
+ : deny('denied-unknown-origin');
}
return deny('denied-unknown-origin');
}
- if (matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)) {
+ if (
+ facts.installOrigin === 'agent-forge' &&
+ matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)
+ ) {
return allow('local-current-org-prefix', false);
}
return deny('denied-unknown-origin');
}
+
+/**
+ * Incremental broker gate: official prefix (`cindy-` / `filo-` / `xd-`) keeps
+ * today's grant without consulting facts. Everything else asks the resolver.
+ * Unavailable facts are fail-closed (no broker).
+ */
+export function authorizeGhostTokenBroker(
+ ghostId: string,
+ load: { kind: 'ready'; facts: GhostFirstPartyFacts } | { kind: string },
+): boolean {
+ if (isBrokerEligibleGhostId(ghostId)) return true;
+ if (load.kind !== 'ready' || !('facts' in load)) return false;
+ return resolveGhostFirstPartyPrivilege(load.facts).brokerEligible;
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index 1ec3bfbd60..2cb3fc6b58 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@ -46,6 +46,7 @@ import {
} from './ghostOauthFlow.js';
import {
changedBuiltinOauthClientSecretKeys,
+ isBrokerEligibleGhostId,
isFirstPartyHostPrivilegeGhostId,
type GhostManifest,
type GhostSecretOauthDecl,
@@ -156,6 +157,11 @@ export interface GhostOauthAccountManagerDeps {
withMutationLock?: <T>(ghostId: string, task: () => Promise<T> | T) => Promise<T>;
/** 延时器(仅 invalid_grant 轮换探测用;测试注入即时假体,生产缺省 setTimeout)。 */
sleep?: (ms: number) => Promise<void>;
+ /**
+ * tokenBroker 资格复核。官方前缀命中照今天放行;否则问 first-party 判据。
+ * 缺省只认静态官方前缀,存量单测零行为变化。
+ */
+ isTokenBrokerAuthorized?: (ghostId: string) => boolean;
}
/**
@@ -172,7 +178,12 @@ export type GhostOauthConnectResult =
| { ok: true; account: GhostOauthAccountView }
| {
ok: false;
- error: 'NO_CLIENT_CONFIG' | 'ACCOUNT_LIMIT' | 'VAULT_WRITE_FAILED' | GhostOauthFlowError;
+ error:
+ | 'NO_CLIENT_CONFIG'
+ | 'ACCOUNT_LIMIT'
+ | 'VAULT_WRITE_FAILED'
+ | 'BROKER_FORBIDDEN'
+ | GhostOauthFlowError;
detail?: string;
};
@@ -185,7 +196,13 @@ export type GhostOauthAccessTokenResult =
* 或指定账号不存在);AUTH_EXPIRED = refresh token 失效需重新授权;
* REFRESH_FAILED / NETWORK = 瞬时失败可重试。
*/
- error: 'NO_CLIENT_CONFIG' | 'NO_ACCOUNT' | 'AUTH_EXPIRED' | 'REFRESH_FAILED' | 'NETWORK';
+ error:
+ | 'NO_CLIENT_CONFIG'
+ | 'NO_ACCOUNT'
+ | 'AUTH_EXPIRED'
+ | 'REFRESH_FAILED'
+ | 'NETWORK'
+ | 'BROKER_FORBIDDEN';
detail?: string;
};
@@ -828,6 +845,10 @@ export class GhostOauthAccountManager {
* 多行)。标签为 null(未声明 identity / 拉取失败)时无从判定,保持追加。
* client 凭证未填直接拒;授权流程失败原样透传结构化错误(设置页据此提示)。
*/
+ private isTokenBrokerAuthorized(ghostId: string): boolean {
+ return this.deps.isTokenBrokerAuthorized?.(ghostId) ?? isBrokerEligibleGhostId(ghostId);
+ }
+
async connectAccount(
ghostId: string,
secretKey: string,
@@ -852,6 +873,13 @@ export class GhostOauthAccountManager {
deliveryHosts?: readonly string[];
},
): Promise<GhostOauthConnectResult> {
+ if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(ghostId)) {
+ return {
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ detail: '当前安装来源或组织身份无权使用授权 broker',
+ };
+ }
if (opts?.clientId !== undefined) {
const allowedClientIds = [decl.clientId, ...(decl.clientIdAlternatives ?? [])];
if (!decl.tokenBroker || !allowedClientIds.includes(opts.clientId)) {
@@ -895,7 +923,7 @@ export class GhostOauthAccountManager {
broker: this.deps.broker,
brandName: this.deps.brandName,
logger: this.deps.logger,
- // 端口回收器只对第一方官方意识放行(与 tokenBroker 连接闸同口径):
+ // 端口回收器只对第一方官方意识放行:
// 回收 = 强杀占用进程,而"杀谁"由 redirectPort 决定——第三方 manifest
// 可声明任意端口(如 5432),放开等于让任意意识借「连接账号」之手
// 强杀用户本地服务(Postgres 等),故第三方一律回落"占用即报错"。
@@ -929,7 +957,7 @@ export class GhostOauthAccountManager {
});
label = identity.label;
display = identity.display;
- // 头像下载只对第一方官方意识放行(与 tokenBroker / 端口回收同口径):
+ // 头像下载只对第一方官方意识放行:
// 头像地址是身份端点响应里的任意 https,不受 hosts 白名单约束——放开
// 等于给第三方意识一个"主机代发 GET + 小图字节回沙箱"的 SSRF 读原语。
// 下载本身不带任何凭证(CDN 域名不在注入白名单);失败降级无头像。
@@ -1134,6 +1162,9 @@ export class GhostOauthAccountManager {
decl: GhostOauthDecl,
accountId?: string,
): Promise<GhostOauthAccessTokenResult> {
+ if (decl.tokenBroker !== undefined && !this.isTokenBrokerAuthorized(ghostId)) {
+ return { ok: false, error: 'BROKER_FORBIDDEN' };
+ }
const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
const resolvedId = accountId ?? manifest.defaultAccountId;
if (!resolvedId) return { ok: false, error: 'NO_ACCOUNT' };
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts b/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts
index a424b2ad50..34d8bca2cd 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthBroker.ts
@@ -1,8 +1,10 @@
/**
* ghostOauthBroker.ts — tokenBroker 声明的 XDT server 授权 broker 调用器。
* ---------------------------------------------------------------------------
- * oauth 详单声明 `tokenBroker: "<slug>"` 的意识(仅第一方,门控在装入闸与
- * 连接闸),code 换 token 与 refresh 不直连服务商 tokenUrl,改经 XDT server
+ * oauth 详单声明 `tokenBroker: "<slug>"` 的意识。静态官方前缀照旧放行;
+ * 其余资格由装入来源与当前组织事实共同判定。校验层保持纯函数不感知装入语境,
+ * 门控在装入闸与连接闸。符合资格后,code 换 token 与 refresh 不直连服务商
+ * tokenUrl,改经 XDT server
* 的授权 broker 端点(`/api/integrations/<slug>/oauth/exchange|refresh`,JWT
* 保护)——client secret 由服务端持有,不随包分发。本模块只做两件事:
* 调 server + 把响应映射成 GhostOauthTokenBundle,授权流程本体仍在
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
index 5bd0617b71..d3a2ad86ab 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts
@@ -76,8 +76,10 @@ export interface GhostOauthClientConfig {
/**
* 可选:XDT server token broker 的 provider slug(如 'jira')。声明后
* code 换 token 与 refresh 不直连 tokenUrl,改经注入的 broker 调用器
- * (client secret 在服务端,不随包分发)。仅第一方官方意识可用,门控在
- * 运行时接线层。broker 模式兼容 PKCE(pkce 缺省开):verifier 经 broker
+ * (client secret 在服务端,不随包分发)。静态官方前缀照旧放行;其余资格由装入
+ * 来源与当前组织事实共同判定。校验层保持纯函数不感知装入语境,门控在运行时
+ * 接线层。broker 模式兼容
+ * PKCE(pkce 缺省开):verifier 经 broker
* exchange 透传到服务端,由 provider 决定是否消费(feishu 要、jira/slack
* 显式声明 pkce:false)。
*/
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 60120d45a9..e9b65107d6 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -292,11 +292,14 @@ import {
type ConnectionAudienceResolver,
} from './connectionAudienceResolver.js';
import {
+ applyGhostFirstPartyFactsOverrides,
loadGhostFirstPartyFactsLoader,
type GhostFirstPartyFactsLoader,
type GhostFirstPartyFactsLoad,
+ type GhostFirstPartyFactsOverrides,
type GhostFirstPartyFactsPurpose,
} from './ghostFirstPartyFacts.js';
+import { authorizeGhostTokenBroker } from './ghostFirstPartyPrivilege.js';
import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';
import { GhostFsSlot } from './fsSlot.js';
import { GhostLibrarySlot } from './librarySlot.js';
@@ -1495,6 +1498,8 @@ export function getGhostManager(): GhostManager {
// 随包批准入口的 builtin-only 边界:id 必须对应一颗随包种子。该入口不经用户
// 确认就铸出批准,不能只靠"唯一调用者是随包对账"这条纪律。
isTrustedBundledId: (id) => listBuiltinSeedIds(builtinSeedRootDirs()).includes(id),
+ isTokenBrokerAuthorized: (manifest) =>
+ isGhostTokenBrokerAuthorized(manifest.id, 'install'),
isTrustedBundledSource,
recordBuiltinTombstone: (id) => recordBuiltinTombstone(brainRootDir(), id, log),
clearBuiltinTombstone: (id) => clearBuiltinTombstone(brainRootDir(), id, log),
@@ -2568,6 +2573,13 @@ function getConnectionAudienceResolver(): ConnectionAudienceResolver {
.find((candidate) => candidate.manifest.id === ghostId)?.manifest ?? null,
readInstalledManifestDigest: readInstalledGhostManifestDigest,
readMarketInstallation: (ghostId) => getPluginMarketLedger().installationForGhost(ghostId),
+ readApprovedPackageSha256: (ghostId) =>
+ getGhostManager().approvedInstallEvidence(ghostId)?.packageSha256 ?? null,
+ readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),
+ lookupOrganizationPrefix: (orgId) =>
+ createOrganizationPrefixStore(
+ ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
+ ).lookup(orgId),
log,
});
}
@@ -2597,6 +2609,7 @@ function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {
createOrganizationPrefixStore(
ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
).lookup(orgId),
+ readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),
});
}
return ghostFirstPartyFactsLoaderSingleton;
@@ -2616,13 +2629,30 @@ function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {
export function loadGhostFirstPartyFactsForGhost(
ghostId: string,
purpose: GhostFirstPartyFactsPurpose,
+ overrides?: GhostFirstPartyFactsOverrides,
): GhostFirstPartyFactsLoad {
const state = getAuthState();
const user = state.isAuthenticated ? state.user : null;
- return getGhostFirstPartyFactsLoader().load(ghostId, purpose, {
- membershipKind: user?.membershipKind ?? 'personal',
- orgId: user?.orgId ?? null,
- });
+ return applyGhostFirstPartyFactsOverrides(
+ getGhostFirstPartyFactsLoader().load(ghostId, purpose, {
+ membershipKind: user?.membershipKind ?? 'personal',
+ orgId: user?.orgId ?? null,
+ }),
+ overrides,
+ );
+}
+
+function isGhostTokenBrokerAuthorized(
+ ghostId: string,
+ purpose: GhostFirstPartyFactsPurpose,
+ overrides?: GhostFirstPartyFactsOverrides,
+): boolean {
+ // Official prefix keeps today's grant without consulting facts.
+ if (isBrokerEligibleGhostId(ghostId)) return true;
+ return authorizeGhostTokenBroker(
+ ghostId,
+ loadGhostFirstPartyFactsForGhost(ghostId, purpose, overrides),
+ );
}
/** Main-memory-only Connection token issuer/cache. */
@@ -4524,8 +4554,9 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
// 意识 OAuth 的 token 端点(Google / Atlassian 等)多在境外。
fetchImpl: (url, init) => outboundFetch(url, init as RequestInit),
openExternal: (url) => shell.openExternal(url),
- // tokenBroker 声明的意识(仅第一方,门控在装入闸与连接闸)经独立
- // oauth-broker 服务换/刷 token:serverApiFetch 自带登录 JWT 注入与
+ // 静态官方前缀照旧放行;其余资格由装入来源与当前组织事实共同判定。
+ // 校验层保持纯函数不感知装入语境,门控在装入闸与连接闸。经独立 oauth-broker
+ // 服务换/刷 token:serverApiFetch 自带登录 JWT 注入与
// TOKEN_EXPIRED 自动刷新。基地址来自运行期端点清单;当前 region 提供该
// 服务时恒指 broker,**不再回退主 server 老路由**
// (2026-07 apiBaseUrl 清理:旧"编译期注入可能为空 → 回退"的分支随
@@ -4586,6 +4617,7 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
return currentDecl !== undefined && isDeepStrictEqual(currentDecl, decl);
},
withMutationLock: withActiveOwnerGhostOauthMutationLock,
+ isTokenBrokerAuthorized: (ghostId) => isGhostTokenBrokerAuthorized(ghostId, 'runtime'),
});
}
return ghostOauthManagerSingleton;
@@ -4713,6 +4745,13 @@ export async function executeGhostSetupAction(args: {
message: '授权声明已变更,请重新尝试',
};
}
+ if (decl.tokenBroker !== undefined && !isGhostTokenBrokerAuthorized(args.ghostId, 'runtime')) {
+ return {
+ ok: false,
+ errorCode: 'AUTH_FAILED',
+ message: '当前安装来源或组织身份无权使用授权 broker',
+ };
+ }
const connected = await getGhostOauthAccountManager().connectAccount(
args.ghostId,
secretKey,
@@ -5210,20 +5249,26 @@ export function rejectReservedGhostIdForCustomMarket(id: string): void {
}
/**
- * tokenBroker 第一方门控·装入闸:oauth 详单声明了 tokenBroker 的意识,XDT
- * server 的授权 broker(带用户登录 JWT 的服务端资产)只对官方前缀 id 开放,
- * 第三方包声明即拒装(连接闸在 /oauth connect 端点二次兜底)。不区分
- * dev/packaged:broker 是服务端资产,dev 也不豁免。
+ * tokenBroker 第一方门控·装入闸。官方前缀命中照今天放行;否则问 first-party
+ * 判据。不区分 dev/packaged:broker 是服务端资产,dev 也不豁免。
*/
-function rejectUnauthorizedTokenBroker(manifest: GhostManifest): void {
+function rejectUnauthorizedTokenBroker(
+ manifest: GhostManifest,
+ overrides?: GhostFirstPartyFactsOverrides,
+): void {
if (isBrokerEligibleGhostId(manifest.id)) return;
const brokered = (manifest.network?.secrets ?? []).some(
(s) => s.oauth?.tokenBroker !== undefined,
);
if (!brokered) return;
+ if (isGhostTokenBrokerAuthorized(manifest.id, 'install', overrides)) return;
+ const reason =
+ overrides?.installOrigin === 'manual'
+ ? '手动装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装,或让插件作者在组织身份下使用 ghost forge 构建'
+ : '当前安装来源或组织身份无权使用授权 broker';
throwIpcError(
'GHOST_FILE_INVALID',
- `id "${manifest.id}" 声明了 oauth.tokenBroker——XDT 授权 broker 仅第一方官方意识可用`,
+ `id "${manifest.id}" 声明了 oauth.tokenBroker——${reason}`,
);
}
@@ -5368,6 +5413,14 @@ export async function installOrUpdateMarketGhostPackage(
permissionPolicy?:
| { mode: 'manual'; sourceType: PluginMarketItemSource }
| { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };
+ /**
+ * Organization server-market packages pass this Host-built fact because the
+ * ledger row is written after install/update. Official-prefix ids never
+ * consult it (they short-circuit). Not "first install only": the same
+ * commitDownloadedPackage path covers org server-market install, update,
+ * defaultInstall, and source replacement.
+ */
+ pendingMarketRecord?: GhostFirstPartyFactsOverrides['marketRecord'];
/** 安装锁内从当前已落位包读取的 canonical 权限基线。 */
permissionBaselineManifest?: GhostManifest;
/** 用户已在页面确认过的权限清单;真实包未超出则跳过 Host。 */
@@ -5399,6 +5452,8 @@ async function installOrUpdateMarketGhostPackageLocked(
permissionPolicy?:
| { mode: 'manual'; sourceType: PluginMarketItemSource }
| { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };
+ /** Same Host-built org server-market fact as the exported entry; not first-install only. */
+ pendingMarketRecord?: GhostFirstPartyFactsOverrides['marketRecord'];
permissionBaselineManifest?: GhostManifest;
reviewedManifest?: GhostManifest;
approvedPackageSha256?: string;
@@ -5531,7 +5586,12 @@ async function installOrUpdateMarketGhostPackageLocked(
throw new GhostPackagePermissionReviewRequiredError(review);
}
}
- rejectUnauthorizedTokenBroker(inspected.canonicalManifest);
+ rejectUnauthorizedTokenBroker(
+ inspected.canonicalManifest,
+ expected.pendingMarketRecord !== undefined
+ ? { marketRecord: expected.pendingMarketRecord }
+ : undefined,
+ );
// Node 高风险条目由 renderer 装入确认卡权限清单如实展示;
// 2026-07-24 Lizi 定案:不再有 Main 侧原生二次确认弹窗(PR #333,本处为其
@@ -6001,6 +6061,7 @@ export function registerGhostIpc(): void {
networkHosts: runtimeManifest.network?.hosts,
manager: getGhostOauthAccountManager(),
ghostId,
+ isTokenBrokerAuthorized: (id) => isGhostTokenBrokerAuthorized(id, 'runtime'),
withMutationLock: withActiveOwnerGhostOauthMutationLock,
onChanged: (secretKey) => {
getGhostSetupChangeBus().emit(ghostId, { source: 'oauth', ref: secretKey });
@@ -6898,7 +6959,6 @@ export function registerGhostIpc(): void {
throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');
}
rejectReservedGhostId(probe.manifest.id);
- rejectUnauthorizedTokenBroker(probe.manifest);
// Node 高风险提示在 renderer 装入确认卡的权限清单里如实展示;
// 2026-07-24 Lizi 定案:不再追加 Main 原生二次确认弹窗。
const enable = installOpts?.enable === true;
@@ -6927,6 +6987,7 @@ export function registerGhostIpc(): void {
throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
}
const installOrigin = forgeInstall.kind === 'agent-forge' ? 'agent-forge' : 'manual';
+ rejectUnauthorizedTokenBroker(probe.manifest, { installOrigin });
return {
ghost: await installAndDock(manager, lizFilePath, {
ghostId: probe.manifest.id,
@@ -6989,7 +7050,6 @@ export function registerGhostIpc(): void {
throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');
}
rejectReservedGhostId(inspected.manifest.id);
- rejectUnauthorizedTokenBroker(inspected.manifest);
// 从熄灯到换版收尾整段持 owner 租约:熄灯之后每一步都在改"当前 owner"的插件世界,
// 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。租约在锁外,
// 与市场/本地装入/卸载共用的按 ghostId 互斥叠加(二者语义不同,决策 A 都保留)。
@@ -7017,6 +7077,7 @@ export function registerGhostIpc(): void {
throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
}
const updateOrigin = forgeUpdate.kind === 'agent-forge' ? 'agent-forge' : 'manual';
+ rejectUnauthorizedTokenBroker(inspected.manifest, { installOrigin: updateOrigin });
return await withGhostInstallLock(inspected.manifest.id, async () => {
const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
runtime.stop(inspected.manifest.id);
@@ -7220,6 +7281,7 @@ export function registerGhostIpc(): void {
const owner = captureGhostMutationOwner();
const result = await manager.inspectInstalledReapproval(id);
if ('rejection' in result) throwInstallError(result.rejection);
+ rejectUnauthorizedTokenBroker(result.manifest);
const inspectTicket = reapproveTickets.issue({
owner,
id,
@@ -7330,9 +7392,12 @@ export function registerGhostIpc(): void {
assertGhostSupportsCurrentCindy(result.canonicalManifest);
// 官方前缀在 inspect 就拒(确认弹窗都不该弹出来),install/update 双保险再拦。
rejectReservedGhostId(result.manifest.id);
- rejectUnauthorizedTokenBroker(result.manifest);
let packTicket: string | undefined;
const inspectController = getForgePackStagingControllerIfConfigured();
+ const peekTicket = inspectController?.peekMatchingStagingPath(lizFilePath) ?? null;
+ rejectUnauthorizedTokenBroker(result.manifest, {
+ installOrigin: peekTicket ? 'agent-forge' : 'manual',
+ });
const forgeInspect = inspectController
? consumeForgePackAtInspect(inspectController, {
filePath: lizFilePath,
@@ -7406,12 +7471,19 @@ export function registerGhostIpc(): void {
inspectPackage: async (filePath) => {
const probe = await manager.inspect(filePath);
if ('rejection' in probe) return false;
- // tokenBroker 门控(同 rejectUnauthorizedTokenBroker):第三方包
- // 声明即不可装入,官方前缀豁免。
+ // tokenBroker 门控(同 rejectUnauthorizedTokenBroker):官方前缀照旧;
+ // 其余问已装 receipt 的装入来源与当前组织身份。
const brokered = (probe.manifest.network?.secrets ?? []).some(
(s) => s.oauth?.tokenBroker !== undefined,
);
- if (brokered && !isBrokerEligibleGhostId(probe.manifest.id)) return false;
+ if (
+ brokered &&
+ !isGhostTokenBrokerAuthorized(probe.manifest.id, 'install', {
+ installOrigin: manager.readEffectiveInstallOrigin(probe.manifest.id),
+ })
+ ) {
+ return false;
+ }
// 指令查重(同 install/update):与当前已装撞名即拒,排除自身。
const commandFold = probe.manifest.command?.toLowerCase();
if (commandFold === undefined) return true;
diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.ts
index 9460b3b081..3d6f7f7acd 100644
--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts
@@ -148,7 +148,13 @@ export interface NetworkSlotDeps {
| { ok: true; accessToken: string; accountId: string }
| {
ok: false;
- error: 'NO_CLIENT_CONFIG' | 'NO_ACCOUNT' | 'AUTH_EXPIRED' | 'REFRESH_FAILED' | 'NETWORK';
+ error:
+ | 'NO_CLIENT_CONFIG'
+ | 'NO_ACCOUNT'
+ | 'AUTH_EXPIRED'
+ | 'REFRESH_FAILED'
+ | 'NETWORK'
+ | 'BROKER_FORBIDDEN';
detail?: string;
}
>;
@@ -1642,6 +1648,8 @@ export class GhostNetworkSlot {
return { error: `凭证「${secret.label}」尚未连接账号(或指定的账号不存在)——请到主界面侧边栏「插件」的本插件详情页点「连接账号」完成授权` };
case 'AUTH_EXPIRED':
return { error: `凭证「${secret.label}」的账号授权已失效——请到主界面侧边栏「插件」的本插件详情页重新连接该账号` };
+ case 'BROKER_FORBIDDEN':
+ return { error: `凭证「${secret.label}」当前身份无权使用授权 broker` };
case 'NETWORK':
return { error: `凭证「${secret.label}」刷新令牌时网络失败,请稍后重试` };
default:
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
index 02ba92ff6d..a061f958ad 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostOauthEndpoint.test.ts
@@ -199,6 +199,40 @@ describe('POST /oauth/<key>/connect', () => {
expect(JSON.parse(outcome.body ?? '{}')).toMatchObject({ ok: false, error: 'TIMEOUT' });
});
+ it('tokenBroker 声明在注入判据返回 false 时被拒,返回 true 时放行', async () => {
+ const brokerDecl: GhostOauthDecl = { ...DECL, tokenBroker: 'feishu' };
+ const secrets = new Map<string, GhostOauthDecl>([['acct', brokerDecl]]);
+ const denied = fakeManager();
+ const forbidden = await handleGhostOauthRequest({
+ method: 'POST',
+ pathname: '/oauth/acct/connect',
+ readBodyText: async () => '',
+ oauthSecrets: secrets,
+ manager: denied,
+ ghostId: 'acme-feishu',
+ isTokenBrokerAuthorized: () => false,
+ });
+ expect(forbidden.status).toBe(200);
+ expect(JSON.parse(forbidden.body ?? '{}')).toMatchObject({
+ ok: false,
+ error: 'BROKER_FORBIDDEN',
+ });
+ expect(denied.connectAccount).not.toHaveBeenCalled();
+
+ const allowed = fakeManager();
+ const ok = await handleGhostOauthRequest({
+ method: 'POST',
+ pathname: '/oauth/acct/connect',
+ readBodyText: async () => '',
+ oauthSecrets: secrets,
+ manager: allowed,
+ ghostId: 'xd-feishu',
+ isTokenBrokerAuthorized: () => true,
+ });
+ expect(ok.status).toBe(200);
+ expect(allowed.connectAccount).toHaveBeenCalled();
+ });
+
it('GET → 405;流程异常 → 500', async () => {
expect((await call({ method: 'GET', pathname: '/oauth/acct/connect' })).status).toBe(405);
expect(
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
index 96d4f553ab..5ab29af614 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
@@ -90,6 +90,8 @@ export async function handleGhostOauthRequest(args: {
networkHosts?: readonly string[];
manager: GhostOauthEndpointManager;
ghostId: string;
+ /** Official prefix first; otherwise first-party resolver. Defaults to official-prefix only. */
+ isTokenBrokerAuthorized?: (ghostId: string) => boolean;
/** Serialize credential/account persistence with package OAuth migration. */
withMutationLock?: <T>(ghostId: string, task: () => Promise<T> | T) => Promise<T>;
/** Successful semantic persistence only; never receives credential values. */
@@ -205,15 +207,16 @@ export async function handleGhostOauthRequest(args: {
if (action === 'connect' && segments.length === 2) {
if (method !== 'POST') return { status: 405 };
- // tokenBroker 第一方门控·连接闸(装入闸的运行时兜底,覆盖 dev 装入等
- // 旁路):XDT 授权 broker 只对官方前缀意识开放。
- if (decl.tokenBroker !== undefined && !isBrokerEligibleGhostId(ghostId)) {
+ // tokenBroker 第一方门控·连接闸。官方前缀命中照今天放行;否则问接线处判据。
+ const brokerAuthorized =
+ args.isTokenBrokerAuthorized?.(ghostId) ?? isBrokerEligibleGhostId(ghostId);
+ if (decl.tokenBroker !== undefined && !brokerAuthorized) {
return {
status: 200,
body: JSON.stringify({
ok: false,
error: 'BROKER_FORBIDDEN',
- detail: 'tokenBroker 仅第一方官方意识可用',
+ detail: '当前安装来源或组织身份无权使用授权 broker',
}),
};
}
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index 82708f0fb1..f05e5ecb8c 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
@@ -1130,6 +1130,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
});
expect(result.ghost?.manifest.id).toBe('alpha');
expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
// 打包产物是临时文件,装完即删
expect(runtime.install.mock.calls[0]?.[0]).toMatch(/cindy-custom-market-alpha-.*\.cindy$/);
expect(fs.existsSync(runtime.install.mock.calls[0]?.[0] as string)).toBe(false);
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index bcfce87670..cc5bdabf39 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -1115,6 +1115,66 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.api.listAll).toHaveBeenCalledTimes(1);
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
expect(ghost?.enabled).toBe(true);
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
+ });
+
+ it('passes a Host-built pendingMarketRecord only for organization server-market packages', async () => {
+ const orgItem = summary({
+ ghostId: 'acme-tool',
+ scope: 'organization',
+ organizationId: 'org-1',
+ source: 'local-market',
+ installed: false,
+ } as Partial<VisiblePluginSummary> & { source: string; installed: boolean });
+ runtime.install.mockResolvedValue({
+ manifest: manifest('acme-tool'),
+ dir: '/userData/cindy-brain/acme-tool',
+ enabled: true,
+ });
+ const orgHarness = harness([orgItem]);
+ await orgHarness.service.install(orgItem.id, {
+ ...reviewedInstallOptions(orgItem),
+ expectedManifest: manifest('acme-tool'),
+ });
+ expect(runtime.install).toHaveBeenCalledWith(
+ expect.stringMatching(/\.cindy$/),
+ expect.objectContaining({
+ pendingMarketRecord: {
+ scope: 'organization',
+ organizationId: 'org-1',
+ source: 'market',
+ installed: true,
+ },
+ }),
+ );
+ const pending = runtime.install.mock.calls[0]?.[1]?.pendingMarketRecord as {
+ source: string;
+ installed: boolean;
+ };
+ expect(pending.source).toBe('market');
+ expect(pending.installed).toBe(true);
+
+ runtime.install.mockReset();
+ const publicItem = summary({ scope: 'public', organizationId: null });
+ runtime.install.mockResolvedValue({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const publicHarness = harness([publicItem]);
+ await publicHarness.service.install(publicItem.id, reviewedInstallOptions(publicItem));
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
+
+ runtime.install.mockReset();
+ const personalItem = summary({ scope: 'personal', organizationId: null });
+ runtime.install.mockResolvedValue({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const personalHarness = harness([personalItem]);
+ await personalHarness.service.install(personalItem.id, reviewedInstallOptions(personalItem));
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('pendingMarketRecord');
});
it('manual market install accepts the normalized setup manifest returned by detail', async () => {
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 09e752a8d5..c49e83ed2b 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -1967,6 +1967,16 @@ export class PluginMarketService {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
...(plugin.ghostId === 'cindy-github' ? { officialCindyGithub: true } : {}),
+ ...(plugin.scope === 'organization' && plugin.organizationId
+ ? {
+ pendingMarketRecord: {
+ scope: plugin.scope,
+ organizationId: plugin.organizationId,
+ source: 'market',
+ installed: true,
+ },
+ }
+ : {}),
...(options.permissionPolicy
? {
permissionPolicy: options.permissionPolicy,
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index bd19c254be..5206bb426c 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -782,8 +782,8 @@ export interface GhostSecretOauthDecl {
* 可选:XDT server token broker 的 provider slug(2026-07-14,xd-atlassian
* 意识化前置)。声明后 code 换 token 与 refresh 不直连 tokenUrl,改经主机
* 调 XDT server 的授权 broker(带登录 JWT;client secret 在服务端,不随包
- * 分发)。与 clientSecret 互斥。**仅第一方官方前缀意识可用**——校验层保持
- * 纯函数不感知装入语境,门控在运行时装入闸与连接闸(cindy-brain)。
+ * 分发)。与 clientSecret 互斥。静态官方前缀照旧放行;其余资格由装入来源与
+ * 当前组织事实共同判定。校验层保持纯函数不感知装入语境,门控在装入闸与连接闸。
*/
tokenBroker?: string;
/**
@@ -1643,15 +1643,15 @@ export function isOfficialGhostId(id: string): boolean {
/**
* 用户装入通道(拖入 / 选文件 / forge 转交)是否拒装该 id。
- * 本阶段与 `isOfficialGhostId` 等价;后续会放宽,让本组织前缀通过。
+ * 当前与 `isOfficialGhostId` 等价;本批不放宽组织前缀。
*/
export function isUserInstallReservedGhostId(id: string): boolean {
return isOfficialGhostId(id);
}
/**
- * 该 id 能否声明 `oauth.tokenBroker`(装入闸与连接闸)。
- * 本阶段与 `isOfficialGhostId` 等价;后续会既放宽又收紧。
+ * 该 id 是否命中 `oauth.tokenBroker` 的静态官方前缀资格。
+ * 非官方资格由运行时 first-party 判据增量放行,不改这张静态表。
*/
export function isBrokerEligibleGhostId(id: string): boolean {
return isOfficialGhostId(id);
@@ -1659,7 +1659,7 @@ export function isBrokerEligibleGhostId(id: string): boolean {
/**
* 该 id 能否拿宿主原语:OAuth 端口回收、身份头像代下载。
- * 本阶段与 `isOfficialGhostId` 等价;后续会收紧。
+ * 仅认静态官方前缀;本轮不随 Broker 资格放宽。
*/
export function isFirstPartyHostPrivilegeGhostId(id: string): boolean {
return isOfficialGhostId(id);
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 0d31815420..da8a1c24bd 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -544,8 +544,8 @@ export interface GhostSecretOauthDecl {
* 可选:服务端 token broker 的 provider slug(2026-07-14 增补)。
* 声明后 code 换 token 与 refresh 不直连 tokenUrl,改经主机
* 调服务端的授权 broker(带登录 JWT;client secret 在服务端,不随包
- * 分发)。与 clientSecret 互斥。**仅第一方官方前缀意识可用**——校验层保持
- * 纯函数不感知装入语境,门控在运行时装入闸与连接闸(cindy-brain)。
+ * 分发)。与 clientSecret 互斥。静态官方前缀照旧放行;其余资格由装入来源与
+ * 当前组织事实共同判定。校验层保持纯函数不感知装入语境,门控在装入闸与连接闸。
*/
tokenBroker?: string;
/**