Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): preserve market authorization boundaries
liugaowei863b3ff642c1
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 044f8c2bd3..f36a57bfc5 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -43,6 +43,7 @@ import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';import { checkSkillMdConsistency } from './skillSlot.js';import {createGhostInstallReceipt,+ effectiveInstallOrigin,GhostInstallReceiptStore,hashApprovedSkillContent,readLegacyInstallTrust,@@ -1022,6 +1023,18 @@ export class GhostManager {return this.receiptStore.rootDir();}+ /** 新安装不再写来源;这里只识别旧 receipt,避免存量 Forge Broker 资格断裂。 */+ 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@@ -2831,6 +2844,11 @@ export class GhostManager {},};}+ const legacyInstallOrigin =+ approvalResult.state === 'approved' &&+ effectiveInstallOrigin(approvalResult.receipt) === 'agent-forge'+ ? 'agent-forge'+ : undefined;// 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时,重新安装仍采用原// `.disabled` 镜像;损坏 receipt 一律保持停用。const enabled =@@ -3005,6 +3023,7 @@ export class GhostManager {packageSha256,revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ ...(legacyInstallOrigin ? { installOrigin: legacyInstallOrigin } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });} catch (err) {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.tsindex 28e5dbb335..41f459b5d8 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts@@ -60,6 +60,7 @@ function loader(overrides: Partial<LoadGhostFirstPartyFactsLoaderOptions> = {})readMarketInstallation: () => null,readApprovedPackageSha256: () => null,lookupOrganizationPrefix: () => ({ kind: 'absent' }),+ readInstallOrigin: () => 'manual',...overrides,});}@@ -82,6 +83,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {builtin: true,marketRecord: null,currentOrganization: null,+ installOrigin: 'manual',});expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({brokerEligible: true,@@ -163,6 +165,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {builtin: false,marketRecord: null,currentOrganization: null,+ installOrigin: 'manual',},});});@@ -210,6 +213,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {builtin: false,marketRecord: null,currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },+ installOrigin: 'manual',},});});@@ -235,6 +239,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {approvedPackageSha256: MARKET_ROW.sha256,},currentOrganization: { organizationId: 'org-a', pluginPrefix: null },+ installOrigin: 'manual',},});});@@ -285,6 +290,7 @@ describe('loadGhostFirstPartyFactsLoader', () => {inspectedPackageSha256,),currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },+ installOrigin: 'manual' as const,},});@@ -308,4 +314,25 @@ describe('loadGhostFirstPartyFactsLoader', () => {});});+ it('copies only the legacy Forge origin and fails closed when it cannot be read', () => {+ const forged = loader({+ readInstallOrigin: () => 'agent-forge',+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),+ }).load('acme-tool', 'runtime', ORG_A);+ expect(forged).toMatchObject({+ kind: 'ready',+ facts: { installOrigin: 'agent-forge' },+ });++ const unreadable = loader({+ readInstallOrigin: () => {+ throw new Error('EACCES');+ },+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),+ }).load('acme-tool', 'runtime', ORG_A);+ expect(unreadable).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.tsindex f94565bd5d..a2f3972853 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts@@ -30,6 +30,7 @@ function facts(partial: Partial<GhostFirstPartyFacts> & Pick<GhostFirstPartyFactbuiltin: false,marketRecord: null,currentOrganization: null,+ installOrigin: 'manual',...partial,};}@@ -313,6 +314,45 @@ describe('resolveGhostFirstPartyPrivilege', () => {});});+ it('keeps Broker only for a legacy Forge receipt under the current organization prefix', () => {+ expect(+ resolveGhostFirstPartyPrivilege(+ facts({+ ghostId: 'acme-feishu',+ currentOrganization: CURRENT_ORG,+ installOrigin: 'agent-forge',+ }),+ ),+ ).toEqual({+ brokerEligible: true,+ hostPrimitiveEligible: false,+ basis: 'legacy-forge-current-org-prefix',+ });+ expect(+ resolveGhostFirstPartyPrivilege(+ facts({+ ghostId: 'acme-feishu',+ marketRecord: market({+ scope: 'personal',+ organizationId: null,+ source: 'local-market',+ }),+ currentOrganization: CURRENT_ORG,+ installOrigin: 'agent-forge',+ }),+ ).brokerEligible,+ ).toBe(true);+ expect(+ resolveGhostFirstPartyPrivilege(+ facts({+ ghostId: 'other-feishu',+ currentOrganization: CURRENT_ORG,+ installOrigin: 'agent-forge',+ }),+ ).brokerEligible,+ ).toBe(false);+ });+// 台账里有这条 id 但 installed 为 false 时,曾经会整段跳过市场分支、落到末尾那条// 「本地包 + 本组织前缀 → 放行」的兜底。于是同一条 `scope: 'personal'` 记录// (明确不可信)把 installed 从 true 改成 false,结论就从 deny 翻成 allow ——diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex e5855a743f..c02fba6265 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -8,6 +8,7 @@ import { validateGhostManifest } from '../../../shared/ghost';import {createGhostInstallReceipt,+ effectiveInstallOrigin,type GhostInstallReceipt,GhostInstallReceiptStore,} from '../ghostInstallReceipt';@@ -19,8 +20,9 @@ describe('GhostInstallReceiptStore cleanup', () => {beforeEach(async () => {workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-cleanup-'));- stateRoot = path.join(workDir, 'state');- await fs.promises.mkdir(stateRoot);+ const rawStateRoot = path.join(workDir, 'state');+ await fs.promises.mkdir(rawStateRoot);+ stateRoot = await fs.promises.realpath(rawStateRoot);store = new GhostInstallReceiptStore(() => stateRoot, async ({ parentDir, targetName, operation }) => {if (operation === 'remove') await fs.promises.rm(path.join(parentDir, targetName), { recursive: true, force: true });});@@ -227,6 +229,21 @@ describe('GhostInstallReceiptStore cleanup', () => {});});+ it('preserves only the legacy Forge origin as an effective authorization fact', async () => {+ await store.write(+ createGhostInstallReceipt({+ ...createSetupReceipt(),+ installOrigin: 'agent-forge',+ }),+ );++ const read = store.read('hello');+ expect(read.state).toBe('approved');+ if (read.state !== 'approved') return;+ expect(effectiveInstallOrigin(read.receipt)).toBe('agent-forge');+ expect(effectiveInstallOrigin({ installOrigin: 'future-origin' })).toBe('manual');+ });+it('treats only a missing migration marker as absent', () => {expect(store.hasMigrationMarker('hello')).toBe(false);});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex c3c21de54a..bb87e94581 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -14,6 +14,31 @@ describe('market Ghost session boundary', () => {resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),'utf8',).replace(/\r\n/g, '\n');+ const marketServiceSource = readFileSync(+ resolve(process.cwd(), 'src/main/plugin-market/service.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('keeps automatic custom updates bound to the owner captured by synchronization', () => {+ const installStart = marketServiceSource.indexOf(' private async customInstall(');+ const installEnd = marketServiceSource.indexOf(+ '\n private async installDetail(',+ installStart,+ );+ const installBody = marketServiceSource.slice(installStart, installEnd);+ const automaticStart = marketServiceSource.indexOf(' private async applyAutomaticUpgrades(');+ const automaticEnd = marketServiceSource.indexOf(+ '\n private localInstallSnapshot(',+ automaticStart,+ );+ const automaticBody = marketServiceSource.slice(automaticStart, automaticEnd);++ expect(installBody).toContain('owner = captureMarketOwner(),');+ expect(installBody).toContain('const ledger = this.ledgerForOwner(owner);');+ expect(installBody).toContain('const manager = this.sourceManagerForOwner(owner);');+ expect(installBody).toContain('requireSameMarketOwner(owner);');+ expect(automaticBody).toContain(' true,\n owner,\n );');+ });it('requires the pre-approval session generation when acquiring the mutation lease', () => {const captureStart = source.indexOf(diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.tsindex eb64dfc401..2c0c97f4fc 100644--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts@@ -63,6 +63,8 @@ export interface LoadGhostFirstPartyFactsLoaderOptions {/** Missing or legacy package evidence must return null. */readApprovedPackageSha256(ghostId: string): string | null;lookupOrganizationPrefix(orgId: string): OrganizationPrefixLookup;+ /** 新安装返回 manual;仅旧 receipt 会返回 agent-forge。 */+ readInstallOrigin(ghostId: string): 'manual' | 'agent-forge';}function actionFor(purpose: GhostFirstPartyFactsPurpose): GhostFirstPartyFactsUnavailableAction {@@ -101,6 +103,7 @@ export function bindPendingMarketRecordToInspectedPackage(}export type GhostFirstPartyFactsOverrides = {+ installOrigin?: 'manual' | 'agent-forge';marketRecord?: GhostFirstPartyMarketRecord | null;};@@ -113,6 +116,7 @@ export function applyGhostFirstPartyFactsOverrides(kind: 'ready',facts: {...load.facts,+ ...(overrides.installOrigin !== undefined ? { installOrigin: overrides.installOrigin } : {}),...(overrides.marketRecord !== undefined ? { marketRecord: overrides.marketRecord } : {}),},};@@ -152,6 +156,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',@@ -160,6 +171,7 @@ export function loadGhostFirstPartyFactsLoader(builtin,marketRecord,currentOrganization: null,+ installOrigin,},};}@@ -181,7 +193,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;@@ -203,6 +215,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.tsindex ed9f79aa7c..9262ab0abf 100644--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts@@ -47,6 +47,7 @@ export type GhostFirstPartyBasis =| 'builtin-official'| 'market-public'| 'market-organization-current'+ | 'legacy-forge-current-org-prefix'| 'denied-alias'| 'denied-foreign-org'| 'denied-unknown-origin';@@ -79,6 +80,8 @@ export interface GhostFirstPartyFacts {builtin: boolean;marketRecord: GhostFirstPartyMarketRecord | null;currentOrganization: GhostFirstPartyCurrentOrganization | null;+ /** 仅来自升级前 receipt;新安装恒为 manual。 */+ installOrigin: 'manual' | 'agent-forge';}function matchesCurrentOrgPrefix(@@ -185,9 +188,23 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Gh}return allow('market-organization-current', false);}+ if (+ facts.installOrigin === 'agent-forge' &&+ (record.source === 'git-market' || record.source === 'local-market') &&+ matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)+ ) {+ return allow('legacy-forge-current-org-prefix', false);+ }return deny('denied-unknown-origin');}+ if (+ facts.installOrigin === 'agent-forge' &&+ matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)+ ) {+ return allow('legacy-forge-current-org-prefix', false);+ }+return deny('denied-unknown-origin');}diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex a36e417c84..78d733732e 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -65,6 +65,11 @@ export interface GhostInstallReceipt {* 重算可变安装目录的整包字节,所以不要据此认为安装内容持续完整。*/packageSha256?: string;+ /**+ * 旧版 Forge 安装写入的来源标记。新安装不再写入;保留只读是为了让升级前+ * 已获 Broker 资格的存量插件不会在客户端升级后突然失效。+ */+ installOrigin?: string;/*** 按 skill item 目录钉住的固化字节指纹(`item.dir` → sha256)。声明了 skill 能力* 时逐项必填,没声明时是空对象。@@ -1020,7 +1025,11 @@ export function createGhostInstallReceipt(input: {packageSha256?: string;revision?: string;iconDataUrl?: string;+ installOrigin?: string;}): GhostInstallReceipt {+ if (input.installOrigin !== undefined && !isPersistableInstallOrigin(input.installOrigin)) {+ throw new Error('receipt installOrigin 不合法');+ }return {schemaVersion: RECEIPT_SCHEMA_VERSION,id: input.manifest.id,@@ -1032,9 +1041,28 @@ export function createGhostInstallReceipt(input: {skillContentSha256: input.skillContentSha256,...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),+ ...(input.installOrigin !== undefined ? { installOrigin: input.installOrigin } : {}),};}+const MAX_INSTALL_ORIGIN_CHARS = 64;+const INSTALL_ORIGIN_PATTERN = /^[a-z0-9-]+$/;++function isPersistableInstallOrigin(value: string): boolean {+ return (+ value.length > 0 &&+ value.length <= MAX_INSTALL_ORIGIN_CHARS &&+ INSTALL_ORIGIN_PATTERN.test(value)+ );+}++/** 旧 receipt 的授权视图:只有历史 agent-forge 值有效,其余一律降级。 */+export function effectiveInstallOrigin(+ receipt: Pick<GhostInstallReceipt, 'installOrigin'>,+): 'manual' | 'agent-forge' {+ return receipt.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual';+}+/*** 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。*@@ -1164,6 +1192,16 @@ function validateReceipt(if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };localeResources[localePath] = validated.resource;}+ let installOrigin: string | undefined;+ if (value.installOrigin !== undefined) {+ if (+ typeof value.installOrigin !== 'string' ||+ !isPersistableInstallOrigin(value.installOrigin)+ ) {+ return { ok: false, reason: 'receipt installOrigin 不合法' };+ }+ installOrigin = value.installOrigin;+ }return {ok: true,receipt: {@@ -1177,6 +1215,7 @@ function validateReceipt(skillContentSha256,...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),+ ...(installOrigin !== undefined ? { installOrigin } : {}),},};}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex f61740cb41..4184a8c305 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -26,6 +26,7 @@ import {GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,GHOST_NOTIFY_MIN_INTERVAL_MS,ghostInstallApprovalToken,+ ghostNetworkAuthorizationWithinCap,isGhostInstallApprovalToken,ghostAppContextLocale,unreviewedGhostPermissionItems,@@ -2586,6 +2587,7 @@ function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {createOrganizationPrefixStore(ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),).lookup(orgId),+ readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),});}return ghostFirstPartyFactsLoaderSingleton;@@ -5642,7 +5644,10 @@ async function installOrUpdateMarketGhostPackageLocked(undefined,inspected.canonicalManifest,);- if (undeclaredCapabilities.length > 0) {+ if (+ undeclaredCapabilities.length > 0 ||+ !ghostNetworkAuthorizationWithinCap(expected.manifestCap, inspected.canonicalManifest)+ ) {log.warn('market package exceeds catalog manifest capabilities', {ghostId: expected.ghostId,keys: undeclaredCapabilities.map((item) => item.key),diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.tsindex 40b6fe0953..b575b87680 100644--- a/apps/desktop/src/main/plugin-market/install.ts+++ b/apps/desktop/src/main/plugin-market/install.ts@@ -15,6 +15,7 @@ import crypto from 'node:crypto';import { app } from 'electron';import {+ ghostNetworkAuthorizationWithinCap,unreviewedGhostPermissionItems,validateGhostManifest,type GhostManifest,@@ -193,7 +194,10 @@ export async function installCustomMarketPlugin(input: {undefined,inspected.canonicalManifest,);- if (extraCapabilities.length > 0) {+ if (+ extraCapabilities.length > 0 ||+ !ghostNetworkAuthorizationWithinCap(validated.manifest, inspected.canonicalManifest)+ ) {throwIpcError('GHOST_FILE_INVALID','The packaged Plugin capabilities exceed the selected market manifest',diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 15a693e29a..0d6b1a16ed 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -13,6 +13,7 @@ import { app, dialog } from 'electron';import {GHOST_ICON_MAX_BYTES,+ ghostNetworkAuthorizationWithinCap,ghostInstallApprovalToken,ghostIconMimeType,isSafeGhostRelativePath,@@ -1248,6 +1249,7 @@ export class PluginMarketService {ref: { marketName: string; ghostId: string },options: PluginMarketInstallOptions,automatic = false,+ owner = captureMarketOwner(),): Promise<PluginMarketInstallResult> {if (options.expectedManifest === undefined) {throwIpcError(@@ -1255,7 +1257,6 @@ export class PluginMarketService {'Custom Plugin install must be bound to the selected manifest',);}- const owner = captureMarketOwner();const ledger = this.ledgerForOwner(owner);const manager = this.sourceManagerForOwner(owner);// 互斥键与 uninstall 一致使用规范化 pluginId,保证同插件的安装/更新/卸载串行。@@ -1747,7 +1748,10 @@ export class PluginMarketService {undefined,inspected.canonicalManifest,);- if (extraCapabilities.length > 0) {+ if (+ extraCapabilities.length > 0 ||+ !ghostNetworkAuthorizationWithinCap(manifestCap, inspected.canonicalManifest)+ ) {throwIpcError('GHOST_FILE_INVALID','Downloaded Plugin package capabilities exceed the market manifest',@@ -2474,6 +2478,7 @@ export class PluginMarketService {allowSourceReplacement: false,},true,+ owner,);local = this.localInstallSnapshot(ledger);this.clearAutomaticUpgradeFailure(retryKey, releaseKey);diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 24847e6ecb..6ea58a5a9a 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -13,6 +13,7 @@ import {ghostContentKeys,ghostExternalLinkUrls,ghostLocalePathFor,+ ghostNetworkAuthorizationWithinCap,ghostNetworkHostMatches,ghostPanelKind,ghostPermissionBaselineKey,@@ -4370,6 +4371,55 @@ describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {});describe('ghostPermissionProjectionFingerprint', () => {+ it('market cap compares network credential injection semantics, not only display items', () => {+ const reviewed = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'model', 'network'],+ settingsHtml: 'settings.html',+ network: {+ hosts: ['api.example.com', 'upload.example.com'],+ secrets: [+ {+ key: 'api_token',+ label: 'API Token',+ inject: {+ hosts: ['api.example.com'],+ header: 'Authorization',+ format: 'Bearer {value}',+ },+ },+ ],+ },+ });+ const actual = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'model', 'network'],+ settingsHtml: 'settings.html',+ network: {+ hosts: ['api.example.com', 'upload.example.com'],+ secrets: [+ {+ key: 'api_token',+ label: 'API Token',+ inject: {+ hosts: ['upload.example.com'],+ header: 'Authorization',+ format: 'Bearer {value}',+ },+ },+ ],+ },+ });+ expect(reviewed.ok && actual.ok).toBe(true);+ if (!reviewed.ok || !actual.ok) return;++ expect(unreviewedGhostPermissionItems(reviewed.manifest, undefined, actual.manifest)).toEqual(+ [],+ );+ expect(ghostNetworkAuthorizationWithinCap(reviewed.manifest, actual.manifest)).toBe(false);+ expect(ghostNetworkAuthorizationWithinCap(reviewed.manifest, reviewed.manifest)).toBe(true);+ });+it('same-key/different-labelArgs 同时作废 baseline、diff 与真实包复核', () => {const reviewed = validateGhostManifest({...goodChipManifest(),diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 3fba76473d..ca609edbd6 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -2459,6 +2459,69 @@ export function unreviewedGhostPermissionItems();}+/**+ * 市场清单对真实包的 network 授权语义上限。+ *+ * `ghostPermissionItems` 是给人看的能力投影,不能作为凭证流向的安全判据:+ * 同一 secret 改写 inject.hosts、header、exchange 或 OAuth 目标时,展示项可能+ * 完全相同。这里单独比较 Host 真正消费的字段;允许真实包少声明 host/secret/+ * connection,但不能扩大任何一项。+ */+export function ghostNetworkAuthorizationWithinCap(+ reviewed: GhostManifest,+ actual: GhostManifest,+): boolean {+ const actualNetwork = actual.network;+ if (!actualNetwork) return true;+ const reviewedNetwork = reviewed.network;+ if (!reviewedNetwork) return false;++ const isStringSubset = (values: readonly string[], cap: readonly string[]): boolean =>+ values.every((value) => cap.includes(value));+ if (!isStringSubset(actualNetwork.hosts, reviewedNetwork.hosts)) return false;++ const reviewedSecrets = new Map(+ (reviewedNetwork.secrets ?? []).map((secret) => [secret.key, secret] as const),+ );+ for (const secret of actualNetwork.secrets ?? []) {+ const cap = reviewedSecrets.get(secret.key);+ if (!cap || (secret.source ?? 'user') !== (cap.source ?? 'user')) return false;+ if (secret.inject.header !== cap.inject.header || secret.inject.format !== cap.inject.format) {+ return false;+ }+ const actualHosts = secret.inject.hosts ?? actualNetwork.hosts;+ const reviewedHosts = cap.inject.hosts ?? reviewedNetwork.hosts;+ if (!isStringSubset(actualHosts, reviewedHosts)) return false;+ if (secret.url !== undefined && secret.url !== cap.url) return false;+ if (+ secret.exchange !== undefined &&+ JSON.stringify(secret.exchange) !== JSON.stringify(cap.exchange)+ ) {+ return false;+ }+ if (secret.oauth !== undefined && JSON.stringify(secret.oauth) !== JSON.stringify(cap.oauth)) {+ return false;+ }+ }++ const reviewedConnections = new Map(+ (reviewedNetwork.connections ?? []).map((connection) => [connection.key, connection] as const),+ );+ for (const connection of actualNetwork.connections ?? []) {+ const cap = reviewedConnections.get(connection.key);+ if (!cap) return false;+ if (+ connection.inject.header !== cap.inject.header ||+ connection.inject.format !== cap.inject.format ||+ (connection.maxConnections ?? GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL) >+ (cap.maxConnections ?? GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL)+ ) {+ return false;+ }+ }+ return true;+}+/*** icon 允许的图片扩展名 → mime(校验与 main 读盘供图共用同一口径)。* 不收 svg:svg 可携带脚本,虽经 <img> 渲染不执行,仍不给这个面。