Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): enforce broker redirect ports at admission
fmfsaisaie16f27046516
diff --git a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts b/apps/desktop/src/main/__tests__/installedGhostManifest.test.tsindex 0c2f937a44..204ed9ab88 100644--- a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts+++ b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts@@ -24,6 +24,32 @@ function manifest(id = 'legacy-plugin'): Record<string, unknown> {};}+function legacyBrokerManifest(): Record<string, unknown> {+ return {+ ...manifest('legacy-broker'),+ slots: ['network'],+ tools: undefined,+ settingsHtml: 'settings.html',+ network: {+ hosts: ['accounts.example.com'],+ secrets: [+ {+ key: 'account',+ label: 'Account',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.example.com/authorize',+ tokenUrl: 'https://accounts.example.com/token',+ clientId: 'builtin-client-id',+ tokenBroker: 'jira',+ },+ },+ ],+ },+ };+}+afterEach(() => {for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });});@@ -65,6 +91,17 @@ describe('installed ghost manifest compatibility', () => {expect(parsed.ok).toBe(false);});+ it('keeps an installed legacy broker manifest readable when redirectPort was never declared', () => {+ const parsed = parseInstalledGhostManifest(legacyBrokerManifest());++ expect(parsed.ok).toBe(true);+ if (!parsed.ok) return;+ expect(parsed.manifest.network?.secrets?.[0]?.oauth).toMatchObject({+ tokenBroker: 'jira',+ });+ expect(parsed.manifest.network?.secrets?.[0]?.oauth?.redirectPort).toBeUndefined();+ });+it('reads an installed ghost.json through the bounded compatibility path', () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-manifest-'));roots.push(root);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 557f948256..9cf5d73509 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -18,7 +18,7 @@ import {unixPermissionsForRepackedEntry,} from '../ghostZipPermissions';import { signGhostPackage } from '../ghostSignature';-import { hashApprovedSkillContent } from '../ghostInstallReceipt';+import { GhostInstallReceiptStore, hashApprovedSkillContent } from '../ghostInstallReceipt';import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess';/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */@@ -3310,6 +3310,62 @@ describe('GhostManager · Host approval receipt', () => {'---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',});+ it('keeps a legacy broker receipt approved and present in list without redirectPort', async () => {+ const legacyBrokerManifest = {+ ...goodManifest('legacy-broker'),+ slots: ['network'],+ tools: undefined,+ settingsHtml: 'settings.html',+ network: {+ hosts: ['accounts.example.com'],+ secrets: [+ {+ key: 'account',+ label: 'Account',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.example.com/authorize',+ tokenUrl: 'https://accounts.example.com/token',+ clientId: 'builtin-client-id',+ tokenBroker: 'jira',+ },+ },+ ],+ },+ };+ const installed = await manager.install(+ await makeCindy('legacy-broker.cindy', legacyBrokerManifest, {+ 'main.js': '// previously installed broker plugin',+ }),+ );+ expect(installed).toMatchObject({ ghost: { approval: { state: 'approved' } } });++ // stateRoot 必须先规范化再交给 store,避免 macOS /var 别名制造假失败。+ const stateRoot = fs.realpathSync.native(path.join(workDir, 'ghosts-install-state'));+ const receiptStore = new GhostInstallReceiptStore(+ () => stateRoot,+ async ({ parentDir, targetName, operation }) => {+ if (operation === 'remove') {+ await fs.promises.rm(path.join(parentDir, targetName), {+ recursive: true,+ force: true,+ });+ }+ },+ );+ expect(receiptStore.read('legacy-broker')).toMatchObject({ state: 'approved' });++ // 新进程从盘上回读仍须投影该插件;若规则误放回共用 validator,这里会消失。+ const restarted = new GhostManager({ getRootDir: () => rootDir });+ expect(restarted.list()).toEqual([+ expect.objectContaining({+ manifest: expect.objectContaining({ id: 'legacy-broker' }),+ approval: expect.objectContaining({ state: 'approved' }),+ }),+ ]);+ });+it('rejects an approved snapshot root replaced by a same-bytes link', async () => {await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));const ghost = manager.list()[0];diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 16501b195c..ce3d09c825 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -147,6 +147,51 @@ async function makeSrcDir(files: Record<string, string | Buffer>): Promise<strin}describe('packGhostDir', () => {+ it('rejects a new tokenBroker package without redirectPort but accepts the declared-port shape', async () => {+ const brokerManifest = {+ ...GOOD_MANIFEST,+ slots: ['network'],+ tools: undefined,+ settingsHtml: 'settings.html',+ network: {+ hosts: ['accounts.example.com'],+ secrets: [+ {+ key: 'account',+ label: 'Account',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.example.com/authorize',+ tokenUrl: 'https://accounts.example.com/token',+ clientId: 'builtin-client-id',+ tokenBroker: 'jira',+ },+ },+ ],+ },+ };+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(brokerManifest),+ 'main.js': '// broker plugin',+ 'settings.html': '<main>settings</main>',+ });++ await expect(packGhostDir(dir)).resolves.toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: expect.stringContaining('同一项 oauth 中声明 redirectPort'),+ });+ expect(fs.existsSync(path.join(dir, 'demo-1.0.0.cindy'))).toBe(false);++ const secret = brokerManifest.network.secrets[0] as {+ oauth: Record<string, unknown>;+ };+ secret.oauth.redirectPort = 17872;+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(brokerManifest));+ await expect(packGhostDir(dir)).resolves.toMatchObject({ ok: true });+ });+it.skipIf(process.platform === 'win32')('archives real Unix execute bits while stripping special bits',async () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostBrokerRedirectPort.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostBrokerRedirectPort.test.tsnew file mode 100644index 0000000000..e96d75491f--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostBrokerRedirectPort.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';++import { validateGhostManifest, type GhostManifest } from '../../../shared/ghost.js';+import { ghostBrokerRedirectPortInstallError } from '../ghostBrokerRedirectPort.js';++function brokerManifest(redirectPort?: number): GhostManifest {+ const parsed = validateGhostManifest({+ schemaVersion: 2,+ id: 'broker-plugin',+ name: 'Broker plugin',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['network'],+ settingsHtml: 'settings.html',+ network: {+ hosts: ['accounts.example.com'],+ secrets: [+ {+ key: 'account',+ label: 'Account',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.example.com/authorize',+ tokenUrl: 'https://accounts.example.com/token',+ clientId: 'builtin-client-id',+ tokenBroker: 'jira',+ ...(redirectPort === undefined ? {} : { redirectPort }),+ },+ },+ ],+ },+ });+ if (!parsed.ok) throw new Error(parsed.reason);+ return parsed.manifest;+}++describe('ghostBrokerRedirectPortInstallError', () => {+ it('classifies a new broker package without redirectPort on its own actionable IPC code', () => {+ expect(ghostBrokerRedirectPortInstallError(brokerManifest())).toEqual({+ code: 'GHOST_BROKER_REDIRECT_PORT_REQUIRED',+ reason: expect.stringContaining('同一项 oauth 中声明 redirectPort'),+ });+ });++ it('does not require one global port value or widen the rule to non-broker OAuth', () => {+ // 任意合法声明值都通过,排除“偷偷钉死某个 provider 端口”的错实现。+ expect(ghostBrokerRedirectPortInstallError(brokerManifest(17872))).toBeNull();++ const plain = brokerManifest(17872);+ const oauth = plain.network?.secrets?.[0]?.oauth;+ if (!oauth) throw new Error('expected OAuth fixture');+ delete oauth.tokenBroker;+ delete oauth.redirectPort;+ // 普通 OAuth 可用随机 loopback 端口,排除“所有 OAuth 都必须声明”的错实现。+ expect(ghostBrokerRedirectPortInstallError(plain)).toBeNull();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 99504fedc7..e8eff2782b 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -54,6 +54,7 @@ import {unixRegularFilePermissionsForArchive,} from './ghostZipPermissions.js';import { isPathInsideDir } from './dirDeposit.js';+import { brokerRedirectPortDeclarationIssue } from './ghostBrokerRedirectPort.js';import { checkSkillMdConsistency } from './skillSlot.js';/**@@ -625,6 +626,10 @@ export async function scaffoldGhostDir(if (!validation.ok) {return { ok: false, errorCode: 'INVALID_INPUT', message: `插件信息不合格:${validation.reason}` };}+ const brokerPortIssue = brokerRedirectPortDeclarationIssue(validation.manifest);+ if (brokerPortIssue) {+ return { ok: false, errorCode: 'INVALID_INPUT', message: `插件信息不合格:${brokerPortIssue}` };+ }try {await fs.promises.lstat(targetDir);@@ -802,6 +807,10 @@ async function buildGhostPackage(if (!v.ok) {return { ok: false, errorCode: 'MANIFEST_INVALID', message: `清单不合格:${v.reason}` };}+ const brokerPortIssue = brokerRedirectPortDeclarationIssue(v.manifest);+ if (brokerPortIssue) {+ return { ok: false, errorCode: 'MANIFEST_INVALID', message: `清单不合格:${brokerPortIssue}` };+ }if (manifestBytes.byteLength > GHOST_INSTALL_MANIFEST_MAX_BYTES) {return {ok: false,diff --git a/apps/desktop/src/main/cindy-brain/ghostBrokerRedirectPort.ts b/apps/desktop/src/main/cindy-brain/ghostBrokerRedirectPort.tsnew file mode 100644index 0000000000..3906656149--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostBrokerRedirectPort.ts@@ -0,0 +1,31 @@+import type { GhostManifest } from '../../shared/ghost.js';+import type { IpcErrorCode } from '../../shared/ipc-errors.js';++export const BROKER_REDIRECT_PORT_REQUIRED_REASON =+ '声明 oauth.tokenBroker 时必须在同一项 oauth 中声明 redirectPort,确保授权最后一跳能回到本机监听端口';++/**+ * 新包准入检查:broker 的最终回跳必须有清单声明的本机监听端口。+ *+ * 不要把它并回 validateGhostManifest。后者还承担批准 receipt 与已装目录的+ * 兼容读取;旧包缺少该字段时仍须可读,只在新包进入 Forge / 安装通道时拒绝。+ */+export function brokerRedirectPortDeclarationIssue(manifest: GhostManifest): string | null {+ const missing = (manifest.network?.secrets ?? []).some(+ (secret) => secret.oauth?.tokenBroker !== undefined && secret.oauth.redirectPort === undefined,+ );+ return missing ? BROKER_REDIRECT_PORT_REQUIRED_REASON : null;+}++export interface GhostBrokerRedirectPortInstallError {+ code: Extract<IpcErrorCode, 'GHOST_BROKER_REDIRECT_PORT_REQUIRED'>;+ reason: string;+}++/** IPC 装入通道的结构化错误;Renderer 只按 code 选择本地化文案。 */+export function ghostBrokerRedirectPortInstallError(+ manifest: GhostManifest,+): GhostBrokerRedirectPortInstallError | null {+ const reason = brokerRedirectPortDeclarationIssue(manifest);+ return reason ? { code: 'GHOST_BROKER_REDIRECT_PORT_REQUIRED', reason } : null;+}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 36fe166931..e7853b3e90 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -304,6 +304,7 @@ import {} from './ghostFirstPartyFacts.js';import { authorizeGhostTokenBroker } from './ghostFirstPartyPrivilege.js';import { ghostTokenBrokerInstallError } from './ghostTokenBrokerInstallError.js';+import { ghostBrokerRedirectPortInstallError } from './ghostBrokerRedirectPort.js';import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';import { GhostFsSlot } from './fsSlot.js';import { GhostLibrarySlot } from './librarySlot.js';@@ -5277,6 +5278,12 @@ function rejectUnauthorizedTokenBroker();}+/** 新包装入准入;批准 receipt / 已装目录回读不经过这里。 */+function rejectBrokerWithoutDeclaredRedirectPort(manifest: GhostManifest): void {+ const error = ghostBrokerRedirectPortInstallError(manifest);+ if (error) throwIpcError(error.code, error.reason);+}+/** install 失败分类 → IPC 错误码。 */function throwInstallError(rejection: InstallRejection): never {switch (rejection.code) {@@ -7405,6 +7412,7 @@ export function registerGhostIpc(): void {let packTicket: string | undefined;const inspectController = getForgePackStagingControllerIfConfigured();const peekTicket = inspectController?.peekMatchingStagingPath(lizFilePath) ?? null;+ rejectBrokerWithoutDeclaredRedirectPort(result.manifest);rejectUnauthorizedTokenBroker(result.manifest, {installOrigin: peekTicket ? 'agent-forge' : 'manual',});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 600370037b..23d44e8e27 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -187,6 +187,31 @@ function setupSecretManifest(id = 'cindy-test', version = '1.0.0') {};}+function brokerManifestWithoutPort(id = 'cindy-test', version = '1.0.0') {+ return {+ ...manifest(id, version),+ slots: ['network'],+ settingsHtml: 'settings.html',+ network: {+ hosts: ['accounts.example.com'],+ secrets: [+ {+ key: 'account',+ label: 'Account',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.example.com/authorize',+ tokenUrl: 'https://accounts.example.com/token',+ clientId: 'builtin-client-id',+ tokenBroker: 'jira',+ },+ },+ ],+ },+ };+}+function normalizedManifest(raw: unknown): GhostManifest {const validated = validateGhostManifest(raw);if (!validated.ok) throw new Error(validated.reason);@@ -1088,6 +1113,31 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).not.toHaveBeenCalled();});+ it('keeps a no-port broker release visible in detail but rejects market installation before download', async () => {+ const item = summary();+ const brokerManifest = brokerManifestWithoutPort();+ const normalizedBrokerManifest = normalizedManifest(brokerManifest);+ const h = harness([item]);+ h.api.detail.mockResolvedValue({+ ...item,+ currentRelease: { ...item.currentRelease, manifest: brokerManifest },+ } as VisiblePluginDetail);++ // 详情必须继续可读;把准入检查错放到共用 validator 或 detail 会先在这里报错。+ await expect(h.service.detail(item.id)).resolves.toMatchObject({+ manifest: { network: { secrets: [{ oauth: { tokenBroker: 'jira' } }] } },+ });++ await expect(+ h.service.install(item.id, {+ expectedReleaseId: item.currentRelease.id,+ expectedManifest: normalizedBrokerManifest,+ }),+ ).rejects.toThrow('[GHOST_BROKER_REDIRECT_PORT_REQUIRED]');+ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ });+// 2026-07-26 定案:市场首装一律装完即开,手动安装与 defaultInstall 归一,// 不再向装入入口透传 initiallyEnabled(启用语义收敛在市场装入入口本身)。it('manual market install goes through the auto-enable install entry', async () => {@@ -2374,6 +2424,41 @@ describe('PluginMarketService migration and defaultInstall', () => {]);});+ it('rejects a no-port broker auto-upgrade without disturbing the installed legacy version', async () => {+ const item = summary({+ scope: 'organization',+ organizationId: 'org-1',+ defaultInstall: true,+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },+ });+ const oldManifest = manifest(item.ghostId, '1.0.0');+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];+ const h = harness([item]);+ h.ledger.upsertInstallation({+ ...recordForTest(item),+ releaseId: 'release-1',+ version: '1.0.0',+ manifestDigest: ghostManifestDigest(oldManifest),+ });+ h.api.detail.mockResolvedValueOnce({+ ...item,+ currentRelease: {+ ...item.currentRelease,+ manifest: brokerManifestWithoutPort(item.ghostId, '2.0.0'),+ },+ } as VisiblePluginDetail);++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('update-available');+ expect(runtime.ghosts[0]?.manifest.version).toBe('1.0.0');+ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ });+it('aggregates upgrade notices and filters directional controls from a single name', async () => {const item = summary({scope: 'organization',diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex c11c027260..1ac22a187a 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -79,6 +79,7 @@ import {} from '../utils/readBoundedFile.js';import { readInstalledGhostManifest } from '../installedGhostManifest.js';import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';+import { ghostBrokerRedirectPortInstallError } from '../cindy-brain/ghostBrokerRedirectPort.js';import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';import { PluginMarketApi } from './api.js';import { createOrganizationPrefixStore } from './organizationPrefixStore.js';@@ -1679,7 +1680,7 @@ export class PluginMarketService {}private async installDetail(- plugin: VisiblePluginSummary | VisiblePluginDetail,+ plugin: VisiblePluginDetail,options: {/** 手动安装时已向用户展示;默认安装时作为自动授权的目录权限上限。 */reviewedManifest?: GhostManifest;@@ -1713,6 +1714,14 @@ export class PluginMarketService {if (owner.mode === 'local' && plugin.scope !== 'public') {throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');}+ const admissionManifest = validateGhostManifest(plugin.currentRelease.manifest);+ if (!admissionManifest.ok) {+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');+ }+ const brokerPortError = ghostBrokerRedirectPortInstallError(admissionManifest.manifest);+ if (brokerPortError) {+ throwIpcError(brokerPortError.code, brokerPortError.reason);+ }const existing = getGhostManager().list().find((ghost) => ghost.manifest.id === plugin.ghostId);diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.tsindex 064e922541..6ec7412f22 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts@@ -19,6 +19,9 @@ describe('ghostInstallErrorKey', () => {expect(ghostInstallErrorKey('GHOST_BROKER_NOT_AUTHORIZED')).toBe('settings.ghosts.errors.brokerNotAuthorized',);+ expect(ghostInstallErrorKey('GHOST_BROKER_REDIRECT_PORT_REQUIRED')).toBe(+ 'settings.ghosts.errors.brokerRedirectPortRequired',+ );// This control kills a broad remap that turns every malformed .cindy error// into the Broker guidance.expect(ghostInstallErrorKey('GHOST_FILE_INVALID')).toBe('settings.ghosts.errors.fileInvalid');@@ -38,6 +41,17 @@ describe('ghostInstallErrorKey', () => {},);+ it.each(['zh-CN', 'en', 'ja', 'ko', 'zh-TW'])(+ 'keeps the missing redirectPort admission error distinct and actionable in %s',+ (locale) => {+ const message = i18n+ .getFixedT(locale)(ghostInstallErrorKey('GHOST_BROKER_REDIRECT_PORT_REQUIRED'))+ .toString();+ expect(message).toContain('redirectPort');+ expect(message).not.toBe(i18n.getFixedT(locale)('settings.ghosts.errors.fileInvalid'));+ },+ );+it.each(['zh-CN', 'en', 'ja', 'ko', 'zh-TW'])('renders the complete reserved-prefix authority in the %s install error',(locale) => {diff --git a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts b/apps/desktop/src/renderer/cindy-brain/installErrorKey.tsindex 80d241e88e..8513bf3b99 100644--- a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts+++ b/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts@@ -19,6 +19,8 @@ export function ghostInstallErrorKey(code: string | undefined): string {return 'settings.ghosts.errors.brokerManualInstallNotAuthorized';case 'GHOST_BROKER_NOT_AUTHORIZED':return 'settings.ghosts.errors.brokerNotAuthorized';+ case 'GHOST_BROKER_REDIRECT_PORT_REQUIRED':+ return 'settings.ghosts.errors.brokerRedirectPortRequired';case 'NOT_FOUND':return 'settings.ghosts.errors.sourceMissing';// 批准状态相关的前置条件失败在这条链路上只有一种下一步动作:重新确认权限。diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 5154b8d29c..376b371458 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4440,6 +4440,7 @@"idReserved": "{{reservedGhostIdPrefixes}} are reserved for official plugins and can’t be installed by dragging in a package, choosing a file, transferring from ghost_forge_pack, or using a custom plugin marketplace. Install the corresponding official plugin from the Cindy plugin market","brokerManualInstallNotAuthorized": "A manually installed .cindy package is not authorized to use the authorization broker. Install it from your organization’s plugin market, or ask the author to build it with ghost_forge_pack while signed in to the organization.","brokerNotAuthorized": "This installation source or organization identity is not authorized to use the authorization broker. Install it from your organization’s plugin market, or ask the author to build it with ghost_forge_pack while signed in to the organization.",+ "brokerRedirectPortRequired": "This plugin declares an authorization broker but does not declare redirectPort in the same OAuth configuration. Ask the author to add the field so the final authorization hop can return to the local listening port.","sourceMissing": "The selected file could not be found","generic": "Operation failed. Please try again.","updateIdMismatch": "The selected file is plugin \"{{id}}\", which does not match this plugin \"{{expected}}\""diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex cfae2e83ea..4a872fa2dc 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4439,6 +4439,7 @@"idReserved": "{{reservedGhostIdPrefixes}} は公式プラグイン用の予約済みプレフィックスです。ドラッグ、ファイル選択、ghost_forge_pack からの受け渡し、カスタムプラグインマーケットからはインストールできません。対応する公式プラグインは Cindy プラグインマーケットからインストールしてください","brokerManualInstallNotAuthorized": "手動でインストールした .cindy は認可 broker を使用できません。組織のプラグインマーケットからインストールするか、作者に組織アカウントで ghost_forge_pack を使ってビルドするよう依頼してください。","brokerNotAuthorized": "現在のインストール元または組織アカウントには、認可 broker を使用する権限がありません。組織のプラグインマーケットからインストールするか、作者に組織アカウントで ghost_forge_pack を使ってビルドするよう依頼してください。",+ "brokerRedirectPortRequired": "このプラグインは認可 broker を宣言していますが、同じ OAuth 設定に redirectPort がありません。認可の最後の転送先をローカルの待受ポートに戻せるよう、作者にこのフィールドの追加を依頼してください。","sourceMissing": "選択したファイルが見つかりません","generic": "操作に失敗しました。もう一度お試しください","updateIdMismatch": "選択したファイルはプラグイン「{{id}}」で、このプラグイン「{{expected}}」と一致しません"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b210dd0b10..3771f69726 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4439,6 +4439,7 @@"idReserved": "{{reservedGhostIdPrefixes}}는 공식 플러그인용 예약 접두사입니다. 끌어다 놓기, 파일 선택, ghost_forge_pack 전달 또는 사용자 지정 플러그인 마켓으로는 설치할 수 없습니다. 해당 공식 플러그인은 Cindy 플러그인 마켓에서 설치하세요","brokerManualInstallNotAuthorized": "수동으로 설치한 .cindy는 인증 broker를 사용할 수 없습니다. 조직 플러그인 마켓에서 설치하거나, 작성자에게 조직 계정으로 ghost_forge_pack을 사용해 빌드하도록 요청하세요.","brokerNotAuthorized": "현재 설치 출처 또는 조직 계정에는 인증 broker 사용 권한이 없습니다. 조직 플러그인 마켓에서 설치하거나, 작성자에게 조직 계정으로 ghost_forge_pack을 사용해 빌드하도록 요청하세요.",+ "brokerRedirectPortRequired": "이 플러그인은 인증 broker를 선언했지만 같은 OAuth 설정에 redirectPort를 선언하지 않았습니다. 인증의 마지막 단계가 로컬 수신 포트로 돌아올 수 있도록 작성자에게 이 필드를 추가해 달라고 요청하세요.","sourceMissing": "선택한 파일을 찾을 수 없습니다","generic": "작업에 실패했습니다. 다시 시도해 주세요","updateIdMismatch": "선택한 파일은 플러그인 \"{{id}}\"로, 현재 플러그인 \"{{expected}}\"와 일치하지 않습니다"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 8cac6d2cf6..5d37ff9c76 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4439,6 +4439,7 @@"idReserved": "{{reservedGhostIdPrefixes}} 是官方插件保留前缀,不能通过拖入、选择文件、ghost_forge_pack 转交或自定义插件市场装入;请从 Cindy 插件市场安装对应的官方插件","brokerManualInstallNotAuthorized": "手动装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装,或让作者在组织身份下使用 ghost_forge_pack 构建","brokerNotAuthorized": "当前安装来源或组织身份无权使用授权 broker;请从组织插件市场安装,或让作者在组织身份下使用 ghost_forge_pack 构建",+ "brokerRedirectPortRequired": "这个插件声明了授权 broker,但没有在同一项 OAuth 配置中声明 redirectPort。请让作者补上该字段,确保授权最后一跳能回到本机监听端口。","sourceMissing": "找不到所选文件","generic": "操作失败,请稍后重试","updateIdMismatch": "所选文件是插件「{{id}}」,与当前插件「{{expected}}」不一致"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 3481f29ee2..1696d87707 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4439,6 +4439,7 @@"idReserved": "{{reservedGhostIdPrefixes}} 是官方插件保留字首,無法透過拖入、選取檔案、ghost_forge_pack 轉交或自訂插件市場安裝;請從 Cindy 插件市場安裝對應的官方插件","brokerManualInstallNotAuthorized": "手動安裝的 .cindy 無法使用授權 broker;請改從組織插件市場安裝,或請作者以組織身分使用 ghost_forge_pack 建置","brokerNotAuthorized": "目前的安裝來源或組織身分無權使用授權 broker;請從組織插件市場安裝,或請作者以組織身分使用 ghost_forge_pack 建置",+ "brokerRedirectPortRequired": "這個插件宣告了授權 broker,但沒有在同一項 OAuth 設定中宣告 redirectPort。請讓作者補上該欄位,確保授權最後一跳能回到本機監聽連接埠。","sourceMissing": "找不到所選檔案","generic": "操作失敗,請稍後重試","updateIdMismatch": "所選檔案是插件「{{id}}」,與當前插件「{{expected}}」不一致"diff --git a/apps/desktop/src/shared/__tests__/ghost.oauth.test.ts b/apps/desktop/src/shared/__tests__/ghost.oauth.test.tsindex 20c3b6ac1e..6569199359 100644--- a/apps/desktop/src/shared/__tests__/ghost.oauth.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.oauth.test.ts@@ -286,7 +286,7 @@ describe('ghost · oauth 凭证声明校验', () => {}});- it('tokenBroker:必须带 redirectPort;非 broker 仍可省略', () => {+ it('tokenBroker 无 redirectPort 仍可从共用读路径解析;新包约束由 Host 准入点承担', () => {const base = {authorizeUrl: 'https://accounts.example.com/authorize',tokenUrl: 'https://accounts.example.com/token',@@ -295,11 +295,17 @@ describe('ghost · oauth 凭证声明校验', () => {const missingPort = validateGhostManifest(oauthManifest({ oauth: { ...base, tokenBroker: 'jira' } }),);- expect(missingPort.ok).toBe(false);- if (!missingPort.ok) expect(missingPort.reason).toContain('必须同时声明 redirectPort');+ expect(missingPort.ok).toBe(true);+ if (missingPort.ok) {+ expect(missingPort.manifest.network?.secrets?.[0]?.oauth).toMatchObject({+ tokenBroker: 'jira',+ });+ expect(+ missingPort.manifest.network?.secrets?.[0]?.oauth?.redirectPort,+ ).toBeUndefined();+ }- // This positive pair prevents accidentally requiring a fixed global port,- // while the no-broker control prevents widening the requirement to OAuth as a whole.+ // 这两个对照防止兼容调整误伤原本合法的显式端口与普通 OAuth。expect(validateGhostManifest(oauthManifest({ oauth: { ...base, tokenBroker: 'jira', redirectPort: 17872 } }),diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex d9dbdb5c8b..0fdfd4da57 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -4752,13 +4752,6 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {'network.secrets[].oauth.tokenBroker 与 clientSecret 互斥(broker 模式下 secret 由服务端持有,不随包分发)',};}- if (oa.redirectPort === undefined) {- return {- ok: false,- reason:- 'network.secrets[].oauth.tokenBroker 必须同时声明 redirectPort(broker 的 redirect_uri 端口必须稳定)',- };- }}if (oaClientIdAlternatives !== undefined && oa.tokenBroker === undefined) {return {diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 0251856b73..57a6373b3b 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -181,6 +181,7 @@ export type IpcErrorCode =| 'GHOST_ID_RESERVED' // id 属 shared/ghost.ts 登记的官方保留前缀,用户通道拒装(防抢注蹭凭证别名)| 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED' // 手动 .cindy 来源无权使用授权 broker| 'GHOST_BROKER_NOT_AUTHORIZED' // 当前来源或组织身份无权使用授权 broker+ | 'GHOST_BROKER_REDIRECT_PORT_REQUIRED' // 新包声明授权 broker 时缺少本机回跳端口// 自定义插件市场源(Git / 本地文件夹)| 'MARKET_SOURCE_INVALID' // 来源格式非法 / 本地路径不是目录 / 参数组合不允许| 'MARKET_GIT_UNAVAILABLE' // 未安装 Git 或版本 < 2.25(稀疏检出下限)@@ -381,6 +382,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['GHOST_ID_RESERVED','GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED','GHOST_BROKER_NOT_AUTHORIZED',+ 'GHOST_BROKER_REDIRECT_PORT_REQUIRED','MARKET_SOURCE_INVALID','MARKET_GIT_UNAVAILABLE','MARKET_CLONE_AUTH_FAILED',