A full-featured download manager.
feat(plugins): support signed official optional installs (#2312)
Dr_rOot732120373c72
diff --git a/.claude/rules/plugin-registry.md b/.claude/rules/plugin-registry.mdindex b6f658c8..8c79f782 100644--- a/.claude/rules/plugin-registry.md+++ b/.claude/rules/plugin-registry.md@@ -34,8 +34,14 @@ fixture, and conformance corpus.entry. Its required, optional, and host permissions must each be a subset ofthe corresponding registry preview. Any mismatch aborts installation, andgrants always derive from the parsed manifest.-- Reserved publisher namespaces remain unavailable to community manifests.- Incompatible entries remain viewable but not installable.+- Reserved publisher namespaces remain unavailable to unsigned community+ manifests. Optional official packages may claim `motrix.*` only after the+ exact archive passes the pinned Ed25519 signature check. They retain+ community permission/consent policy and cannot use builtin-only hook roles.+ Reverify retained archives at discovery and activation; read trusted+ manifests and executable code from those bytes. Registry labels alone+ never grant official identity. Incompatible entries remain viewable but+ not installable.- `motrix://plugins/<id>` is navigation-only. It must not encode or trigger aninstall; every installation requires the in-app consent flow.diff --git a/docs/manual-media-merge.md b/docs/manual-media-merge.mdindex 5fe5822e..febfc12e 100644--- a/docs/manual-media-merge.md+++ b/docs/manual-media-merge.md@@ -11,10 +11,14 @@ separately and is not part of Motrix's default bundle. Itscompatibility and package availability; a signed release is required fordirectory installation.+The plugin requires `Motrix >=2.0.0-beta.47 <3.0.0`. Older hosts show the required+range and current version and block installation before permission confirmation.+Configure FFmpeg in **Settings → Integration → Media Tools**, then install the-plugin's `.moext` package from the Plugins page. The plugin requests the `ffmpeg`-permission. If you configure FFmpeg after activating the plugin, disable and-re-enable the plugin to refresh its capability snapshot.+signed official package from the plugin marketplace once it is available. See+[official optional plugins](official-optional-plugins.md). The plugin requests the+`ffmpeg` permission. If you configure FFmpeg after activating the plugin, disable+and re-enable the plugin to refresh its capability snapshot.There are two entry points:diff --git a/docs/manual-media-merge.zh-CN.md b/docs/manual-media-merge.zh-CN.mdindex 184fba36..2a14acfa 100644--- a/docs/manual-media-merge.zh-CN.md+++ b/docs/manual-media-merge.zh-CN.md@@ -9,8 +9,12 @@[插件目录](https://motrix.app/zh/plugins/motrix.media-merge/)提供兼容版本和安装包状态;通过目录安装需要先发布正式签名包。-先在 **设置 → 集成 → 媒体工具** 中配置 FFmpeg,再到插件页面安装插件的 `.moext`-文件。插件需要 `ffmpeg` 权限。如果在插件启用后才配置 FFmpeg,请停用再启用插件,+插件要求 `Motrix >=2.0.0-beta.47 <3.0.0`。旧版宿主会显示所需版本范围和当前版本,+并在权限确认前阻止安装。++先在 **设置 → 集成 → 媒体工具** 中配置 FFmpeg,待官方签名包上线后从插件市场安装。+详见[官方可选插件](official-optional-plugins.zh-CN.md)。插件需要 `ffmpeg` 权限。+如果在插件启用后才配置 FFmpeg,请停用再启用插件,以刷新能力状态。支持两种入口:diff --git a/docs/official-optional-plugins.md b/docs/official-optional-plugins.mdnew file mode 100644index 00000000..cd1674a8--- /dev/null+++ b/docs/official-optional-plugins.md@@ -0,0 +1,62 @@+# Official optional plugins++Official optional plugins are installed from the plugin marketplace. Choose a+plugin, select **Install**, review its permissions, then confirm. Optional+permissions remain off until granted. Installed plugins can be disabled,+updated, or uninstalled from their detail page in both the desktop and server+applications.++Motrix displays **Official Motrix signature verified** only after checking the+complete package against its pinned official signing keys. Marketplace labels+alone do not establish this identity. Package size, SHA-256, manifest identity,+version, engine requirements, and declared permissions must also match the+marketplace entry.++The app retains the signed archive and checks it again during discovery and+before execution. Trusted manifests and executable code are read from that+archive, not the extracted files. An invalid signature prevents loading.++Official optional plugins use the same permission confirmation, optional grants,+and upgrade consent as community plugins. Official signing allows the+`motrix.*` namespace but does not grant built-in-only hook roles such as+`pre-resolve`. Plugins bundled with the app continue to use the separate signed+built-in update channel and cannot be replaced through optional installation.++## Host compatibility++`motrix.media-merge` is an official optional plugin. Its current manifest requires+`>=2.0.0-beta.47 <3.0.0`: beta.46 is rejected; beta.47, later 2.0 betas, and+compatible 2.x releases are accepted; 3.0.0 is rejected. Configure FFmpeg before+installing it and review the required `ffmpeg` permission.++An incompatible marketplace entry remains visible with installation disabled.+Its detail page shows the full required range and the current host version,+with guidance to upgrade or switch to a compatible version. The host checks the+registry requirement before downloading, then independently checks the package+manifest before requesting consent. Package imports also return the requirement+and current version when manifest compatibility fails. Both desktop and server+use the same localized message. No plugin is installed and no grants are saved+on this failure. A range with an upper bound must not be shortened to “version+”.++The screenshots below use local UI fixtures to illustrate the actual components;+they do not indicate that a package has been published to the live marketplace.++++++## Publishing requirements++The registry v2 format is unchanged. An optional official entry supplies a+package URL, size, SHA-256, and an Ed25519 `package.signature` over the exact+`.moext` bytes, using a key trusted by the app. Both existing registry origins+remain supported: identity is established by signature verification. An entry+marked `builtin` must have a valid official signature to enter optional+installation when it is not bundled with the app.++The manifest must support non-bundled execution. In particular, the retired+`motrix.scraper-hook` 1.0.0 package uses `pre-resolve` and remains unavailable for+optional installation. Publish and list the revised `enrich` implementation+before offering it again. Updating the app alone does not publish that package.+Unsigned local files or arbitrary download URLs cannot claim official identity;+this installation channel obtains the detached signature from the registry.diff --git a/docs/official-optional-plugins.zh-CN.md b/docs/official-optional-plugins.zh-CN.mdnew file mode 100644index 00000000..252879db--- /dev/null+++ b/docs/official-optional-plugins.zh-CN.md@@ -0,0 +1,50 @@+# 官方可选插件++官方可选插件通过插件市场安装。选择插件,点击**安装**,检查权限后确认。+可选权限默认关闭,需用户单独授予。安装后可在详情页禁用、更新或卸载,+桌面应用和服务器应用均支持这些操作。++Motrix 使用内置的官方签名公钥验证完整安装包后,才会显示+**已验证 Motrix 官方签名**。市场中的标签本身不能证明官方身份。+安装包大小、SHA-256、清单中的插件标识、版本、引擎要求和声明权限+也必须与市场条目一致。++应用会保留签名安装包,并在发现插件和执行插件前重新验证。+可信清单和执行代码均从安装包读取,不使用解压目录中的对应文件。+签名无效时不会加载插件。++官方可选插件与社区插件使用相同的权限确认、可选权限授权和升级确认流程。+官方签名允许使用 `motrix.*` 命名空间,但不授予 `pre-resolve` 等+内置插件专属的 hook 角色。随应用分发的内置插件继续使用独立的签名更新通道,+不能通过可选安装覆盖。++## 宿主版本兼容性++`motrix.media-merge` 也是官方可选插件。当前清单要求+`>=2.0.0-beta.47 <3.0.0`:拒绝 beta.46;接受 beta.47、后续 2.0 beta 和+符合范围的 2.x 正式版;拒绝 3.0.0。安装前需要配置 FFmpeg,并确认必需的+`ffmpeg` 权限。++不兼容的市场条目仍可查看,但安装按钮禁用。详情页显示完整版本范围、当前宿主+版本,并提示升级或切换到满足要求的版本。宿主在下载前检查市场版本要求,读取包后+还会在权限确认前独立检查清单。导入安装包时,若清单版本检查失败,也返回所需版本和+当前版本。桌面端和 Server 使用相同的本地化提示;失败时不安装插件、不保存授权。+存在版本上限时,不应将范围简写为“某版本+”。++以下截图使用本地界面示例数据展示实际组件,不代表插件包已在在线市场发布。++++++## 发布要求++注册表 v2 格式保持不变。官方可选插件条目需要提供安装包 URL、大小、SHA-256,+以及使用应用信任的密钥对完整 `.moext` 字节签署的 Ed25519 `package.signature`。+现有两种注册表来源均受支持,官方身份由签名验证确定。+标记为 `builtin`、但未随应用内置的条目,必须具有有效的官方签名才能进入可选安装流程。++清单必须支持非内置运行。已退役的 `motrix.scraper-hook` 1.0.0 使用+`pre-resolve`,仍不能作为可选插件安装。需要先发布并上架改为 `enrich`+的新实现,再恢复提供此插件。仅更新应用不会发布该安装包。+未签名的本地文件或任意下载 URL 不能声明官方身份;此安装通道从注册表获取独立签名。diff --git a/screenshots/motrix-official-plugin-consent-cn-light.png b/screenshots/motrix-official-plugin-consent-cn-light.pngnew file mode 100644index 00000000..7ed9faf1Binary files /dev/null and b/screenshots/motrix-official-plugin-consent-cn-light.png differdiff --git a/screenshots/motrix-plugin-version-requirement-cn-light.png b/screenshots/motrix-plugin-version-requirement-cn-light.pngnew file mode 100644index 00000000..e9c97276Binary files /dev/null and b/screenshots/motrix-plugin-version-requirement-cn-light.png differdiff --git a/src/core/plugin/host/plugin-host.test.ts b/src/core/plugin/host/plugin-host.test.tsindex da6b8d20..20285987 100644--- a/src/core/plugin/host/plugin-host.test.ts+++ b/src/core/plugin/host/plugin-host.test.ts@@ -13,6 +13,8 @@ import { AppCapabilityHost } from '../capabilities/app'import { I18nCapabilityHost } from '../capabilities/i18n'import type { CapabilityHost } from '../capabilities/interface'import { LogCapabilityHost } from '../capabilities/log'+import { writeInstallRecord } from '../install/install-record'+import { OFFICIAL_ARCHIVE_FILENAME } from '../install/official-package'import { PluginRegistry } from '../plugin-registry'import { PluginStateStore } from '../state/plugin-state-store'import { ActivationDispatcher } from './activation-dispatcher'@@ -1636,112 +1638,167 @@ describe('PluginHost.activate — builtin overlay bundle read path', () => {rmSync(root, { recursive: true, force: true })})- it('sends the BUNDLE dist/plugin.js to the worker, not the tampered tree copy', async () => {- const builtinDir = path.join(root, 'builtin')- const overlayDir = path.join(root, 'builtin-updates')+ it.each(['builtin', 'official'] as const)(+ '%s executes the signed bundle rather than the tampered tree',+ async (mode) => {+ const builtinDir = path.join(root, 'builtin')+ const overlayDir = path.join(root, 'builtin-updates')- // Seed at v1.0.0 (read-only app resources, in this fixture just a plain- // dir). The overlay below is v1.1.0, so arbitration picks the overlay.- plantPlugin(builtinDir, OVERLAY_ID)+ // Seed at v1.0.0 (read-only app resources, in this fixture just a plain+ // dir). The overlay below is v1.1.0, so arbitration picks the overlay.+ if (mode === 'builtin') plantPlugin(builtinDir, OVERLAY_ID)- const { pem, sign: signFn } = keypair()- const overlayEntryDir = path.join(overlayDir, OVERLAY_ID)- mkdirSync(path.join(overlayEntryDir, 'dist'), { recursive: true })- const manifestJSON = JSON.stringify({- manifestVersion: 1,- id: OVERLAY_ID,- name: OVERLAY_ID,- version: '1.1.0',- description: 'd',- categories: ['integration'],- engines: { motrix: '>=2.0.0' },- main: 'dist/plugin.js',- permissions: [],- activationEvents: ['onStartup'],- contributes: {},- })- writeFileSync(- path.join(overlayEntryDir, 'motrix-plugin.json'),- manifestJSON- )- // Tree copy carries a TAMPERED marker — must never reach the worker once- // the overlay's signature is verified.- writeFileSync(- path.join(overlayEntryDir, 'dist', 'plugin.js'),- 'globalThis.__MOTRIX_TEST_SOURCE__ = "TREE_TAMPERED"'- )+ const { pem, sign: signFn } = keypair()+ const overlayEntryDir = path.join(+ mode === 'builtin' ? overlayDir : path.join(root, 'plugins'),+ OVERLAY_ID+ )+ mkdirSync(path.join(overlayEntryDir, 'dist'), { recursive: true })+ const manifestJSON = JSON.stringify({+ manifestVersion: 1,+ id: OVERLAY_ID,+ name: OVERLAY_ID,+ version: '1.1.0',+ description: 'd',+ categories: ['integration'],+ engines: { motrix: '>=2.0.0' },+ main: 'dist/plugin.js',+ permissions: [],+ activationEvents: ['onStartup'],+ contributes: {},+ })+ writeFileSync(+ path.join(overlayEntryDir, 'motrix-plugin.json'),+ manifestJSON+ )+ // Tree copy carries a TAMPERED marker — must never reach the worker once+ // the overlay's signature is verified.+ writeFileSync(+ path.join(overlayEntryDir, 'dist', 'plugin.js'),+ 'globalThis.__MOTRIX_TEST_SOURCE__ = "TREE_TAMPERED"'+ )- const bundleBytes = makeZip([- { name: 'motrix-plugin.json', data: Buffer.from(manifestJSON) },- {- name: 'dist/plugin.js',- data: Buffer.from(- 'globalThis.__MOTRIX_TEST_SOURCE__ = "BUNDLE_VERIFIED"'+ const bundleBytes = makeZip([+ { name: 'motrix-plugin.json', data: Buffer.from(manifestJSON) },+ {+ name: 'dist/plugin.js',+ data: Buffer.from(+ 'globalThis.__MOTRIX_TEST_SOURCE__ = "BUNDLE_VERIFIED"'+ ),+ },+ ])+ writeFileSync(+ path.join(+ overlayEntryDir,+ mode === 'builtin' ? 'bundle.moext' : OFFICIAL_ARCHIVE_FILENAME),- },- ])- writeFileSync(path.join(overlayEntryDir, 'bundle.moext'), bundleBytes)- writeFileSync(- path.join(overlayEntryDir, '_overlay.json'),- JSON.stringify({- version: 1,- packageUrl: 'https://dl.motrix.app/p/overlay-demo.moext',- sha256: createHash('sha256').update(bundleBytes).digest('hex'),- signature: signFn(bundleBytes),- recordedAt: 1700000000000,- })- )+ bundleBytes+ )+ writeFileSync(+ path.join(overlayEntryDir, '_overlay.json'),+ JSON.stringify({+ version: 1,+ packageUrl: 'https://dl.motrix.app/p/overlay-demo.moext',+ sha256: createHash('sha256').update(bundleBytes).digest('hex'),+ signature: signFn(bundleBytes),+ recordedAt: 1700000000000,+ })+ )- const registry = new PluginRegistry({- pluginsDir: path.join(root, 'plugins'),- builtinDir,- overlayDir,- stateStore,- hostVersion: '2.5.0',- signingPubkeys: [pem],- })- await registry.discover()- // Sanity: the entry really is overlay-backed before we assert on it.- expect(registry.get(OVERLAY_ID)?.overlay).toBeDefined()- expect(registry.get(OVERLAY_ID)?.manifest.version).toBe('1.1.0')+ if (mode === 'official') {+ await writeInstallRecord(overlayEntryDir, {+ version: 1,+ pluginId: OVERLAY_ID,+ source: {+ type: 'registry',+ url: `registry:${OVERLAY_ID}`,+ bundleSha256: 'a'.repeat(64),+ recordedAt: 0,+ },+ grants: {},+ consentSnapshot: {+ permissions: [],+ optionalPermissions: [],+ hostPermissions: [],+ invokesCommands: [],+ publicCommands: {},+ requestedHeapMB: 32,+ enginesMotrix: '>=2.0.0',+ },+ official: {+ signature: signFn(bundleBytes),+ archiveSha256: createHash('sha256')+ .update(bundleBytes)+ .digest('hex'),+ },+ })+ }- const host = new PluginHost({- registry,- stateStore,- capabilityHost: capHost,- workerScriptPath: workerPath,- appVersion: '2.5.0',- runtime: 'server',- hostLanguage: 'en-US',- // Same ephemeral test key the registry above verified the overlay- // against — production omits this and falls back to the pinned- // build-time key, same as PluginRegistryOptions.signingPubkeys.- signingPubkeys: [pem],- })+ const registry = new PluginRegistry({+ pluginsDir: path.join(root, 'plugins'),+ builtinDir,+ overlayDir,+ stateStore,+ hostVersion: '2.5.0',+ signingPubkeys: [pem],+ })+ await registry.discover()+ // Discovery must establish the selected signed-package identity.+ expect(+ mode === 'builtin'+ ? registry.get(OVERLAY_ID)?.overlay+ : registry.get(OVERLAY_ID)?.official+ ).toBeDefined()+ expect(registry.get(OVERLAY_ID)?.manifest.version).toBe('1.1.0')- // Seam: CapabilityBridge sends the manifest+bundleSource to the worker- // via `this.worker.postMessage({ type: 'init', ..., bundleSource })`.- // Spying on the real Worker class's prototype (both this file and- // CapabilityBridge import the same 'node:worker_threads' module) lets us- // observe the exact string handed to the sandbox without needing the- // stub worker to echo anything back.- const postSpy = vi.spyOn(Worker.prototype, 'postMessage')- try {- await host.activate(OVERLAY_ID)+ const host = new PluginHost({+ registry,+ stateStore,+ capabilityHost: capHost,+ workerScriptPath: workerPath,+ appVersion: '2.5.0',+ runtime: 'server',+ hostLanguage: 'en-US',+ // Same ephemeral test key the registry above verified the overlay+ // against — production omits this and falls back to the pinned+ // build-time key, same as PluginRegistryOptions.signingPubkeys.+ signingPubkeys: [pem],+ })- const initCall = postSpy.mock.calls.find(- ([msg]) => (msg as { type?: string } | undefined)?.type === 'init'- )- expect(initCall).toBeDefined()- const bundleSource = (initCall as [{ bundleSource: string }])[0]- .bundleSource- expect(bundleSource).toContain('BUNDLE_VERIFIED')- expect(bundleSource).not.toContain('TREE_TAMPERED')- } finally {- postSpy.mockRestore()- await host.shutdown()+ // Seam: CapabilityBridge sends the manifest+bundleSource to the worker+ // via `this.worker.postMessage({ type: 'init', ..., bundleSource })`.+ // Spying on the real Worker class's prototype (both this file and+ // CapabilityBridge import the same 'node:worker_threads' module) lets us+ // observe the exact string handed to the sandbox without needing the+ // stub worker to echo anything back.+ const postSpy = vi.spyOn(Worker.prototype, 'postMessage')+ try {+ await host.activate(OVERLAY_ID)++ const initCall = postSpy.mock.calls.find(+ ([msg]) => (msg as { type?: string } | undefined)?.type === 'init'+ )+ expect(initCall).toBeDefined()+ const bundleSource = (initCall as [{ bundleSource: string }])[0]+ .bundleSource+ expect(bundleSource).toContain('BUNDLE_VERIFIED')+ expect(bundleSource).not.toContain('TREE_TAMPERED')+ if (mode === 'official') {+ await host.deactivate(OVERLAY_ID)+ writeFileSync(+ path.join(overlayEntryDir, OFFICIAL_ARCHIVE_FILENAME),+ Buffer.concat([bundleBytes, Buffer.from('tampered')])+ )+ await expect(host.activate(OVERLAY_ID)).rejects.toThrow(+ 'official_signature_invalid'+ )+ }+ } finally {+ postSpy.mockRestore()+ await host.shutdown()+ }}- })+ )// Negative counterpart to the read-path test above: the overlay's// bundle.moext bytes are tampered with AFTER the signature was computeddiff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.tsindex 5582af3f..447f8fc2 100644--- a/src/core/plugin/host/plugin-host.ts+++ b/src/core/plugin/host/plugin-host.ts@@ -10,6 +10,7 @@ import type { CapabilityHost } from '../capabilities/interface'import type { GrantsManager } from '../grants/grants-manager'import { ffmpegSatisfies } from '../install/ffmpeg-semver'import { readMoextEntry } from '../install/moext-reader'+import { loadOfficialPackage } from '../install/official-package'import { resolveInsidePluginDir } from '../manifest/path-safety'import type { PluginRegistry } from '../plugin-registry'import type { PluginStateStore } from '../state/plugin-state-store'@@ -452,7 +453,34 @@ export class PluginHost {}let bundleSource: string- if (indexed.overlay) {+ if (indexed.official) {+ const archive = await this.awaitActivation(+ pluginId,+ attempt,+ loadOfficialPackage(+ indexed.rootDir,+ indexed.official,+ this.opts.signingPubkeys+ )+ )+ const entryBytes = await this.awaitActivation(+ pluginId,+ attempt,+ readMoextEntry(archive.bytes, indexed.manifest.main)+ )+ if (!entryBytes) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }+ this.assertExecutableDigest(+ pluginId,+ indexed.executableDigest,+ entryBytes+ )+ bundleSource = entryBytes.toString('utf8')+ } else if (indexed.overlay) {// Firefox packed-XPI model (2026-07-18 design §4): a builtin// hot-update overlay's EXECUTED CODE comes from the signature-verified// bundle.moext, never the separately-tamperable extracted tree — andiff --git a/src/core/plugin/install/consent-payload.test.ts b/src/core/plugin/install/consent-payload.test.tsindex a0dfe142..55ac9d9b 100644--- a/src/core/plugin/install/consent-payload.test.ts+++ b/src/core/plugin/install/consent-payload.test.ts@@ -121,7 +121,7 @@ describe('buildConsentPayload', () => {])})- it('always sets notVerified=true in Phase 1A (no signing yet)', () => {+ it('defaults to unverified until the installer verifies an official signature', () => {const payload = buildConsentPayload(makeManifest(),baseSource,diff --git a/src/core/plugin/install/e2e-install.test.ts b/src/core/plugin/install/e2e-install.test.tsindex 5c04d192..65132047 100644--- a/src/core/plugin/install/e2e-install.test.ts+++ b/src/core/plugin/install/e2e-install.test.ts@@ -17,12 +17,17 @@ import {import { tmpdir } from 'node:os'import path from 'node:path'import type { RegistryPluginDTO } from '@shared/schemas/registry'+import { keypair } from '@test-utils/moext'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ServerPluginInstallService } from '../../../server/plugin/install-service'import type { CapabilityHost } from '../capabilities/interface'+import { GrantsManager } from '../grants/grants-manager'import { PluginHost } from '../host/plugin-host'import { PluginRegistry } from '../plugin-registry'import { downloadRegistryMoext } from '../registry/registry-fetcher'import { PluginStateStore } from '../state/plugin-state-store'+import { readInstallRecord } from './install-record'+import { OFFICIAL_ARCHIVE_FILENAME } from './official-package'import {PluginInstaller,type PluginInstallerOptions,@@ -234,6 +239,7 @@ async function makeInstaller(builtinDir: path.join(tmp, 'builtin-empty'),stateStore,hostVersion: '2.5.0',+ signingPubkeys: extra.signingPubkeys,})calls = {deactivated: [],@@ -1087,3 +1093,251 @@ describe('registry source install', () => {).rejects.toThrowError(/registry_manifest_mismatch/)})})++describe('official optional plugin lifecycle', () => {+ const id = 'motrix.optional-demo'+ let signing: ReturnType<typeof keypair>++ beforeEach(async () => {+ signing = keypair()+ installer = await makeInstaller({ signingPubkeys: [signing.pem] })+ })++ async function packageFor(over: Record<string, unknown> = {}) {+ const manifest = JSON.parse(+ manifestJSON({ id, optionalPermissions: ['notify'], ...over })+ )+ const file = await writeMoext(+ path.join(inputDir, `${manifest.version}.moext`),+ JSON.stringify(manifest)+ )+ const bytes = await readFile(file)+ const entry: RegistryPluginDTO = {+ ...manifest,+ origin: 'builtin',+ compatible: true,+ optionalPermissions: manifest.optionalPermissions ?? [],+ hostPermissions: manifest.hostPermissions ?? [],+ package: {+ url: 'https://dl.motrix.app/p/optional.moext',+ size: bytes.length,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ signature: signing.sign(bytes),+ },+ }+ return { file, bytes, entry }+ }++ async function stage(over: Record<string, unknown> = {}) {+ const { file, entry } = await packageFor(over)+ return installer.stage(+ file,+ { type: 'registry', pluginId: entry.id },+ { expect: buildRegistryExpectation(entry) }+ )+ }++ it.each([+ ['2.0.0-beta.46', false],+ ['2.0.0-beta.47', true],+ ['2.0.0-beta.48', true],+ ['2.0.0', true],+ ['3.0.0', false],+ ])(+ 'enforces the signed media-merge manifest requirement on host %s',+ async (hostVersion, compatible) => {+ installer = await makeInstaller({+ hostVersion,+ signingPubkeys: [signing.pem],+ ffmpegDetect: async () => ({ available: true, version: '7.0.0' }),+ })+ const result = stage({+ id: 'motrix.media-merge',+ version: '0.1.0',+ engines: { motrix: '>=2.0.0-beta.47 <3.0.0' },+ permissions: ['ffmpeg'],+ optionalPermissions: [],+ categories: ['post-action'],+ })+ if (compatible) {+ const staged = await result+ expect(staged.committed).toBe(false)+ expect(staged.consent.trustSurface.notVerified).toBe(false)+ expect(staged.consent.trustSurface.enginesMotrix).toBe(+ '>=2.0.0-beta.47 <3.0.0'+ )+ expect(staged.consent.ffmpegRuntime).toMatchObject({+ available: true,+ requiredByPlugin: 'required',+ })+ } else {+ await expect(result).rejects.toMatchObject({+ required: '>=2.0.0-beta.47 <3.0.0',+ hostVersion,+ })+ expect(registry.list()).toEqual([])+ }+ }+ )++ it('installs through the server registry boundary with consent, persists grants, rediscovers and uninstalls', async () => {+ const { entry, bytes } = await packageFor()+ const service = new ServerPluginInstallService({+ installer,+ registryClient: { get: async () => entry } as never,+ pluginsDir,+ hostVersion: '2.5.0',+ fetchImpl: (async () => new Response(bytes)) as typeof fetch,+ })+ const result = await service.stage({ sourceType: 'registry', pluginId: id })+ expect(result.committed).toBe(false)+ expect(result.consent.trustSurface.notVerified).toBe(false)+ await installer.commit(result.stagingId, { notify: 'denied' })+ expect(registry.get(id)?.origin).toBe('community')+ expect(registry.list()[0].source?.type).toBe('official')+ const grants = new GrantsManager({ registry })+ expect(await grants.effectivePermissionsFor(id)).not.toContain('notify')+ await grants.updateGrants(id, { notify: 'granted' })+ expect(await grants.effectivePermissionsFor(id)).toContain('notify')+ const dir = path.join(pluginsDir, id)+ // Extracted files are not the source of trusted metadata or executable code.+ await writeFile(+ path.join(dir, 'motrix-plugin.json'),+ manifestJSON({ id, permissions: ['http'] })+ )+ await writeFile(path.join(dir, 'dist/plugin.js'), 'tampered')+ await registry.discover()+ expect(registry.get(id)?.manifest.permissions).toEqual([])+ expect(registry.get(id)?.executableDigest).toBe(+ createHash('sha256').update('console.log(1);').digest('hex')+ )+ expect(await grants.getGrants(id)).toEqual({ notify: 'granted' })+ await installer.uninstall(id)+ expect(registry.get(id)).toBeUndefined()+ expect(existsSync(dir)).toBe(false)+ })++ it.each(['missing', 'wrong-key', 'tampered'])(+ 'rejects %s signatures before offering consent',+ async (kind) => {+ const { file, entry } = await packageFor()+ if (kind === 'missing') delete entry.package!.signature+ if (kind === 'wrong-key')+ entry.package!.signature = keypair().sign(await readFile(file))+ if (kind === 'tampered')+ await writeFile(+ file,+ Buffer.concat([await readFile(file), Buffer.from('changed')])+ )+ await expect(+ installer.stage(+ file,+ { type: 'registry', pluginId: id },+ { expect: buildRegistryExpectation(entry) }+ )+ ).rejects.toThrow('official_signature_invalid')+ expect(registry.get(id)).toBeUndefined()+ }+ )++ it('does not grant official identity to an unsigned local reserved-id package', async () => {+ const { file, entry } = await packageFor()+ await expect(+ installer.stage(file, {+ type: 'local',+ absPath: file,+ fileHash: entry.package!.sha256,+ })+ ).rejects.toThrow('publisher name is reserved')+ })++ it('rejects built-in-only hooks even with an authentic official signature', async () => {+ await expect(+ stage({+ hostPermissions: ['*://*/*'],+ contributes: { hooks: { beforeCreate: { role: 'pre-resolve' } } },+ })+ ).rejects.toThrow('official_builtin_hook')+ })++ it('keeps other reserved publishers unavailable to optional official packages', async () => {+ await expect(stage({ id: 'system.optional-demo' })).rejects.toThrow(+ 'publisher name is reserved'+ )+ })++ it('preserves registry manifest consistency after signature verification', async () => {+ const { file, entry } = await packageFor()+ entry.version = '9.0.0'+ await expect(+ installer.stage(+ file,+ { type: 'registry', pluginId: id },+ { expect: buildRegistryExpectation(entry) }+ )+ ).rejects.toThrow('registry_manifest_mismatch')+ })++ it('updates without new consent only for an unchanged trust surface', async () => {+ const first = await stage()+ await installer.commit(first.stagingId, { notify: 'denied' })+ expect((await stage({ version: '1.0.1' })).committed).toBe(true)+ expect(registry.get(id)?.manifest.version).toBe('1.0.1')+ const expanded = await stage({ version: '1.1.0', permissions: ['storage'] })+ expect(expanded.committed).toBe(false)+ expect(expanded.consent.diff?.permissionsAdded).toEqual(['storage'])+ await installer.commit(expanded.stagingId, { notify: 'denied' })+ expect(registry.get(id)?.manifest.version).toBe('1.1.0')+ })++ it('does not accept tampered archives at commit or rediscovery', async () => {+ const first = await stage()+ const stagedPath = path.join(+ pluginsDir,+ '_staging',+ first.stagingId,+ 'archive.moext'+ )+ await writeFile(+ stagedPath,+ Buffer.concat([await readFile(stagedPath), Buffer.from('changed')])+ )+ await expect(installer.commit(first.stagingId, {})).rejects.toThrow(+ 'official_signature_invalid'+ )+ await installer.cancel(first.stagingId)+ const second = await stage()+ await installer.commit(second.stagingId, {})+ const archive = path.join(pluginsDir, id, OFFICIAL_ARCHIVE_FILENAME)+ await writeFile(+ archive,+ Buffer.concat([await readFile(archive), Buffer.from('changed')])+ )+ await registry.discover()+ expect(registry.get(id)).toBeUndefined()+ expect(registry.loadErrors()[0].message).toContain(+ 'official_signature_invalid'+ )+ })++ it('rejects a forged proof and never installs over an existing builtin', async () => {+ const first = await stage()+ await installer.commit(first.stagingId, {})+ const dir = path.join(pluginsDir, id)+ const record = (await readInstallRecord(dir))!+ record.official!.signature = keypair().sign(Buffer.from('other'))+ await writeFile(path.join(dir, '_install.json'), JSON.stringify(record))+ await registry.discover()+ expect(registry.get(id)).toBeUndefined()+ const builtinDir = path.join(tmp, 'builtin-empty', id)+ await mkdir(path.join(builtinDir, 'dist'), { recursive: true })+ await writeFile(+ path.join(builtinDir, 'motrix-plugin.json'),+ manifestJSON({ id })+ )+ await writeFile(path.join(builtinDir, 'dist/plugin.js'), 'console.log(1)')+ await registry.discover()+ expect(registry.get(id)?.origin).toBe('builtin')+ await expect(stage()).rejects.toThrow('builtin_already_installed')+ })+})diff --git a/src/core/plugin/install/install-record.ts b/src/core/plugin/install/install-record.tsindex 6b6d2c80..cc3ec00f 100644--- a/src/core/plugin/install/install-record.ts+++ b/src/core/plugin/install/install-record.ts@@ -19,6 +19,13 @@ export const InstallRecordSchema = z.object({version: z.literal(1),pluginId: z.string().min(1),+ official: z+ .object({+ signature: z.string().min(1).max(256),+ archiveSha256: Sha256Hex,+ })+ .strict()+ .optional(),source: z.object({type: z.enum(INSTALL_SOURCE_TYPES),diff --git a/src/core/plugin/install/official-package.ts b/src/core/plugin/install/official-package.tsnew file mode 100644index 00000000..7a569c4f--- /dev/null+++ b/src/core/plugin/install/official-package.ts@@ -0,0 +1,43 @@+import path from 'node:path'+import { AppError, ErrorCode } from '@shared/errors'+import type { OfficialPackageProof } from '@shared/types/plugin-install'+import { verifyBuiltinSignature } from '../update/signature'+import { type LoadedMoext, loadMoext } from './moext-reader'++export const OFFICIAL_ARCHIVE_FILENAME = '_official.moext'++export function verifyOfficialPackage(+ archive: LoadedMoext,+ signature: string | undefined,+ pubkeys?: readonly string[]+): OfficialPackageProof {+ if (+ !signature ||+ !verifyBuiltinSignature(archive.bytes, signature, pubkeys)+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }+ return { signature, archiveSha256: archive.archiveSha256 }+}++/** Read and verify the same bytes used for manifest parsing and execution. */+export async function loadOfficialPackage(+ pluginDir: string,+ proof: OfficialPackageProof,+ pubkeys?: readonly string[]+): Promise<LoadedMoext> {+ const archive = await loadMoext(+ path.join(pluginDir, OFFICIAL_ARCHIVE_FILENAME)+ )+ verifyOfficialPackage(archive, proof.signature, pubkeys)+ if (archive.archiveSha256 !== proof.archiveSha256) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }+ return archive+}diff --git a/src/core/plugin/install/plugin-installer.ts b/src/core/plugin/install/plugin-installer.tsindex bc1923ee..5898eb8a 100644--- a/src/core/plugin/install/plugin-installer.ts+++ b/src/core/plugin/install/plugin-installer.ts@@ -27,6 +27,7 @@ import type {GrantsMap,InstallRecord,InstallRecordSource,+ OfficialPackageProof,} from '@shared/types/plugin-install'import type { FfmpegDetection } from '../capabilities/ffmpeg-detect'import type { CapabilityHost } from '../capabilities/interface'@@ -48,6 +49,10 @@ import {writeInstallRecord,} from './install-record'import { extractLoadedMoext, loadMoext } from './moext-reader'+import {+ OFFICIAL_ARCHIVE_FILENAME,+ verifyOfficialPackage,+} from './official-package'import { computePublicCommandHashes } from './public-command-hash'import {assertMatchesRegistryExpectation,@@ -106,6 +111,8 @@ export interface PluginInstallerOptions {stateStore: PluginStateStorecapabilityHost: CapabilityHosthostVersion: string+ /** Test seam; production always uses the pinned official signing keys. */+ signingPubkeys?: readonly string[]/*** Optional Plan D dependency. Until Plan D lands, the installer falls* back to local hash computation only.@@ -137,6 +144,7 @@ interface StagedInstall {archivePath: stringarchiveSha256: stringpreviousRecord: InstallRecord | null+ official?: OfficialPackageProofruntimeHost?: PluginRuntimeHostLike}@@ -251,6 +259,15 @@ export class PluginInstaller {const extractedDir = path.join(stagingDir, 'tree')const archivePath = path.join(stagingDir, 'archive.moext')const loadedMoext = await loadMoext(moextPath)+ const official =+ options?.expect?.requiresOfficialSignature ||+ options?.expect?.officialSignature+ ? verifyOfficialPackage(+ loadedMoext,+ options.expect.officialSignature,+ this.opts.signingPubkeys+ )+ : undefinedconst pinnedSha256 =sourceInput.type === 'local'? sourceInput.fileHash@@ -285,6 +302,7 @@ export class PluginInstaller {try {const result = parseManifest(manifestRaw, {hostVersion: this.opts.hostVersion,+ official: official !== undefined,})parsedManifest = await resolveManifestForInstall(result.manifest as PluginManifest,@@ -317,6 +335,21 @@ export class PluginInstaller {)const prev = await readInstallRecord(finalDir)+ if (this.opts.registry.get(parsedManifest.id)?.origin === 'builtin') {+ await rm(stagingDir, { recursive: true, force: true })+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.builtin_already_installed'+ )+ }+ if (prev?.official && !official) {+ await rm(stagingDir, { recursive: true, force: true })+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }+if (this.opts.serverAck) {const r = this.opts.serverAck(source, prev)if (!r.ok) {@@ -407,6 +440,7 @@ export class PluginInstaller {installedCalleeTitles,{ ffmpegDetection })+ consent.trustSurface.notVerified = official === undefined// Locale/manifest resolution is complete. A pending consent transaction// only needs the protected archive, so do not retain a second extracted@@ -423,6 +457,7 @@ export class PluginInstaller {archivePath,archiveSha256: loadedMoext.archiveSha256,previousRecord: prev,+ official,runtimeHost: options?.runtimeHost,}this.pending.set(stagingId, staged)@@ -473,6 +508,12 @@ export class PluginInstaller {staged.pluginId)const prev = await readInstallRecord(finalDir)+ if (this.opts.registry.get(staged.pluginId)?.origin === 'builtin') {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.builtin_already_installed'+ )+ }if (!sameInstallRecord(prev, staged.previousRecord)) {throw new AppError(ErrorCode.PluginManifestInvalid,@@ -494,6 +535,7 @@ export class PluginInstaller {enginesMotrix: staged.newManifest.engines.motrix,hostPermissions: staged.newManifest.hostPermissions ?? [],},+ ...(staged.official ? { official: staged.official } : {}),}const commitDir = path.join(this.opts.pluginsDir,@@ -513,10 +555,24 @@ export class PluginInstaller {if (loadedMoext.archiveSha256 !== staged.archiveSha256) {throw new AppError(ErrorCode.PluginManifestInvalid,- 'plugin.install.sha256_mismatch'+ staged.official+ ? 'plugin.install.official_signature_invalid'+ : 'plugin.install.sha256_mismatch')}await extractLoadedMoext(loadedMoext, commitDir)+ if (staged.official) {+ verifyOfficialPackage(+ loadedMoext,+ staged.official.signature,+ this.opts.signingPubkeys+ )+ await writeFile(+ path.join(commitDir, OFFICIAL_ARCHIVE_FILENAME),+ loadedMoext.bytes,+ { flag: 'wx', mode: 0o600 }+ )+ }await writeInstallRecord(commitDir, record)await mkdir(this.opts.pluginsDir, { recursive: true })@@ -536,6 +592,15 @@ export class PluginInstaller {this.installCommandSchemas(staged.pluginId, staged.newManifest)await this.opts.registry.discover()+ if (+ staged.official &&+ !this.opts.registry.get(staged.pluginId)?.official+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }if (supersededExecutable) {// Admission remains closed until this succeeds. If durable// terminalization fails, the catch below restores the old bundlediff --git a/src/core/plugin/install/registry-expectation.ts b/src/core/plugin/install/registry-expectation.tsindex 4457ddee..9328e9a7 100644--- a/src/core/plugin/install/registry-expectation.ts+++ b/src/core/plugin/install/registry-expectation.ts@@ -16,6 +16,9 @@ export interface RegistryExpectation {hostPermissions: ReadonlyArray<string>/** Complete .moext digest verified by the registry download boundary. */packageSha256?: string+ /** Metadata is only a claim; the installer must verify the archive itself. */+ officialSignature?: string+ requiresOfficialSignature?: boolean}export function buildRegistryExpectation(@@ -30,6 +33,9 @@ export function buildRegistryExpectation(hostPermissions: entry.hostPermissions,}if (entry.package?.sha256) expectation.packageSha256 = entry.package.sha256+ if (entry.package?.signature)+ expectation.officialSignature = entry.package.signature+ if (entry.origin === 'builtin') expectation.requiresOfficialSignature = truereturn expectation}diff --git a/src/core/plugin/manifest/parse.ts b/src/core/plugin/manifest/parse.tsindex a2e08d5a..3815362d 100644--- a/src/core/plugin/manifest/parse.ts+++ b/src/core/plugin/manifest/parse.ts@@ -36,6 +36,8 @@ export interface ParseManifestOptions {// publishers (motrix.*); community plugins discovered or installed at// runtime always default to 'community'.origin?: 'community' | 'builtin'+ /** Host-only result of checking the package against pinned official keys. */+ official?: boolean}export interface ManifestWarning {@@ -188,10 +190,14 @@ export function parseManifest(// Step 3: Enforce reserved-publisher invariant. Community plugins must not// claim a reserved publisher (motrix.*, verified.*, official.*, system.*).- // Built-ins shipped inside the app bundle are exempt — they originate from- // <resourcesDir>/builtin-plugins/ and the registry passes origin='builtin'.+ // Official optional packages earn only the motrix.* namespace through+ // signature verification. Bundled builtins keep their separate origin gate.const origin = opts.origin ?? 'community'- if (origin !== 'builtin' && isReservedPublisher(result.data.id)) {+ if (+ origin !== 'builtin' &&+ isReservedPublisher(result.data.id) &&+ !(opts.official && result.data.id.startsWith('motrix.'))+ ) {throw new PluginManifestInvalid('plugin.manifest.id_reserved_publisher',`publisher name is reserved: "${result.data.id}"`,@@ -271,6 +277,12 @@ export function parseManifest(if (!entry) continueconst role = entry.role as HookRoleif (role === 'pre-resolve' && origin !== 'builtin') {+ if (opts.official) {+ throw new PluginManifestInvalid(+ 'plugin.install.official_builtin_hook',+ 'plugin.install.official_builtin_hook'+ )+ }throw new PluginManifestInvalid('plugin.manifest.role.requires_builtin',`contributes.hooks.${hookName}.role "pre-resolve" is reserved for built-in plugins`,diff --git a/src/core/plugin/plugin-registry.ts b/src/core/plugin/plugin-registry.tsindex cda88f79..b588ef57 100644--- a/src/core/plugin/plugin-registry.ts+++ b/src/core/plugin/plugin-registry.ts@@ -14,8 +14,11 @@ import type {PluginSource,PluginStateRecord,} from '@shared/types/plugin'+import type { OfficialPackageProof } from '@shared/types/plugin-install'import { FfmpegStaging } from './hooks/staging-dir'+import { readInstallRecord } from './install/install-record'import { readMoextEntry } from './install/moext-reader'+import { loadOfficialPackage } from './install/official-package'import {flattenLocaleDict,type ManifestLocaleDict,@@ -68,6 +71,8 @@ export interface IndexedPlugin {* can render a "Dev mode" badge.*/dev?: boolean+ /** Official optional packages retain community permission and hook policy. */+ official?: OfficialPackageProof & { recordedAt: number }/*** Present when this builtin's effective code was earned from the* signature-verified <overlayDir>/<id> hot-update overlay rather than the@@ -510,11 +515,38 @@ export class PluginRegistry {continue}}- const raw = await readFile(path.join(dir, 'motrix-plugin.json'), 'utf8')+ const record =+ origin === 'community' ? await readInstallRecord(dir) : null+ const officialArchive = record?.official+ ? await loadOfficialPackage(+ dir,+ record.official,+ this.opts.signingPubkeys+ )+ : undefined+ const manifestBytes = officialArchive+ ? await readMoextEntry(officialArchive.bytes, 'motrix-plugin.json')+ : undefined+ if (officialArchive && !manifestBytes) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }+ const raw =+ manifestBytes?.toString('utf8') ??+ (await readFile(path.join(dir, 'motrix-plugin.json'), 'utf8'))const { manifest } = parseManifest(raw, {hostVersion: this.opts.hostVersion,origin,+ official: officialArchive !== undefined,})+ if (officialArchive && record?.pluginId !== manifest.id) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }if (manifest.id !== name) {this.errors.push({pluginDir: dir,@@ -533,9 +565,18 @@ export class PluginRegistry {}const resolved = await this.i18nResolve(manifest, dir)const state = this.getOrCreateState(resolved.id)- const executableDigest = await digestFile(- resolveInsidePluginDir(dir, resolved.main)- )+ const signedExecutable = officialArchive+ ? await readMoextEntry(officialArchive.bytes, resolved.main)+ : undefined+ if (officialArchive && !signedExecutable) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.official_signature_invalid'+ )+ }+ const executableDigest = signedExecutable+ ? digestBytes(signedExecutable)+ : await digestFile(resolveInsidePluginDir(dir, resolved.main))this.byId.set(resolved.id, {manifestRaw: manifest,manifest: resolved,@@ -543,6 +584,14 @@ export class PluginRegistry {rootDir: dir,executableDigest,state,+ ...(record?.official+ ? {+ official: {+ ...record.official,+ recordedAt: record.source.recordedAt,+ },+ }+ : {}),})} catch (e: unknown) {// For AppError (PluginManifestInvalid / PluginEngineVersionTooOld),@@ -868,6 +917,7 @@ function executablePolicyFingerprint(entry: IndexedPlugin): string {manifest: entry.manifestRaw,origin: entry.origin,overlaySignature: entry.overlay?.signature ?? null,+ official: entry.official ?? null,rootDir: entry.rootDir,})}@@ -887,6 +937,13 @@ function digestBytes(bytes: Uint8Array): string {}function deriveListSource(p: IndexedPlugin): PluginSource | undefined {+ if (p.official) {+ return {+ type: 'official',+ url: `registry:${p.manifest.id}`,+ recordedAt: p.official.recordedAt,+ }+ }if (p.origin === 'builtin') {return p.overlay? {diff --git a/src/core/plugin/registry/registry-client.test.ts b/src/core/plugin/registry/registry-client.test.tsindex fb61b5c0..8a4a3407 100644--- a/src/core/plugin/registry/registry-client.test.ts+++ b/src/core/plugin/registry/registry-client.test.ts@@ -85,6 +85,24 @@ describe('RegistryClient', () => {})}+ it('annotates the media-merge beta requirement with the actual host version', async () => {+ const body = structuredClone(fixture)+ body.plugins[0].id = 'motrix.media-merge'+ body.plugins[0].engines.motrix = '>=2.0.0-beta.47 <3.0.0'+ const { impl } = makeFetch([{ status: 200, body }])+ const client = makeClient(impl)+ for (const [hostVersion, compatible] of [+ ['2.0.0-beta.46', false],+ ['2.0.0-beta.47', true],+ ['2.0.0', true],+ ['3.0.0', false],+ ] as const) {+ expect(await client.get('motrix.media-merge', hostVersion)).toMatchObject(+ { hostVersion, compatible }+ )+ }+ })+it('rejects a legacy file envelope, fetches unconditionally, and overwrites in format 2', async () => {await writeFile(cachePath,diff --git a/src/core/plugin/registry/registry-client.ts b/src/core/plugin/registry/registry-client.tsindex 2ca2d915..49a11c0f 100644--- a/src/core/plugin/registry/registry-client.ts+++ b/src/core/plugin/registry/registry-client.ts@@ -124,6 +124,7 @@ export class RegistryClient {hostVersion,entries: file.plugins.map((entry) => ({...entry,+ hostVersion,compatible: semverSatisfies(hostVersion, entry.engines.motrix),})),}diff --git a/src/core/plugin/registry/update-scan.test.ts b/src/core/plugin/registry/update-scan.test.tsindex 5ba8681d..0e2edb7a 100644--- a/src/core/plugin/registry/update-scan.test.ts+++ b/src/core/plugin/registry/update-scan.test.ts@@ -157,3 +157,20 @@ describe('scanForUpdates', () => {).toEqual([])})})++describe('official optional updates', () => {+ it('uses normal consent updates for signed packages and hides unsigned downgrades', () => {+ const installed = { ...INSTALLED, source: { type: 'official' } }+ expect(scanForUpdates([installed], [entry()])).toEqual([])+ const signed = entry()+ signed.package!.signature = 'signed-package'+ expect(scanForUpdates([installed], [signed])).toEqual([+ {+ pluginId: INSTALLED.id,+ currentVersion: '1.0.0',+ latestVersion: '1.1.0',+ channel: 'community',+ },+ ])+ })+})diff --git a/src/core/plugin/registry/update-scan.ts b/src/core/plugin/registry/update-scan.tsindex c1c9143e..0f8f6997 100644--- a/src/core/plugin/registry/update-scan.ts+++ b/src/core/plugin/registry/update-scan.ts@@ -33,6 +33,7 @@ export function scanForUpdates(const entry = byId.get(plugin.id)if (!entry?.compatible || !entry.package) continueif (!semverGt(entry.version, plugin.version)) continue+ if (sourceType === 'official' && !entry.package.signature) continueif (sourceType === 'builtin' || sourceType === 'builtin-update') {// Builtin channel: only signed entries are ever offered — thediff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 148f1a8b..6adb09d4 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -4,6 +4,7 @@ import path from 'node:path'import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'import { EventBus } from '@core/events/event-bus'+import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'import { SettingsManager } from '@core/settings/settings-manager'import { ErrorCode } from '@shared/errors'@@ -300,6 +301,54 @@ function fakeCtx() {}describe('buildCommandHandlers', () => {+ it('returns the exact media-merge version requirement before downloading or requesting consent', async () => {+ const ctx = {+ ...fakeCtx(),+ hostVersion: '2.0.0-beta.46',+ registryClient: {+ get: vi.fn().mockResolvedValue({+ compatible: false,+ engines: { motrix: '>=2.0.0-beta.47 <3.0.0' },+ }),+ },+ }+ const handlers = buildCommandHandlers(ctx as unknown as CommandContext)+ await expect(+ handlers[Commands.InstallPlugin]?.({+ sourceType: 'registry',+ pluginId: 'motrix.media-merge',+ })+ ).resolves.toEqual({+ incompatible: {+ required: '>=2.0.0-beta.47 <3.0.0',+ hostVersion: '2.0.0-beta.46',+ },+ })+ expect(ctx.pluginInstaller.stage).not.toHaveBeenCalled()+ expect(ctx.eventBus.emit).not.toHaveBeenCalled()+ })++ it('preserves version details for a local package without requesting consent', async () => {+ const ctx = fakeCtx()+ ctx.pluginInstaller.stage.mockRejectedValueOnce(+ new PluginEngineVersionTooOld('>=2.0.0-beta.47 <3.0.0', '2.0.0-beta.46')+ )+ const handlers = buildCommandHandlers(ctx as unknown as CommandContext)+ await expect(+ handlers[Commands.InstallPlugin]?.({+ sourceType: 'local',+ absPath: '/tmp/fixture.moext',+ fileHash: 'a'.repeat(64),+ })+ ).resolves.toEqual({+ incompatible: {+ required: '>=2.0.0-beta.47 <3.0.0',+ hostVersion: '2.0.0-beta.46',+ },+ })+ expect(ctx.eventBus.emit).not.toHaveBeenCalled()+ })+it('installs FFmpeg only from the fixed service with no renderer-supplied URLs or keys', async () => {const ctx = fakeCtx()const handlers = buildCommandHandlers(ctx as unknown as CommandContext)diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 449eccd4..d989fb51 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -31,6 +31,7 @@ import {} from '@core/plugin/install/registry-expectation'import type { SourceInput } from '@core/plugin/install/source-resolver'import { downloadUrlMoext } from '@core/plugin/install/url-fetcher'+import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { RegistryClient } from '@core/plugin/registry/registry-client'import { downloadRegistryMoext } from '@core/plugin/registry/registry-fetcher'@@ -125,6 +126,7 @@ import {type CliInstallRequest,} from '@shared/types/cli-tool'import { EngineRecoveryAction, EngineState } from '@shared/types/engine'+import type { PluginInstallCompatibilityFailure } from '@shared/types/plugin-install'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'@@ -1734,49 +1736,61 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {},[Commands.InstallPlugin]: async (payload: unknown) => {- const parsed = installPluginPayloadSchema.parse(payload)- let moextPath: string- let expect: RegistryExpectation | undefined- if (parsed.sourceType === 'registry') {- const entry = await registryClient.get(parsed.pluginId, hostVersion)- if (!entry) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.registry_entry_missing'- )- }- // The UI disables the button; main still enforces the gate- // (viewable-but-not-installable is a contract, not a style).- if (!entry.compatible) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.registry_incompatible'+ try {+ const parsed = installPluginPayloadSchema.parse(payload)+ let moextPath: string+ let expect: RegistryExpectation | undefined+ if (parsed.sourceType === 'registry') {+ const entry = await registryClient.get(parsed.pluginId, hostVersion)+ if (!entry) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.registry_entry_missing'+ )+ }+ // The UI disables the button; main still enforces the gate+ // (viewable-but-not-installable is a contract, not a style).+ if (!entry.compatible) {+ throw new PluginEngineVersionTooOld(+ entry.engines.motrix,+ hostVersion+ )+ }+ moextPath = path.join(+ userDataDir,+ 'plugin-downloads',+ `registry-${parsed.pluginId}-${Date.now()}.moext`)+ await downloadRegistryMoext(entry, moextPath)+ expect = buildRegistryExpectation(entry)+ } else {+ moextPath = await materializeMoext(parsed)}- moextPath = path.join(- userDataDir,- 'plugin-downloads',- `registry-${parsed.pluginId}-${Date.now()}.moext`+ const result = await pluginInstaller.stage(+ moextPath,+ toSourceInput(parsed),+ { expect, runtimeHost: pluginHost })- await downloadRegistryMoext(entry, moextPath)- expect = buildRegistryExpectation(entry)- } else {- moextPath = await materializeMoext(parsed)- }- const result = await pluginInstaller.stage(- moextPath,- toSourceInput(parsed),- { expect, runtimeHost: pluginHost }- )- if (result.committed && result.pluginId) {- eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })- } else {- eventBus.emit(Events.PluginInstallConsentRequested, {- stagingId: result.stagingId,- consent: result.consent,- })+ if (result.committed && result.pluginId) {+ eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })+ } else {+ eventBus.emit(Events.PluginInstallConsentRequested, {+ stagingId: result.stagingId,+ consent: result.consent,+ })+ }+ return result+ } catch (error) {+ if (error instanceof PluginEngineVersionTooOld) {+ return {+ incompatible: {+ required: error.required,+ hostVersion: error.hostVersion,+ },+ } satisfies PluginInstallCompatibilityFailure+ }+ throw error}- return result},[Commands.CheckPluginUpdates]: async (payload: unknown) => {diff --git a/src/renderer/routes/plugins/components/inline-consent-panel.test.tsx b/src/renderer/routes/plugins/components/inline-consent-panel.test.tsxindex f2c91a6f..99620e45 100644--- a/src/renderer/routes/plugins/components/inline-consent-panel.test.tsx+++ b/src/renderer/routes/plugins/components/inline-consent-panel.test.tsx@@ -53,6 +53,24 @@ describe('InlineConsentPanel', () => {expect(screen.getByText(/Before installing/)).toBeInTheDocument()})+ it('shows verified official identity without skipping permission review', () => {+ render(+ <InlineConsentPanel+ consent={{+ ...baseConsent,+ trustSurface: { ...baseConsent.trustSurface, notVerified: false },+ }}+ grants={{}}+ onGrantsChange={() => {}}+ />+ )+ expect(+ screen.getByText('Official Motrix signature verified')+ ).toBeInTheDocument()+ expect(screen.getByText(/Before installing/)).toBeInTheDocument()+ expect(screen.getByText('Send notifications')).toBeInTheDocument()+ })+it('renders one PermissionRow per permission (required + optional)', () => {render(<InlineConsentPaneldiff --git a/src/renderer/routes/plugins/components/inline-consent-panel.tsx b/src/renderer/routes/plugins/components/inline-consent-panel.tsxindex c39010e7..154c57f0 100644--- a/src/renderer/routes/plugins/components/inline-consent-panel.tsx+++ b/src/renderer/routes/plugins/components/inline-consent-panel.tsx@@ -36,6 +36,12 @@ export function InlineConsentPanel({ consent, grants, onGrantsChange }: Props) {<PluginAudienceBadge tone={isBroadHost ? 'review' : 'safe'} /></div>+ {consent.trustSurface.notVerified === false && (+ <p className="text-xs text-muted-foreground">+ {t('plugins.install.officialVerified')}+ </p>+ )}+<div className="grid gap-2">{consent.trustSurface.permissions.map((p) => (<PermissionRow key={p.name} permission={p.name} granted={true} />diff --git a/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx b/src/renderer/routes/plugins/components/registry-detail-panel.test.tsxindex 1ad48395..3692d9be 100644--- a/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx+++ b/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx@@ -84,6 +84,25 @@ describe('RegistryDetailPanel install affordance', () => {expect(screen.getByTestId('registry-install-btn')).toBeDisabled()})+ it.each(['electron', 'web'] as const)(+ 'explains the required range and current host on %s',+ (kind) => {+ renderPanel(+ kind,+ entry({+ id: 'motrix.media-merge',+ compatible: false,+ engines: { motrix: '>=2.0.0-beta.47 <3.0.0' },+ hostVersion: '2.0.0-beta.46',+ })+ )+ expect(screen.getByRole('status')).toHaveTextContent(+ 'This plugin requires Motrix >=2.0.0-beta.47 <3.0.0; current version: 2.0.0-beta.46'+ )+ expect(screen.getByTestId('registry-install-btn')).toBeDisabled()+ }+ )+it('shows the verified registry Install button on web', () => {renderPanel('web', entry())expect(screen.getByTestId('registry-install-btn')).toBeEnabled()diff --git a/src/renderer/routes/plugins/components/registry-detail-panel.tsx b/src/renderer/routes/plugins/components/registry-detail-panel.tsxindex cd8d2bc3..98173e96 100644--- a/src/renderer/routes/plugins/components/registry-detail-panel.tsx+++ b/src/renderer/routes/plugins/components/registry-detail-panel.tsx@@ -116,6 +116,14 @@ export function RegistryDetailPanel({ entry }: Props) {{t('plugins.registry.viewOnWebsite')}</Button></div>+ {!entry.compatible && entry.hostVersion && (+ <p role="status" className="text-sm text-muted-foreground">+ {t('plugins.install.hostIncompatible', {+ required: entry.engines.motrix,+ current: entry.hostVersion,+ })}+ </p>+ )}</Card>{features.length > 0 && (diff --git a/src/renderer/routes/plugins/hooks/use-plugin-install.ts b/src/renderer/routes/plugins/hooks/use-plugin-install.tsindex 41b29af4..656ebd61 100644--- a/src/renderer/routes/plugins/hooks/use-plugin-install.ts+++ b/src/renderer/routes/plugins/hooks/use-plugin-install.ts@@ -1,7 +1,12 @@import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'-import type { ConsentPayload, GrantsMap } from '@shared/types/plugin-install'+import type {+ ConsentPayload,+ GrantsMap,+ PluginInstallCompatibilityFailure,+} from '@shared/types/plugin-install'import { useState } from 'react'+import { useTranslation } from 'react-i18next'// Wire shape mirrors installPluginPayloadSchema in src/main/ipc/commands.ts.// `fileHash` is the SHA-256 hex digest of the .moext file content — it@@ -22,19 +27,46 @@ interface InstallResult {}export function usePluginInstall() {+ const { t } = useTranslation()const [stagingId, setStagingId] = useState<string | null>(null)const [consent, setConsent] = useState<ConsentPayload | null>(null)const [pending, setPending] = useState(false)const [error, setError] = useState<string | null>(null)- async function startInstall(input: InstallSource): Promise<void> {+ function showError(e: unknown): void {+ const message = e instanceof Error ? e.message : String(e)+ const messages = {+ 'plugin.install.official_signature_invalid':+ 'plugins.install.officialSignatureInvalid',+ 'plugin.install.official_builtin_hook':+ 'plugins.install.officialBuiltinOnly',+ 'plugin.install.builtin_already_installed':+ 'plugins.install.builtinAlreadyInstalled',+ } as const+ const key = Object.keys(messages).find((code) => message.endsWith(code)) as+ | keyof typeof messages+ | undefined+ setError(key ? t(messages[key]) : message)+ }++ async function startInstall(input: InstallSource): Promise<boolean> {setPending(true)setError(null)try {- const r = (await transport.invoke(- Commands.InstallPlugin,- input- )) as InstallResult+ const r = (await transport.invoke(Commands.InstallPlugin, input)) as+ | InstallResult+ | PluginInstallCompatibilityFailure+ if ('incompatible' in r) {+ setStagingId(null)+ setConsent(null)+ setError(+ t('plugins.install.hostIncompatible', {+ required: r.incompatible.required,+ current: r.incompatible.hostVersion,+ })+ )+ return false+ }if (r.committed) {setStagingId(null)setConsent(null)@@ -42,18 +74,33 @@ export function usePluginInstall() {setStagingId(r.stagingId)setConsent(r.consent)}+ return r.committed} catch (e) {- setError(e instanceof Error ? e.message : String(e))+ showError(e)+ return false} finally {setPending(false)}}- async function confirm(grants: GrantsMap): Promise<void> {- if (!stagingId) return- await transport.invoke(Commands.ConfirmPluginInstall, { stagingId, grants })- setStagingId(null)- setConsent(null)+ async function confirm(grants: GrantsMap): Promise<boolean> {+ if (!stagingId || pending) return false+ setPending(true)+ setError(null)+ try {+ await transport.invoke(Commands.ConfirmPluginInstall, {+ stagingId,+ grants,+ })+ setStagingId(null)+ setConsent(null)+ return true+ } catch (e) {+ showError(e)+ return false+ } finally {+ setPending(false)+ }}async function cancel(): Promise<void> {diff --git a/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx b/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsxindex d001fe38..e28bc029 100644--- a/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx+++ b/src/renderer/routes/plugins/plugin-install-dialog.registry.test.tsx@@ -33,6 +33,32 @@ beforeEach(() => {})describe('PluginInstallDialog with fixedSource', () => {+ it('explains media-merge compatibility without showing consent or allowing commit', async () => {+ mockInvoke.mockResolvedValueOnce({+ incompatible: {+ required: '>=2.0.0-beta.47 <3.0.0',+ hostVersion: '2.0.0-beta.46',+ },+ })+ const onOpenChange = vi.fn()+ render(+ <PluginInstallDialog+ open+ onOpenChange={onOpenChange}+ fixedSource={{ sourceType: 'registry', pluginId: 'motrix.media-merge' }}+ />+ )+ expect(+ await screen.findByText(+ /This plugin requires Motrix >=2.0.0-beta.47 <3.0.0; current version: 2.0.0-beta.46/+ )+ ).toBeInTheDocument()+ expect(screen.queryByTestId('consent-panel')).toBeNull()+ expect(screen.getByTestId('install-commit-btn')).toBeDisabled()+ expect(onOpenChange).not.toHaveBeenCalled()+ expect(mockInvoke).toHaveBeenCalledTimes(1)+ })+it('auto-starts a registry install and hides the source picker', async () => {render(<PluginInstallDialog@@ -112,4 +138,80 @@ describe('PluginInstallDialog with fixedSource', () => {channel: 'community',})})+ it('explains why a retired builtin package cannot be installed as optional', async () => {+ mockInvoke.mockRejectedValueOnce(+ new Error(+ "Error invoking remote method 'command:installPlugin': AppError: plugin.install.official_builtin_hook"+ )+ )+ render(+ <PluginInstallDialog+ open+ onOpenChange={() => {}}+ fixedSource={{+ sourceType: 'registry',+ pluginId: 'motrix.scraper-hook',+ }}+ />+ )+ expect(+ await screen.findByText(/This version requires built-in privileges/)+ ).toBeInTheDocument()+ expect(screen.getByTestId('install-commit-btn')).toBeDisabled()+ })++ it('closes after a trust-equivalent upgrade commits during staging', async () => {+ mockInvoke.mockResolvedValueOnce({+ committed: true,+ pluginId: 'motrix.optional-demo',+ })+ const onOpenChange = vi.fn()+ usePluginsStore.setState({+ updates: {+ 'motrix.optional-demo': {+ latestVersion: '1.0.1',+ channel: 'community',+ },+ },+ })+ render(+ <PluginInstallDialog+ open+ onOpenChange={onOpenChange}+ fixedSource={{+ sourceType: 'registry',+ pluginId: 'motrix.optional-demo',+ }}+ />+ )+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))+ expect(+ usePluginsStore.getState().updates['motrix.optional-demo']+ ).toBeUndefined()+ })++ it('keeps consent open and displays a localized verification failure at commit', async () => {+ const onOpenChange = vi.fn()+ render(+ <PluginInstallDialog+ open+ onOpenChange={onOpenChange}+ fixedSource={{+ sourceType: 'registry',+ pluginId: 'motrix.optional-demo',+ }}+ />+ )+ await screen.findByTestId('consent-panel')+ mockInvoke.mockRejectedValueOnce(+ new Error('plugin.install.official_signature_invalid')+ )+ fireEvent.click(screen.getByTestId('install-commit-btn'))+ expect(+ await screen.findByText(+ /The official plugin signature could not be verified/+ )+ ).toBeInTheDocument()+ expect(onOpenChange).not.toHaveBeenCalled()+ })})diff --git a/src/renderer/routes/plugins/plugin-install-dialog.test.tsx b/src/renderer/routes/plugins/plugin-install-dialog.test.tsxindex de069df2..f29f83f7 100644--- a/src/renderer/routes/plugins/plugin-install-dialog.test.tsx+++ b/src/renderer/routes/plugins/plugin-install-dialog.test.tsx@@ -63,7 +63,7 @@ beforeEach(() => {state.stagingId = nullstate.consent = nullstate.startInstall = vi.fn()- state.confirm = vi.fn()+ state.confirm = vi.fn().mockResolvedValue(true)state.cancel = vi.fn()})diff --git a/src/renderer/routes/plugins/plugin-install-dialog.tsx b/src/renderer/routes/plugins/plugin-install-dialog.tsxindex 2cac2661..d81312df 100644--- a/src/renderer/routes/plugins/plugin-install-dialog.tsx+++ b/src/renderer/routes/plugins/plugin-install-dialog.tsx@@ -92,7 +92,12 @@ export function PluginInstallDialog({if (!fixedSource || startedRef.current) returnstartedRef.current = truesetGrants({})- void install.startInstall(fixedSource)+ void install.startInstall(fixedSource).then((committed) => {+ if (!committed) return+ if (fixedSource.sourceType === 'registry')+ clearUpdate(fixedSource.pluginId)+ onOpenChange(false)+ })}, [open, fixedSource])function close() {@@ -107,7 +112,7 @@ export function PluginInstallDialog({async function onInstall() {if (!install.consent) return- await install.confirm(grants)+ if (!(await install.confirm(grants))) return// A successful commit means the registry entry's version is now// installed — drop the "Update to vX" affordance immediately rather// than waiting for the next CheckPluginUpdates poll to re-offer a@@ -129,7 +134,7 @@ export function PluginInstallDialog({await install.cancel()}setGrants({})- await install.startInstall(args)+ if (await install.startInstall(args)) close()}const ffmpegBlocking =diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex 090fa941..f896eb47 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -12,6 +12,7 @@ import type { GrantsManager } from '@core/plugin/grants/grants-manager'import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'import type { PluginHost } from '@core/plugin/host/plugin-host'import type { PluginInstaller } from '@core/plugin/install/plugin-installer'+import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { RegistryClient } from '@core/plugin/registry/registry-client'import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'@@ -1727,6 +1728,30 @@ describe('server plugin enable/disable commands', () => {})describe('server plugin lifecycle commands', () => {+ it('returns compatibility details without emitting consent or installation events', async () => {+ const ctx = makeFakeCtx()+ ;(+ ctx.pluginInstallService.stage as ReturnType<typeof vi.fn>+ ).mockRejectedValueOnce(+ new PluginEngineVersionTooOld('>=2.0.0-beta.47 <3.0.0', '2.0.0-beta.46')+ )+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )+ await expect(+ handlers[Commands.InstallPlugin]?.({+ sourceType: 'registry',+ pluginId: 'motrix.media-merge',+ })+ ).resolves.toEqual({+ incompatible: {+ required: '>=2.0.0-beta.47 <3.0.0',+ hostVersion: '2.0.0-beta.46',+ },+ })+ expect(ctx.eventBus.emit).not.toHaveBeenCalled()+ })+it('stages an install and publishes the consent request', async () => {const ctx = makeFakeCtx();(diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 1f1fa9cb..6cad9e3c 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -20,6 +20,7 @@ import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'import type { PluginHost } from '@core/plugin/host/plugin-host'import type { PluginInstaller } from '@core/plugin/install/plugin-installer'+import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { RegistryClient } from '@core/plugin/registry/registry-client'import { scanForUpdates } from '@core/plugin/registry/update-scan'@@ -96,6 +97,7 @@ import {taskTrackerEditSchema,} from '@shared/schemas/task-tracker'import { EngineRecoveryAction } from '@shared/types/engine'+import type { PluginInstallCompatibilityFailure } from '@shared/types/plugin-install'import type { ProxySettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'@@ -1046,16 +1048,28 @@ export function buildServerCommandHandlers(},[Commands.InstallPlugin]: async (payload: unknown) => {- const result = await pluginInstallService.stage(payload, pluginHost)- if (result.committed && result.pluginId) {- eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })- } else {- eventBus.emit(Events.PluginInstallConsentRequested, {- stagingId: result.stagingId,- consent: result.consent,- })+ try {+ const result = await pluginInstallService.stage(payload, pluginHost)+ if (result.committed && result.pluginId) {+ eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })+ } else {+ eventBus.emit(Events.PluginInstallConsentRequested, {+ stagingId: result.stagingId,+ consent: result.consent,+ })+ }+ return result+ } catch (error) {+ if (error instanceof PluginEngineVersionTooOld) {+ return {+ incompatible: {+ required: error.required,+ hostVersion: error.hostVersion,+ },+ } satisfies PluginInstallCompatibilityFailure+ }+ throw error}- return result},[Commands.ConfirmPluginInstall]: async (payload: unknown) => {diff --git a/src/server/plugin/install-service.test.ts b/src/server/plugin/install-service.test.tsindex cd4fe024..9be78f5b 100644--- a/src/server/plugin/install-service.test.ts+++ b/src/server/plugin/install-service.test.ts@@ -46,6 +46,31 @@ function makeService(overrides: Record<string, unknown> = {}) {}describe('ServerPluginInstallService', () => {+ it('rejects incompatible media-merge before downloading or staging its package', async () => {+ const fetchImpl = vi.fn()+ const { service, stage } = makeService({+ hostVersion: '2.0.0-beta.46',+ registryClient: {+ get: vi.fn().mockResolvedValue({+ compatible: false,+ engines: { motrix: '>=2.0.0-beta.47 <3.0.0' },+ }),+ },+ fetchImpl,+ })+ await expect(+ service.stage({+ sourceType: 'registry',+ pluginId: 'motrix.media-merge',+ })+ ).rejects.toMatchObject({+ required: '>=2.0.0-beta.47 <3.0.0',+ hostVersion: '2.0.0-beta.46',+ })+ expect(fetchImpl).not.toHaveBeenCalled()+ expect(stage).not.toHaveBeenCalled()+ })+it('accepts a local package only from an allowed import root', async () => {const packagePath = path.join(incomingDir, 'fixture.moext')await writeFile(packagePath, 'fixture')diff --git a/src/server/plugin/install-service.ts b/src/server/plugin/install-service.tsindex 9b55ece6..e17ad726 100644--- a/src/server/plugin/install-service.ts+++ b/src/server/plugin/install-service.ts@@ -15,6 +15,7 @@ import {type RegistryExpectation,} from '@core/plugin/install/registry-expectation'import type { SourceInput } from '@core/plugin/install/source-resolver'+import { PluginEngineVersionTooOld } from '@core/plugin/manifest/errors'import type { RegistryClient } from '@core/plugin/registry/registry-client'import { downloadRegistryMoext } from '@core/plugin/registry/registry-fetcher'import { AppError, ErrorCode } from '@shared/errors'@@ -248,9 +249,9 @@ export class ServerPluginInstallService {)}if (!entry.compatible) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.registry_incompatible'+ throw new PluginEngineVersionTooOld(+ entry.engines.motrix,+ this.options.hostVersion)}const target = this.downloadPath('registry')diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 86d9e9c7..f5cb1187 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -1591,7 +1591,12 @@"title": "إضافة مكوّن إضافي","url": "URL","url.spec": "عنوان الحزمة (.moext)",- "warning": "قبل التثبيت: تابع فقط إذا كنت تثق بالمؤلف وتتوقع استخدام الإضافة لصلاحيات الوصول المذكورة أعلاه."+ "warning": "قبل التثبيت: تابع فقط إذا كنت تثق بالمؤلف وتتوقع استخدام الإضافة لصلاحيات الوصول المذكورة أعلاه.",+ "officialVerified": "تم التحقق من توقيع Motrix الرسمي",+ "officialSignatureInvalid": "تعذر التحقق من توقيع الإضافة الرسمي. حاول تحديث متجر الإضافات.",+ "officialBuiltinOnly": "يتطلب هذا الإصدار صلاحيات الإضافات المضمنة. ثبّت إصدارًا أحدث يدعم التثبيت الاختياري.",+ "builtinAlreadyInstalled": "هذه الإضافة مضمنة بالفعل. استخدم إجراء التحديث الخاص بها.",+ "hostIncompatible": "تتطلب هذه الإضافة Motrix {{required}}؛ الإصدار الحالي: {{current}}. قم بالترقية أو التبديل إلى إصدار متوافق من Motrix ثم أعد المحاولة."},"lead": "أضف ميزات صغيرة إلى Motrix. احتفظ بالإضافات التي تثق بها، وعطّل الباقي.","logs": {diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 2ffeca89..2252f21b 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -1523,7 +1523,12 @@"title": "Добавяне на приставка","url": "URL","url.spec": "URL адрес на пакета (.moext)",- "warning": "Преди инсталиране: продължете само ако имате доверие на автора и очаквате приставката да използва посочения по-горе достъп."+ "warning": "Преди инсталиране: продължете само ако имате доверие на автора и очаквате приставката да използва посочения по-горе достъп.",+ "officialVerified": "Официалният подпис на Motrix е проверен",+ "officialSignatureInvalid": "Официалният подпис на приставката не може да бъде проверен. Опреснете каталога.",+ "officialBuiltinOnly": "Тази версия изисква права на вградена приставка. Инсталирайте по-нова версия, която поддържа незадължителна инсталация.",+ "builtinAlreadyInstalled": "Тази приставка вече е вградена. Използвайте действието за обновяване.",+ "hostIncompatible": "Тази приставка изисква Motrix {{required}}; текуща версия: {{current}}. Надстройте или преминете към съвместима версия на Motrix и опитайте отново."},"lead": "Добавяйте малки функции към Motrix. Оставете включени приставките, на които имате доверие, и изключете останалите.","logs": {diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex ae770246..65fe8eb9 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -1540,7 +1540,12 @@"title": "Afegir un connector","url": "URL","url.spec": "URL del paquet (.moext)",- "warning": "Abans d'instal·lar: continueu només si confieu en l'autor i espereu que el connector utilitzi l'accés indicat més amunt."+ "warning": "Abans d'instal·lar: continueu només si confieu en l'autor i espereu que el connector utilitzi l'accés indicat més amunt.",+ "officialVerified": "Signatura oficial de Motrix verificada",+ "officialSignatureInvalid": "No s’ha pogut verificar la signatura oficial del connector. Actualitzeu el catàleg.",+ "officialBuiltinOnly": "Aquesta versió requereix privilegis de connector integrat. Instal·leu una versió més recent que admeti la instal·lació opcional.",+ "builtinAlreadyInstalled": "Aquest connector ja està integrat. Feu servir la seva acció d’actualització.",+ "hostIncompatible": "Aquest complement requereix Motrix {{required}}; versió actual: {{current}}. Actualitza o canvia a una versió compatible de Motrix i torna-ho a provar."},"lead": "Afegiu petites funcions al Motrix. Manteniu els connectors de confiança i desactiveu la resta.","logs": {diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex acc250f6..427648c4 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -2341,7 +2341,12 @@"localPrepareFailed": "Diese Plugin-Datei konnte nicht vorbereitet werden: {{detail}}","dropHint": ".moext-Datei hier ablegen, um dieses Plugin zu prüfen","dragDisabledHint": "Drag-and-drop wird in dieser Umgebung nicht unterstützt. Verwenden Sie eine GitHub-Adresse oder URL.",- "warning": "Vor der Installation: Fahren Sie nur fort, wenn Sie dem Autor vertrauen und die oben aufgeführten Zugriffe durch das Plugin erwarten."+ "warning": "Vor der Installation: Fahren Sie nur fort, wenn Sie dem Autor vertrauen und die oben aufgeführten Zugriffe durch das Plugin erwarten.",+ "officialVerified": "Offizielle Motrix-Signatur bestätigt",+ "officialSignatureInvalid": "Die offizielle Signatur des Plugins konnte nicht bestätigt werden. Aktualisiere den Marktplatz.",+ "officialBuiltinOnly": "Diese Version benötigt Berechtigungen eines integrierten Plugins. Installiere eine neuere Version, die eine optionale Installation unterstützt.",+ "builtinAlreadyInstalled": "Dieses Plugin ist bereits integriert. Verwende seine Aktualisierungsfunktion.",+ "hostIncompatible": "Dieses Plugin benötigt Motrix {{required}}. Aktuelle Version: {{current}}. Aktualisiere Motrix oder wechsle zu einer kompatiblen Version und versuche es erneut."},"consent": {"installTitle": "{{name}} {{version}} installieren?",diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex 430ba173..3ff3ec10 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -1523,7 +1523,12 @@"title": "Προσθήκη πρόσθετου","url": "URL","url.spec": "URL πακέτου (.moext)",- "warning": "Πριν από την εγκατάσταση: συνεχίστε μόνο αν εμπιστεύεστε τον δημιουργό και περιμένετε να χρησιμοποιήσει την πρόσβαση που αναφέρεται παραπάνω."+ "warning": "Πριν από την εγκατάσταση: συνεχίστε μόνο αν εμπιστεύεστε τον δημιουργό και περιμένετε να χρησιμοποιήσει την πρόσβαση που αναφέρεται παραπάνω.",+ "officialVerified": "Η επίσημη υπογραφή του Motrix επαληθεύτηκε",+ "officialSignatureInvalid": "Δεν ήταν δυνατή η επαλήθευση της επίσημης υπογραφής του πρόσθετου. Ανανεώστε τον κατάλογο.",+ "officialBuiltinOnly": "Αυτή η έκδοση απαιτεί δικαιώματα ενσωματωμένου πρόσθετου. Εγκαταστήστε νεότερη έκδοση που υποστηρίζει προαιρετική εγκατάσταση.",+ "builtinAlreadyInstalled": "Αυτό το πρόσθετο είναι ήδη ενσωματωμένο. Χρησιμοποιήστε την ενέργεια ενημέρωσής του.",+ "hostIncompatible": "Αυτό το πρόσθετο απαιτεί Motrix {{required}}· τρέχουσα έκδοση: {{current}}. Αναβαθμίστε ή μεταβείτε σε συμβατή έκδοση του Motrix και δοκιμάστε ξανά."},"lead": "Προσθέστε μικρές λειτουργίες στο Motrix. Κρατήστε όσες εμπιστεύεστε και απενεργοποιήστε τις υπόλοιπες.","logs": {diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 48771c67..1b23c3fc 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -2341,7 +2341,12 @@"localPrepareFailed": "Could not prepare this plugin file: {{detail}}","dropHint": "Drop a .moext file here to check this plugin","dragDisabledHint": "Drag-and-drop is not supported in this environment. Use a GitHub address or a URL.",- "warning": "Before installing: only continue if you trust the author and expect it to use the access listed above."+ "warning": "Before installing: only continue if you trust the author and expect it to use the access listed above.",+ "officialVerified": "Official Motrix signature verified",+ "officialSignatureInvalid": "The official plugin signature could not be verified. Try refreshing the marketplace.",+ "officialBuiltinOnly": "This version requires built-in privileges. Install a newer version that supports optional installation.",+ "builtinAlreadyInstalled": "This plugin is already built in. Use its update action instead.",+ "hostIncompatible": "This plugin requires Motrix {{required}}; current version: {{current}}. Upgrade or switch to a compatible Motrix version and try again."},"consent": {"installTitle": "Install {{name}} {{version}}?",diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex 290ba945..206e1fbb 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -2356,7 +2356,12 @@"localPrepareFailed": "No se pudo preparar este archivo de plugin: {{detail}}","dropHint": "Arrastra aquí un archivo .moext para comprobar este plugin","dragDisabledHint": "Este entorno no permite arrastrar y soltar. Usa una dirección de GitHub o una URL.",- "warning": "Antes de instalar: continúa solo si confías en el autor y esperas que el plugin use los accesos indicados arriba."+ "warning": "Antes de instalar: continúa solo si confías en el autor y esperas que el plugin use los accesos indicados arriba.",+ "officialVerified": "Firma oficial de Motrix verificada",+ "officialSignatureInvalid": "No se pudo verificar la firma oficial del complemento. Actualiza el catálogo.",+ "officialBuiltinOnly": "Esta versión requiere privilegios de un complemento integrado. Instala una versión más reciente que admita la instalación opcional.",+ "builtinAlreadyInstalled": "Este complemento ya está integrado. Usa su opción de actualización.",+ "hostIncompatible": "Este complemento requiere Motrix {{required}}; versión actual: {{current}}. Actualiza o cambia a una versión compatible de Motrix e inténtalo de nuevo."},"consent": {"installTitle": "¿Instalar {{name}} {{version}}?",diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex 15163501..cca4e23c 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -1523,7 +1523,12 @@"title": "افزودن افزونه","url": "نشانی","url.spec": "نشانی بسته (.moext)",- "warning": "پیش از نصب: فقط اگر به نویسنده اعتماد دارید و انتظار دارید افزونه از دسترسیهای بالا استفاده کند، ادامه دهید."+ "warning": "پیش از نصب: فقط اگر به نویسنده اعتماد دارید و انتظار دارید افزونه از دسترسیهای بالا استفاده کند، ادامه دهید.",+ "officialVerified": "امضای رسمی Motrix تأیید شد",+ "officialSignatureInvalid": "امضای رسمی افزونه تأیید نشد. فهرست افزونهها را تازهسازی کنید.",+ "officialBuiltinOnly": "این نسخه به مجوزهای افزونهٔ داخلی نیاز دارد. نسخهٔ جدیدتری نصب کنید که نصب اختیاری را پشتیبانی کند.",+ "builtinAlreadyInstalled": "این افزونه از قبل داخلی است. از گزینهٔ بهروزرسانی آن استفاده کنید.",+ "hostIncompatible": "این افزونه به Motrix {{required}} نیاز دارد؛ نسخهٔ فعلی: {{current}}. Motrix را ارتقا دهید یا به نسخهای سازگار تغییر دهید و دوباره تلاش کنید."},"lead": "قابلیتهای کوچکی به Motrix اضافه کنید. افزونههای مورد اعتماد را نگه دارید و بقیه را خاموش کنید.","logs": {diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex 053ad039..01c24209 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -1540,7 +1540,12 @@"title": "Ajouter une extension","url": "URL","url.spec": "URL du paquet (.moext)",- "warning": "Avant l’installation : continuez uniquement si vous faites confiance à l’auteur et acceptez l’utilisation des accès indiqués ci-dessus."+ "warning": "Avant l’installation : continuez uniquement si vous faites confiance à l’auteur et acceptez l’utilisation des accès indiqués ci-dessus.",+ "officialVerified": "Signature officielle de Motrix vérifiée",+ "officialSignatureInvalid": "La signature officielle du plugin n’a pas pu être vérifiée. Actualisez le catalogue.",+ "officialBuiltinOnly": "Cette version nécessite les privilèges d’un plugin intégré. Installez une version plus récente prenant en charge l’installation facultative.",+ "builtinAlreadyInstalled": "Ce plugin est déjà intégré. Utilisez son action de mise à jour.",+ "hostIncompatible": "Ce plugin nécessite Motrix {{required}} ; version actuelle : {{current}}. Mettez à niveau ou passez à une version compatible de Motrix, puis réessayez."},"lead": "Ajoutez des fonctionnalités à Motrix. Gardez les extensions de confiance et désactivez les autres.","logs": {diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex 9c5b31b2..d27c14dc 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -2341,7 +2341,12 @@"localPrepareFailed": "A bővítményfájlt nem sikerült előkészíteni: {{detail}}","dropHint": "Húzz ide egy .moext fájlt a bővítmény ellenőrzéséhez","dragDisabledHint": "A fogd és vidd művelet ebben a környezetben nem támogatott. Használj GitHub-címet vagy URL-t.",- "warning": "Telepítés előtt: csak akkor folytasd, ha megbízol a szerzőben, és számítasz arra, hogy a bővítmény a fent felsorolt hozzáféréseket használja."+ "warning": "Telepítés előtt: csak akkor folytasd, ha megbízol a szerzőben, és számítasz arra, hogy a bővítmény a fent felsorolt hozzáféréseket használja.",+ "officialVerified": "A hivatalos Motrix-aláírás ellenőrizve",+ "officialSignatureInvalid": "A bővítmény hivatalos aláírása nem ellenőrizhető. Frissítse a katalógust.",+ "officialBuiltinOnly": "Ez a verzió beépített bővítmény jogosultságait igényli. Telepítsen újabb, választható telepítést támogató verziót.",+ "builtinAlreadyInstalled": "Ez a bővítmény már be van építve. Használja a frissítési műveletét.",+ "hostIncompatible": "A bővítményhez Motrix {{required}} szükséges; jelenlegi verzió: {{current}}. Frissítsen vagy váltson kompatibilis Motrix-verzióra, és próbálja újra."},"consent": {"installTitle": "Telepíted a(z) {{name}} {{version}} verzióját?",diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex 1c463962..a0d2df58 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -2325,7 +2325,12 @@"localPrepareFailed": "Berkas plugin ini tidak dapat disiapkan: {{detail}}","dropHint": "Letakkan berkas .moext di sini untuk memeriksa plugin","dragDisabledHint": "Seret dan lepas tidak didukung dalam lingkungan ini. Gunakan alamat GitHub atau URL.",- "warning": "Sebelum memasang: lanjutkan hanya jika Anda memercayai pembuatnya dan penggunaan akses yang tercantum di atas sesuai dengan yang Anda harapkan."+ "warning": "Sebelum memasang: lanjutkan hanya jika Anda memercayai pembuatnya dan penggunaan akses yang tercantum di atas sesuai dengan yang Anda harapkan.",+ "officialVerified": "Tanda tangan resmi Motrix terverifikasi",+ "officialSignatureInvalid": "Tanda tangan resmi plugin tidak dapat diverifikasi. Coba segarkan katalog plugin.",+ "officialBuiltinOnly": "Versi ini memerlukan hak akses plugin bawaan. Instal versi lebih baru yang mendukung instalasi opsional.",+ "builtinAlreadyInstalled": "Plugin ini sudah menjadi bawaan. Gunakan tindakan pembaruannya.",+ "hostIncompatible": "Plugin ini memerlukan Motrix {{required}}; versi saat ini: {{current}}. Tingkatkan atau beralih ke versi Motrix yang kompatibel, lalu coba lagi."},"consent": {"installTitle": "Pasang {{name}} {{version}}?",diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex 60e1421b..b4c71282 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -2357,7 +2357,12 @@"localPrepareFailed": "Impossibile preparare il file del plugin: {{detail}}","dropHint": "Trascina qui un file .moext per verificare il plugin","dragDisabledHint": "Il trascinamento non è supportato in questo ambiente. Usa un indirizzo GitHub o un URL.",- "warning": "Prima di installare: continua solo se ti fidi dell’autore e prevedi che il plugin usi gli accessi elencati sopra."+ "warning": "Prima di installare: continua solo se ti fidi dell’autore e prevedi che il plugin usi gli accessi elencati sopra.",+ "officialVerified": "Firma ufficiale di Motrix verificata",+ "officialSignatureInvalid": "Impossibile verificare la firma ufficiale del plugin. Aggiorna il catalogo.",+ "officialBuiltinOnly": "Questa versione richiede privilegi di un plugin integrato. Installa una versione più recente che supporti l’installazione facoltativa.",+ "builtinAlreadyInstalled": "Questo plugin è già integrato. Usa la sua funzione di aggiornamento.",+ "hostIncompatible": "Questo plugin richiede Motrix {{required}}; versione attuale: {{current}}. Aggiorna o passa a una versione compatibile di Motrix e riprova."},"consent": {"installTitle": "Installare {{name}} {{version}}?",diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex e0e058a7..94c61f59 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -2325,7 +2325,12 @@"localPrepareFailed": "このプラグインファイルを準備できませんでした:{{detail}}","dropHint": "ここに .moext ファイルをドロップしてプラグインを確認","dragDisabledHint": "この環境ではドラッグ&ドロップに対応していません。GitHub のアドレスまたは URL を使用してください。",- "warning": "インストール前に:作者を信頼でき、上記のアクセス権の使用を想定している場合にのみ続行してください。"+ "warning": "インストール前に:作者を信頼でき、上記のアクセス権の使用を想定している場合にのみ続行してください。",+ "officialVerified": "Motrix の公式署名を検証済み",+ "officialSignatureInvalid": "プラグインの公式署名を検証できませんでした。マーケットを更新してください。",+ "officialBuiltinOnly": "このバージョンには内蔵プラグイン専用の権限が必要です。任意インストールに対応した新しいバージョンをインストールしてください。",+ "builtinAlreadyInstalled": "このプラグインはすでに内蔵されています。プラグインの更新機能を使用してください。",+ "hostIncompatible": "このプラグインには Motrix {{required}} が必要です。現在のバージョンは {{current}} です。対応する Motrix バージョンに更新または切り替えて、再試行してください。"},"consent": {"installTitle": "{{name}} {{version}} をインストールしますか?",diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex 9deb8f28..44e7a41d 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -2325,7 +2325,12 @@"localPrepareFailed": "이 플러그인 파일을 준비하지 못했습니다: {{detail}}","dropHint": "이 플러그인을 확인하려면 .moext 파일을 여기에 끌어다 놓으세요","dragDisabledHint": "이 환경에서는 끌어다 놓기를 지원하지 않습니다. GitHub 주소 또는 URL을 사용하세요.",- "warning": "설치 전 확인: 제작자를 신뢰하고 위에 나열된 접근 권한을 사용할 것으로 예상하는 경우에만 계속하세요."+ "warning": "설치 전 확인: 제작자를 신뢰하고 위에 나열된 접근 권한을 사용할 것으로 예상하는 경우에만 계속하세요.",+ "officialVerified": "Motrix 공식 서명 확인됨",+ "officialSignatureInvalid": "플러그인의 공식 서명을 확인할 수 없습니다. 마켓을 새로 고침해 주세요.",+ "officialBuiltinOnly": "이 버전은 내장 플러그인 전용 권한이 필요합니다. 선택 설치를 지원하는 최신 버전을 설치해 주세요.",+ "builtinAlreadyInstalled": "이 플러그인은 이미 내장되어 있습니다. 플러그인 업데이트 기능을 사용해 주세요.",+ "hostIncompatible": "이 플러그인에는 Motrix {{required}}이(가) 필요합니다. 현재 버전: {{current}}. 호환되는 Motrix 버전으로 업그레이드하거나 변경한 후 다시 시도하세요."},"consent": {"installTitle": "{{name}} {{version}}을(를) 설치하시겠습니까?",diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex bed82e63..9e6f4912 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -1523,7 +1523,12 @@"title": "Legg til programtillegg","url": "URL","url.spec": "Pakke-URL (.moext)",- "warning": "Før installering: Fortsett bare hvis du stoler på utvikleren og forventer at tillegget bruker tilgangen som er oppført ovenfor."+ "warning": "Før installering: Fortsett bare hvis du stoler på utvikleren og forventer at tillegget bruker tilgangen som er oppført ovenfor.",+ "officialVerified": "Offisiell Motrix-signatur bekreftet",+ "officialSignatureInvalid": "Kunne ikke bekrefte den offisielle signaturen til programtillegget. Oppdater katalogen.",+ "officialBuiltinOnly": "Denne versjonen krever rettigheter for innebygde programtillegg. Installer en nyere versjon som støtter valgfri installasjon.",+ "builtinAlreadyInstalled": "Dette programtillegget er allerede innebygd. Bruk oppdateringsfunksjonen.",+ "hostIncompatible": "Dette programtillegget krever Motrix {{required}}; gjeldende versjon: {{current}}. Oppgrader eller bytt til en kompatibel Motrix-versjon og prøv igjen."},"lead": "Legg til små funksjoner i Motrix. Behold dem du stoler på, og slå av resten.","logs": {diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 1246590a..defb664a 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -1523,7 +1523,12 @@"title": "Plug-in toevoegen","url": "URL","url.spec": "Bundel-URL (.moext)",- "warning": "Vóór installatie: ga alleen door als je de auteur vertrouwt en verwacht dat de plug-in de hierboven vermelde toegang gebruikt."+ "warning": "Vóór installatie: ga alleen door als je de auteur vertrouwt en verwacht dat de plug-in de hierboven vermelde toegang gebruikt.",+ "officialVerified": "Officiële Motrix-handtekening geverifieerd",+ "officialSignatureInvalid": "De officiële handtekening van de plug-in kon niet worden geverifieerd. Vernieuw de catalogus.",+ "officialBuiltinOnly": "Deze versie vereist rechten van een ingebouwde plug-in. Installeer een nieuwere versie die optionele installatie ondersteunt.",+ "builtinAlreadyInstalled": "Deze plug-in is al ingebouwd. Gebruik de bijbehorende updatefunctie.",+ "hostIncompatible": "Deze plug-in vereist Motrix {{required}}; huidige versie: {{current}}. Werk Motrix bij of schakel over naar een compatibele versie en probeer het opnieuw."},"lead": "Voeg kleine functies toe aan Motrix. Laat de plug-ins die je vertrouwt ingeschakeld en schakel de rest uit.","logs": {diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex dc813636..7c202735 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -2373,7 +2373,12 @@"localPrepareFailed": "Nie udało się przygotować tego pliku wtyczki: {{detail}}","dropHint": "Upuść tutaj plik .moext, aby sprawdzić tę wtyczkę","dragDisabledHint": "To środowisko nie obsługuje przeciągania i upuszczania. Użyj adresu GitHub lub adresu URL.",- "warning": "Przed instalacją: kontynuuj tylko wtedy, gdy ufasz autorowi i oczekujesz, że wtyczka będzie korzystać z wymienionych powyżej uprawnień."+ "warning": "Przed instalacją: kontynuuj tylko wtedy, gdy ufasz autorowi i oczekujesz, że wtyczka będzie korzystać z wymienionych powyżej uprawnień.",+ "officialVerified": "Oficjalny podpis Motrix zweryfikowany",+ "officialSignatureInvalid": "Nie udało się zweryfikować oficjalnego podpisu wtyczki. Odśwież katalog.",+ "officialBuiltinOnly": "Ta wersja wymaga uprawnień wbudowanej wtyczki. Zainstaluj nowszą wersję obsługującą opcjonalną instalację.",+ "builtinAlreadyInstalled": "Ta wtyczka jest już wbudowana. Użyj jej funkcji aktualizacji.",+ "hostIncompatible": "Ta wtyczka wymaga Motrix {{required}}; bieżąca wersja: {{current}}. Zaktualizuj Motrix lub przejdź na zgodną wersję i spróbuj ponownie."},"consent": {"installTitle": "Zainstalować {{name}} {{version}}?",diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex dcaf4711..4d3690d9 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -2357,7 +2357,12 @@"localPrepareFailed": "Não foi possível preparar este arquivo de plugin: {{detail}}","dropHint": "Arraste um arquivo .moext para cá para verificar este plugin","dragDisabledHint": "Arrastar e soltar não é compatível com este ambiente. Use um endereço GitHub ou um URL.",- "warning": "Antes de instalar: continue apenas se confiar no autor e esperar que o plugin use os acessos listados acima."+ "warning": "Antes de instalar: continue apenas se confiar no autor e esperar que o plugin use os acessos listados acima.",+ "officialVerified": "Assinatura oficial do Motrix verificada",+ "officialSignatureInvalid": "Não foi possível verificar a assinatura oficial do plugin. Atualize o catálogo.",+ "officialBuiltinOnly": "Esta versão exige privilégios de plugin integrado. Instale uma versão mais recente que permita a instalação opcional.",+ "builtinAlreadyInstalled": "Este plugin já está integrado. Use a função de atualização dele.",+ "hostIncompatible": "Este plugin requer Motrix {{required}}; versão atual: {{current}}. Atualize ou mude para uma versão compatível do Motrix e tente novamente."},"consent": {"installTitle": "Instalar {{name}} {{version}}?",diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex 577cd89e..a35e409c 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -1540,7 +1540,12 @@"title": "Adaugă modul","url": "URL","url.spec": "URL pachet (.moext)",- "warning": "Înainte de instalare: continuă doar dacă ai încredere în autor și te aștepți ca modulul să folosească accesul indicat mai sus."+ "warning": "Înainte de instalare: continuă doar dacă ai încredere în autor și te aștepți ca modulul să folosească accesul indicat mai sus.",+ "officialVerified": "Semnătura oficială Motrix a fost verificată",+ "officialSignatureInvalid": "Semnătura oficială a extensiei nu a putut fi verificată. Reîmprospătați catalogul.",+ "officialBuiltinOnly": "Această versiune necesită privilegii de extensie integrată. Instalați o versiune mai nouă care acceptă instalarea opțională.",+ "builtinAlreadyInstalled": "Această extensie este deja integrată. Utilizați funcția sa de actualizare.",+ "hostIncompatible": "Acest plugin necesită Motrix {{required}}; versiunea curentă: {{current}}. Actualizează sau treci la o versiune compatibilă de Motrix și încearcă din nou."},"lead": "Adaugă funcții mici în Motrix. Păstrează active modulele în care ai încredere și dezactivează-le pe celelalte.","logs": {diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex 2fc861ef..a9935bf9 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -2373,7 +2373,12 @@"localPrepareFailed": "Не удалось подготовить файл плагина: {{detail}}","dropHint": "Перетащите файл .moext сюда, чтобы проверить плагин","dragDisabledHint": "Перетаскивание не поддерживается в этой среде. Используйте адрес GitHub или URL.",- "warning": "Перед установкой убедитесь, что доверяете автору и согласны с использованием плагином указанного выше доступа."+ "warning": "Перед установкой убедитесь, что доверяете автору и согласны с использованием плагином указанного выше доступа.",+ "officialVerified": "Официальная подпись Motrix проверена",+ "officialSignatureInvalid": "Не удалось проверить официальную подпись плагина. Обновите каталог.",+ "officialBuiltinOnly": "Эта версия требует прав встроенного плагина. Установите более новую версию с поддержкой необязательной установки.",+ "builtinAlreadyInstalled": "Этот плагин уже встроен. Используйте его функцию обновления.",+ "hostIncompatible": "Для этого плагина требуется Motrix {{required}}; текущая версия: {{current}}. Обновите Motrix или перейдите на совместимую версию и повторите попытку."},"consent": {"installTitle": "Установить {{name}} {{version}}?",diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex b900288c..13815502 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -1506,7 +1506,12 @@"title": "เพิ่มปลั๊กอิน","url": "URL","url.spec": "URL แพ็กเกจ (.moext)",- "warning": "ก่อนติดตั้ง: ดำเนินการต่อเฉพาะเมื่อเชื่อถือผู้เขียนและคาดหมายให้ปลั๊กอินใช้สิทธิ์ที่แสดงไว้ข้างต้น"+ "warning": "ก่อนติดตั้ง: ดำเนินการต่อเฉพาะเมื่อเชื่อถือผู้เขียนและคาดหมายให้ปลั๊กอินใช้สิทธิ์ที่แสดงไว้ข้างต้น",+ "officialVerified": "ตรวจสอบลายเซ็นอย่างเป็นทางการของ Motrix แล้ว",+ "officialSignatureInvalid": "ไม่สามารถตรวจสอบลายเซ็นอย่างเป็นทางการของปลั๊กอินได้ ลองรีเฟรชตลาดปลั๊กอิน",+ "officialBuiltinOnly": "เวอร์ชันนี้ต้องใช้สิทธิ์ของปลั๊กอินในตัว โปรดติดตั้งเวอร์ชันใหม่ที่รองรับการติดตั้งแบบเลือกได้",+ "builtinAlreadyInstalled": "ปลั๊กอินนี้มีอยู่ในตัวแล้ว โปรดใช้ฟังก์ชันอัปเดตของปลั๊กอิน",+ "hostIncompatible": "ปลั๊กอินนี้ต้องใช้ Motrix {{required}}; เวอร์ชันปัจจุบัน: {{current}} โปรดอัปเกรดหรือเปลี่ยนเป็น Motrix เวอร์ชันที่เข้ากันได้แล้วลองอีกครั้ง"},"lead": "เพิ่มความสามารถเล็กๆ ให้ Motrix เปิดใช้เฉพาะปลั๊กอินที่เชื่อถือและปิดที่เหลือ","logs": {diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex 3c567e99..6843b0f7 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -2341,7 +2341,12 @@"localPrepareFailed": "Bu eklenti dosyası hazırlanamadı: {{detail}}","dropHint": "Bu eklentiyi kontrol etmek için buraya bir .moext dosyası bırakın","dragDisabledHint": "Bu ortamda sürükleyip bırakma desteklenmiyor. GitHub adresi veya URL kullanın.",- "warning": "Yüklemeden önce: yalnızca yazara güveniyorsanız ve eklentinin yukarıda belirtilen erişimleri kullanmasını bekliyorsanız devam edin."+ "warning": "Yüklemeden önce: yalnızca yazara güveniyorsanız ve eklentinin yukarıda belirtilen erişimleri kullanmasını bekliyorsanız devam edin.",+ "officialVerified": "Resmî Motrix imzası doğrulandı",+ "officialSignatureInvalid": "Eklentinin resmî imzası doğrulanamadı. Eklenti mağazasını yenilemeyi deneyin.",+ "officialBuiltinOnly": "Bu sürüm yerleşik eklenti yetkileri gerektirir. İsteğe bağlı kurulumu destekleyen daha yeni bir sürüm yükleyin.",+ "builtinAlreadyInstalled": "Bu eklenti zaten yerleşiktir. Güncelleme işlevini kullanın.",+ "hostIncompatible": "Bu eklenti Motrix {{required}} gerektirir; mevcut sürüm: {{current}}. Motrix uygulamasını yükseltin veya uyumlu bir sürüme geçip yeniden deneyin."},"consent": {"installTitle": "{{name}} {{version}} yüklensin mi?",diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex 8be71311..a610535d 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -1557,7 +1557,12 @@"title": "Додати плагін","url": "URL","url.spec": "URL-адреса пакунка (.moext)",- "warning": "Перед встановленням: продовжуйте, лише якщо довіряєте автору й очікуєте, що плагін використовуватиме вказаний вище доступ."+ "warning": "Перед встановленням: продовжуйте, лише якщо довіряєте автору й очікуєте, що плагін використовуватиме вказаний вище доступ.",+ "officialVerified": "Офіційний підпис Motrix перевірено",+ "officialSignatureInvalid": "Не вдалося перевірити офіційний підпис плагіна. Оновіть каталог.",+ "officialBuiltinOnly": "Ця версія потребує прав вбудованого плагіна. Установіть новішу версію з підтримкою необов’язкового встановлення.",+ "builtinAlreadyInstalled": "Цей плагін уже вбудований. Скористайтеся його функцією оновлення.",+ "hostIncompatible": "Цей плагін потребує Motrix {{required}}; поточна версія: {{current}}. Оновіть Motrix або перейдіть на сумісну версію та повторіть спробу."},"lead": "Додавайте невеликі можливості до Motrix. Залишайте довірені плагіни, решту вимикайте.","logs": {diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex 15a54ff0..8a5fc7f2 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -2325,7 +2325,12 @@"localPrepareFailed": "Không thể chuẩn bị tệp tiện ích này: {{detail}}","dropHint": "Thả tệp .moext vào đây để kiểm tra tiện ích","dragDisabledHint": "Môi trường này không hỗ trợ kéo và thả. Hãy dùng địa chỉ GitHub hoặc URL.",- "warning": "Trước khi cài: chỉ tiếp tục nếu bạn tin tưởng tác giả và đồng ý với việc tiện ích sử dụng các quyền truy cập liệt kê ở trên."+ "warning": "Trước khi cài: chỉ tiếp tục nếu bạn tin tưởng tác giả và đồng ý với việc tiện ích sử dụng các quyền truy cập liệt kê ở trên.",+ "officialVerified": "Đã xác minh chữ ký chính thức của Motrix",+ "officialSignatureInvalid": "Không thể xác minh chữ ký chính thức của tiện ích. Hãy làm mới danh mục.",+ "officialBuiltinOnly": "Phiên bản này yêu cầu quyền của tiện ích tích hợp. Hãy cài phiên bản mới hơn hỗ trợ cài đặt tùy chọn.",+ "builtinAlreadyInstalled": "Tiện ích này đã được tích hợp. Hãy dùng chức năng cập nhật của tiện ích.",+ "hostIncompatible": "Plugin này yêu cầu Motrix {{required}}; phiên bản hiện tại: {{current}}. Hãy nâng cấp hoặc chuyển sang phiên bản Motrix tương thích rồi thử lại."},"consent": {"installTitle": "Cài {{name}} {{version}}?",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 7a7f819f..687069f3 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -2325,7 +2325,12 @@"localPrepareFailed": "无法准备此插件文件:{{detail}}","dropHint": "将 .moext 文件拖至此处以检查该插件","dragDisabledHint": "当前环境不支持拖拽。请使用 GitHub 地址或链接。",- "warning": "安装前请注意:只有信任作者并预期它会使用上述权限时,才继续安装。"+ "warning": "安装前请注意:只有信任作者并预期它会使用上述权限时,才继续安装。",+ "officialVerified": "已验证 Motrix 官方签名",+ "officialSignatureInvalid": "无法验证此插件的官方签名,请刷新插件市场后重试。",+ "officialBuiltinOnly": "此版本需要内置插件专属权限,请安装支持可选安装的新版本。",+ "builtinAlreadyInstalled": "此插件已内置,请使用插件的更新功能。",+ "hostIncompatible": "此插件需要 Motrix {{required}},当前版本为 {{current}}。请升级或切换到满足要求的 Motrix 版本后重试。"},"consent": {"installTitle": "安装 {{name}} {{version}}?",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 97228d87..1053b84e 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -2425,7 +2425,12 @@"localPrepareFailed": "無法準備此外掛程式檔案:{{detail}}","dropHint": "將 .moext 檔案拖放到這裡以檢查此外掛程式","dragDisabledHint": "此環境不支援拖放。請使用 GitHub 位址或 URL。",- "warning": "安裝前請確認:只有在信任作者,且預期其使用上列權限時才繼續。"+ "warning": "安裝前請確認:只有在信任作者,且預期其使用上列權限時才繼續。",+ "officialVerified": "已驗證 Motrix 官方簽章",+ "officialSignatureInvalid": "無法驗證此外掛的官方簽章,請重新整理外掛市集後再試。",+ "officialBuiltinOnly": "此版本需要內建外掛專屬權限,請安裝支援選用安裝的新版本。",+ "builtinAlreadyInstalled": "此外掛已內建,請使用外掛的更新功能。",+ "hostIncompatible": "此擴充功能需要 Motrix {{required}},目前版本為 {{current}}。請升級或切換至符合要求的 Motrix 版本後重試。"},"consent": {"installTitle": "要安裝 {{name}} {{version}} 嗎?",diff --git a/src/shared/schemas/registry.ts b/src/shared/schemas/registry.tsindex 4aab1295..df02c3d0 100644--- a/src/shared/schemas/registry.ts+++ b/src/shared/schemas/registry.ts@@ -326,4 +326,6 @@ export function resolveRegistryListing(/** Registry entry annotated for the renderer with the host-version gate. */export interface RegistryPluginDTO extends RegistryPlugin {compatible: boolean+ /** Supplied by the host; optional for renderers connected to older servers. */+ hostVersion?: string}diff --git a/src/shared/types/plugin-install.ts b/src/shared/types/plugin-install.tsindex 7d2e26c6..6b1367e3 100644--- a/src/shared/types/plugin-install.ts+++ b/src/shared/types/plugin-install.ts@@ -53,6 +53,13 @@ export interface InstallRecord {/** optionalPermission name → state at last consent confirmation */grants: GrantsMapconsentSnapshot: ConsentSnapshot+ /** Signature over the retained archive, rechecked at discovery and activation. */+ official?: OfficialPackageProof+}++export interface OfficialPackageProof {+ signature: string+ archiveSha256: string}export interface TrustSurfaceDiff {@@ -106,8 +113,8 @@ export interface ConsentPayloadTrustSurface {publicCommandsExposed: ReadonlyArray<ConsentPayloadPublicCommand>requestedHeapMB?: numberenginesMotrix: string- /** Always `true` in Phase 1A — there is no signing yet. */- notVerified: true+ /** False only after verification against the pinned official signing keys. */+ notVerified: boolean}export interface ConsentPayloadFfmpegRuntime {@@ -126,3 +133,11 @@ export interface ConsentPayload {diff: TrustSurfaceDiff | nullffmpegRuntime: ConsentPayloadFfmpegRuntime}++/** Expected install failure, returned as data so both transports retain details. */+export interface PluginInstallCompatibilityFailure {+ incompatible: {+ required: string+ hostVersion: string+ }+}diff --git a/src/shared/types/plugin.ts b/src/shared/types/plugin.tsindex a8289cc2..4b5fc953 100644--- a/src/shared/types/plugin.ts+++ b/src/shared/types/plugin.ts@@ -23,6 +23,7 @@ export type PluginSourceType =// <userData>/builtin-updates overlay rather than the read-only seed.| 'builtin-update'| 'registry'+ | 'official'export interface PluginSource {type: PluginSourceTypediff --git a/tests/scripts/audit-server-runtime.test.ts b/tests/scripts/audit-server-runtime.test.tsindex 0173884e..123e078a 100644--- a/tests/scripts/audit-server-runtime.test.ts+++ b/tests/scripts/audit-server-runtime.test.ts@@ -1,6 +1,8 @@+import { execFileSync } from 'node:child_process'import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import os from 'node:os'import path from 'node:path'+import { pathToFileURL } from 'node:url'import { build, type UserConfig } from 'vite'import { afterEach, describe, expect, it } from 'vitest'import { auditServerRuntime } from '../../scripts/audit-server-runtime.mjs'@@ -33,7 +35,7 @@ async function writeFixtureFile(await writeFile(target, content)}-async function scanInMemoryBuild(config: UserConfig): Promise<string[]> {+async function buildChunks(config: UserConfig) {const result = await build({...config,configFile: false,@@ -49,14 +51,17 @@ async function scanInMemoryBuild(config: UserConfig): Promise<string[]> {throw new Error('unexpected Vite watch build')}- const specifiers = new Set<string>()const outputs = Array.isArray(result) ? result : [result]- for (const output of outputs) {- for (const item of output.output) {- if (item.type !== 'chunk') continue- for (const specifier of scanStaticModuleSpecifiers(item.code)) {- specifiers.add(specifier)- }+ return outputs.flatMap((output) =>+ output.output.filter((item) => item.type === 'chunk')+ )+}++async function scanInMemoryBuild(config: UserConfig): Promise<string[]> {+ const specifiers = new Set<string>()+ for (const chunk of await buildChunks(config)) {+ for (const specifier of scanStaticModuleSpecifiers(chunk.code)) {+ specifiers.add(specifier)}}return [...specifiers].sort()@@ -333,6 +338,53 @@ describe('Server package contracts', () => {})describe('Server built external audit', () => {+ it('strips source documentation while preserving legal notices, names, and runtime strings', async () => {+ const root = await mkdtemp(+ path.join(os.tmpdir(), 'motrix-server-comments-')+ )+ temporaryRoots.push(root)+ const input = path.join(root, 'fixture.mjs')+ await writeFile(+ input,+ [+ '/*! @license fixture-license */',+ '/** Build-only documentation marker. */',+ 'export function fixtureOperation(value) {',+ ' return { value, text: "/** runtime string */" }',+ '}',+ ].join('\n')+ )+ const chunks = await buildChunks({+ ...serverViteConfig,+ build: {+ ...serverViteConfig.build,+ lib: { entry: input, formats: ['es'] },+ },+ })+ expect(chunks).toHaveLength(1)+ const code = chunks[0].code+ expect(code).not.toContain('Build-only documentation marker')+ expect(code).toContain('@license fixture-license')+ const output = path.join(root, 'built.mjs')+ await writeFile(output, code)+ const result = execFileSync(+ process.execPath,+ [+ '--input-type=module',+ '--eval',+ [+ `import { fixtureOperation } from ${JSON.stringify(pathToFileURL(output).href)}`,+ 'console.log(JSON.stringify({ name: fixtureOperation.name, result: fixtureOperation(42) }))',+ ].join('\n'),+ ],+ { encoding: 'utf8' }+ )+ expect(JSON.parse(result)).toEqual({+ name: 'fixtureOperation',+ result: { value: 42, text: '/** runtime string */' },+ })+ })+it('matches the actual Server and worker build externals to runtime roots', async () => {const contract = validateServerRuntimeContract(JSON.parse(diff --git a/vite.server.config.ts b/vite.server.config.tsindex a507a4cb..ccbaf010 100644--- a/vite.server.config.ts+++ b/vite.server.config.ts@@ -41,6 +41,9 @@ export default defineConfig({output: {entryFileNames: '[name].mjs',chunkFileNames: 'chunks/[name]-[hash].mjs',+ // Source documentation is not runtime payload. Preserve legal notices+ // and optimization annotations without minifying names or code.+ comments: { jsdoc: false, legal: true, annotation: true },},},},