Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 对齐市场下载边界与失败提示
liugaowei5e734589517e
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex a37887311d..3d3ea7e998 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -4,6 +4,11 @@ import crypto from 'node:crypto';import { isDeepStrictEqual } from 'node:util';import JSZip from 'jszip';+import {+ PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,+ PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES,+ PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES,+} from '@cindy/plugin-protocol';import {GHOST_MANIFEST_FILE,@@ -60,7 +65,7 @@ import { installedFileModeFromZip, isZipSymbolicLinkMode } from './ghostZipPermi/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;-export const MAX_NODE_CINDY_FILE_BYTES = 128 * 1024 * 1024;+export const MAX_NODE_CINDY_FILE_BYTES = PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES;/** 身份卡本身只应是小 JSON;先限流读取,避免在识别包类型前被单文件撑爆内存。 */const MAX_GHOST_MANIFEST_BYTES = GHOST_MANIFEST_MAX_BYTES;@@ -104,9 +109,9 @@ async function readRegularFileStableWithLimit(}/** 解压后总大小/条目数上限;Node 包允许携带已打包 CLI,但仍有硬闸。 */export const MAX_BASIC_UNCOMPRESSED_BYTES = 32 * 1024 * 1024;-export const MAX_NODE_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;+export const MAX_NODE_UNCOMPRESSED_BYTES = PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES;export const MAX_BASIC_ZIP_ENTRIES = 256;-export const MAX_NODE_ZIP_ENTRIES = 2_048;+export const MAX_NODE_ZIP_ENTRIES = PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES;/** 停用标记文件名(安装目录内;存在即停用)。 */const DISABLED_MARKER_FILE = '.disabled';/** 安装时由主机写入的信任快照与权限 receipt;作者包不能提供。 */diff --git a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts b/apps/desktop/src/main/plugin-market/__tests__/download.test.tsindex f382bcc64f..25018cbd7a 100644--- a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts@@ -4,6 +4,7 @@ import os from 'node:os';import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';+import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';const fetchMock = vi.hoisted(() => vi.fn());vi.mock('electron', () => ({ net: { fetch: fetchMock } }));@@ -14,15 +15,13 @@ const files: string[] = [];afterEach(() => {fetchMock.mockReset();- for (const file of files.splice(0)) fs.rmSync(file, { force: true });+ vi.useRealTimers();+ for (const file of files.splice(0)) fs.rmSync(file, { force: true, recursive: true });});function target(): string {- const file = path.join(- os.tmpdir(),- `cindy-plugin-download-${process.pid}-${Date.now()}-${Math.random()}.cindy`,- );- files.push(file);- return file;+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-download-'));+ files.push(dir);+ return path.join(dir, 'package.cindy');}function expected(bytes: Buffer) {@@ -33,6 +32,240 @@ function expected(bytes: Buffer) {}describe('downloadVerifiedPlugin', () => {+ it('accepts a package above the former 8 MiB market limit', async () => {+ const bytes = Buffer.alloc(9 * 1024 * 1024, 7);+ fetchMock.mockResolvedValue(new Response(bytes));+ const file = target();+ await downloadVerifiedPlugin('https://downloads.example.test/a', expected(bytes), file);+ // 不对数百万个字节逐项执行断言,仍核验完整大小和 SHA-256。+ expect(expected(fs.readFileSync(file))).toEqual(expected(bytes));+ });++ it('rejects over 128 MiB before starting a download', async () => {+ await expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ {+ sizeBytes: PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES + 1,+ sha256: '0'.repeat(64),+ },+ target(),+ ),+ ).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('allows the exact archive limit to reach the download boundary', async () => {+ fetchMock.mockResolvedValue(new Response(null, { status: 503 }));+ await expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ {+ sizeBytes: PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,+ sha256: '0'.repeat(64),+ },+ target(),+ ),+ ).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_FAILED' });+ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it.each([0, -1, NaN, 1.5])('rejects invalid release size %s', async (sizeBytes) => {+ await expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ {+ sizeBytes,+ sha256: '0'.repeat(64),+ },+ target(),+ ),+ ).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('does not overwrite or remove an existing target', async () => {+ const bytes = Buffer.from('new');+ const file = target();+ fs.writeFileSync(file, 'existing');+ fetchMock.mockResolvedValue(new Response(bytes));+ await expect(+ downloadVerifiedPlugin('https://downloads.example.test/a', expected(bytes), file),+ ).rejects.toMatchObject({ code: 'EEXIST' });+ expect(fs.readFileSync(file, 'utf8')).toBe('existing');+ });++ it('removes a truncated download', async () => {+ const file = target();+ fetchMock.mockResolvedValue(new Response(Buffer.from('short')));+ await expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ expected(Buffer.from('longer')),+ file,+ ),+ ).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });+ expect(fs.existsSync(file)).toBe(false);+ });++ it('sanitizes native network errors including signed URLs', async () => {+ fetchMock.mockRejectedValue(new Error('net::ERR_FAILED https://private.test/?secret=signed'));+ const file = target();+ await expect(+ downloadVerifiedPlugin('https://downloads.example.test/a', expected(Buffer.from('a')), file),+ ).rejects.toMatchObject({+ code: 'GHOST_DOWNLOAD_FAILED',+ message: expect.not.stringContaining('signed'),+ });+ expect(fs.existsSync(file)).toBe(false);+ });++ it('times out while waiting for headers', async () => {+ vi.useFakeTimers();+ fetchMock.mockImplementation(+ (_url, { signal }) =>+ new Promise((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });+ }),+ );+ const file = target();+ const result = expect(+ downloadVerifiedPlugin('https://downloads.example.test/a', expected(Buffer.from('a')), file),+ ).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_TIMEOUT' });+ await vi.advanceTimersByTimeAsync(60_000);+ await result;+ expect(fs.existsSync(file)).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('removes a partial download when the response stalls', async () => {+ vi.useFakeTimers();+ let pulls = 0;+ fetchMock.mockImplementation((_url, { signal }) =>+ Promise.resolve(+ new Response(+ new ReadableStream(+ {+ start(controller) {+ signal.addEventListener('abort', () => controller.error(new Error('aborted')), {+ once: true,+ });+ },+ pull(controller) {+ if (++pulls === 1) controller.enqueue(Buffer.from('a'));+ },+ },+ { highWaterMark: 0 },+ ),+ ),+ ),+ );+ const file = target();+ const result = expect(+ downloadVerifiedPlugin('https://downloads.example.test/a', expected(Buffer.from('ab')), file),+ ).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_TIMEOUT' });+ await vi.waitFor(() => expect(pulls).toBe(2));+ await vi.advanceTimersByTimeAsync(60_000);+ await result;+ expect(fs.existsSync(file)).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('continues beyond 60 seconds while receiving chunks and hashes them in order', async () => {+ vi.useFakeTimers();+ let pulls = 0;+ fetchMock.mockImplementation((_url, { signal }) =>+ Promise.resolve(+ new Response(+ new ReadableStream(+ {+ start(controller) {+ signal.addEventListener('abort', () => controller.error(new Error('aborted')), {+ once: true,+ });+ },+ pull(controller) {+ const chunk = ++pulls;+ return new Promise<void>((resolve) =>+ setTimeout(() => {+ controller.enqueue(Buffer.from(String(chunk)));+ if (chunk === 3) controller.close();+ resolve();+ }, 30_000),+ );+ },+ },+ { highWaterMark: 0 },+ ),+ ),+ ),+ );+ const file = target();+ const result = downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ expected(Buffer.from('123')),+ file,+ );+ for (let i = 1; i <= 3; i++) {+ await vi.waitFor(() => expect(pulls).toBe(i));+ await vi.advanceTimersByTimeAsync(30_000);+ }+ await result;+ expect(fs.readFileSync(file, 'utf8')).toBe('123');+ expect(vi.getTimerCount()).toBe(0);+ });+ it('aborts at 120 seconds even when download progress keeps resetting the idle timer', async () => {+ vi.useFakeTimers();+ const startedAt = Date.now();+ let abortedAt = 0;+ let pulls = 0;+ let streamController!: ReadableStreamDefaultController<Uint8Array>;+ fetchMock.mockImplementation((_url, { signal }) =>+ Promise.resolve(+ new Response(+ new ReadableStream<Uint8Array>(+ {+ start(controller) {+ streamController = controller;+ signal.addEventListener(+ 'abort',+ () => {+ abortedAt = Date.now();+ controller.error(new Error('aborted'));+ },+ { once: true },+ );+ },+ pull() {+ pulls++;+ },+ },+ { highWaterMark: 0 },+ ),+ ),+ ),+ );+ const file = target();+ const result = expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ expected(Buffer.from('1234')),+ file,+ ),+ ).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_TIMEOUT' });+ for (let i = 1; i <= 3; i++) {+ await vi.waitFor(() => expect(pulls).toBe(i));+ await vi.advanceTimersByTimeAsync(30_000);+ streamController.enqueue(Buffer.from(String(i)));+ }+ await vi.waitFor(() => expect(pulls).toBe(4));+ await vi.advanceTimersByTimeAsync(30_000);+ await result;+ expect(abortedAt - startedAt).toBe(120_000);+ expect(fs.existsSync(file)).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+ });+it('writes only bytes matching the release size and SHA-256', async () => {const bytes = Buffer.from('verified plugin bytes');fetchMock.mockResolvedValue(@@ -62,10 +295,14 @@ describe('downloadVerifiedPlugin', () => {const file = target();await expect(- downloadVerifiedPlugin('https://downloads.example.test/a', {- ...expected(bytes),- sha256: '0'.repeat(64),- }, file),+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ {+ ...expected(bytes),+ sha256: '0'.repeat(64),+ },+ file,+ ),).rejects.toThrow('SHA-256');expect(fs.existsSync(file)).toBe(false);});@@ -93,11 +330,7 @@ describe('downloadVerifiedPlugin', () => {fetchMock.mockResolvedValue(response);await expect(- downloadVerifiedPlugin(- 'https://downloads.example.test/a',- expected(bytes),- target(),- ),+ downloadVerifiedPlugin('https://downloads.example.test/a', expected(bytes), target()),).rejects.toThrow('Content-Length');expect(cancel).toHaveBeenCalledOnce();});diff --git a/apps/desktop/src/main/plugin-market/download.ts b/apps/desktop/src/main/plugin-market/download.tsindex 5bf0da3845..4180be8e7e 100644--- a/apps/desktop/src/main/plugin-market/download.ts+++ b/apps/desktop/src/main/plugin-market/download.ts@@ -2,9 +2,12 @@ import crypto from 'node:crypto';import fs from 'node:fs';import { net } from 'electron';+import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';-const MAX_PLUGIN_BYTES = 8 * 1024 * 1024;-const PLUGIN_DOWNLOAD_TIMEOUT_MS = 60_000;+import { createIpcError } from '../../shared/ipc-errors.js';++const PLUGIN_DOWNLOAD_IDLE_TIMEOUT_MS = 60_000;+const PLUGIN_DOWNLOAD_TOTAL_TIMEOUT_MS = 120_000;/** 下载并校验 `.cindy` 原始字节,写入调用方提供的临时路径。 */export async function downloadVerifiedPlugin(@@ -12,39 +15,90 @@ export async function downloadVerifiedPlugin(expected: { sizeBytes: number; sha256: string },targetPath: string,): Promise<void> {- if (expected.sizeBytes <= 0 || expected.sizeBytes > MAX_PLUGIN_BYTES) {- throw new Error(`Plugin 包大小超限: ${expected.sizeBytes}`);+ if (!Number.isSafeInteger(expected.sizeBytes) || expected.sizeBytes <= 0) {+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin Release size is invalid');}- const response = await net.fetch(url, {- method: 'GET',- cache: 'no-store',- redirect: 'error',- signal: AbortSignal.timeout(PLUGIN_DOWNLOAD_TIMEOUT_MS),- });- if (!response.ok) throw new Error(`Plugin 下载失败 (${response.status})`);- if (!response.body) throw new Error('Plugin 下载响应体为空');- const contentLength = response.headers.get('content-length');- if (contentLength !== null && Number(contentLength) !== expected.sizeBytes) {- await response.body.cancel().catch(() => undefined);- throw new Error('Plugin 下载 Content-Length 与 Release 不一致');+ if (expected.sizeBytes > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES) {+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin archive exceeds 128 MiB');}+ const controller = new AbortController();+ const totalTimer = setTimeout(() => controller.abort(), PLUGIN_DOWNLOAD_TOTAL_TIMEOUT_MS);+ let timer: ReturnType<typeof setTimeout> | undefined;+ const resetIdleTimer = () => {+ clearTimeout(timer);+ timer = setTimeout(() => controller.abort(), PLUGIN_DOWNLOAD_IDLE_TIMEOUT_MS);+ };+ const network = async <T>(operation: Promise<T>): Promise<T> => {+ try {+ return await operation;+ } catch {+ throw createIpcError(+ controller.signal.aborted ? 'GHOST_DOWNLOAD_TIMEOUT' : 'GHOST_DOWNLOAD_FAILED',+ controller.signal.aborted ? 'Plugin download timed out' : 'Plugin download failed',+ );+ }+ };+ resetIdleTimer();+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;+ let file: fs.promises.FileHandle | undefined;+ let complete = false;+ try {+ const response = await network(+ net.fetch(url, {+ method: 'GET',+ cache: 'no-store',+ redirect: 'error',+ signal: controller.signal,+ }),+ );+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ throw createIpcError('GHOST_DOWNLOAD_FAILED', `Plugin download HTTP ${response.status}`);+ }+ if (!response.body)+ throw createIpcError('GHOST_DOWNLOAD_FAILED', 'Plugin response body is empty');+ const contentLength = response.headers.get('content-length');+ if (contentLength !== null && Number(contentLength) !== expected.sizeBytes) {+ await response.body.cancel().catch(() => undefined);+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载 Content-Length 与 Release 不一致');+ }- const reader = response.body.getReader();- const chunks: Buffer[] = [];- let size = 0;- while (true) {- const { done, value } = await reader.read();- if (done) break;- size += value.byteLength;- if (size > expected.sizeBytes || size > MAX_PLUGIN_BYTES) {- await reader.cancel();- throw new Error('Plugin 下载字节数超过 Release 声明');+ reader = response.body.getReader();+ resetIdleTimer();+ file = await fs.promises.open(targetPath, 'wx', 0o600);+ const hash = crypto.createHash('sha256');+ let size = 0;+ while (true) {+ if (controller.signal.aborted)+ throw createIpcError('GHOST_DOWNLOAD_TIMEOUT', 'Plugin download timed out');+ const { done, value } = await network(reader.read());+ if (done) break;+ size += value.byteLength;+ if (size > expected.sizeBytes) {+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载字节数超过 Release 声明');+ }+ if (value.byteLength > 0) {+ resetIdleTimer();+ hash.update(value);+ await file.writeFile(value);+ }+ }+ if (controller.signal.aborted)+ throw createIpcError('GHOST_DOWNLOAD_TIMEOUT', 'Plugin download timed out');+ if (size !== expected.sizeBytes)+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载字节数与 Release 不一致');+ if (hash.digest('hex') !== expected.sha256)+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载 SHA-256 校验失败');+ await file.close();+ complete = true;+ } finally {+ clearTimeout(totalTimer);+ clearTimeout(timer);+ await reader?.cancel().catch(() => undefined);+ reader?.releaseLock();+ if (file && !complete) {+ await file.close().catch(() => undefined);+ await fs.promises.rm(targetPath, { force: true });}- chunks.push(Buffer.from(value));}- if (size !== expected.sizeBytes) throw new Error('Plugin 下载字节数与 Release 不一致');- const bytes = Buffer.concat(chunks, size);- const sha256 = crypto.createHash('sha256').update(bytes).digest('hex');- if (sha256 !== expected.sha256) throw new Error('Plugin 下载 SHA-256 校验失败');- await fs.promises.writeFile(targetPath, bytes, { mode: 0o600, flag: 'wx' });}diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.tsindex 64e14ca399..0b7dd0a4b9 100644--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts@@ -17,6 +17,8 @@ describe('pluginMarketErrorKey', () => {['PERMISSION_DENIED', 'accessDenied'],['UNSUPPORTED_CAPABILITY', 'notConfigured'],['GHOST_FILE_INVALID', 'invalidPackage'],+ ['GHOST_DOWNLOAD_TIMEOUT', 'downloadTimeout'],+ ['GHOST_DOWNLOAD_FAILED', 'downloadFailed'],['GHOST_BROKER_REDIRECT_PORT_REQUIRED', 'brokerRedirectPortRequired'],])('maps %s to localized market copy', (code, suffix) => {expect(pluginMarketErrorKey(serializedIpcError(code))).toBe(@@ -30,6 +32,14 @@ describe('pluginMarketErrorKey', () => {);});+ it.each(['zh-CN', 'zh-TW', 'en', 'ja', 'ko'])('has download error copy in %s', (locale) => {+ for (const code of ['GHOST_FILE_INVALID', 'GHOST_DOWNLOAD_TIMEOUT', 'GHOST_DOWNLOAD_FAILED']) {+ const key = pluginMarketErrorKey(serializedIpcError(code));+ expect(i18n.getResource(locale, 'common', key)).toEqual(expect.any(String));+ expect(i18n.getFixedT(locale)(key)).not.toBe(key);+ }+ });+it('never exposes a plain main-process error message', () => {expect(pluginMarketErrorKey(new Error('不应显示给 renderer 的内部错误'))).toBe('settings.ghosts.market.errors.generic',diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.tsindex 6b4f1a51b5..824868ecae 100644--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts@@ -17,6 +17,10 @@ export function pluginMarketErrorKey(error: unknown): string {return 'settings.ghosts.market.errors.notConfigured';case 'GHOST_FILE_INVALID':return 'settings.ghosts.market.errors.invalidPackage';+ case 'GHOST_DOWNLOAD_TIMEOUT':+ return 'settings.ghosts.market.errors.downloadTimeout';+ case 'GHOST_DOWNLOAD_FAILED':+ return 'settings.ghosts.market.errors.downloadFailed';case 'GHOST_ID_RESERVED':return 'settings.ghosts.errors.idReserved';case 'GHOST_BROKER_REDIRECT_PORT_REQUIRED':diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e918f42815..d539382f0a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4963,7 +4963,9 @@"stateChanged": "The account, plugin, or release changed during this operation. Review the latest state and try again.","accessDenied": "This plugin operation is not permitted or was cancelled.","notConfigured": "The plugin market is not available in this environment.",- "invalidPackage": "This plugin package is invalid or is not supported by this version of Cindy.",+ "invalidPackage": "This plugin package is invalid and cannot be installed. Contact the publisher.",+ "downloadTimeout": "The plugin download timed out. Please try again later.",+ "downloadFailed": "The plugin download failed. Check your connection and try again.","brokerRedirectPortRequired": "This plugin declares an authorization broker but is missing redirectPort in the same OAuth configuration, so it cannot be installed from the plugin marketplace. Contact the publisher to add the field and publish a new release."},"securityTitle": "Install and permissions",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5c0739026d..878f63b2e6 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4962,7 +4962,9 @@"stateChanged": "操作中にアカウント、プラグイン、またはリリースが変更されました。最新の状態を確認して、もう一度お試しください。","accessDenied": "このプラグイン操作は許可されていないか、キャンセルされました。","notConfigured": "この環境ではプラグインマーケットを利用できません。",- "invalidPackage": "このプラグインパッケージは無効か、現在の Cindy バージョンではサポートされていません。",+ "invalidPackage": "プラグインパッケージに問題があるため、インストールできません。発行元にお問い合わせください。",+ "downloadTimeout": "プラグインのダウンロードがタイムアウトしました。しばらくしてからもう一度お試しください。",+ "downloadFailed": "プラグインのダウンロードに失敗しました。接続を確認して、もう一度お試しください。","brokerRedirectPortRequired": "このプラグインは認可 broker を宣言していますが、同じ OAuth 設定に redirectPort がないため、プラグインマーケットからインストールできません。発行元にこのフィールドを追加して新しいバージョンを公開するよう連絡してください。"},"securityTitle": "インストールと権限",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 013c3f9ae8..75ac39ce2a 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4962,7 +4962,9 @@"stateChanged": "작업 중 계정, 플러그인 또는 릴리스가 변경되었습니다. 최신 상태를 확인한 후 다시 시도해 주세요.","accessDenied": "이 플러그인 작업은 허용되지 않았거나 취소되었습니다.","notConfigured": "이 환경에서는 플러그인 마켓을 사용할 수 없습니다.",- "invalidPackage": "이 플러그인 패키지가 올바르지 않거나 현재 Cindy 버전에서 지원되지 않습니다.",+ "invalidPackage": "플러그인 패키지에 문제가 있어 설치할 수 없습니다. 게시자에게 문의해 주세요.",+ "downloadTimeout": "플러그인 다운로드 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요.",+ "downloadFailed": "플러그인을 다운로드하지 못했습니다. 네트워크 연결을 확인한 후 다시 시도해 주세요.","brokerRedirectPortRequired": "이 플러그인은 인증 broker를 선언했지만 같은 OAuth 설정에 redirectPort가 없어 플러그인 마켓에서 설치할 수 없습니다. 게시자에게 이 필드를 추가해 새 버전을 게시해 달라고 알려 주세요."},"securityTitle": "설치 및 권한",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 10c4f946af..dd7a95ee69 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4962,7 +4962,9 @@"stateChanged": "操作期间账号、插件或版本已发生变化,请确认最新状态后重试。","accessDenied": "当前插件操作不被允许,或操作已取消。","notConfigured": "当前环境未提供插件市场。",- "invalidPackage": "该插件包无效,或当前 Cindy 版本不支持它。",+ "invalidPackage": "插件安装包异常,无法安装,请联系发布者。",+ "downloadTimeout": "插件下载超时,请稍后重试。",+ "downloadFailed": "插件下载失败,请检查网络后重试。","brokerRedirectPortRequired": "该插件声明了授权 broker,但同一项 OAuth 配置缺少 redirectPort,无法从插件市场安装。请联系发布者补充该字段并重新发布。"},"securityTitle": "安装与权限",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 31c0ddef70..862c81213e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4961,7 +4961,9 @@"stateChanged": "操作期間帳號、插件或版本已發生變化,請確認最新狀態後重試。","accessDenied": "當前插件操作不被允許,或操作已取消。","notConfigured": "當前環境未提供插件市場。",- "invalidPackage": "該插件包無效,或當前 Cindy 版本不支援它。",+ "invalidPackage": "插件安裝包異常,無法安裝,請聯絡釋出者。",+ "downloadTimeout": "插件下載逾時,請稍後重試。",+ "downloadFailed": "插件下載失敗,請檢查網路後重試。","brokerRedirectPortRequired": "此插件宣告了授權 broker,但同一項 OAuth 設定缺少 redirectPort,無法從插件市場安裝。請聯絡釋出者補上該欄位並重新釋出。"},"securityTitle": "安裝與權限",diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 6caded6ba7..d0c7ea2789 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -207,6 +207,8 @@ export type IpcErrorCode =| 'TERMINAL_ALREADY_DISPOSED' // 在已 dispose 的 session 上调 restart 等操作// 意识(.cindy 装入)| 'GHOST_FILE_INVALID' // 不是合法 zip / 缺 ghost.json / 清单不合格 / 超限+ | 'GHOST_DOWNLOAD_TIMEOUT' // 市场包下载总时限或无进展超时+ | 'GHOST_DOWNLOAD_FAILED' // 市场包下载网络失败| 'GHOST_HOST_UNSUPPORTED' // 插件包使用了当前 Cindy 不认识的未来 schema| 'GHOST_COMMAND_CONFLICT' // 显式指令与已装意识撞名(装入拒绝)| 'GHOST_ID_RESERVED' // id 属 shared/ghost.ts 登记的官方保留前缀,用户通道拒装(防抢注蹭凭证别名)@@ -434,6 +436,8 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['TERMINAL_SHELL_NOT_FOUND','TERMINAL_ALREADY_DISPOSED','GHOST_FILE_INVALID',+ 'GHOST_DOWNLOAD_TIMEOUT',+ 'GHOST_DOWNLOAD_FAILED','GHOST_HOST_UNSUPPORTED','GHOST_COMMAND_CONFLICT','GHOST_ID_RESERVED',diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 4f62a83877..9d460fb168 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -148,7 +148,8 @@- 同一 release 自动更新失败后,在当前进程内按 owner、来源路由和 release 做指数退避(5 分钟起、最长 6 小时),日志记录失败次数与下次重试时间;来源发布新 release 时立即解除。忙碌跳过不记失败,用户手动重试不受退避限制。-- 服务端包必须通过 release SHA/大小校验,真实包能力不得超出该 release 的市场 manifest;+- 服务端包必须通过 release SHA/大小及 id/版本校验,安装与运行时能力以真实包内的+ Manifest 为准,不将服务端目录的 Manifest 投影作为第二份能力上限。自定义市场以发现并规范化的 manifest 为能力上限。能力上限内的新版声明可静默更新,超出则按包内容不一致拒绝并留待来源修复,不转成用户审批流程。能力上限按 Host 实际消费语义比较:真实包不得从无到有增加 `settingsHtml` 设置 WebView 或扩大固定 `settingsHeight`;@@ -157,6 +158,14 @@真实包同名工具的 `parameters` JSON Schema 必须与市场规范值一致(仅对象键顺序可不同)。- 本地 `.cindy` 没有稳定来源,不自动更新;用户再次导入同 id 新包时直接原位更新,由 Main保持当前启用状态。+- 市场下载与本地安装使用一致的 Node 包体边界:压缩包最多 128 MiB、解包总量最多+ 256 MiB、最多 2048 个条目;普通沙箱包仍为 8 MiB/32 MiB/256 个条目。+ 下载前尚未识别真实包类型,按 128 MiB 限流;下载后由共用安装器按真实包类型校验。+ 市场下载采用 120 秒总超时和 60 秒无进展超时,任一触发即中止;分块写临时文件并校验+ 完整大小和 SHA-256,失败清理本次临时文件,不替换现有安装。错误提示区分下载超时、+ 网络失败与安装包异常;服务端负责包体大小发布准入,客户端保留防御校验而不另设体积提示。+ 实现与回归见 `apps/desktop/src/main/plugin-market/download.ts` 及同目录的+ `__tests__/download.test.ts`。- Host receipt 是安装事务和运行完整性的状态记录,不是一次交互式“能力授权”。合法的安装/更新事务直接写入 receipt,钉住 canonical manifest、trust、启停态与随机 `revision`;`ghostInstallApprovalToken()` 只是 Renderer 与 Main 之间防止并发漂移的前置条件,不是权限凭证。