Skip to content

A full-featured download manager.

feat(plugins): add signed security policy enforcement (#2326)

Dr_rOot36b6aafec23c
diff --git a/.claude/rules/language-and-docs.md b/.claude/rules/language-and-docs.md
index a5bbd1b5..da8f002a 100644
--- a/.claude/rules/language-and-docs.md
+++ b/.claude/rules/language-and-docs.md
@@ -30,3 +30,29 @@ description: Language, bilingual public docs, and private-context boundaries
private account, application, or adjacent repository.
- Rewrite private source material as a standalone public artifact and review
it before committing.
+
+## Maintainer Documentation
+
+- Maintainer operation manuals, deployment runbooks, internal specifications,
+ and implementation plans belong in Obsidian by default. A request to prepare
+ one does not authorize adding it to the repository, committing it, or
+ pushing it. Put it in the repository only when the user explicitly requests
+ a public repository document.
+- Use the project's `pnpm docs` gateway for these documents. Invoke it as
+ `pnpm run docs -- <command>` (or the `docs:*` scripts), because bare
+ `pnpm docs` can resolve to pnpm's built-in package-documentation command.
+ Start with `pnpm run docs -- help` and `pnpm run docs -- doctor`.
+- Resolve the destination from the ignored `obsidian-docs.config.json`. In a
+ new worktree, use `--config <existing-local-config>` when a configured
+ checkout is available. Keep vault names and machine paths out of tracked
+ rules and public documentation.
+- Create documents through `pnpm run docs -- create <directory> <name.md>
+ --from <temporary-file>` using a source file outside the repository. Check
+ existing notes before replacing content; use `--overwrite` only for the
+ intended update. Do not substitute raw vault filesystem writes or UI
+ automation for this gateway.
+- Read back saved content and check code blocks and literal escape sequences;
+ a successful create command alone does not prove the manual is intact.
+- If the gateway or configuration is unavailable, report the specific blocker
+ and retain a temporary copy outside the repository. Do not fall back to
+ placing the manual in `docs/` or publishing it in a PR.
diff --git a/docs/official-optional-plugins.md b/docs/official-optional-plugins.md
index cd1674a8..476cfd27 100644
--- a/docs/official-optional-plugins.md
+++ b/docs/official-optional-plugins.md
@@ -60,3 +60,112 @@ 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.
+
+## Security policy support
+
+The security-policy implementation covers bundled, optional official, community,
+and manually imported plugins in both Electron and Server. **This change does
+not provision a production policy service.** Until independent public keys and
+a signed baseline are checked into `src/shared/plugin-security-trust.ts`, the
+service is dormant, makes no requests, and provides no remote revocation.
+Existing package-signature verification remains in force.
+
+Once provisioned, each host checks a shared static HTTPS feed every 12 hours,
+with ±10% jitter. Checks use ETags and are coalesced; the schedule and retry
+backoff survive restart. A due startup or desktop-resume check is spread over
+5–30 seconds. Failures retry after approximately 15 minutes, one hour, then
+three hours, respecting bounded `Retry-After`. Requests have a five-second
+deadline and a 256 KiB response limit. No plugin inventory is transmitted and
+renderer windows do not poll separately. Server and desktop share the same
+core implementation. No network request is made during plugin invocation or
+page navigation. Routine failures are logged without repeated dialogs.
+
+Rules match a plugin ID with optional inclusive lower/exclusive upper version
+bounds, or an exact `.moext` SHA-256. Version comparisons include prereleases.
+Archive hashes are distinct from executable-entry hashes. New installations
+retain their archive hash; legacy unpacked plugins and bundled seeds may lack
+it, so advisories affecting those installations must also include ID/version
+selectors. Development directories still receive ID/version checks. These are
+known-threat rules, not malware detection or a safety certification.
+
+Accepted rules are checked before installation consent, again at commit, at
+activation, and through the existing execution-policy leases. A new block closes
+admission, aborts leases, terminates the guest without running guest cleanup,
+and terminalizes its queued post-deliveries with `security_revoked`. Returned
+series-hook results are rechecked before engine dispatch and database commit;
+in-flight create requests use the existing engine compensation path. Config,
+grants, plugin files, and the user's enabled preference are preserved. A cache
+verification failure holds execution but does not permanently discard queued
+deliveries. Already completed external side effects cannot be undone.
+
+Known blocks persist offline and after signed metadata expires. Other existing
+plugins remain usable offline. A new external archive can be installed offline,
+but its first activation requires a successful trusted check within 24 hours
+and unexpired signed metadata. Its host-owned admission receipt is bound to the
+exact archive and survives restart. Builtin overlay updates require fresh
+policy before committing. A higher signed revision must explicitly withdraw
+an advisory to release its block; omission or narrowing is rejected. Updating
+to an unaffected version can also remove the block. Normal activation resumes
+according to the unchanged enabled preference; historical dead letters are
+not replayed. Clients without this implementation cannot enforce these rules.
+
+### Policy format and publication
+
+`src/shared/schemas/plugin-security.ts` is the authoritative strict contract.
+The payload contains `schemaVersion: 1`, a monotonically increasing `revision`,
+UTC `issuedAt`/`expiresAt`, and an `advisories` array. Each advisory has a unique
+`id`, `status` (`active` or `withdrawn`), `reason` (`malware`, `vulnerability`, or
+`compromised`), and one or more `affected` selectors. Selectors are ORed:
+
+```json
+[
+ { "kind": "plugin", "pluginId": "example.demo", "fromInclusive": "1.0.0", "beforeExclusive": "1.2.0" },
+ { "kind": "archive", "sha256": "<64 lowercase hexadecimal characters>" }
+]
+```
+
+Optional `fixedVersion` and an HTTPS `motrix.app` advisory `url` provide guidance
+only. No commands, code, automatic installation, or deletion are allowed. Keep
+withdrawn records and their original selectors in subsequent snapshots. If an
+affected range was incorrect, withdraw that ID and add a corrected new ID.
+
+The envelope is `{payload, signatures}`. `payload` is canonical base64 of the
+exact UTF-8 JSON bytes. Each Ed25519 signature covers the UTF-8 prefix
+`motrix-plugin-security-v1\n` followed by those decoded bytes. Any pinned policy
+key may verify it; package-signing keys must not be reused. This is a bounded
+signed-feed protocol, not an implementation of the full TUF role hierarchy.
+Policy lifetime is capped at 14 days; publish renewed signed metadata before
+expiration even when advisories are unchanged. HTTP 304 never extends the
+signed expiration. Expiry detects stale distribution but cannot deliver a new
+block to an offline client. Network rollback protection uses the persisted
+revision and the bundled baseline; replacing the client or its trusted local
+profile is outside this mechanism's protection.
+
+Prepare an envelope offline using an independently managed Ed25519 private key:
+
+```sh
+node --import tsx scripts/sign-plugin-security.mjs \
+ --input policy.json --key /secure/policy-signing.pem \
+ --previous previous-signed.json --output next-signed.json
+pnpm run check:plugin-security -- --require-configured
+```
+
+Omit `--previous` only for the initial policy. The signing tool validates the
+payload and transitions, verifies its output, and refuses to overwrite an
+artifact. It does not generate keys or publish anything. Provision the public
+key, an empty signed initial baseline, and the actual HTTPS URL in the build;
+run the required configured check before distributing an enabled build. Never
+commit private keys or sign test revocations with production keys. Rotate keys
+through a host release containing both the old and new public keys before
+switching signers; supply `--previous-public-key /trusted/old-public.pem` when
+signing with the new key so the preceding envelope is verified with the old key.
+Do not silently treat a signature failure as an initial publication.
+
+Publish only reviewed envelopes through a protected deployment workflow to a
+CDN-cached static object, with a short edge TTL (for example five minutes), stable
+ETags, and an atomic object replacement. Keep versioned artifacts for audit;
+undo a mistaken rule with a higher revision and explicit withdrawal, never by
+restoring an old object. Under healthy networking a 12-hour client schedule may
+take about 13 hours to observe a new block, plus CDN/network delays. A storage
+failure preserves in-memory blocks and closes new first admissions, but no
+implementation can promise persistence across power loss when disk writes fail.
diff --git a/docs/official-optional-plugins.zh-CN.md b/docs/official-optional-plugins.zh-CN.md
index 252879db..93f7e5a7 100644
--- a/docs/official-optional-plugins.zh-CN.md
+++ b/docs/official-optional-plugins.zh-CN.md
@@ -48,3 +48,88 @@ Motrix 使用内置的官方签名公钥验证完整安装包后,才会显示
`pre-resolve`,仍不能作为可选插件安装。需要先发布并上架改为 `enrich`
的新实现,再恢复提供此插件。仅更新应用不会发布该安装包。
未签名的本地文件或任意下载 URL 不能声明官方身份;此安装通道从注册表获取独立签名。
+
+## 安全策略支持
+
+安全策略实现覆盖 Electron 和 Server 中的内置、官方可选、社区及手动导入插件。
+**本次变更尚未配置生产策略服务。** 在 `src/shared/plugin-security-trust.ts`
+中接入独立公钥和签名基线前,服务不启动、不发请求,也不提供远程禁用能力。
+已有的安装包签名验证继续生效。
+
+接入后,每个宿主每 12 小时检查一次公共静态 HTTPS 策略,加入 ±10% 随机偏移。
+请求使用 ETag 并合并并发检查;检查时间和失败退避会持久化,重启不会重复请求。
+启动或桌面端唤醒时,已到期的检查随机延迟 5~30 秒。失败后依次约 15 分钟、
+1 小时、3 小时重试,并遵守有上限的 `Retry-After`。单次请求限时 5 秒,响应上限
+256 KiB。不上传已安装插件清单,各窗口不单独轮询。Server 与桌面端共用核心实现;
+执行插件和切换页面不发网络请求。普通同步失败只记日志,不反复弹窗。
+
+规则按插件 ID 和版本范围,或完整 `.moext` 的 SHA-256 匹配。版本下限包含、上限
+不包含,比较保留预发布版本语义。安装包哈希与执行入口文件哈希分别记录。新安装
+的插件保留包哈希;旧版解压插件和随应用分发的内置种子可能缺少该哈希,针对这些
+安装的公告必须同时包含 ID/版本规则。开发目录也接受 ID/版本检查。这是已知威胁
+封禁机制,不能替代恶意代码检测,也不构成安全认证。
+
+宿主在安装权限确认前、提交安装时、激活时及现有执行策略租约中检查规则。
+新禁用规则先关闭执行入口、取消租约,终止插件执行环境并跳过插件自己的退出
+回调;排队的后置投递以 `security_revoked` 原因终止。串行 Hook 返回的暂存结果
+在引擎派发和数据库提交前再次校验;已派发的创建请求沿用现有引擎补偿清理流程。
+保留配置、权限、插件文件
+及用户原来的启用偏好。缓存验证失败会暂停执行,但不会永久丢弃排队投递。
+已经完成的外部操作无法撤回。
+
+已确认的禁用在离线和签名元数据过期后继续有效,其他已有插件可离线运行。
+新外部安装包可以离线安装,但首次激活需要最近 24 小时内成功检查可信策略,且
+签名元数据尚未过期。宿主保存与具体安装包绑定的检查凭据,重启后仍可使用。
+内置覆盖更新在提交前要求策略新鲜。解除禁用必须通过更高签名版本明确撤回公告;
+遗漏或缩小原规则会被拒绝。更新到未受影响的版本也可解除对应禁用。
+解除后按用户原来的启用偏好恢复正常激活,不重放已终止的投递。未实现此机制的
+历史客户端无法执行这些规则。
+
+### 策略格式与发布
+
+`src/shared/schemas/plugin-security.ts` 是权威的严格协议。正文包含
+`schemaVersion: 1`、单调递增的 `revision`、UTC `issuedAt`/`expiresAt` 和
+`advisories` 数组。每条公告有唯一 `id`、`status`(`active` 或 `withdrawn`)、
+`reason`(`malware`、`vulnerability` 或 `compromised`),以及至少一条
+`affected` 匹配条件。任意一条条件命中即生效:
+
+```json
+[
+ { "kind": "plugin", "pluginId": "example.demo", "fromInclusive": "1.0.0", "beforeExclusive": "1.2.0" },
+ { "kind": "archive", "sha256": "<64 lowercase hexadecimal characters>" }
+]
+```
+
+可选的 `fixedVersion` 和 HTTPS `motrix.app` 公告 `url` 只用于提示。
+协议不允许下发命令、代码、自动安装或删除操作。后续快照必须保留已撤回的记录
+及原有匹配条件。范围错误时,撤回旧公告,再用新 ID 发布更正后的规则。
+
+签名信封为 `{payload, signatures}`。`payload` 是正文 UTF-8 原始字节的标准
+base64;每个 Ed25519 签名覆盖 UTF-8 前缀 `motrix-plugin-security-v1\n`
+与解码后的正文。任一内置策略公钥验证成功即可接受;不得复用安装包签名密钥。
+这是有边界的签名静态策略协议,并未实现完整 TUF 角色体系。策略有效期上限为
+14 天,即使规则未变化,也须在过期前重新签发。HTTP 304 不会延长签名有效期。
+过期检查可发现长期陈旧的分发内容,但无法把新禁用规则送达离线客户端。
+网络防回滚依赖本地持久化版本和随包基线;替换客户端或其可信本地配置不在保护范围内。
+
+使用独立管理的 Ed25519 私钥离线生成信封:
+
+```sh
+node --import tsx scripts/sign-plugin-security.mjs \
+ --input policy.json --key /secure/policy-signing.pem \
+ --previous previous-signed.json --output next-signed.json
+pnpm run check:plugin-security -- --require-configured
+```
+
+只有初始策略可省略 `--previous`。工具验证格式和版本变更、验证签名结果,且拒绝
+覆盖已有产物;不会生成密钥或发布文件。将公钥、初始空规则签名基线及真实 HTTPS
+地址接入构建,在分发启用此功能的版本前执行强制配置校验。不得提交私钥,也不得
+用生产密钥签署测试封禁。轮换时先通过宿主版本分发同时信任新旧公钥的构建,再切换
+签名方;新密钥签名时传入 `--previous-public-key /trusted/old-public.pem`,
+使用旧公钥验证上一份信封,不能把验签失败当作首次发布。
+
+只通过受保护的部署工作流发布已审核信封,使用 CDN 缓存静态对象,设置较短边缘
+TTL(例如 5 分钟)、稳定 ETag 和原子替换。保留带版本的审计产物;误封用更高版本
+明确撤回,不恢复旧对象。正常网络下,12 小时检查周期可能约 13 小时才发现新规则,
+另加 CDN 和网络延迟。存储失败时保留内存禁用并阻止新的首次激活;磁盘写入失败时,
+无法承诺断电后仍能保存刚收到的策略。
diff --git a/package.json b/package.json
index e7087a36..57b75f2c 100644
--- a/package.json
+++ b/package.json
@@ -19,11 +19,11 @@
"prestart": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron && pnpm run build:finalize-fs",
"start": "node scripts/dev.mjs",
"build": "pnpm run build:builtin && pnpm run build:native-host && pnpm run build:finalize-fs && pnpm build:electron",
- "build:electron": "pnpm run build:legal && node scripts/ensure-native-abi.mjs electron && vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.config.ts",
+ "build:electron": "pnpm run build:legal && pnpm run check:plugin-security && node scripts/ensure-native-abi.mjs electron && vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.config.ts",
"stage:electron": "node scripts/stage-electron-app.mjs",
"verify:electron-package": "node scripts/verify-electron-package.mjs",
"smoke:electron-package": "pnpm run ensure:electron-runtime && node scripts/smoke-electron-package.mjs",
- "build:server": "pnpm run build:builtin && pnpm run build:legal && node scripts/ensure-server-finalize-fs.mjs && vite build --config vite.server.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.web.config.ts",
+ "build:server": "pnpm run build:builtin && pnpm run build:legal && pnpm run check:plugin-security && node scripts/ensure-server-finalize-fs.mjs && vite build --config vite.server.config.ts && vite build --config vite.worker.config.ts && vite build --config vite.renderer.web.config.ts",
"stage:server": "node scripts/stage-server-app.mjs",
"verify:server-package": "node scripts/verify-server-package.mjs",
"smoke:server-package": "node scripts/smoke-server-package.mjs",
@@ -42,6 +42,7 @@
"prestart:server": "node scripts/ensure-native-abi.mjs node",
"start:server": "MOTRIX_SKIP_ELECTRON_REBUILD=1 node dist/server/index.mjs",
"check:boundaries": "node scripts/check-boundaries.mjs",
+ "check:plugin-security": "node --import tsx scripts/check-plugin-security.mjs",
"check:file-names": "node scripts/check-file-names.mjs",
"check:flatpak": "node scripts/verify-flatpak-packaging.mjs",
"check:i18n": "node --import tsx scripts/check-i18n.mjs",
diff --git a/scripts/check-plugin-security.mjs b/scripts/check-plugin-security.mjs
new file mode 100644
index 00000000..c2d83f56
--- /dev/null
+++ b/scripts/check-plugin-security.mjs
@@ -0,0 +1,37 @@
+#!/usr/bin/env node
+import { createPublicKey } from 'node:crypto'
+import { verifySecurityPolicy } from '../src/core/plugin/security/policy-verifier.ts'
+import { BUILTIN_SIGNING_PUBKEYS } from '../src/shared/builtin-signing.ts'
+import { PLUGIN_SECURITY_TRUST } from '../src/shared/plugin-security-trust.ts'
+
+const trust = PLUGIN_SECURITY_TRUST
+if (trust.publicKeys.length === 0) {
+ console.log(
+ 'Plugin security policy is not provisioned; synchronization is dormant.'
+ )
+ if (process.argv.includes('--require-configured')) process.exitCode = 1
+} else {
+ const fingerprint = (pem) =>
+ createPublicKey(pem)
+ .export({ format: 'der', type: 'spki' })
+ .toString('base64')
+ const packageKeys = new Set(BUILTIN_SIGNING_PUBKEYS.map(fingerprint))
+ if (trust.publicKeys.some((key) => packageKeys.has(fingerprint(key))))
+ throw new Error('Security and package signing keys must be independent')
+ if (!trust.baseline) throw new Error('A signed policy baseline is required')
+ const url = new URL(trust.url)
+ if (
+ url.protocol !== 'https:' ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash
+ )
+ throw new Error('A static public HTTPS feed is required')
+ const policy = verifySecurityPolicy(trust.baseline, trust.publicKeys)
+ if (Date.parse(policy.expiresAt) <= Date.now())
+ throw new Error('Refresh the signed baseline before release')
+ console.log(
+ `Plugin security trust verified; baseline revision ${policy.revision}.`
+ )
+}
diff --git a/scripts/sign-plugin-security.mjs b/scripts/sign-plugin-security.mjs
new file mode 100644
index 00000000..5adc0ef3
--- /dev/null
+++ b/scripts/sign-plugin-security.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+// Run with: node --import tsx scripts/sign-plugin-security.mjs --input policy.json
+// --key /secure/signing.pem --output signed.json [--previous previous-signed.json]
+import { createPrivateKey, createPublicKey, sign } from 'node:crypto'
+import { readFile, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseArgs } from 'node:util'
+import {
+ assertPolicyTransition,
+ verifySecurityPolicy,
+} from '../src/core/plugin/security/policy-verifier.ts'
+import { PLUGIN_SECURITY_SIGNATURE_CONTEXT } from '../src/shared/plugin-security-trust.ts'
+import { PluginSecurityPolicySchema } from '../src/shared/schemas/plugin-security.ts'
+
+export function signPluginSecurityPolicy(
+ input,
+ privateKeyPem,
+ previousEnvelope,
+ previousPublicKeyPem
+) {
+ const policy = PluginSecurityPolicySchema.parse(input)
+ const key = createPrivateKey(privateKeyPem)
+ if (key.asymmetricKeyType !== 'ed25519')
+ throw new Error('An Ed25519 key is required')
+ const publicKey = createPublicKey(key)
+ .export({ format: 'pem', type: 'spki' })
+ .toString()
+ if (previousEnvelope) {
+ const previous = verifySecurityPolicy(previousEnvelope, [
+ previousPublicKeyPem ?? publicKey,
+ ])
+ if (policy.revision <= previous.revision)
+ throw new Error('Publication requires a new revision')
+ assertPolicyTransition(previous, policy)
+ }
+ const now = Date.now()
+ if (
+ Date.parse(policy.issuedAt) > now + 5 * 60_000 ||
+ Date.parse(policy.expiresAt) <= now
+ )
+ throw new Error('Cannot publish an expired or future policy')
+ const payload = Buffer.from(JSON.stringify(policy))
+ const signature = sign(
+ null,
+ Buffer.concat([Buffer.from(PLUGIN_SECURITY_SIGNATURE_CONTEXT), payload]),
+ key
+ )
+ const envelope = JSON.stringify({
+ payload: payload.toString('base64'),
+ signatures: [signature.toString('base64')],
+ })
+ verifySecurityPolicy(envelope, [publicKey])
+ return `${envelope}\n`
+}
+
+async function main() {
+ const { values } = parseArgs({
+ options: {
+ input: { type: 'string' },
+ key: { type: 'string' },
+ output: { type: 'string' },
+ previous: { type: 'string' },
+ 'previous-public-key': { type: 'string' },
+ },
+ })
+ if (!values.input || !values.key || !values.output)
+ throw new Error('--input, --key and --output are required')
+ const envelope = signPluginSecurityPolicy(
+ JSON.parse(await readFile(values.input, 'utf8')),
+ await readFile(values.key, 'utf8'),
+ values.previous ? await readFile(values.previous, 'utf8') : undefined,
+ values['previous-public-key']
+ ? await readFile(values['previous-public-key'], 'utf8')
+ : undefined
+ )
+ // Never overwrite an existing publication artifact or print key material.
+ await writeFile(values.output, envelope, { flag: 'wx', mode: 0o600 })
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ main().catch((error) => {
+ console.error(error.message)
+ process.exitCode = 1
+ })
+}
diff --git a/src/core/plugin/hooks/hook-orchestrator.test.ts b/src/core/plugin/hooks/hook-orchestrator.test.ts
index 9620bb9c..1cbdda6b 100644
--- a/src/core/plugin/hooks/hook-orchestrator.test.ts
+++ b/src/core/plugin/hooks/hook-orchestrator.test.ts
@@ -254,6 +254,34 @@ describe('HookOrchestrator', () => {
)
})
+ it('does not count security cancellation as a plugin failure or change the enabled preference', async () => {
+ const { host } = makeMockHost([
+ {
+ id: 'revoked',
+ role: 'resolve',
+ hooks: ['beforeCreate'],
+ handler: () => {
+ throw new Error('bridge disposed')
+ },
+ },
+ ])
+ host.isSecurityRestricted = () => true
+ const breaker = { success: vi.fn(), failure: vi.fn(), isOpen: () => false }
+ const orchestrator = new HookOrchestrator({
+ host,
+ breaker,
+ hookTimeoutMs: TIMEOUTS,
+ ...ORCH_OPTS_BASE,
+ })
+ const result = await orchestrator.runBeforeCreateHttp(
+ makeBeforeCreateDto(),
+ 'task-1'
+ )
+ expect(result.aborted).toBe(true)
+ expect(breaker.failure).not.toHaveBeenCalled()
+ expect(host.disable).not.toHaveBeenCalled()
+ })
+
it('discovers an inactive registry candidate and activates it on Hook demand', async () => {
const plugin: FixturePlugin = {
id: 'idle-plugin',
diff --git a/src/core/plugin/hooks/hook-orchestrator.ts b/src/core/plugin/hooks/hook-orchestrator.ts
index 7292f235..4270260e 100644
--- a/src/core/plugin/hooks/hook-orchestrator.ts
+++ b/src/core/plugin/hooks/hook-orchestrator.ts
@@ -206,6 +206,8 @@ export class HookOrchestrator {
const abort = newHookAbort(timeout)
try {
+ const check = this.opts.host.capturePolicyCheck?.(entry.id)
+ if (check) staged.bindPolicyCheck(entry.id, check)
const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)
await this.opts.host.invokeHook(entry.id, 'beforeCreate', {
taskId,
@@ -231,8 +233,7 @@ export class HookOrchestrator {
this.breaker.success(entry.id, 'beforeCreate')
} catch (e) {
if (e instanceof DownloadSourceError) throw e
- this.breaker.failure(entry.id, 'beforeCreate')
- await this.maybeDisable(entry.id, 'beforeCreate')
+ await this.recordPluginFailure(entry.id, 'beforeCreate')
const message = (e as Error).message
await this.opts.auditLog?.log({
type: 'chain.plugin_error',
@@ -293,6 +294,7 @@ export class HookOrchestrator {
contributors: merged.contributors,
})
+ staged.assertPolicyCurrent()
return { final, contributors: merged.contributors, staged }
}
@@ -355,6 +357,8 @@ export class HookOrchestrator {
const abort = newHookAbort(timeout)
try {
+ const check = this.opts.host.capturePolicyCheck?.(entry.id)
+ if (check) staged.bindPolicyCheck(entry.id, check)
const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)
await this.opts.host.invokeHook(entry.id, 'beforeFinalize', {
taskId,
@@ -387,8 +391,7 @@ export class HookOrchestrator {
}
this.breaker.success(entry.id, 'beforeFinalize')
} catch (e) {
- this.breaker.failure(entry.id, 'beforeFinalize')
- await this.maybeDisable(entry.id, 'beforeFinalize')
+ await this.recordPluginFailure(entry.id, 'beforeFinalize')
const message = (e as Error).message
await this.opts.auditLog?.log({
type: 'chain.plugin_error',
@@ -453,6 +456,7 @@ export class HookOrchestrator {
stagingBytesDiscarded: 0,
})
+ staged.assertPolicyCurrent()
return { final, finalFilePath, replacement, staged }
}
@@ -503,8 +507,7 @@ export class HookOrchestrator {
})
this.breaker.success(entry.id, hook)
} catch (e) {
- this.breaker.failure(entry.id, hook)
- await this.maybeDisable(entry.id, hook)
+ await this.recordPluginFailure(entry.id, hook)
await this.opts.auditLog?.log({
type: 'chain.plugin_error',
hook,
@@ -629,6 +632,17 @@ export class HookOrchestrator {
}
}
+ private async recordPluginFailure(
+ pluginId: string,
+ hook: AnyHook
+ ): Promise<void> {
+ // Host-enforced cancellation must not trip the plugin's error breaker or
+ // overwrite the user's enabled preference.
+ if (this.opts.host.isSecurityRestricted?.(pluginId)) return
+ this.breaker.failure(pluginId, hook)
+ await this.maybeDisable(pluginId, hook)
+ }
+
private metadataSnapshot(
taskId: string,
pluginId: string
diff --git a/src/core/plugin/hooks/staged-effects.test.ts b/src/core/plugin/hooks/staged-effects.test.ts
index 10b263f1..2a2182b8 100644
--- a/src/core/plugin/hooks/staged-effects.test.ts
+++ b/src/core/plugin/hooks/staged-effects.test.ts
@@ -41,6 +41,34 @@ describe('StagedEffectStore', () => {
// ── 2. HTTP patch merge ──────────────────────────────────────────────────────
+ it('rejects revoked returned results before the transaction callback or metadata write', () => {
+ const db = makeDb()
+ let revoked = false
+ store.bindPolicyCheck('plugin-a', () => {
+ if (revoked) throw new Error('security revoked')
+ })
+ store.appendMeta({
+ pluginId: 'plugin-a',
+ op: 'set',
+ key: 'result',
+ value: true,
+ })
+ store.assertPolicyCurrent()
+ // Taking finalize staging must retain the policy fence for the later commit.
+ store.takeAllStagings()
+ revoked = true
+ const commit = vi.fn()
+ expect(() => store.commitMetadata(db, 'task-1', commit)).toThrow(
+ 'security revoked'
+ )
+ expect(commit).not.toHaveBeenCalled()
+ expect(allRows(db, 'task-1')).toEqual([])
+ store.removeFromPlugin('plugin-a')
+ expect(() => store.commitMetadata(db, 'task-1', commit)).not.toThrow()
+ expect(commit).toHaveBeenCalledOnce()
+ db.close()
+ })
+
it('multiple plugins append HTTP patches; latestStagedFields returns post-merge view', () => {
store.appendHttp('plugin-a', 'resolve', {
uris: ['https://cdn.example.com/file.zip'],
diff --git a/src/core/plugin/hooks/staged-effects.ts b/src/core/plugin/hooks/staged-effects.ts
index bfac9ba7..8e5c5e47 100644
--- a/src/core/plugin/hooks/staged-effects.ts
+++ b/src/core/plugin/hooks/staged-effects.ts
@@ -32,6 +32,20 @@ export class StagedEffectStore {
private metaOps: StagedMetadataOp[] = []
private finalizePath: string | undefined
private stagings: Map<string, FfmpegStaging> = new Map()
+ private policyChecks = new Map<string, () => void>()
+
+ bindPolicyCheck(pluginId: string, check: () => void): void {
+ this.policyChecks.set(pluginId, check)
+ }
+
+ get hasPolicyChecks(): boolean {
+ return this.policyChecks.size > 0
+ }
+
+ /** Revalidate returned guest results at the host's commit boundary. */
+ assertPolicyCurrent(): void {
+ for (const check of this.policyChecks.values()) check()
+ }
appendHttp(pluginId: string, role: RoleBand, patch: StagedHttpPatch): void {
// Shallow-clone at the boundary so later caller mutations don't leak in.
@@ -117,6 +131,7 @@ export class StagedEffectStore {
)
db.transaction(() => {
+ this.assertPolicyCurrent()
tx()
const serialized = validateStagedMetadataQuota(db, taskId, this.metaOps)
const now = Date.now()
@@ -150,6 +165,7 @@ export class StagedEffectStore {
this.metaOps = []
this.finalizePath = undefined
this.stagings.clear()
+ this.policyChecks.clear()
}
/**
@@ -165,6 +181,7 @@ export class StagedEffectStore {
this.httpPatches = this.httpPatches.filter((e) => e.pluginId !== pluginId)
this.metaOps = this.metaOps.filter((o) => o.pluginId !== pluginId)
this.stagings.delete(pluginId)
+ this.policyChecks.delete(pluginId)
}
}
diff --git a/src/core/plugin/host/activation-dispatcher.ts b/src/core/plugin/host/activation-dispatcher.ts
index b9a1a3e6..9ebcca0f 100644
--- a/src/core/plugin/host/activation-dispatcher.ts
+++ b/src/core/plugin/host/activation-dispatcher.ts
@@ -82,7 +82,7 @@ export class ActivationDispatcher {
skipped.push({ id: dto.id, reason: 'no registry entry' })
continue
}
- if (!reg.state.enabled) {
+ if (!reg.state.enabled || dto.security) {
skipped.push({ id: dto.id, reason: 'disabled' })
continue
}
diff --git a/src/core/plugin/host/capability-bridge.test.ts b/src/core/plugin/host/capability-bridge.test.ts
index 084d07b7..468fc864 100644
--- a/src/core/plugin/host/capability-bridge.test.ts
+++ b/src/core/plugin/host/capability-bridge.test.ts
@@ -189,6 +189,16 @@ function validBeforeCreatePayload() {
}
describe('CapabilityBridge', () => {
+ it('security teardown preempts an ordinary disposal without sending guest cleanup', async () => {
+ const { bridge } = makeBridge()
+ const worker = bridge.getWorker()
+ const post = vi.spyOn(worker, 'postMessage')
+ const ordinary = bridge.dispose()
+ await bridge.dispose(true)
+ expect(worker.threadId).toBe(-1)
+ await ordinary
+ expect(post).not.toHaveBeenCalledWith({ type: 'event', event: 'shutdown' })
+ })
it('routes a worker log call to the LogCapabilityHost', async () => {
const dir = mkdtempSync(path.join(tmpdir(), 'mbr-'))
const workerPath = writeStubWorker(dir)
diff --git a/src/core/plugin/host/capability-bridge.ts b/src/core/plugin/host/capability-bridge.ts
index 181745fb..82e76e0d 100644
--- a/src/core/plugin/host/capability-bridge.ts
+++ b/src/core/plugin/host/capability-bridge.ts
@@ -379,6 +379,7 @@ export class CapabilityBridge {
private readonly worker: Worker
private readonly log: ReturnType<CapabilityHost['createLog']>
private disposed = false
+ private forceDisposing = false
// Per-plugin lazy instances (constructed once on first use).
private pluginHttpHost: HttpCapabilityHost | null = null
@@ -505,6 +506,7 @@ export class CapabilityBridge {
}
private async onMessage(msg: WorkerToHost): Promise<void> {
+ if (this.disposed) return
if (msg.type === 'ready') {
this.events.onReady?.()
return
@@ -2211,8 +2213,12 @@ export class CapabilityBridge {
for (const [opId] of matches) this.ffmpegOps.delete(opId)
}
- async dispose(): Promise<void> {
- if (this.disposed) return
+ async dispose(force = false): Promise<void> {
+ if (force) this.forceDisposing = true
+ if (this.disposed) {
+ if (force) await this.worker.terminate()
+ return
+ }
this.disposed = true
this.failPendingHook('plugin.runtime.bridge_disposed', 'bridge disposed')
const httpCalls = this.abortHttpCalls(() => true)
@@ -2221,8 +2227,11 @@ export class CapabilityBridge {
entry.handle.abort()
}
this.ffmpegOps.clear()
- await Promise.allSettled(httpCalls.map((entry) => entry.settled))
- this.worker.postMessage({ type: 'event', event: 'shutdown' })
+ if (!force) {
+ await Promise.allSettled(httpCalls.map((entry) => entry.settled))
+ if (!this.forceDisposing)
+ this.worker.postMessage({ type: 'event', event: 'shutdown' })
+ }
await this.worker.terminate()
}
diff --git a/src/core/plugin/host/plugin-host.test.ts b/src/core/plugin/host/plugin-host.test.ts
index 20285987..f000b4c5 100644
--- a/src/core/plugin/host/plugin-host.test.ts
+++ b/src/core/plugin/host/plugin-host.test.ts
@@ -230,6 +230,106 @@ describe('PluginHost', () => {
rmSync(root, { recursive: true, force: true })
})
+ it('revokes a running guest without executing guest cleanup or changing user preference', async () => {
+ let revoked = false
+ vi.spyOn(registry, 'securityDecision').mockImplementation((id) =>
+ revoked && id === 'alice.demo'
+ ? { blocked: true, reason: 'malware', advisoryIds: ['MTX-TEST-1'] }
+ : undefined
+ )
+ const host = new PluginHost({
+ registry,
+ stateStore,
+ capabilityHost: capHost,
+ workerScriptPath: workerPath,
+ appVersion: '2.5.0',
+ runtime: 'server',
+ hostLanguage: 'en-US',
+ })
+ const unavailable = vi.fn().mockResolvedValue(1)
+ host.bindPluginUnavailable(unavailable)
+ try {
+ await host.activate('alice.demo')
+ await host.activate('bob.demo')
+ const bridge = host.bridgeFor('alice.demo')!
+ const guestCleanup = vi.spyOn(bridge, 'runDeactivate')
+ const checkReturnedResult = host.capturePolicyCheck('alice.demo')
+ checkReturnedResult()
+ const lease = host.acquirePolicyLease(
+ 'alice.demo',
+ registry.policyGenerationFor('alice.demo')
+ )
+ revoked = true
+ const stopping = host.enforceSecurityPolicy()
+ expect(lease.signal.aborted).toBe(true)
+ expect(checkReturnedResult).toThrow(
+ expect.objectContaining({ code: ErrorCode.PluginSecurityBlocked })
+ )
+ expect(host.isActive('alice.demo')).toBe(false)
+ await expect(host.activate('alice.demo')).rejects.toMatchObject({
+ code: ErrorCode.PluginSecurityBlocked,
+ })
+ await stopping
+ expect(guestCleanup).not.toHaveBeenCalled()
+ expect(unavailable).toHaveBeenCalledWith(
+ 'alice.demo',
+ 'security_revoked',
+ expect.any(Number)
+ )
+ expect(stateStore.get('alice.demo')?.enabled).toBe(true)
+ expect(host.isQuiescent('alice.demo')).toBe(true)
+ expect(host.isActive('bob.demo')).toBe(true)
+ expect(
+ registry.entries().find((entry) => entry.manifest.id === 'alice.demo')
+ ?.enabled
+ ).toBe(false)
+ lease.release()
+ } finally {
+ await host.shutdown()
+ }
+ })
+
+ it('does not reopen a revoked plugin when durable retention fails', async () => {
+ vi.spyOn(registry, 'securityDecision').mockReturnValue({
+ blocked: true,
+ reason: 'vulnerability',
+ advisoryIds: ['MTX-TEST-1'],
+ })
+ const host = new PluginHost({
+ registry,
+ stateStore,
+ capabilityHost: capHost,
+ workerScriptPath: workerPath,
+ appVersion: '2.5.0',
+ runtime: 'server',
+ hostLanguage: 'en-US',
+ })
+ host.bindPluginUnavailable(async () => {
+ throw new Error('database unavailable')
+ })
+ try {
+ await expect(host.enforceSecurityPolicy()).rejects.toThrow(
+ 'database unavailable'
+ )
+ await expect(host.activate('alice.demo')).rejects.toMatchObject({
+ code: ErrorCode.PluginSecurityBlocked,
+ })
+ expect(() =>
+ host.acquirePolicyLease(
+ 'alice.demo',
+ registry.policyGenerationFor('alice.demo')
+ )
+ ).toThrow()
+ expect(stateStore.get('alice.demo')?.enabled).toBe(true)
+ await new ActivationDispatcher(registry, host).dispatch({
+ kind: 'startup',
+ })
+ expect(host.activeIds()).toEqual([])
+ } finally {
+ await host.shutdown()
+ }
+ })
+
it('activates a plugin and marks it active', async () => {
const host = new PluginHost({
registry,
diff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.ts
index 447f8fc2..a2641717 100644
--- a/src/core/plugin/host/plugin-host.ts
+++ b/src/core/plugin/host/plugin-host.ts
@@ -13,6 +13,7 @@ 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 { PluginSecurityService } from '../security/security-service'
import type { PluginStateStore } from '../state/plugin-state-store'
import { verifyBuiltinSignature } from '../update/signature'
import type { HookName } from './bridge-protocol'
@@ -65,7 +66,11 @@ export interface PluginPolicyLease {
release(): void
}
-export type PluginUnavailableReason = 'disabled' | 'uninstalled' | 'quarantined'
+export type PluginUnavailableReason =
+ | 'disabled'
+ | 'uninstalled'
+ | 'quarantined'
+ | 'security_revoked'
export type PluginUnavailableHandler = (
pluginId: string,
@@ -74,6 +79,8 @@ export type PluginUnavailableHandler = (
) => Promise<number>
export interface PluginHostOptions {
+ security?: PluginSecurityService
+ onSecurityChanged?: () => void
registry: PluginRegistry
stateStore: PluginStateStore
capabilityHost: CapabilityHost
@@ -172,6 +179,8 @@ export class PluginHost {
private idleTimer?: NodeJS.Timeout
private unsubscribeLocale: () => void = () => {}
private shuttingDown = false
+ private unsubscribeSecurity: () => void = () => {}
+ private readonly securityStops = new Map<string, Promise<void>>()
constructor(private readonly opts: PluginHostOptions) {
this.maxActivePlugins = opts.maxActivePlugins ?? DEFAULT_MAX_ACTIVE_PLUGINS
@@ -185,6 +194,8 @@ export class PluginHost {
this.unsubscribeLocale = this.opts.capabilityHost.onLocaleChange((lang) => {
this.broadcastLocaleChange(lang)
})
+ this.unsubscribeSecurity =
+ opts.security?.subscribe(() => this.enforceSecurityPolicy()) ?? (() => {})
}
private broadcastLocaleChange(_lang: string): void {
@@ -298,6 +309,7 @@ export class PluginHost {
pluginId: string,
options: { waitForDeactivation?: boolean } = {}
): Promise<void> {
+ this.opts.registry.assertSecurityAllowed?.(pluginId)
if (this.shuttingDown) {
throw new AppError(
ErrorCode.PluginRuntimeFault,
@@ -393,6 +405,12 @@ export class PluginHost {
`plugin ${pluginId} is disabled`
)
}
+ await this.awaitActivation(
+ pluginId,
+ attempt,
+ this.opts.registry.recordSecurityAdmission?.(pluginId) ??
+ Promise.resolve()
+ )
const policyGeneration = this.policyGenerationFor(pluginId)
if (this.active.size >= this.maxActivePlugins) {
throw new AppError(
@@ -743,6 +761,12 @@ export class PluginHost {
await attempt?.promise.catch(() => undefined)
const active = this.active.get(pluginId)
if (!active) return
+ if (this.opts.registry.securityDecision?.(pluginId)) {
+ active.admissionAbort.abort()
+ await this.teardownActive(pluginId, active, true)
+ await this.laneFor(pluginId).drain()
+ return
+ }
const lane = this.laneFor(pluginId)
const drained = await lane.drainWithin(this.deactivateBudgetMs)
if (!drained) {
@@ -775,6 +799,8 @@ export class PluginHost {
active: Active,
forced: boolean
): Promise<void> {
+ // A revoked guest must not run its own cleanup or issue more capabilities.
+ if (forced) await this.disposeActiveBridge(pluginId, active, true)
// 1. Run worker-side deactivate handlers (budget enforced by bridge).
if (!forced) {
try {
@@ -817,11 +843,12 @@ export class PluginHost {
private async disposeActiveBridge(
pluginId: string,
- active: Active
+ active: Active,
+ force = false
): Promise<void> {
if (!active.disposeNeedsBackstop) {
try {
- await active.bridge.dispose()
+ await active.bridge.dispose(force)
return
} catch (error) {
active.disposeNeedsBackstop = true
@@ -877,6 +904,7 @@ export class PluginHost {
pluginId: string,
attempt: ActivationAttempt
): void {
+ this.opts.registry.assertSecurityAllowed?.(pluginId)
if (!this.isActivationCurrent(pluginId, attempt)) {
throw this.activationSupersededError(pluginId)
}
@@ -1069,6 +1097,26 @@ export class PluginHost {
return this.policyBarriers.has(pluginId)
}
+ isSecurityRestricted(pluginId: string): boolean {
+ return !!this.opts.registry.securityDecision?.(pluginId)
+ }
+
+ /** A returned hook result remains subject to revocation until committed. */
+ capturePolicyCheck(pluginId: string): () => void {
+ const generation = this.policyGenerationFor(pluginId)
+ const check = () => {
+ this.opts.registry.assertSecurityAllowed?.(pluginId)
+ if (
+ this.policyBarriers.has(pluginId) ||
+ this.policyGenerationFor(pluginId) !== generation
+ ) {
+ throw laneAdmissionClosed(pluginId)
+ }
+ }
+ check()
+ return check
+ }
+
/**
* Registers an invocation-scoped policy lease. Policy mutation aborts every
* registered lease before waiting for the plugin lane or worker teardown.
@@ -1077,6 +1125,7 @@ export class PluginHost {
pluginId: string,
expectedGeneration: number
): PluginPolicyLease {
+ this.opts.registry.assertSecurityAllowed?.(pluginId)
if (
this.policyBarriers.has(pluginId) ||
this.policyGenerationFor(pluginId) !== expectedGeneration
@@ -1199,6 +1248,8 @@ export class PluginHost {
async shutdown(): Promise<void> {
this.shuttingDown = true
+ this.unsubscribeSecurity()
+ await this.opts.security?.stop()
this.unsubscribeLocale()
if (this.idleTimer) clearInterval(this.idleTimer)
const pluginIds = new Set([
@@ -1239,6 +1290,7 @@ export class PluginHost {
}
private activeForUse(pluginId: string): Active | undefined {
+ if (this.opts.registry.securityDecision?.(pluginId)) return undefined
if (this.quiescing.has(pluginId) || this.policyBarriers.has(pluginId)) {
return undefined
}
@@ -1281,6 +1333,51 @@ export class PluginHost {
if (!this.shuttingDown) this.laneFor(pluginId).reopen()
}
}
+
+ /** Called on signed-policy refresh; closes all affected lanes before awaiting IO. */
+ enforceSecurityPolicy(): Promise<void> {
+ const operations: Promise<void>[] = []
+ for (const plugin of this.opts.registry.list()) {
+ if (!plugin.security || plugin.security.reason === 'pending') continue
+ const existing = this.securityStops.get(plugin.id)
+ if (existing) {
+ operations.push(existing)
+ continue
+ }
+ this.opts.registry.bumpPolicyGeneration(plugin.id)
+ this.laneFor(plugin.id).close()
+ this.abortPolicyAdmission(plugin.id)
+ const active = this.active.get(plugin.id)
+ const termination = active
+ ? this.disposeActiveBridge(plugin.id, active, true)
+ : Promise.resolve()
+ void termination.catch(() => undefined)
+ const operation = this.applyPolicyMutation(plugin.id, async () => {
+ await termination
+ // An installer may have already replaced the affected identity while
+ // this mutation waited for its lane. Never terminalize its fixed successor.
+ const decision = this.opts.registry.securityDecision(plugin.id)
+ if (decision && decision.advisoryIds.length > 0) {
+ await this.pluginUnavailable(plugin.id, 'security_revoked')
+ }
+ }).finally(() => {
+ this.securityStops.delete(plugin.id)
+ this.opts.onSecurityChanged?.()
+ })
+ this.securityStops.set(plugin.id, operation)
+ operations.push(operation)
+ }
+ this.opts.onSecurityChanged?.()
+ return Promise.all(operations).then(() => undefined)
+ }
+
+ notifySecurityWake(): void {
+ this.opts.security?.notifyWake()
+ }
+
+ refreshSecurityPolicy(force = false): Promise<void> {
+ return this.opts.security?.refresh(force) ?? Promise.resolve()
+ }
}
function isTimerActivityMessage(
diff --git a/src/core/plugin/install/e2e-install.test.ts b/src/core/plugin/install/e2e-install.test.ts
index 65132047..7659c15b 100644
--- a/src/core/plugin/install/e2e-install.test.ts
+++ b/src/core/plugin/install/e2e-install.test.ts
@@ -18,6 +18,7 @@ import { tmpdir } from 'node:os'
import path from 'node:path'
import type { RegistryPluginDTO } from '@shared/schemas/registry'
import { keypair } from '@test-utils/moext'
+import { securityFixture } from '@test-utils/plugin-security'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ServerPluginInstallService } from '../../../server/plugin/install-service'
import type { CapabilityHost } from '../capabilities/interface'
@@ -25,6 +26,7 @@ import { GrantsManager } from '../grants/grants-manager'
import { PluginHost } from '../host/plugin-host'
import { PluginRegistry } from '../plugin-registry'
import { downloadRegistryMoext } from '../registry/registry-fetcher'
+import { PluginSecurityService } from '../security/security-service'
import { PluginStateStore } from '../state/plugin-state-store'
import { readInstallRecord } from './install-record'
import { OFFICIAL_ARCHIVE_FILENAME } from './official-package'
@@ -240,6 +242,7 @@ async function makeInstaller(
stateStore,
hostVersion: '2.5.0',
signingPubkeys: extra.signingPubkeys,
+ security: extra.security,
})
calls = {
deactivated: [],
@@ -1341,3 +1344,131 @@ describe('official optional plugin lifecycle', () => {
await expect(stage()).rejects.toThrow('builtin_already_installed')
})
})
+
+describe('security gates across installation and first activation', () => {
+ it('blocks an exact third-party archive even when its ID is not listed', async () => {
+ const fixture = securityFixture()
+ const now = Date.now()
+ const moext = await writeMoext(
+ path.join(inputDir, 'blocked.moext'),
+ manifestJSON()
+ )
+ const archiveSha256 = createHash('sha256')
+ .update(await readFile(moext))
+ .digest('hex')
+ const policy = fixture.policy(now, {
+ advisories: [
+ {
+ id: 'MTX-TEST-1',
+ status: 'active',
+ reason: 'malware',
+ affected: [{ kind: 'archive', sha256: archiveSha256 }],
+ },
+ ],
+ })
+ const security = new PluginSecurityService({
+ cachePath: path.join(tmp, 'security.json'),
+ trust: fixture.trust,
+ fetchImpl: async () => new Response(fixture.sign(policy)),
+ })
+ await security.refresh()
+ installer = await makeInstaller({ security })
+ try {
+ await expect(
+ installer.stage(moext, { type: 'github', spec: 'example/test' })
+ ).rejects.toMatchObject({ code: 'PLUGIN_SECURITY_BLOCKED' })
+ expect(registry.get('example.test')).toBeUndefined()
+ } finally {
+ await security.stop()
+ }
+ })
+
+ it('rechecks policy after consent and rejects a newly revoked package', async () => {
+ const fixture = securityFixture()
+ let now = Date.now()
+ let policy = fixture.policy(now, { advisories: [] })
+ const security = new PluginSecurityService({
+ cachePath: path.join(tmp, 'security.json'),
+ trust: fixture.trust,
+ now: () => now,
+ fetchImpl: async () => new Response(fixture.sign(policy)),
+ })
+ installer = await makeInstaller({ security })
+ try {
+ const moext = await writeMoext(
+ path.join(inputDir, 'consent.moext'),
+ manifestJSON()
+ )
+ const staged = await installer.stage(moext, {
+ type: 'github',
+ spec: 'example/test',
+ })
+ now += 60_000
+ policy = fixture.policy(now, {
+ revision: 2,
+ advisories: [
+ {
+ id: 'MTX-TEST-2',
+ status: 'active',
+ reason: 'malware',
+ affected: [{ kind: 'plugin', pluginId: 'example.test' }],
+ },
+ ],
+ })
+ await security.refresh(true)
+ await expect(
+ installer.commit(staged.stagingId, {})
+ ).rejects.toMatchObject({ code: 'PLUGIN_SECURITY_BLOCKED' })
+ expect(registry.get('example.test')).toBeUndefined()
+ } finally {
+ await security.stop()
+ }
+ })
+
+ it('installs offline but holds first admission until a fresh policy, then preserves that receipt offline', async () => {
+ const fixture = securityFixture()
+ let now = Date.now()
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockRejectedValue(new Error('offline'))
+ const security = new PluginSecurityService({
+ cachePath: path.join(tmp, 'security.json'),
+ trust: fixture.trust,
+ now: () => now,
+ fetchImpl,
+ })
+ installer = await makeInstaller({ security })
+ try {
+ const moext = await writeMoext(
+ path.join(inputDir, 'offline.moext'),
+ manifestJSON()
+ )
+ const staged = await installer.stage(moext, {
+ type: 'github',
+ spec: 'example/test',
+ })
+ await installer.commit(staged.stagingId, {})
+ expect(registry.securityDecision('example.test')?.reason).toBe('pending')
+ await expect(
+ registry.recordSecurityAdmission('example.test')
+ ).rejects.toMatchObject({ code: 'PLUGIN_SECURITY_PENDING' })
+ now += 60_000
+ fetchImpl.mockResolvedValue(
+ new Response(fixture.sign(fixture.policy(now, { advisories: [] })))
+ )
+ await security.refresh(true)
+ await registry.recordSecurityAdmission('example.test')
+ now += 26 * 60 * 60_000
+ expect(security.isFresh()).toBe(false)
+ await registry.discover()
+ expect(registry.securityDecision('example.test')).toBeUndefined()
+ const record = await readInstallRecord(
+ path.join(pluginsDir, 'example.test')
+ )
+ expect(record?.source.archiveSha256).toMatch(/^[a-f0-9]{64}$/)
+ expect(record?.grants).toEqual({})
+ } finally {
+ await security.stop()
+ }
+ })
+})
diff --git a/src/core/plugin/install/install-record.ts b/src/core/plugin/install/install-record.ts
index cc3ec00f..f7170437 100644
--- a/src/core/plugin/install/install-record.ts
+++ b/src/core/plugin/install/install-record.ts
@@ -19,6 +19,7 @@ export const InstallRecordSchema = z
.object({
version: z.literal(1),
pluginId: z.string().min(1),
+ securityReviewed: z.boolean().optional(),
official: z
.object({
signature: z.string().min(1).max(256),
@@ -31,6 +32,7 @@ export const InstallRecordSchema = z
type: z.enum(INSTALL_SOURCE_TYPES),
url: z.string().min(1),
bundleSha256: Sha256Hex,
+ archiveSha256: Sha256Hex.optional(),
recordedAt: z.number().int(),
})
.strict(),
diff --git a/src/core/plugin/install/plugin-installer.ts b/src/core/plugin/install/plugin-installer.ts
index 5898eb8a..ad1fc116 100644
--- a/src/core/plugin/install/plugin-installer.ts
+++ b/src/core/plugin/install/plugin-installer.ts
@@ -39,6 +39,7 @@ import { parseManifest } from '../manifest/parse'
import { resolveInsidePluginDir } from '../manifest/path-safety'
import type { PluginRegistry } from '../plugin-registry'
import type { PluginExecutableIdentity } from '../post/delivery-types'
+import type { PluginSecurityService } from '../security/security-service'
import type { PluginStateStore } from '../state/plugin-state-store'
import { buildConsentPayload } from './consent-payload'
import { ffmpegSatisfies } from './ffmpeg-semver'
@@ -106,6 +107,7 @@ export interface PluginInstallerRetentionSink {
}
export interface PluginInstallerOptions {
+ security?: PluginSecurityService
pluginsDir: string
registry: PluginRegistry
stateStore: PluginStateStore
@@ -327,8 +329,20 @@ export class PluginInstaller {
type: normalized.type,
url: normalized.url,
bundleSha256,
+ archiveSha256: loadedMoext.archiveSha256,
recordedAt: Date.now(),
}
+ try {
+ await this.opts.security?.refreshIfStale()
+ this.opts.security?.assertAllowed({
+ pluginId: parsedManifest.id,
+ version: parsedManifest.version,
+ archiveSha256: loadedMoext.archiveSha256,
+ })
+ } catch (error) {
+ await rm(stagingDir, { recursive: true, force: true })
+ throw error
+ }
const finalDir = resolvePluginInstallDir(
this.opts.pluginsDir,
parsedManifest.id
@@ -525,6 +539,7 @@ export class PluginInstaller {
version: 1,
pluginId: staged.pluginId,
source: staged.source,
+ securityReviewed: !this.opts.security?.configured,
grants,
consentSnapshot: {
permissions: staged.newManifest.permissions,
@@ -547,6 +562,11 @@ export class PluginInstaller {
let supersededExecutable: PluginExecutableIdentity | undefined
try {
+ this.opts.security?.assertAllowed({
+ pluginId: staged.pluginId,
+ version: staged.newManifest.version,
+ archiveSha256: staged.archiveSha256,
+ })
// Never commit the long-lived staging tree: it was visible while the
// consent dialog was open. Re-read through one file descriptor, verify
// the staged archive digest, then extract those exact bytes into the
@@ -592,6 +612,11 @@ export class PluginInstaller {
this.installCommandSchemas(staged.pluginId, staged.newManifest)
await this.opts.registry.discover()
+ this.opts.security?.assertAllowed({
+ pluginId: staged.pluginId,
+ version: staged.newManifest.version,
+ archiveSha256: staged.archiveSha256,
+ })
if (
staged.official &&
!this.opts.registry.get(staged.pluginId)?.official
diff --git a/src/core/plugin/plugin-registry.ts b/src/core/plugin/plugin-registry.ts
index b588ef57..60db5fec 100644
--- a/src/core/plugin/plugin-registry.ts
+++ b/src/core/plugin/plugin-registry.ts
@@ -7,6 +7,10 @@ import {
type SupportedLocale,
} from '@shared/constants/locales'
import { AppError, ErrorCode } from '@shared/errors'
+import type {
+ PluginSecurityDecision,
+ PluginSecurityIdentity,
+} from '@shared/schemas/plugin-security'
import { semverGt } from '@shared/semver'
import type {
PluginListDTO,
@@ -26,12 +30,18 @@ import {
} from './manifest/i18n-resolve'
import { parseManifest } from './manifest/parse'
import { resolveInsidePluginDir } from './manifest/path-safety'
+import {
+ hasSecurityAdmission,
+ recordSecurityAdmission,
+} from './security/admission-receipts'
+import type { PluginSecurityService } from './security/security-service'
import type { PluginStateStore } from './state/plugin-state-store'
import { verifyBuiltinSignature } from './update/signature'
const log = getLogger('plugin:registry')
export interface PluginRegistryOptions {
+ security?: PluginSecurityService
pluginsDir: string // community: <userDataDir>/plugins
builtinDir: string // built-in: <resourcesDir>/builtin-plugins
stateStore: PluginStateStore
@@ -57,6 +67,8 @@ export interface PluginRegistryOptions {
}
export interface IndexedPlugin {
+ archiveSha256?: string
+ securityPending?: boolean
manifestRaw: PluginManifest
manifest: PluginManifest
origin: 'community' | 'builtin'
@@ -583,6 +595,14 @@ export class PluginRegistry {
origin,
rootDir: dir,
executableDigest,
+ archiveSha256:
+ record?.official?.archiveSha256 ?? record?.source.archiveSha256,
+ securityPending:
+ record?.securityReviewed === false &&
+ !(await hasSecurityAdmission(
+ this.opts.pluginsDir,
+ record.source.archiveSha256
+ )),
state,
...(record?.official
? {
@@ -757,6 +777,7 @@ export class PluginRegistry {
origin: 'builtin',
rootDir: dir,
executableDigest: digestBytes(executable),
+ archiveSha256: digestBytes(bundle),
state,
overlay: {
packageUrl: meta.packageUrl,
@@ -832,7 +853,7 @@ export class PluginRegistry {
return {
pluginId,
generation: this.policyGenerationFor(pluginId),
- enabled: entry.state.enabled,
+ enabled: entry.state.enabled && !this.securityDecision(pluginId),
version: entry.manifest.version,
rootDir: entry.rootDir,
executableDigest: entry.executableDigest,
@@ -860,7 +881,7 @@ export class PluginRegistry {
out.push({
manifest: p.manifest,
origin: p.origin,
- enabled: p.state.enabled,
+ enabled: p.state.enabled && !this.securityDecision(p.manifest.id),
executableDigest: p.executableDigest,
})
}
@@ -882,6 +903,7 @@ export class PluginRegistry {
errorCount: p.state.errorCount,
lastError: p.state.lastError,
source: deriveListSource(p),
+ security: this.securityDecision(p.manifest.id),
})
}
return out
@@ -890,6 +912,60 @@ export class PluginRegistry {
loadErrors(): ReadonlyArray<LoadError> {
return this.errors
}
+
+ securityIdentity(pluginId: string): PluginSecurityIdentity | undefined {
+ const entry = this.byId.get(pluginId)
+ return entry
+ ? {
+ pluginId,
+ version: entry.manifest.version,
+ archiveSha256: entry.archiveSha256,
+ }
+ : undefined
+ }
+
+ securityDecision(pluginId: string): PluginSecurityDecision | undefined {
+ const identity = this.securityIdentity(pluginId)
+ if (!identity) return undefined
+ const decision = this.opts.security?.decision(identity)
+ if (decision) return decision
+ if (
+ this.byId.get(pluginId)?.securityPending &&
+ this.opts.security &&
+ !this.opts.security.isFresh()
+ ) {
+ return { blocked: true, reason: 'pending', advisoryIds: [] }
+ }
+ return undefined
+ }
+
+ assertSecurityAllowed(pluginId: string): void {
+ const decision = this.securityDecision(pluginId)
+ if (decision)
+ throw new AppError(
+ decision.reason === 'pending'
+ ? ErrorCode.PluginSecurityPending
+ : ErrorCode.PluginSecurityBlocked,
+ decision.reason === 'pending'
+ ? 'plugins.security.pending'
+ : 'plugins.security.blocked'
+ )
+ }
+
+ async recordSecurityAdmission(pluginId: string): Promise<void> {
+ this.assertSecurityAllowed(pluginId)
+ const entry = this.byId.get(pluginId)
+ if (!entry?.securityPending) return
+ if (!entry.archiveSha256) {
+ throw new AppError(
+ ErrorCode.PluginSecurityPending,
+ 'plugins.security.pending'
+ )
+ }
+ await recordSecurityAdmission(this.opts.pluginsDir, entry.archiveSha256)
+ this.assertSecurityAllowed(pluginId)
+ if (this.byId.get(pluginId) === entry) entry.securityPending = false
+ }
}
/**
diff --git a/src/core/plugin/post/delivery-retention.ts b/src/core/plugin/post/delivery-retention.ts
index 95fd5a56..2c1d9440 100644
--- a/src/core/plugin/post/delivery-retention.ts
+++ b/src/core/plugin/post/delivery-retention.ts
@@ -181,7 +181,7 @@ export interface PostDeliveryRetentionRepository {
}): Promise<number>
terminalizePlugin(input: {
pluginId: string
- reason: 'disabled' | 'uninstalled' | 'quarantined'
+ reason: 'disabled' | 'uninstalled' | 'quarantined' | 'security_revoked'
at: number
}): Promise<number>
terminalizePermissionRevoked(input: {
@@ -263,7 +263,7 @@ export class PostDeliveryRetention {
async pluginUnavailable(
pluginId: string,
- reason: 'disabled' | 'uninstalled' | 'quarantined',
+ reason: 'disabled' | 'uninstalled' | 'quarantined' | 'security_revoked',
at: number
): Promise<number> {
return this.terminalize(
diff --git a/src/core/plugin/post/delivery-types.ts b/src/core/plugin/post/delivery-types.ts
index eb669288..f4c51251 100644
--- a/src/core/plugin/post/delivery-types.ts
+++ b/src/core/plugin/post/delivery-types.ts
@@ -24,6 +24,7 @@ export const postDeliveryPermanentReasons = [
'disabled',
'uninstalled',
'quarantined',
+ 'security_revoked',
'permission_revoked',
'output_invalid',
'attempt_limit',
@@ -305,6 +306,7 @@ export type PostDeliveryPolicyDecision =
| 'disabled'
| 'uninstalled'
| 'quarantined'
+ | 'security_revoked'
message?: string
}
diff --git a/src/core/plugin/runtime/plugin-hook-runtime.ts b/src/core/plugin/runtime/plugin-hook-runtime.ts
index ed51ede7..67be501e 100644
--- a/src/core/plugin/runtime/plugin-hook-runtime.ts
+++ b/src/core/plugin/runtime/plugin-hook-runtime.ts
@@ -132,7 +132,7 @@ export class PluginHookRuntime {
pluginUnavailable(
pluginId: string,
- reason: 'disabled' | 'uninstalled' | 'quarantined',
+ reason: 'disabled' | 'uninstalled' | 'quarantined' | 'security_revoked',
at: number
): Promise<number> {
return this.retention.pluginUnavailable(pluginId, reason, at)
@@ -228,6 +228,14 @@ export class PluginHookRuntime {
if (!current) {
return { kind: 'permanent', reason: 'uninstalled' }
}
+ const security = this.options.registry.securityDecision?.(
+ record.executable.pluginId
+ )
+ if (security) {
+ if (security.advisoryIds.length === 0)
+ throw new PolicySnapshotStaleError()
+ return { kind: 'permanent', reason: 'security_revoked' }
+ }
if (!current.enabled) {
return { kind: 'permanent', reason: 'disabled' }
}
diff --git a/src/core/plugin/runtime/runtime-factory.ts b/src/core/plugin/runtime/runtime-factory.ts
index 14a7c4f4..19d0dad2 100644
--- a/src/core/plugin/runtime/runtime-factory.ts
+++ b/src/core/plugin/runtime/runtime-factory.ts
@@ -68,7 +68,8 @@ export interface PluginRuntimeAssembly {
finalizeFilesystem: NativeFinalizeFilesystemAdapter
persistTaskWithPluginMetadata(
task: DownloadTask,
- operations: readonly StagedMetadataOp[]
+ operations: readonly StagedMetadataOp[],
+ beforeCommit?: () => void
): Promise<void>
}
@@ -176,7 +177,11 @@ export async function createPluginRuntime(
hooks,
finalize,
finalizeFilesystem,
- persistTaskWithPluginMetadata: (task, operations) =>
- options.session.persistTaskWithPluginMetadata(task, operations),
+ persistTaskWithPluginMetadata: (task, operations, beforeCommit) =>
+ options.session.persistTaskWithPluginMetadata(
+ task,
+ operations,
+ beforeCommit
+ ),
}
}
diff --git a/src/core/plugin/security/admission-receipts.ts b/src/core/plugin/security/admission-receipts.ts
new file mode 100644
index 00000000..2ce86dd0
--- /dev/null
+++ b/src/core/plugin/security/admission-receipts.ts
@@ -0,0 +1,35 @@
+import { mkdir, readFile } from 'node:fs/promises'
+import path from 'node:path'
+import writeFileAtomic from 'write-file-atomic'
+
+function receiptPath(pluginsDir: string, archiveSha256: string): string {
+ if (!/^[a-f0-9]{64}$/.test(archiveSha256))
+ throw new Error('Invalid archive digest')
+ // Outside every plugin directory and extraction root. A package cannot
+ // supply its own receipt. Receipts survive uninstall for the same bytes.
+ return path.join(pluginsDir, '_security-admissions', archiveSha256)
+}
+
+export async function hasSecurityAdmission(
+ pluginsDir: string,
+ archiveSha256: string | undefined
+): Promise<boolean> {
+ if (!archiveSha256) return false
+ try {
+ return (
+ (await readFile(receiptPath(pluginsDir, archiveSha256), 'utf8')) ===
+ 'approved\n'
+ )
+ } catch {
+ return false
+ }
+}
+
+export async function recordSecurityAdmission(
+ pluginsDir: string,
+ archiveSha256: string
+): Promise<void> {
+ const file = receiptPath(pluginsDir, archiveSha256)
+ await mkdir(path.dirname(file), { recursive: true })
+ await writeFileAtomic(file, 'approved\n', { mode: 0o600 })
+}
diff --git a/src/core/plugin/security/policy-verifier.test.ts b/src/core/plugin/security/policy-verifier.test.ts
new file mode 100644
index 00000000..5c5dbaea
--- /dev/null
+++ b/src/core/plugin/security/policy-verifier.test.ts
@@ -0,0 +1,130 @@
+import { securityFixture } from '@test-utils/plugin-security'
+import { describe, expect, it } from 'vitest'
+import {
+ assertPolicyTransition,
+ matchingAdvisories,
+ verifySecurityPolicy,
+} from './policy-verifier'
+
+const now = Date.parse('2026-10-06T00:00:00Z')
+
+describe('plugin security wire trust', () => {
+ it('authenticates exact policy bytes with the independent pinned key', () => {
+ const fixture = securityFixture()
+ const policy = fixture.policy(now)
+ expect(
+ verifySecurityPolicy(fixture.sign(policy), fixture.trust.publicKeys)
+ ).toEqual(policy)
+ expect(() =>
+ verifySecurityPolicy(
+ fixture.sign(policy),
+ securityFixture().trust.publicKeys
+ )
+ ).toThrow('signature')
+ const envelope = JSON.parse(fixture.sign(policy))
+ envelope.payload = Buffer.from(
+ JSON.stringify({ ...policy, revision: 99 })
+ ).toString('base64')
+ expect(() =>
+ verifySecurityPolicy(JSON.stringify(envelope), fixture.trust.publicKeys)
+ ).toThrow('signature')
+ })
+
+ it('rejects unknown instructions, ambiguous rules, and unsupported formats', () => {
+ const fixture = securityFixture()
+ const policy = fixture.policy(now)
+ for (const invalid of [
+ { ...policy, schemaVersion: 2 },
+ { ...policy, execute: 'anything' },
+ { ...policy, advisories: [...policy.advisories, ...policy.advisories] },
+ {
+ ...policy,
+ advisories: [
+ { ...policy.advisories[0], url: 'https://attacker.test/' },
+ ],
+ },
+ {
+ ...policy,
+ advisories: [
+ {
+ ...policy.advisories[0],
+ affected: [
+ {
+ kind: 'plugin',
+ pluginId: 'x',
+ beforeExclusive: '1.0.0',
+ fromInclusive: '2.0.0',
+ },
+ ],
+ },
+ ],
+ },
+ ])
+ expect(() =>
+ verifySecurityPolicy(fixture.sign(invalid), fixture.trust.publicKeys)
+ ).toThrow()
+ })
+
+ it('requires explicit withdrawal and monotonic revisions', () => {
+ const fixture = securityFixture()
+ const first = fixture.policy(now, { revision: 2 })
+ expect(() =>
+ assertPolicyTransition(first, { ...first, revision: 1 })
+ ).toThrow('rollback')
+ expect(() =>
+ assertPolicyTransition(first, { ...first, advisories: [] })
+ ).toThrow('reused')
+ expect(() =>
+ assertPolicyTransition(first, { ...first, revision: 3, advisories: [] })
+ ).toThrow('withdrawal')
+ expect(() =>
+ assertPolicyTransition(first, {
+ ...first,
+ revision: 3,
+ advisories: first.advisories.map((entry) => ({
+ ...entry,
+ status: 'withdrawn',
+ })),
+ })
+ ).not.toThrow()
+ })
+
+ it('matches prerelease bounds and exact archives independently of plugin identity', () => {
+ const fixture = securityFixture()
+ const policy = fixture.policy(now, {
+ advisories: [
+ {
+ id: 'MTX-TEST-2',
+ status: 'active',
+ reason: 'vulnerability',
+ affected: [
+ {
+ kind: 'plugin',
+ pluginId: 'motrix.scraper-hook',
+ fromInclusive: '1.0.0-beta.2',
+ beforeExclusive: '1.0.0-beta.4',
+ },
+ { kind: 'archive', sha256: 'a'.repeat(64) },
+ ],
+ },
+ ],
+ })
+ expect(
+ matchingAdvisories(policy, {
+ pluginId: 'motrix.scraper-hook',
+ version: '1.0.0-beta.3',
+ })
+ ).toHaveLength(1)
+ for (const version of ['1.0.0-beta.1', '1.0.0-beta.4', '1.0.0'])
+ expect(
+ matchingAdvisories(policy, { pluginId: 'motrix.scraper-hook', version })
+ ).toHaveLength(0)
+ expect(
+ matchingAdvisories(policy, {
+ pluginId: 'renamed.plugin',
+ version: '9.9.9',
+ archiveSha256: 'a'.repeat(64),
+ })
+ ).toHaveLength(1)
+ })
+})
diff --git a/src/core/plugin/security/policy-verifier.ts b/src/core/plugin/security/policy-verifier.ts
new file mode 100644
index 00000000..28f73cae
--- /dev/null
+++ b/src/core/plugin/security/policy-verifier.ts
@@ -0,0 +1,92 @@
+import { createPublicKey, verify } from 'node:crypto'
+import { PLUGIN_SECURITY_SIGNATURE_CONTEXT } from '@shared/plugin-security-trust'
+import {
+ PLUGIN_SECURITY_MAX_BYTES,
+ PluginSecurityEnvelopeSchema,
+ type PluginSecurityIdentity,
+ type PluginSecurityPolicy,
+ PluginSecurityPolicySchema,
+} from '@shared/schemas/plugin-security'
+import { compareSemver } from '@shared/semver'
+
+export function verifySecurityPolicy(
+ raw: string,
+ publicKeys: readonly string[]
+): PluginSecurityPolicy {
+ if (Buffer.byteLength(raw) > PLUGIN_SECURITY_MAX_BYTES)
+ throw new Error('Security policy exceeds size limit')
+ const envelope = PluginSecurityEnvelopeSchema.parse(JSON.parse(raw))
+ const payload = Buffer.from(envelope.payload, 'base64')
+ if (payload.toString('base64') !== envelope.payload)
+ throw new Error('Noncanonical policy payload')
+ const bytes = Buffer.concat([
+ Buffer.from(PLUGIN_SECURITY_SIGNATURE_CONTEXT),
+ payload,
+ ])
+ const valid = publicKeys.some((pem) => {
+ const key = createPublicKey(pem)
+ if (key.asymmetricKeyType !== 'ed25519') return false
+ return envelope.signatures.some((signature) => {
+ const decoded = Buffer.from(signature, 'base64')
+ return (
+ decoded.length === 64 &&
+ decoded.toString('base64') === signature &&
+ verify(null, bytes, key, decoded)
+ )
+ })
+ })
+ if (!valid) throw new Error('Untrusted security policy signature')
+ return PluginSecurityPolicySchema.parse(JSON.parse(payload.toString('utf8')))
+}
+
+export function assertPolicyTransition(
+ previous: PluginSecurityPolicy | undefined,
+ next: PluginSecurityPolicy
+): void {
+ if (!previous) return
+ if (next.revision < previous.revision)
+ throw new Error('Security policy rollback')
+ if (
+ next.revision === previous.revision &&
+ JSON.stringify(next) !== JSON.stringify(previous)
+ ) {
+ throw new Error('Security policy revision reused')
+ }
+ if (Date.parse(next.issuedAt) < Date.parse(previous.issuedAt))
+ throw new Error('Security policy timestamp rollback')
+ const entries = new Map(next.advisories.map((entry) => [entry.id, entry]))
+ for (const advisory of previous.advisories) {
+ const replacement = entries.get(advisory.id)
+ // Removing or narrowing an existing rule cannot silently release it.
+ // Withdraw it explicitly and issue a new ID for a corrected selector.
+ if (
+ !replacement ||
+ JSON.stringify(replacement.affected) !== JSON.stringify(advisory.affected)
+ ) {
+ throw new Error(
+ 'Security advisory removed or narrowed without withdrawal'
+ )
+ }
+ }
+}
+
+export function matchingAdvisories(
+ policy: PluginSecurityPolicy,
+ identity: PluginSecurityIdentity
+) {
+ return policy.advisories.filter(
+ (advisory) =>
+ advisory.status === 'active' &&
+ advisory.affected.some((selector) => {
+ if (selector.kind === 'archive')
+ return identity.archiveSha256 === selector.sha256
+ return (
+ identity.pluginId === selector.pluginId &&
+ (!selector.fromInclusive ||
+ compareSemver(identity.version, selector.fromInclusive) >= 0) &&
+ (!selector.beforeExclusive ||
+ compareSemver(identity.version, selector.beforeExclusive) < 0)
+ )
+ })
+ )
+}
diff --git a/src/core/plugin/security/security-service.test.ts b/src/core/plugin/security/security-service.test.ts
new file mode 100644
index 00000000..d4a743f2
--- /dev/null
+++ b/src/core/plugin/security/security-service.test.ts
@@ -0,0 +1,217 @@
+// @vitest-environment node
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import {
+ PLUGIN_SECURITY_FRESHNESS_MS,
+ PLUGIN_SECURITY_INTERVAL_MS,
+ PLUGIN_SECURITY_MAX_BYTES,
+} from '@shared/schemas/plugin-security'
+import { securityFixture } from '@test-utils/plugin-security'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { PluginSecurityService } from './security-service'
+
+describe('low-overhead plugin security synchronization', () => {
+ let root: string
+ let now: number
+ const services: PluginSecurityService[] = []
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'motrix-security-'))
+ now = Date.parse('2026-10-06T00:00:00Z')
+ })
+ afterEach(async () => {
+ await Promise.all(services.splice(0).map((service) => service.stop()))
+ vi.useRealTimers()
+ await rm(root, { recursive: true, force: true })
+ })
+
+ function setup(
+ overrides: Partial<
+ ConstructorParameters<typeof PluginSecurityService>[0]
+ > = {}
+ ) {
+ const fixture = securityFixture()
+ const initialPolicy = fixture.policy(now)
+ const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
+ async () =>
+ new Response(fixture.sign(initialPolicy), {
+ headers: { etag: '"policy-1"' },
+ })
+ )
+ const options = {
+ cachePath: path.join(root, 'policy.json'),
+ trust: fixture.trust,
+ fetchImpl,
+ now: () => now,
+ random: () => 0.5,
+ ...overrides,
+ }
+ const service = new PluginSecurityService(options)
+ services.push(service)
+ return { fixture, service, fetchImpl, options }
+ }
+
+ it('coalesces checks, uses 12-hour scheduling, and performs no per-invocation requests', async () => {
+ const { service, fetchImpl } = setup()
+ await Promise.all([
+ service.refresh(),
+ service.refresh(),
+ service.refresh(true),
+ ])
+ for (let i = 0; i < 1000; i++)
+ expect(
+ service.decision({ pluginId: 'alice.demo', version: '1.0.0' })?.blocked
+ ).toBe(true)
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ now += PLUGIN_SECURITY_INTERVAL_MS - 1
+ await service.refresh()
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ now += 1
+ await service.refresh()
+ expect(fetchImpl).toHaveBeenCalledTimes(2)
+ expect(fetchImpl.mock.calls[1][1]?.headers).toMatchObject({
+ 'if-none-match': '"policy-1"',
+ })
+ expect(fetchImpl.mock.calls[0][0]?.toString()).toBe(
+ 'https://security.example.test/plugins-v1.json'
+ )
+ })
+
+ it('persists scheduling across restarts and accepts a valid 304 without extending signed expiry', async () => {
+ const { service, options, fetchImpl } = setup()
+ await service.refresh()
+ const restarted = new PluginSecurityService(options)
+ services.push(restarted)
+ await restarted.initialize()
+ await restarted.refresh()
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ now += PLUGIN_SECURITY_INTERVAL_MS
+ fetchImpl.mockResolvedValue(new Response(null, { status: 304 }))
+ await restarted.refresh()
+ expect(restarted.isFresh()).toBe(true)
+ now += 8 * 24 * 60 * 60_000
+ await restarted.refresh()
+ expect(restarted.isFresh()).toBe(false)
+ expect(
+ restarted.decision({ pluginId: 'alice.demo', version: '1.0.0' })?.blocked
+ ).toBe(true)
+ })
+
+ it('retains known blocks offline and requires a recent check for first admission', async () => {
+ const { service, fetchImpl } = setup()
+ expect(service.isFresh()).toBe(false)
+ await service.refresh()
+ now += 20 * 60 * 60_000
+ fetchImpl.mockRejectedValue(new Error('offline'))
+ await service.refresh()
+ expect(service.isFresh()).toBe(true)
+ now += 6 * 60 * 60_000
+ expect(service.isFresh()).toBe(false)
+ expect(
+ service.decision({ pluginId: 'alice.demo', version: '1.0.0' })?.blocked
+ ).toBe(true)
+ expect(
+ service.decision({ pluginId: 'bob.demo', version: '1.0.0' })
+ ).toBeUndefined()
+ })
+
+ it('rejects rollback, narrowing and invalid signatures without removing known blocks', async () => {
+ const { fixture, service, fetchImpl } = setup()
+ const first = fixture.policy(now, { revision: 3 })
+ fetchImpl.mockResolvedValueOnce(new Response(fixture.sign(first)))
+ await service.refresh()
+ for (const response of [
+ fixture.sign({ ...first, revision: 2 }),
+ fixture.sign({ ...first, revision: 4, advisories: [] }),
+ securityFixture().sign({ ...first, revision: 4, advisories: [] }),
+ '<html>upstream error</html>',
+ 'x'.repeat(PLUGIN_SECURITY_MAX_BYTES + 1),
+ ]) {
+ now += PLUGIN_SECURITY_INTERVAL_MS
+ fetchImpl.mockResolvedValueOnce(new Response(response))
+ await service.refresh(true)
+ expect(
+ service.decision({ pluginId: 'alice.demo', version: '1.0.0' })?.blocked
+ ).toBe(true)
+ }
+ now += PLUGIN_SECURITY_INTERVAL_MS
+ fetchImpl.mockResolvedValueOnce(
+ new Response(
+ fixture.sign({
+ ...first,
+ revision: 4,
+ advisories: first.advisories.map((entry) => ({
+ ...entry,
+ status: 'withdrawn',
+ })),
+ })
+ )
+ )
+ await service.refresh(true)
+ expect(
+ service.decision({ pluginId: 'alice.demo', version: '1.0.0' })
+ ).toBeUndefined()
+ })
+
+ it('keeps admission closed when cache is corrupt or newly accepted policy cannot be saved', async () => {
+ await writeFile(path.join(root, 'policy.json'), 'broken')
+ const { service } = setup({
+ writeCache: async () => {
+ throw new Error('disk full')
+ },
+ })
+ await service.initialize()
+ expect(
+ service.decision({ pluginId: 'bob.demo', version: '1.0.0' })?.reason
+ ).toBe('unavailable')
+ await service.refresh()
+ expect(
+ service.decision({ pluginId: 'alice.demo', version: '1.0.0' })?.reason
+ ).toBe('malware')
+ expect(service.isFresh()).toBe(false)
+ })
+
+ it('backs off across restarts and respects Retry-After without transmitting inventory', async () => {
+ const { service, fetchImpl, options } = setup()
+ fetchImpl.mockResolvedValueOnce(
+ new Response(null, { status: 429, headers: { 'retry-after': '7200' } })
+ )
+ await service.refresh()
+ const cached = JSON.parse(await readFile(options.cachePath, 'utf8'))
+ expect(cached.nextCheckAt - now).toBe(2 * 60 * 60_000)
+ const restarted = new PluginSecurityService(options)
+ services.push(restarted)
+ await restarted.refresh()
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ expect(fetchImpl.mock.calls[0][1]).toMatchObject({
+ credentials: 'omit',
+ redirect: 'error',
+ })
+ })
+
+ it('spreads startup and makes only two scheduled checks per day', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(now)
+ const { service, fetchImpl } = setup({ now: () => Date.now() })
+ await service.initialize()
+ service.start()
+ await vi.advanceTimersByTimeAsync(17_499)
+ expect(fetchImpl).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ await service.refresh()
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(PLUGIN_SECURITY_FRESHNESS_MS - 17_500)
+ expect(fetchImpl).toHaveBeenCalledTimes(2)
+ })
+
+ it('leaves an unprovisioned build dormant with no background requests', async () => {
+ const { service, fetchImpl } = setup({
+ trust: { url: 'https://unused.test/', publicKeys: [], baseline: null },
+ })
+ await service.initialize()
+ service.start()
+ await service.refresh(true)
+ expect(service.configured).toBe(false)
+ expect(fetchImpl).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/core/plugin/security/security-service.ts b/src/core/plugin/security/security-service.ts
new file mode 100644
index 00000000..5c87c2d5
--- /dev/null
+++ b/src/core/plugin/security/security-service.ts
@@ -0,0 +1,437 @@
+import { mkdir, readFile, stat } from 'node:fs/promises'
+import path from 'node:path'
+import { getLogger } from '@core/logger'
+import { AppError, ErrorCode } from '@shared/errors'
+import { PLUGIN_SECURITY_TRUST } from '@shared/plugin-security-trust'
+import {
+ PLUGIN_SECURITY_FRESHNESS_MS,
+ PLUGIN_SECURITY_INTERVAL_MS,
+ PLUGIN_SECURITY_MAX_BYTES,
+ type PluginSecurityDecision,
+ type PluginSecurityIdentity,
+ type PluginSecurityPolicy,
+} from '@shared/schemas/plugin-security'
+import writeFileAtomic from 'write-file-atomic'
+import { z } from 'zod'
+import {
+ assertPolicyTransition,
+ matchingAdvisories,
+ verifySecurityPolicy,
+} from './policy-verifier'
+
+const log = getLogger('plugin:security')
+const CACHE_LIMIT = PLUGIN_SECURITY_MAX_BYTES * 2
+const RETRY_MS = [15 * 60_000, 60 * 60_000, 3 * 60 * 60_000]
+const CacheSchema = z
+ .object({
+ version: z.literal(1),
+ envelope: z.string().nullable(),
+ checkedAt: z.number().nonnegative(),
+ nextCheckAt: z.number().nonnegative(),
+ failures: z.number().int().nonnegative().max(100),
+ etag: z.string().max(512).nullable(),
+ })
+ .strict()
+
+export interface PluginSecurityServiceOptions {
+ cachePath: string
+ /** Only tests/embedders inject trust; production uses the pinned build. */
+ trust?: typeof PLUGIN_SECURITY_TRUST
+ fetchImpl?: typeof fetch
+ now?: () => number
+ random?: () => number
+ writeCache?: (file: string, contents: string) => Promise<void>
+}
+
+/** One scheduler per host. Guest admission never performs network IO. */
+export class PluginSecurityService {
+ private readonly trust: typeof PLUGIN_SECURITY_TRUST
+ private readonly now: () => number
+ private readonly random: () => number
+ private policy?: PluginSecurityPolicy
+ private envelope: string | null = null
+ private checkedAt = 0
+ private nextCheckAt = 0
+ private failures = 0
+ private etag: string | null = null
+ private lastAttemptAt = Number.NEGATIVE_INFINITY
+ private integrityFailure = false
+ private storageFailure = false
+ private initialized?: Promise<void>
+ private inflight?: Promise<void>
+ private controller?: AbortController
+ private timer?: NodeJS.Timeout
+ private started = false
+ private stopped = false
+ private readonly listeners = new Set<() => void | Promise<void>>()
+ private readonly decisions = new Map<
+ string,
+ PluginSecurityDecision | undefined
+ >()
+
+ constructor(private readonly options: PluginSecurityServiceOptions) {
+ this.trust = options.trust ?? PLUGIN_SECURITY_TRUST
+ this.now = options.now ?? Date.now
+ this.random = options.random ?? Math.random
+ }
+
+ get configured(): boolean {
+ return this.trust.publicKeys.length > 0
+ }
+
+ initialize(): Promise<void> {
+ this.initialized ??= this.load()
+ return this.initialized
+ }
+
+ private async load(): Promise<void> {
+ if (!this.configured) return
+ if (this.trust.baseline) {
+ this.policy = verifySecurityPolicy(
+ this.trust.baseline,
+ this.trust.publicKeys
+ )
+ this.envelope = this.trust.baseline
+ }
+ try {
+ if ((await stat(this.options.cachePath)).size > CACHE_LIMIT)
+ throw new Error('Oversized policy cache')
+ const saved = CacheSchema.parse(
+ JSON.parse(await readFile(this.options.cachePath, 'utf8'))
+ )
+ if (saved.envelope) {
+ const cached = verifySecurityPolicy(
+ saved.envelope,
+ this.trust.publicKeys
+ )
+ if (!this.policy || cached.revision >= this.policy.revision) {
+ assertPolicyTransition(this.policy, cached)
+ this.policy = cached
+ this.envelope = saved.envelope
+ this.checkedAt = saved.checkedAt
+ this.etag = saved.etag
+ } else {
+ assertPolicyTransition(cached, this.policy)
+ }
+ }
+ const now = this.now()
+ this.nextCheckAt = Math.min(
+ saved.nextCheckAt,
+ now + PLUGIN_SECURITY_FRESHNESS_MS
+ )
+ this.failures = saved.failures
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ this.integrityFailure = true
+ log.warn(
+ { err: error },
+ 'security cache rejected; plugin admission closed until recovery'
+ )
+ }
+ }
+ }
+
+ isFresh(): boolean {
+ if (!this.configured) return true
+ const age = this.now() - this.checkedAt
+ return (
+ !this.integrityFailure &&
+ !this.storageFailure &&
+ this.checkedAt > 0 &&
+ age >= 0 &&
+ age <= PLUGIN_SECURITY_FRESHNESS_MS &&
+ !!this.policy &&
+ Date.parse(this.policy.expiresAt) > this.now()
+ )
+ }
+
+ decision(
+ identity: PluginSecurityIdentity
+ ): PluginSecurityDecision | undefined {
+ if (!this.configured) return undefined
+ if (this.integrityFailure)
+ return { blocked: true, reason: 'unavailable', advisoryIds: [] }
+ const key = JSON.stringify([
+ identity.pluginId,
+ identity.version,
+ identity.archiveSha256,
+ ])
+ if (this.decisions.has(key)) return this.decisions.get(key)
+ const advisories = this.policy
+ ? matchingAdvisories(this.policy, identity)
+ : []
+ const first = advisories[0]
+ const decision: PluginSecurityDecision | undefined = first
+ ? {
+ blocked: true,
+ reason: first.reason,
+ advisoryIds: advisories.map((entry) => entry.id),
+ fixedVersion: first.fixedVersion,
+ url: first.url,
+ }
+ : undefined
+ // Bounded even when an installation source submits many distinct versions.
+ if (this.decisions.size >= 2048) this.decisions.clear()
+ this.decisions.set(key, decision)
+ return decision
+ }
+
+ assertAllowed(identity: PluginSecurityIdentity): void {
+ if (this.decision(identity))
+ throw new AppError(
+ ErrorCode.PluginSecurityBlocked,
+ 'plugins.security.blocked'
+ )
+ }
+
+ subscribe(listener: () => void | Promise<void>): () => void {
+ this.listeners.add(listener)
+ return () => this.listeners.delete(listener)
+ }
+
+ private async notify(): Promise<void> {
+ const results = await Promise.allSettled(
+ [...this.listeners].map((listener) => {
+ try {
+ return Promise.resolve(listener())
+ } catch (error) {
+ return Promise.reject(error)
+ }
+ })
+ )
+ for (const result of results)
+ if (result.status === 'rejected') {
+ log.error(
+ { err: result.reason },
+ 'security policy enforcement failed; admission remains closed'
+ )
+ }
+ }
+
+ start(): void {
+ if (!this.configured || this.started || this.stopped) return
+ this.started = true
+ this.schedule()
+ }
+
+ notifyWake(): void {
+ if (this.now() >= this.nextCheckAt) this.schedule()
+ }
+
+ private schedule(): void {
+ if (!this.started || this.stopped) return
+ if (this.timer) clearTimeout(this.timer)
+ // A due startup/resume check is spread over 5–30 seconds.
+ const delay =
+ this.nextCheckAt > this.now()
+ ? this.nextCheckAt - this.now()
+ : 5_000 + this.random() * 25_000
+ this.timer = setTimeout(() => {
+ void this.refresh()
+ }, delay)
+ this.timer.unref?.()
+ }
+
+ /** Coalesced refresh. Force is rate-limited to one attempt per minute. */
+ refresh(force = false): Promise<void> {
+ if (!this.configured || this.stopped) return Promise.resolve()
+ if (this.inflight) return this.inflight
+ this.inflight = this.initialize()
+ .then(async () => {
+ const now = this.now()
+ if (
+ now - this.lastAttemptAt < 60_000 ||
+ (!force && now < this.nextCheckAt)
+ )
+ return
+ this.lastAttemptAt = now
+ await this.fetchPolicy()
+ })
+ .finally(() => {
+ this.inflight = undefined
+ this.schedule()
+ })
+ return this.inflight
+ }
+
+ /** Installation can request a refresh without bypassing backoff. */
+ async refreshIfStale(): Promise<void> {
+ await this.initialize()
+ if (
+ this.now() - this.checkedAt >= PLUGIN_SECURITY_INTERVAL_MS ||
+ !this.isFresh()
+ )
+ await this.refresh()
+ }
+
+ private async fetchPolicy(): Promise<void> {
+ const controller = new AbortController()
+ this.controller = controller
+ let deadline: NodeJS.Timeout | undefined
+ const timeout = new Promise<never>((_resolve, reject) => {
+ deadline = setTimeout(() => {
+ controller.abort()
+ reject(new Error('Security policy timeout'))
+ }, 5_000)
+ deadline.unref?.()
+ })
+ let retryAfter = 0
+ try {
+ const url = new URL(this.trust.url)
+ if (url.protocol !== 'https:' || url.username || url.password)
+ throw new Error('Invalid security policy URL')
+ const download = async () => {
+ // Public static object: no installed-plugin inventory, credentials, or
+ // per-plugin query parameters. The CDN owns HTTP cache revalidation.
+ const response = await (this.options.fetchImpl ?? fetch)(url, {
+ signal: controller.signal,
+ redirect: 'error',
+ credentials: 'omit',
+ headers: {
+ accept: 'application/json',
+ ...(this.etag ? { 'if-none-match': this.etag } : {}),
+ },
+ })
+ if (response.status === 304 && this.envelope)
+ return { raw: this.envelope, etag: this.etag }
+ if (!response.ok) {
+ const header = response.headers.get('retry-after')
+ const requested =
+ header && /^\d+$/.test(header)
+ ? Number(header) * 1000
+ : header
+ ? Date.parse(header) - this.now()
+ : 0
+ retryAfter = Number.isFinite(requested)
+ ? Math.min(Math.max(0, requested), PLUGIN_SECURITY_FRESHNESS_MS)
+ : 0
+ await response.body?.cancel()
+ throw new Error(`Security feed HTTP ${response.status}`)
+ }
+ if (
+ Number(response.headers.get('content-length')) >
+ PLUGIN_SECURITY_MAX_BYTES
+ ) {
+ await response.body?.cancel()
+ throw new Error('Security feed exceeds size limit')
+ }
+ const reader = response.body?.getReader()
+ if (!reader) throw new Error('Empty security feed')
+ const chunks: Uint8Array[] = []
+ let size = 0
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+ size += value.length
+ if (size > PLUGIN_SECURITY_MAX_BYTES)
+ throw new Error('Security feed exceeds size limit')
+ chunks.push(value)
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined)
+ }
+ const etag = response.headers.get('etag')
+ return {
+ raw: Buffer.concat(chunks).toString('utf8'),
+ etag: etag && etag.length <= 512 ? etag : null,
+ }
+ }
+ const { raw, etag } = await Promise.race([download(), timeout])
+ if (this.stopped) return
+ const next = verifySecurityPolicy(raw, this.trust.publicKeys)
+ const now = this.now()
+ if (
+ Date.parse(next.issuedAt) > now + 5 * 60_000 ||
+ Date.parse(next.expiresAt) <= now
+ )
+ throw new Error('Security feed is expired or from the future')
+ assertPolicyTransition(this.policy, next)
+ const changed = this.envelope !== raw || this.integrityFailure
+ this.policy = next
+ this.envelope = raw
+ this.etag = etag
+ this.integrityFailure = false
+ this.decisions.clear()
+ this.checkedAt = now
+ this.storageFailure = true
+ this.failures = 0
+ this.nextCheckAt = now + this.jitter(PLUGIN_SECURITY_INTERVAL_MS)
+ // Notify synchronously up to each listener's first await: admission is
+ // closed before cache IO or worker teardown. Never roll back this policy
+ // when storage or teardown fails.
+ const enforcement = changed ? this.notify() : Promise.resolve()
+ try {
+ await this.persist()
+ this.storageFailure = false
+ } catch (error) {
+ this.storageFailure = true
+ throw error
+ } finally {
+ await enforcement
+ }
+ // Pending first activations can become available after a durable refresh.
+ await this.notify()
+ } catch (error) {
+ if (this.stopped) return
+ this.failures = Math.min(100, this.failures + 1)
+ this.nextCheckAt =
+ this.now() +
+ Math.max(
+ retryAfter,
+ this.jitter(
+ RETRY_MS[Math.min(this.failures - 1, RETRY_MS.length - 1)]
+ )
+ )
+ log.warn(
+ { err: error },
+ 'security refresh failed; retaining known blocks'
+ )
+ try {
+ await this.persist()
+ } catch (persistError) {
+ this.storageFailure = true
+ log.error(
+ { err: persistError },
+ 'security policy cache could not be persisted'
+ )
+ }
+ } finally {
+ if (deadline) clearTimeout(deadline)
+ controller.abort()
+ if (this.controller === controller) this.controller = undefined
+ }
+ }
+
+ private jitter(duration: number): number {
+ return Math.round(duration * (0.9 + this.random() * 0.2))
+ }
+
+ private async persist(): Promise<void> {
+ if (this.integrityFailure)
+ throw new Error(
+ 'Cannot replace rejected security cache without a trusted refresh'
+ )
+ await mkdir(path.dirname(this.options.cachePath), { recursive: true })
+ const contents = JSON.stringify({
+ version: 1,
+ envelope: this.envelope,
+ checkedAt: this.checkedAt,
+ nextCheckAt: this.nextCheckAt,
+ failures: this.failures,
+ etag: this.etag,
+ })
+ if (this.options.writeCache)
+ await this.options.writeCache(this.options.cachePath, contents)
+ else
+ await writeFileAtomic(this.options.cachePath, contents, { mode: 0o600 })
+ }
+
+ async stop(): Promise<void> {
+ this.stopped = true
+ if (this.timer) clearTimeout(this.timer)
+ this.controller?.abort()
+ await this.inflight
+ this.listeners.clear()
+ }
+}
diff --git a/src/core/plugin/update/builtin-updater.ts b/src/core/plugin/update/builtin-updater.ts
index 4e73753d..518ad7a8 100644
--- a/src/core/plugin/update/builtin-updater.ts
+++ b/src/core/plugin/update/builtin-updater.ts
@@ -13,10 +13,12 @@ import { extractMoext } from '../install/moext-reader'
import { parseManifest } from '../manifest/parse'
import type { PluginExecutableIdentity } from '../post/delivery-types'
import { fetchVerifiedPackageBytes } from '../registry/registry-fetcher'
+import type { PluginSecurityService } from '../security/security-service'
import { verifyBuiltinSignature } from './signature'
import { builtinTrustSurfaceChanged } from './trust-diff'
export interface BuiltinUpdaterOptions {
+ security?: PluginSecurityService
overlayDir: string
hostVersion: string
pubkeys?: ReadonlyArray<string>
@@ -49,6 +51,8 @@ export interface BuiltinUpdaterLifecycleSink {
interface StagedUpdate {
pluginId: string
+ version: string
+ archiveSha256: string
stagingDir: string
}
@@ -119,6 +123,12 @@ export class BuiltinUpdater {
origin: 'builtin',
})
const parsed = manifest as PluginManifest
+ await this.opts.security?.refreshIfStale()
+ this.opts.security?.assertAllowed({
+ pluginId: parsed.id,
+ version: parsed.version,
+ archiveSha256: pkg.sha256,
+ })
if (
parsed.id !== entry.id ||
!parsed.id.startsWith('motrix.') ||
@@ -151,6 +161,8 @@ export class BuiltinUpdater {
const stagingId = path.basename(stagingDir)
this.pending.set(stagingId, {
pluginId: entry.id,
+ version: parsed.version,
+ archiveSha256: pkg.sha256,
stagingDir,
})
return {
@@ -224,6 +236,13 @@ export class BuiltinUpdater {
}
private async commitWithLifecycle(staged: StagedUpdate): Promise<void> {
+ this.opts.security?.assertAllowed(staged)
+ if (this.opts.security && !this.opts.security.isFresh()) {
+ throw new AppError(
+ ErrorCode.PluginSecurityPending,
+ 'plugins.security.pending'
+ )
+ }
const lifecycle = this.lifecycleSink
if (!lifecycle) throw new Error('builtin updater lifecycle sink missing')
const previous = lifecycle.currentExecutable(staged.pluginId)
@@ -241,6 +260,13 @@ export class BuiltinUpdater {
await rename(staged.stagingDir, finalDir)
published = true
await lifecycle.refreshRegistry()
+ this.opts.security?.assertAllowed(staged)
+ if (this.opts.security && !this.opts.security.isFresh()) {
+ throw new AppError(
+ ErrorCode.PluginSecurityPending,
+ 'plugins.security.pending'
+ )
+ }
await lifecycle.supersede(previous, this.now())
} catch (error) {
await this.rollbackPublishedOverlay({
@@ -259,6 +285,13 @@ export class BuiltinUpdater {
}
private async commitWithoutLifecycle(staged: StagedUpdate): Promise<void> {
+ this.opts.security?.assertAllowed(staged)
+ if (this.opts.security && !this.opts.security.isFresh()) {
+ throw new AppError(
+ ErrorCode.PluginSecurityPending,
+ 'plugins.security.pending'
+ )
+ }
const finalDir = path.join(this.opts.overlayDir, staged.pluginId)
const backup = this.backupPath(staged.pluginId, 'update')
const hadPrevious = await moveIfPresent(finalDir, backup)
diff --git a/src/core/session/durable-finalize-runtime.test.ts b/src/core/session/durable-finalize-runtime.test.ts
index e93b8790..8e82eadd 100644
--- a/src/core/session/durable-finalize-runtime.test.ts
+++ b/src/core/session/durable-finalize-runtime.test.ts
@@ -108,6 +108,61 @@ describe('DurableFinalizeRuntime', () => {
expect(events).toEqual(['quiesce', 'materialize', 'release'])
db.close()
})
+
+ it('rejects revocation while preparing identities before any output mutation', async () => {
+ const root = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-revoked-finalize-')
+ )
+ roots.push(root)
+ const sourcePath = path.join(root, 'source.part')
+ const targetPath = path.join(root, 'target.bin')
+ await writeFile(sourcePath, 'original')
+ const db = new Database(':memory:')
+ migrate(db)
+ let revoked = false
+ const fs = {
+ identity: async (artifactPath: string) => {
+ const identity = await readArtifactIdentity(artifactPath)
+ revoked = true
+ return identity
+ },
+ sameFilesystem: vi.fn(),
+ materializePrivate: vi.fn(),
+ makeDurable: vi.fn(),
+ moveNoReplace: vi.fn(),
+ removeKnown: vi.fn(),
+ } satisfies FinalizeArtifactOperations
+ const commitDatabase = vi.fn()
+ const runtime = new DurableFinalizeRuntime({
+ db,
+ fs,
+ session: {
+ persistFinalizedArtifact: async (_task, _occurrence, _input, commit) =>
+ commit(commitDatabase),
+ },
+ })
+ try {
+ await expect(
+ runtime.commit({
+ task: makeDownloadTask({ id: 'revoked', saveDir: root }),
+ occurrence: null,
+ sourcePath,
+ targetPath,
+ metadataOps: [],
+ contributors: ['example.test'],
+ postDeliveries: [],
+ beforeCommit: () => {
+ if (revoked) throw new Error('security revoked')
+ },
+ })
+ ).rejects.toThrow('security revoked')
+ expect(fs.materializePrivate).not.toHaveBeenCalled()
+ expect(fs.moveNoReplace).not.toHaveBeenCalled()
+ expect(commitDatabase).not.toHaveBeenCalled()
+ } finally {
+ db.close()
+ }
+ })
})
it('rejects an invalid target before acquiring leases or reading file identities', async () => {
diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.ts
index 1616b65c..dab79e01 100644
--- a/src/core/session/durable-finalize-runtime.ts
+++ b/src/core/session/durable-finalize-runtime.ts
@@ -60,6 +60,7 @@ export class DurableFinalizeRuntime {
async commit(
input: DurableFinalizeArtifactInput
): Promise<FinalizeCommitResult> {
+ input.beforeCommit?.()
// The final name can carry characters that Windows or exFAT volumes
// cannot reopen. Sanitize the final component once, before validation or
// identity capture, so journal, rebase and database all record the name
@@ -167,6 +168,7 @@ export class DurableFinalizeRuntime {
exactIdentity: artifactIdentityEquals,
sameContent: artifactContentEquals,
})
+ input.beforeCommit?.()
return committer.commit(plan, lease)
}
)
diff --git a/src/core/session/post-delivery-repository.ts b/src/core/session/post-delivery-repository.ts
index 2effeb4d..204beea4 100644
--- a/src/core/session/post-delivery-repository.ts
+++ b/src/core/session/post-delivery-repository.ts
@@ -546,7 +546,7 @@ export class SqlitePostDeliveryRepository
async terminalizePlugin(input: {
pluginId: string
- reason: 'disabled' | 'uninstalled' | 'quarantined'
+ reason: 'disabled' | 'uninstalled' | 'quarantined' | 'security_revoked'
at: number
}): Promise<number> {
return this.terminalizeWhere(
diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.ts
index 17265de9..3d235d28 100644
--- a/src/core/session/session-manager.test.ts
+++ b/src/core/session/session-manager.test.ts
@@ -608,6 +608,19 @@ describe('SessionManager', () => {
)
})
+ it('rejects revoked plugin results after payload preparation and before database persistence', async () => {
+ const candidate = createTask({ id: 'plugin-revoked-candidate' })
+ const beforeCommit = vi.fn(() => {
+ throw new Error('security revoked')
+ })
+ await expect(
+ session.persistTaskWithPluginMetadata(candidate, [], beforeCommit)
+ ).rejects.toThrow('security revoked')
+ expect(beforeCommit).toHaveBeenCalledOnce()
+ expect(db.persistTaskWithPluginMetadata).not.toHaveBeenCalled()
+ expect(taskManager.getById(candidate.id)).toBeUndefined()
+ })
+
it('emits a stable admission-rejected event after the terminal transaction commits', async () => {
const task = createTask({
id: 'm-post-rejected',
diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.ts
index 4d2bec55..5f940d7a 100644
--- a/src/core/session/session-manager.ts
+++ b/src/core/session/session-manager.ts
@@ -426,17 +426,17 @@ export class SessionManager {
*/
persistTaskWithPluginMetadata(
task: DownloadTask,
- operations: readonly StagedMetadataOp[]
+ operations: readonly StagedMetadataOp[],
+ beforeCommit?: () => void
): Promise<void> {
if (this.stopping) {
return Promise.reject(new Error('SessionManager is stopping'))
}
return this.runExclusivePersistence(async () => {
if (task.status === TaskStatus.Removed) return
- this.db.persistTaskWithPluginMetadata(
- await this.buildTaskPayload(task, Date.now()),
- operations
- )
+ const payload = await this.buildTaskPayload(task, Date.now())
+ beforeCommit?.()
+ this.db.persistTaskWithPluginMetadata(payload, operations)
})
}
diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.ts
index 9abffa42..65c2a97c 100644
--- a/src/core/task/actions/finalize-task.test.ts
+++ b/src/core/task/actions/finalize-task.test.ts
@@ -1,3 +1,4 @@
+import { StagedEffectStore } from '@core/plugin/hooks/staged-effects'
import { Events } from '@shared/protocol/events'
import type { DownloadTask, TaskInstance } from '@shared/types/task'
import {
@@ -1939,9 +1940,7 @@ describe('finalizeTask plugin-hook chain (Plan C / T15)', () => {
function makeBeforeFinalizeCommit(
overrides: {
finalFilePath?: string
- staged?: {
- commitMetadata: ReturnType<typeof vi.fn>
- }
+ staged?: StagedEffectStore | { commitMetadata: ReturnType<typeof vi.fn> }
} = {}
) {
return {
@@ -1977,6 +1976,85 @@ describe('finalizeTask plugin-hook chain (Plan C / T15)', () => {
} as unknown as FinalizeTaskDeps['auditLog']
}
+ function makeDirectBtFinalize(policyCheck: () => void) {
+ const task = makeBtTask({
+ diskPath: '/d/movie.iso',
+ finalPath: '/d/movie.iso',
+ instances: [
+ makePrimaryInstance({
+ phase: TaskInstancePhase.BtDownload,
+ diskPath: '/d/movie.iso',
+ payload: {
+ btStorageLayout: {
+ version: 2,
+ strategy: 'direct',
+ torrentRootName: 'original.iso',
+ multiFile: false,
+ finalized: false,
+ },
+ },
+ }),
+ ],
+ })
+ const staged = new StagedEffectStore()
+ staged.bindPolicyCheck('test.before-finalize', policyCheck)
+ const deps = makeDeps({
+ orchestrator: makeOrchestrator(makeBeforeFinalizeCommit({ staged })),
+ commitFinalizedArtifact: vi.fn(async () => {
+ throw new Error('engine writer is still active')
+ }),
+ })
+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)
+ return { task, deps }
+ }
+
+ it.each([TaskStatus.Seeding, TaskStatus.Completed])(
+ 'BT: policy checks alone finalize direct output in place with status %s',
+ async (status) => {
+ const policyCheck = vi.fn()
+ const { task, deps } = makeDirectBtFinalize(policyCheck)
+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue(
+ makeBtTask({ status })
+ )
+ const gid = task.engineTaskId
+
+ await expect(finalizeTask(task.id, deps)).resolves.toBeUndefined()
+
+ expect(policyCheck).toHaveBeenCalled()
+ expect(task.status).toBe(status)
+ expect(task.engineTaskId).toBe(gid)
+ expect(task.instances[0].payload.btStorageLayout).toMatchObject({
+ finalized: true,
+ })
+ expect(deps.commitFinalizedArtifact).not.toHaveBeenCalled()
+ expect(deps.fs.renameAtomic).not.toHaveBeenCalled()
+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()
+ expect(deps.adapter.addTorrent).not.toHaveBeenCalled()
+ }
+ )
+
+ it('BT: rejects a revoked policy after refreshing direct output state', async () => {
+ let revoked = false
+ const { task, deps } = makeDirectBtFinalize(() => {
+ if (revoked) throw new Error('plugin security policy changed')
+ })
+ vi.mocked(deps.adapter.getTaskStatus).mockResolvedValue(
+ makeBtTask({ status: TaskStatus.Seeding })
+ )
+ vi.mocked(deps.adapter.getTaskFiles).mockImplementation(async () => {
+ revoked = true
+ return []
+ })
+
+ await expect(finalizeTask(task.id, deps)).rejects.toThrow(
+ 'plugin security policy changed'
+ )
+
+ expect(task.status).toBe(TaskStatus.Error)
+ expect(deps.commitFinalizedArtifact).not.toHaveBeenCalled()
+ expect(deps.activityRecorder.recordDownloadCompleted).not.toHaveBeenCalled()
+ })
+
it('HTTP: chain commit leaves afterComplete to durable delivery', async () => {
const orchestrator = makeOrchestrator(makeBeforeFinalizeCommit())
const auditLog = makeAuditLog()
diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.ts
index dced1e85..64b6879d 100644
--- a/src/core/task/actions/finalize-task.ts
+++ b/src/core/task/actions/finalize-task.ts
@@ -169,6 +169,7 @@ export interface FinalizeArtifactCommitRequest {
replacement?: { pluginId: string; stagedPath: string }
metadataOps: readonly StagedMetadataOp[]
contributors: readonly string[]
+ beforeCommit?: () => void
fileRebase?: { sourceRoot: string; targetRoot: string }
}
@@ -331,6 +332,7 @@ async function finalizeHttp(
}
try {
+ finalizeOutcome.beforeCommit?.()
await deps.fs.renameAtomic(renameSource, desiredFinalPath)
} catch (e) {
const cause = (e as Error).message
@@ -417,6 +419,7 @@ async function commitHttpArtifactDurably(
replacement: finalizeOutcome.replacement,
metadataOps: finalizeOutcome.metadataOps,
contributors: finalizeOutcome.contributors,
+ beforeCommit: finalizeOutcome.beforeCommit,
fileRebase: {
sourceRoot: renameSource,
targetRoot: desiredFinalPath,
@@ -633,6 +636,7 @@ async function finalizeBt(
replacement: finalizeOutcome.replacement,
metadataOps: finalizeOutcome.metadataOps,
contributors: finalizeOutcome.contributors,
+ beforeCommit: finalizeOutcome.beforeCommit,
fileRebase: {
sourceRoot: renameSource,
targetRoot: publishedFinalPath,
@@ -654,6 +658,7 @@ async function finalizeBt(
}
} else {
try {
+ finalizeOutcome.beforeCommit?.()
await deps.fs.renameAtomic(renameSource, publishedFinalPath)
} catch (e) {
const cause = (e as Error).message
@@ -1043,11 +1048,14 @@ async function finalizeBtInPlace(
targetPath: task.finalPath,
metadataOps: outcome.metadataOps,
contributors: outcome.contributors,
+ beforeCommit: outcome.beforeCommit,
})
deps.taskManager.set(task.id, structuredClone(task))
await recordTaskTransition(task, previousStatus, deps, completedAt)
if (occurrence) await deps.occurrenceDispatcher?.dispatch(occurrence)
} else {
+ // A policy check alone needs no file mutation lease. The commit still
+ // revalidates it while the unchanged engine identity continues seeding.
outcome.commit(() => {})
await persistTaskTransition(task, previousStatus, deps, completedAt)
}
@@ -1288,6 +1296,7 @@ interface BeforeFinalizeOutcomeCommit {
replacement?: { pluginId: string; stagedPath: string }
metadataOps: readonly StagedMetadataOp[]
contributors: readonly string[]
+ beforeCommit?: () => void
/**
* Runs the staged metadata commit (if a db handle is wired) wrapping the
* supplied sync callback inside the same SQLite transaction. When no db
@@ -1349,10 +1358,15 @@ async function runBeforeFinalize(
})
const db = deps.db
const staged = result.staged
+ const beforeCommit = staged.hasPolicyChecks
+ ? staged.assertPolicyCurrent.bind(staged)
+ : undefined
+ beforeCommit?.()
return {
aborted: false,
finalFilePath: result.finalFilePath,
replacement: result.replacement,
+ beforeCommit,
metadataOps:
typeof result.staged.allMetadataOps === 'function'
? result.staged.allMetadataOps()
@@ -1368,6 +1382,7 @@ async function runBeforeFinalize(
]),
].sort(),
commit: (cb: () => void) => {
+ beforeCommit?.()
if (db) {
staged.commitMetadata(db, task.id, cb)
} else {
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index cd6ec937..52a9556d 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -2553,6 +2553,48 @@ describe('handleCreateTask plugin-hook chain (Plan C / T15)', () => {
expect(deps.add).toHaveBeenCalledOnce()
})
+ it.each(['persistence', 'engine'])(
+ 'rejects revocation during %s after a hook has returned',
+ async (boundary) => {
+ let revoked = false
+ const staged = {
+ ...makeStaged(),
+ hasPolicyChecks: true,
+ assertPolicyCurrent: () => {
+ if (revoked) throw new Error('security revoked')
+ },
+ }
+ const deps = makeDeps()
+ const persistTaskWithPluginMetadata = vi.fn(async () => {
+ if (boundary === 'persistence') revoked = true
+ })
+ if (boundary === 'engine') {
+ const addUri = deps.addUri.getMockImplementation() as (
+ ...args: unknown[]
+ ) => Promise<string>
+ deps.addUri.mockImplementation(async (...args) => {
+ const result = await addUri(...args)
+ revoked = true
+ return result
+ })
+ }
+ await expect(
+ handleCreateTask(httpRequest(), {
+ ...deps,
+ orchestrator: makeOrchestrator(makeChainCommit({ staged })),
+ persistTaskWithPluginMetadata,
+ rollbackTaskCreation: vi.fn(async () => undefined),
+ })
+ ).rejects.toThrow('security revoked')
+ expect(persistTaskWithPluginMetadata).toHaveBeenCalledOnce()
+ if (boundary === 'persistence') expect(deps.addUri).not.toHaveBeenCalled()
+ else expect(deps.addUri).toHaveBeenCalledOnce()
+ expect(deps.forceRemove).toHaveBeenCalledOnce()
+ expect(deps.removeDownloadResult).toHaveBeenCalledOnce()
+ expect(deps.add).not.toHaveBeenCalled()
+ }
+ )
+
it('fails closed when metadata is staged without an atomic boundary', async () => {
const staged = makeStaged([
{
diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.ts
index f4e506dd..95b2b4fc 100644
--- a/src/core/task/create-task-handler.ts
+++ b/src/core/task/create-task-handler.ts
@@ -139,7 +139,8 @@ export interface CreateTaskDeps {
*/
persistTaskWithPluginMetadata?: (
task: DownloadTask,
- operations: readonly StagedMetadataOp[]
+ operations: readonly StagedMetadataOp[],
+ beforeCommit?: () => void
) => Promise<void>
/** @deprecated Retained for legacy composition; never used for Hook commit. */
db?: Database.Database
@@ -580,6 +581,7 @@ async function handleCreateTaskUnderAdmission(
// parsed torrents additionally carry per-file output mappings. The adapter
// is responsible for the aria2 wire shape.
let pluginMetadataOps: readonly StagedMetadataOp[] = []
+ let assertPluginPolicyCurrent: (() => void) | undefined
let dispatchEngine: (reservedGid: string) => Promise<string>
let directReplay: DirectReplayRecipe | null = null
let canonicalUris = deriveUris(req)
@@ -784,6 +786,10 @@ async function handleCreateTaskUnderAdmission(
`plugin chain aborted: ${result.reason}`
)
}
+ if (result.staged.hasPolicyChecks) {
+ assertPluginPolicyCurrent = () => result.staged.assertPolicyCurrent()
+ assertPluginPolicyCurrent()
+ }
// Apply merged outputs back to the create params. mergeChain is
// well-defined for the slot keys we care about; absent keys keep
// the user's input intact. Conditionality matches the old code:
@@ -818,6 +824,7 @@ async function handleCreateTaskUnderAdmission(
uriContributor: result.contributors.uris,
finalHeaderCount: result.final.headers.length,
})
+ assertPluginPolicyCurrent?.()
pluginMetadataOps =
typeof result.staged.allMetadataOps === 'function'
? result.staged.allMetadataOps()
@@ -854,6 +861,7 @@ async function handleCreateTaskUnderAdmission(
await pickHttpName(uriBasename(params.uris[0]) ?? 'download')
}
+ assertPluginPolicyCurrent?.()
// Probe only after mux has declined the URL and the plugin chain has
// accepted and finalized its URI/header/proxy outputs. An aborted or
// rewritten request must never probe the stale user-supplied target.
@@ -894,6 +902,7 @@ async function handleCreateTaskUnderAdmission(
// future retry can be reconstructed from TaskInstance. Paths and URIs are
// already canonical fields on the instance; modifier VALUES remain
// engine-call-only so credentials never enter motrix.db.
+ assertPluginPolicyCurrent?.()
directReplay = buildDirectReplayRecipe(
params,
ambientMetadataProfile === null
@@ -927,6 +936,7 @@ async function handleCreateTaskUnderAdmission(
)
}
}
+ assertPluginPolicyCurrent?.()
canonicalUris = [...params.uris]
dispatchEngine = dispatchCreateDownload(params)
} else if (req.payload.kind === 'torrent-base64') {
@@ -1084,6 +1094,15 @@ async function handleCreateTaskUnderAdmission(
deps.taskManager.reserveEngineTaskId(gid)
const persistParent = async (): Promise<void> => {
+ assertPluginPolicyCurrent?.()
+ if (assertPluginPolicyCurrent && deps.persistTaskWithPluginMetadata) {
+ await deps.persistTaskWithPluginMetadata(
+ task,
+ pluginMetadataOps,
+ assertPluginPolicyCurrent
+ )
+ return
+ }
if (pluginMetadataOps.length > 0) {
await deps.persistTaskWithPluginMetadata?.(task, pluginMetadataOps)
return
@@ -1093,7 +1112,8 @@ async function handleCreateTaskUnderAdmission(
const hasDurableIntent = Boolean(
deps.persistTask ||
deps.parentTaskCreated ||
- (pluginMetadataOps.length > 0 && deps.persistTaskWithPluginMetadata)
+ ((pluginMetadataOps.length > 0 || assertPluginPolicyCurrent) &&
+ deps.persistTaskWithPluginMetadata)
)
const rollbackDurableIntent = async (): Promise<boolean> => {
if (!hasDurableIntent) return true
@@ -1147,7 +1167,9 @@ async function handleCreateTaskUnderAdmission(
deps.assertEngineReady?.()
assertAppliedProxyCurrent?.()
}
+ assertPluginPolicyCurrent?.()
const actualGid = await dispatchEngine(gid)
+ assertPluginPolicyCurrent?.()
if (actualGid.toLowerCase() !== gid.toLowerCase()) {
throw new Error(
`Engine returned gid ${actualGid} instead of reserved gid ${gid}`
diff --git a/src/main/index.ts b/src/main/index.ts
index 42e45cef..e6b8fce7 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -60,6 +60,7 @@ import { RegistryClient } from '@core/plugin/registry/registry-client'
import type { PluginHookRuntime } from '@core/plugin/runtime/plugin-hook-runtime'
import { createPluginRuntime } from '@core/plugin/runtime/runtime-factory'
import { PluginRuntimeStartupCoordinator } from '@core/plugin/runtime/startup-coordinator'
+import { PluginSecurityService } from '@core/plugin/security/security-service'
import { PluginStateStore } from '@core/plugin/state/plugin-state-store'
import { BuiltinUpdater } from '@core/plugin/update/builtin-updater'
import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
@@ -1234,7 +1235,10 @@ function buildFinalizeDeps(adapter: Aria2Adapter) {
await durableFinalizeRuntime.commit({
...input,
postDeliveries: post.postDeliveries,
- beforeCommit: post.beforeCommit,
+ beforeCommit: () => {
+ input.beforeCommit?.()
+ post.beforeCommit()
+ },
})
},
}
@@ -1743,7 +1747,10 @@ async function initializeMainProcess(): Promise<void> {
// OS logout/shutdown: skip the quit dialog so session end is never blocked.
powerMonitor.on('shutdown', prepareForSessionEnd)
- powerMonitor.on('resume', () => trackerManager?.notifyWake())
+ powerMonitor.on('resume', () => {
+ trackerManager?.notifyWake()
+ pluginHost?.notifySecurityWake()
+ })
if (gate.isAccepted()) {
const runMode = settingsManager.getApp().runMode
@@ -1911,7 +1918,12 @@ async function initializeMainProcess(): Promise<void> {
// manifest resolution.
const overlayDir = path.join(platform.userDataDir, 'builtin-updates')
const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH
+ const pluginSecurity = new PluginSecurityService({
+ cachePath: path.join(platform.userDataDir, 'plugin-security.json'),
+ })
+ await pluginSecurity.initialize()
const pluginRegistry = new PluginRegistry({
+ security: pluginSecurity,
pluginsDir,
builtinDir,
overlayDir,
@@ -1960,6 +1972,11 @@ async function initializeMainProcess(): Promise<void> {
const detectPluginFfmpeg = async () =>
projectActiveToLegacy(await detectElectronFfmpeg())
const activePluginHost = new PluginHost({
+ security: pluginSecurity,
+ onSecurityChanged: () => {
+ eventBus.emit(Events.PluginSecurityChanged)
+ eventBus.emit(Events.ContributionIndexChanged)
+ },
registry: pluginRegistry,
stateStore: pluginStateStore,
capabilityHost: pluginCapHost,
@@ -2026,6 +2043,7 @@ async function initializeMainProcess(): Promise<void> {
}
const pluginInstaller = new PluginInstaller({
+ security: pluginSecurity,
pluginsDir,
registry: pluginRegistry,
stateStore: pluginStateStore,
@@ -2649,10 +2667,13 @@ async function initializeMainProcess(): Promise<void> {
!nativeMessagingInstaller.preserveOnStartupFailure
)
+ await activePluginHost.enforceSecurityPolicy()
+ pluginSecurity.start()
const registryClient = new RegistryClient({
cachePath: path.join(platform.userDataDir, REGISTRY_CACHE_FILENAME),
})
const builtinUpdater = new BuiltinUpdater({
+ security: pluginSecurity,
overlayDir,
hostVersion: app.getVersion(),
})
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index d989fb51..c85ab09b 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -1634,6 +1634,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
}),
[Commands.EnablePlugin]: async (id: string) => {
+ pluginRegistry.assertSecurityAllowed?.(id)
pluginStateStore.setEnabled(id, true)
// Sync the in-memory IndexedPlugin.state so Queries.ListPlugins and
// downstream gating (PluginHost.activate, ActivationDispatcher,
@@ -1795,6 +1796,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
[Commands.CheckPluginUpdates]: async (payload: unknown) => {
const parsed = checkPluginUpdatesPayloadSchema.parse(payload)
+ await pluginHost.refreshSecurityPolicy?.(parsed?.force)
if (parsed?.force) await registryClient.refresh()
const entries = await registryClient.list(hostVersion)
return scanForUpdates(pluginRegistry.list(), entries)
diff --git a/src/renderer/routes/plugins/components/builtin-update-dialog.tsx b/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
index ec95d5b9..4a59c5b1 100644
--- a/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
+++ b/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
@@ -122,7 +122,13 @@ export function BuiltinUpdateDialog({ pluginId, open, onOpenChange }: Props) {
{phase.kind === 'error' && (
<Alert variant="destructive">
- <span className="text-xs">{phase.message}</span>
+ <span className="text-xs">
+ {phase.message.endsWith('plugins.security.blocked')
+ ? t('plugins.security.blocked')
+ : phase.message.endsWith('plugins.security.pending')
+ ? t('plugins.security.pending')
+ : phase.message}
+ </span>
</Alert>
)}
{phase.kind === 'consent' && (
diff --git a/src/renderer/routes/plugins/components/plugin-card.test.tsx b/src/renderer/routes/plugins/components/plugin-card.test.tsx
index 733ae360..c4f62088 100644
--- a/src/renderer/routes/plugins/components/plugin-card.test.tsx
+++ b/src/renderer/routes/plugins/components/plugin-card.test.tsx
@@ -8,13 +8,18 @@ import type { PluginListDTO } from '@shared/types/plugin'
import { usePluginsStore } from '../store'
import { PluginCard } from './plugin-card'
-const { mockInvoke } = vi.hoisted(() => ({
+const { mockInvoke, openExternal } = vi.hoisted(() => ({
+ openExternal: vi.fn(),
mockInvoke: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@renderer/lib/transport', () => ({
transport: { invoke: mockInvoke, on: vi.fn(), off: vi.fn() },
}))
+vi.mock('@renderer/platform/services', () => ({
+ usePlatformServices: () => ({ openExternal }),
+}))
+
function makePlugin(overrides: Partial<PluginListDTO> = {}): PluginListDTO {
return {
id: 'test.demo-config',
@@ -98,6 +103,39 @@ describe('PluginCard', () => {
).toBeInTheDocument()
})
+ it('shows the security reason and blocks the enable switch without offering Turn on', () => {
+ renderCard(
+ makePlugin({
+ enabled: false,
+ security: {
+ blocked: true,
+ reason: 'malware',
+ advisoryIds: ['MTX-TEST-1'],
+ fixedVersion: '1.2.0',
+ url: 'https://motrix.app/security/MTX-TEST-1',
+ },
+ })
+ )
+ expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false')
+ expect(
+ screen.queryByRole('button', { name: 'Turn on' })
+ ).not.toBeInTheDocument()
+ expect(screen.getByText('MTX-TEST-1')).toBeInTheDocument()
+ expect(
+ screen.getByText('A fix is available in version 1.2.0.')
+ ).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('switch'))
+ expect(mockInvoke).not.toHaveBeenCalled()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'View security advisory' })
+ )
+ expect(openExternal).toHaveBeenCalledWith(
+ 'https://motrix.app/security/MTX-TEST-1'
+ )
+ expect(screen.queryByTestId('detail-route')).not.toBeInTheDocument()
+ })
+
it('safe tone: shows Looks safe badge', () => {
renderCard(makePlugin())
expect(screen.getByText('Looks safe')).toBeInTheDocument()
diff --git a/src/renderer/routes/plugins/components/plugin-card.tsx b/src/renderer/routes/plugins/components/plugin-card.tsx
index ecf31ec5..d5514ec9 100644
--- a/src/renderer/routes/plugins/components/plugin-card.tsx
+++ b/src/renderer/routes/plugins/components/plugin-card.tsx
@@ -16,6 +16,7 @@ import {
import { usePluginsStore } from '../store'
import { PluginAudienceBadge } from './plugin-audience-badge'
import { PluginAvatar } from './plugin-avatar'
+import { PluginSecurityNotice } from './plugin-security-notice'
import { PluginStatusDot } from './plugin-status-dot'
interface Props {
@@ -57,7 +58,13 @@ export function PluginCard({ plugin, hasSchema }: Props) {
applyStatus(plugin.id, next ? 'inactive' : 'disabled', undefined, next)
}
- function handleCardClick() {
+ function handleCardClick(event: ReactMouseEvent) {
+ // Disabled switches do not dispatch their own click handler.
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[role="switch"]')
+ )
+ return
navigate(`/plugins/${plugin.id}`)
}
@@ -85,7 +92,10 @@ export function PluginCard({ plugin, hasSchema }: Props) {
<div className="min-w-0">
<h3 className="flex items-center gap-2 truncate text-sm font-medium leading-5">
{plugin.name}
- <PluginStatusDot status={plugin.status} enabled={plugin.enabled} />
+ <PluginStatusDot
+ status={plugin.status}
+ enabled={plugin.enabled && !plugin.security}
+ />
{update && (
<Badge variant="secondary" className="shrink-0">
{t('plugins.registry.updateAvailable')}
@@ -99,7 +109,8 @@ export function PluginCard({ plugin, hasSchema }: Props) {
</div>
<Switch
- checked={plugin.enabled}
+ checked={plugin.enabled && !plugin.security}
+ disabled={!!plugin.security}
aria-label={t('plugins.detail.enabled')}
onClick={stopPropagation}
onCheckedChange={toggleEnabled}
@@ -107,17 +118,22 @@ export function PluginCard({ plugin, hasSchema }: Props) {
</div>
<p className="line-clamp-2 text-xs text-muted-foreground">{oneLine}</p>
- {audience.tone !== 'safe' && audience.tone !== 'off' && (
- <p className="line-clamp-2 text-xs text-muted-foreground">
- {audience.plain}
- </p>
- )}
+ {plugin.security && <PluginSecurityNotice decision={plugin.security} />}
+ {!plugin.security &&
+ audience.tone !== 'safe' &&
+ audience.tone !== 'off' && (
+ <p className="line-clamp-2 text-xs text-muted-foreground">
+ {audience.plain}
+ </p>
+ )}
<div className="flex flex-wrap items-center gap-2 border-t pt-3">
<Button variant="outline" size="sm" onClick={handlePrimary}>
{audience.primaryAction.label}
</Button>
- {plugin.enabled && <PluginAudienceBadge tone={audience.tone} />}
+ {plugin.enabled && !plugin.security && (
+ <PluginAudienceBadge tone={audience.tone} />
+ )}
{plugin.errorCount > 0 && (
<Badge variant="destructive">
{t('plugins.errors', { count: plugin.errorCount })}
diff --git a/src/renderer/routes/plugins/components/plugin-security-notice.tsx b/src/renderer/routes/plugins/components/plugin-security-notice.tsx
new file mode 100644
index 00000000..84e856ba
--- /dev/null
+++ b/src/renderer/routes/plugins/components/plugin-security-notice.tsx
@@ -0,0 +1,58 @@
+import { Button } from '@renderer/components/ui/button'
+import { usePlatformServices } from '@renderer/platform/services'
+import type { PluginSecurityDecision } from '@shared/schemas/plugin-security'
+import { useTranslation } from 'react-i18next'
+
+export function PluginSecurityNotice({
+ decision,
+}: {
+ decision?: PluginSecurityDecision
+}) {
+ const { t } = useTranslation()
+ const services = usePlatformServices()
+ if (!decision) return null
+ const awaitingVerification =
+ decision.reason === 'pending' || decision.reason === 'unavailable'
+ return (
+ <div
+ role="status"
+ className={
+ awaitingVerification
+ ? 'shrink-0 rounded-md border bg-muted/30 p-3 text-xs space-y-1'
+ : 'shrink-0 rounded-md border border-destructive/30 bg-destructive/5 p-3 text-xs space-y-1'
+ }
+ >
+ <p className="font-medium">
+ {t(
+ awaitingVerification
+ ? 'plugins.status.disabled'
+ : 'plugins.security.blocked'
+ )}
+ </p>
+ <p>{t(`plugins.security.${decision.reason}`)}</p>
+ {decision.advisoryIds.length > 0 && (
+ <p>{decision.advisoryIds.join(', ')}</p>
+ )}
+ {decision.fixedVersion && (
+ <p>
+ {t('plugins.security.fixedVersion', {
+ version: decision.fixedVersion,
+ })}
+ </p>
+ )}
+ {decision.url && (
+ <Button
+ size="sm"
+ variant="link"
+ className="h-auto px-0 text-xs"
+ onClick={(event) => {
+ event.stopPropagation()
+ if (decision.url) void services.openExternal(decision.url)
+ }}
+ >
+ {t('plugins.security.details')}
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/src/renderer/routes/plugins/hooks/use-plugin-install.ts b/src/renderer/routes/plugins/hooks/use-plugin-install.ts
index 656ebd61..05945a30 100644
--- a/src/renderer/routes/plugins/hooks/use-plugin-install.ts
+++ b/src/renderer/routes/plugins/hooks/use-plugin-install.ts
@@ -36,6 +36,8 @@ export function usePluginInstall() {
function showError(e: unknown): void {
const message = e instanceof Error ? e.message : String(e)
const messages = {
+ 'plugins.security.blocked': 'plugins.security.blocked',
+ 'plugins.security.pending': 'plugins.security.pending',
'plugin.install.official_signature_invalid':
'plugins.install.officialSignatureInvalid',
'plugin.install.official_builtin_hook':
diff --git a/src/renderer/routes/plugins/hooks/use-plugins.ts b/src/renderer/routes/plugins/hooks/use-plugins.ts
index 3af197df..e1cc4bd8 100644
--- a/src/renderer/routes/plugins/hooks/use-plugins.ts
+++ b/src/renderer/routes/plugins/hooks/use-plugins.ts
@@ -58,7 +58,6 @@ export function usePlugins(): PluginListDTO[] {
}
inFlight = runRefresh(refreshGeneration)
}
- refresh()
const onStatus = (...args: unknown[]) => {
const p = args[0] as StatusChangedPayload
@@ -84,16 +83,23 @@ export function usePlugins(): PluginListDTO[] {
transport.on(Events.PluginStatusChanged, onStatus)
transport.on(Events.PluginInstalled, onLifecycle)
transport.on(Events.PluginUninstalled, onLifecycle)
+ transport.on(Events.PluginSecurityChanged, onLifecycle)
transport.on(Events.LocaleChanged, onLocale)
transport.on(Events.PluginGrantsChanged, onGrants)
+ const stopConnection = transport.onConnectionChange?.((connection) => {
+ if (connection.state === 'connected') refresh()
+ })
+ refresh()
return () => {
cancelled = true
+ stopConnection?.()
refreshGeneration += 1
refreshQueued = false
transport.off(Events.PluginStatusChanged, onStatus)
transport.off(Events.PluginInstalled, onLifecycle)
transport.off(Events.PluginUninstalled, onLifecycle)
+ transport.off(Events.PluginSecurityChanged, onLifecycle)
transport.off(Events.LocaleChanged, onLocale)
transport.off(Events.PluginGrantsChanged, onGrants)
}
diff --git a/src/renderer/routes/plugins/lib/audience.ts b/src/renderer/routes/plugins/lib/audience.ts
index fa84acff..9f7304cb 100644
--- a/src/renderer/routes/plugins/lib/audience.ts
+++ b/src/renderer/routes/plugins/lib/audience.ts
@@ -269,6 +269,23 @@ export function computePluginAudience(
grants: GrantsMap | undefined,
hasSettingsSchema: boolean = false
): Audience {
+ if (plugin.security) {
+ const titleKey =
+ plugin.security.reason === 'pending' ||
+ plugin.security.reason === 'unavailable'
+ ? 'plugins.status.disabled'
+ : 'plugins.security.blocked'
+ return {
+ tone: 'review',
+ toneLabel: t(titleKey),
+ plain: t(`plugins.security.${plugin.security.reason}`),
+ heroHeadline: t(titleKey),
+ primaryAction: {
+ kind: 'open',
+ label: t('plugins.card.primaryAction.open'),
+ },
+ }
+ }
const errored = plugin.errorCount > 0
const tone = deriveTone(plugin, hostPermissions, grants)
return {
diff --git a/src/renderer/routes/plugins/plugin-detail-page.tsx b/src/renderer/routes/plugins/plugin-detail-page.tsx
index 6e64e15e..700f4aa5 100644
--- a/src/renderer/routes/plugins/plugin-detail-page.tsx
+++ b/src/renderer/routes/plugins/plugin-detail-page.tsx
@@ -45,6 +45,7 @@ import {
hasPluginOperations,
PluginOperations,
} from './components/plugin-operations'
+import { PluginSecurityNotice } from './components/plugin-security-notice'
import { PluginSettingsForm } from './components/plugin-settings-form'
import { PluginStatusDot } from './components/plugin-status-dot'
import { RegistryDetailPanel } from './components/registry-detail-panel'
@@ -182,7 +183,7 @@ export function PluginDetailPage() {
<span className="shrink-0">
<PluginStatusDot
status={listEntry.status}
- enabled={listEntry.enabled}
+ enabled={listEntry.enabled && !listEntry.security}
/>
</span>
</div>
@@ -196,13 +197,15 @@ export function PluginDetailPage() {
<Switch
id="plugin-detail-enabled"
aria-label={t('plugins.detail.enabled')}
- checked={listEntry.enabled}
+ checked={listEntry.enabled && !listEntry.security}
+ disabled={!!listEntry.security}
onCheckedChange={toggleEnabled}
/>
</div>
}
contentClassName="min-h-0 px-6 pb-6"
>
+ <PluginSecurityNotice decision={listEntry.security} />
<Tabs
value={tab}
onValueChange={(v) => setTab(v as DetailTab)}
diff --git a/src/server/index.ts b/src/server/index.ts
index 5769fc92..5f2d721c 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -67,6 +67,7 @@ import { RegistryClient } from '@core/plugin/registry/registry-client'
import type { PluginHookRuntime } from '@core/plugin/runtime/plugin-hook-runtime'
import { createPluginRuntime } from '@core/plugin/runtime/runtime-factory'
import { PluginRuntimeStartupCoordinator } from '@core/plugin/runtime/startup-coordinator'
+import { PluginSecurityService } from '@core/plugin/security/security-service'
import { PluginStateStore } from '@core/plugin/state/plugin-state-store'
import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
import { ProxyBridgeManager } from '@core/proxy/proxy-bridge-manager'
@@ -535,7 +536,12 @@ async function main() {
if (!shellAsyncWork.isAccepting()) return
const pluginStateStore = new PluginStateStore(db.database)
const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH
+ const pluginSecurity = new PluginSecurityService({
+ cachePath: path.join(platform.userDataDir, 'plugin-security.json'),
+ })
+ await pluginSecurity.initialize()
const pluginRegistry = new PluginRegistry({
+ security: pluginSecurity,
pluginsDir,
builtinDir,
stateStore: pluginStateStore,
@@ -585,6 +591,11 @@ async function main() {
const detectPluginFfmpeg = async () =>
projectActiveToLegacy(await detectServerFfmpeg())
const pluginHost = new PluginHost({
+ security: pluginSecurity,
+ onSecurityChanged: () => {
+ eventBus.emit(Events.PluginSecurityChanged)
+ eventBus.emit(Events.ContributionIndexChanged)
+ },
registry: pluginRegistry,
stateStore: pluginStateStore,
capabilityHost: pluginCapHost,
@@ -621,6 +632,7 @@ async function main() {
cachePath: path.join(platform.userDataDir, REGISTRY_CACHE_FILENAME),
})
const pluginInstaller = new PluginInstaller({
+ security: pluginSecurity,
pluginsDir,
registry: pluginRegistry,
stateStore: pluginStateStore,
@@ -785,6 +797,8 @@ async function main() {
},
})
pluginHookRuntime = pluginRuntime.hooks
+ await pluginHost.enforceSecurityPolicy()
+ pluginSecurity.start()
const hookAuditLog = pluginRuntime.auditLog
const hookOrchestrator = pluginRuntime.orchestrator
const postDeliveryAbortController = new AbortController()
@@ -1519,7 +1533,10 @@ async function main() {
await durableFinalizeRuntime.commit({
...input,
postDeliveries: post.postDeliveries,
- beforeCommit: post.beforeCommit,
+ beforeCommit: () => {
+ input.beforeCommit?.()
+ post.beforeCommit()
+ },
})
},
})
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 6cad9e3c..48e058f3 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -961,6 +961,7 @@ export function buildServerCommandHandlers(
},
[Commands.EnablePlugin]: async (id: string) => {
+ pluginRegistry.assertSecurityAllowed?.(id)
pluginStateStore.setEnabled(id, true)
// Sync the in-memory IndexedPlugin.state so Queries.ListPlugins and
// downstream gating (PluginHost.activate, ActivationDispatcher,
@@ -1040,6 +1041,7 @@ export function buildServerCommandHandlers(
[Commands.CheckPluginUpdates]: async (payload: unknown) => {
const parsed = checkPluginUpdatesPayloadSchema.parse(payload)
+ await pluginHost.refreshSecurityPolicy?.(parsed?.force)
if (parsed?.force) await registryClient.refresh()
const entries = await registryClient.list(hostVersion)
return scanForUpdates(pluginRegistry.list(), entries).filter(
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 9175913d..559653a7 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -27,6 +27,8 @@ export enum ErrorCode {
PluginCircuitOpen = 'PLUGIN_CIRCUIT_OPEN',
PluginRuntimeFault = 'PLUGIN_RUNTIME_FAULT',
PluginDirNotConfigured = 'PLUGIN_DIR_NOT_CONFIGURED',
+ PluginSecurityBlocked = 'PLUGIN_SECURITY_BLOCKED',
+ PluginSecurityPending = 'PLUGIN_SECURITY_PENDING',
// NAT Manager
NatDiscoveryFailed = 'NAT_DISCOVERY_FAILED',
NatMappingFailed = 'NAT_MAPPING_FAILED',
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index f5cb1187..9fa8f5b0 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -1734,6 +1734,16 @@
"optional": "وصول اختياري",
"review": "تحتاج إلى مراجعة",
"safe": "تبدو آمنة"
+ },
+ "security": {
+ "blocked": "محظور لأسباب أمنية",
+ "pending": "اتصل بالإنترنت وتحقق من التحديثات قبل تفعيل هذه الإضافة.",
+ "unavailable": "تعذر التحقق من سياسة الأمان. تحقق من التحديثات للمحاولة مجددًا.",
+ "malware": "تم التعرف على هذه الإضافة على أنها ضارة.",
+ "vulnerability": "يحتوي هذا الإصدار من الإضافة على ثغرة أمنية.",
+ "compromised": "تم اختراق قناة توزيع هذه الإضافة.",
+ "fixedVersion": "يتوفر إصلاح في الإصدار {{version}}.",
+ "details": "عرض التنبيه الأمني"
}
},
"quit": {
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 2252f21b..97a69899 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -1662,6 +1662,16 @@
"optional": "Незадължителен достъп",
"review": "Изисква преглед",
"safe": "Изглежда безопасна"
+ },
+ "security": {
+ "blocked": "Блокирано от съображения за сигурност",
+ "pending": "Свържете се с интернет и проверете за актуализации, преди да включите тази добавка.",
+ "unavailable": "Правилата за сигурност не можаха да бъдат проверени. Проверете отново за актуализации.",
+ "malware": "Тази добавка е идентифицирана като злонамерена.",
+ "vulnerability": "Тази версия на добавката има уязвимост в сигурността.",
+ "compromised": "Каналът за разпространение на тази добавка е компрометиран.",
+ "fixedVersion": "Поправка е налична във версия {{version}}.",
+ "details": "Преглед на известието за сигурност"
}
},
"quit": {
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 65fe8eb9..3f654567 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -1680,6 +1680,16 @@
"optional": "Accés opcional",
"review": "Cal revisar-lo",
"safe": "Sembla segur"
+ },
+ "security": {
+ "blocked": "Bloquejat per motius de seguretat",
+ "pending": "Connecteu-vos a Internet i cerqueu actualitzacions abans d’activar aquest connector.",
+ "unavailable": "No s’ha pogut verificar la política de seguretat. Torneu a cercar actualitzacions.",
+ "malware": "Aquest connector s’ha identificat com a maliciós.",
+ "vulnerability": "Aquesta versió del connector té una vulnerabilitat de seguretat.",
+ "compromised": "La distribució d’aquest connector s’ha vist compromesa.",
+ "fixedVersion": "Hi ha una correcció disponible a la versió {{version}}.",
+ "details": "Mostra l’avís de seguretat"
}
},
"quit": {
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index 427648c4..42e9b0e7 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -2693,6 +2693,16 @@
"noAccess": "Aus",
"grant": "Erlauben"
}
+ },
+ "security": {
+ "blocked": "Aus Sicherheitsgründen gesperrt",
+ "pending": "Stellen Sie eine Internetverbindung her und suchen Sie nach Updates, bevor Sie dieses Plugin aktivieren.",
+ "unavailable": "Die Sicherheitsrichtlinie konnte nicht überprüft werden. Suchen Sie erneut nach Updates.",
+ "malware": "Dieses Plugin wurde als schädlich eingestuft.",
+ "vulnerability": "Diese Plugin-Version weist eine Sicherheitslücke auf.",
+ "compromised": "Der Vertriebsweg dieses Plugins wurde kompromittiert.",
+ "fixedVersion": "Eine Korrektur ist in Version {{version}} verfügbar.",
+ "details": "Sicherheitshinweis anzeigen"
}
},
"plugin": {
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 3ff3ec10..2657a9a1 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -1662,6 +1662,16 @@
"optional": "Προαιρετική πρόσβαση",
"review": "Χρειάζεται έλεγχο",
"safe": "Φαίνεται ασφαλές"
+ },
+ "security": {
+ "blocked": "Αποκλείστηκε για λόγους ασφαλείας",
+ "pending": "Συνδεθείτε στο διαδίκτυο και ελέγξτε για ενημερώσεις πριν ενεργοποιήσετε αυτό το πρόσθετο.",
+ "unavailable": "Δεν ήταν δυνατή η επαλήθευση της πολιτικής ασφαλείας. Ελέγξτε ξανά για ενημερώσεις.",
+ "malware": "Αυτό το πρόσθετο αναγνωρίστηκε ως κακόβουλο.",
+ "vulnerability": "Αυτή η έκδοση του πρόσθετου έχει ευπάθεια ασφαλείας.",
+ "compromised": "Η διανομή αυτού του πρόσθετου έχει παραβιαστεί.",
+ "fixedVersion": "Διατίθεται διόρθωση στην έκδοση {{version}}.",
+ "details": "Προβολή ανακοίνωσης ασφαλείας"
}
},
"quit": {
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 1b23c3fc..8f8c0c9b 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -2693,6 +2693,16 @@
"noAccess": "Off",
"grant": "Allow"
}
+ },
+ "security": {
+ "blocked": "Blocked for security reasons",
+ "pending": "Connect to the internet and check for updates before enabling this plugin.",
+ "unavailable": "The security policy could not be verified. Check for updates to retry.",
+ "malware": "This plugin was identified as malicious.",
+ "vulnerability": "This plugin version has a security vulnerability.",
+ "compromised": "This plugin’s distribution was compromised.",
+ "fixedVersion": "A fix is available in version {{version}}.",
+ "details": "View security advisory"
}
},
"plugin": {
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 206e1fbb..f9a70e1a 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -2714,7 +2714,17 @@
"grant": "Permitir"
}
},
- "errors_many": "{{count}} errores"
+ "errors_many": "{{count}} errores",
+ "security": {
+ "blocked": "Bloqueado por motivos de seguridad",
+ "pending": "Conéctate a Internet y busca actualizaciones antes de activar este complemento.",
+ "unavailable": "No se pudo verificar la política de seguridad. Busca actualizaciones para volver a intentarlo.",
+ "malware": "Este complemento se ha identificado como malicioso.",
+ "vulnerability": "Esta versión del complemento tiene una vulnerabilidad de seguridad.",
+ "compromised": "La distribución de este complemento se ha visto comprometida.",
+ "fixedVersion": "Hay una corrección disponible en la versión {{version}}.",
+ "details": "Ver aviso de seguridad"
+ }
},
"plugin": {
"ffmpeg": {
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index cca4e23c..a8ff7888 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -1662,6 +1662,16 @@
"optional": "دسترسی اختیاری",
"review": "نیاز به بررسی",
"safe": "ایمن به نظر می‌رسد"
+ },
+ "security": {
+ "blocked": "به دلایل امنیتی مسدود شده است",
+ "pending": "پیش از فعال کردن این افزونه، به اینترنت وصل شوید و به‌روزرسانی‌ها را بررسی کنید.",
+ "unavailable": "سیاست امنیتی تأیید نشد. برای تلاش دوباره به‌روزرسانی‌ها را بررسی کنید.",
+ "malware": "این افزونه مخرب تشخیص داده شده است.",
+ "vulnerability": "این نسخه از افزونه دارای آسیب‌پذیری امنیتی است.",
+ "compromised": "کانال توزیع این افزونه مورد نفوذ قرار گرفته است.",
+ "fixedVersion": "اصلاحیه در نسخه {{version}} موجود است.",
+ "details": "مشاهده اطلاعیه امنیتی"
}
},
"quit": {
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 01c24209..73e3a006 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -1680,6 +1680,16 @@
"optional": "Accès facultatif",
"review": "À vérifier",
"safe": "Semble sûr"
+ },
+ "security": {
+ "blocked": "Bloqué pour raisons de sécurité",
+ "pending": "Connectez-vous à Internet et recherchez les mises à jour avant d’activer ce plugin.",
+ "unavailable": "La politique de sécurité n’a pas pu être vérifiée. Recherchez les mises à jour pour réessayer.",
+ "malware": "Ce plugin a été identifié comme malveillant.",
+ "vulnerability": "Cette version du plugin présente une faille de sécurité.",
+ "compromised": "La distribution de ce plugin a été compromise.",
+ "fixedVersion": "Un correctif est disponible dans la version {{version}}.",
+ "details": "Voir l’avis de sécurité"
}
},
"quit": {
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index d27c14dc..1e2f5168 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -2693,6 +2693,16 @@
"noAccess": "Kikapcsolva",
"grant": "Engedélyezés"
}
+ },
+ "security": {
+ "blocked": "Biztonsági okokból letiltva",
+ "pending": "A bővítmény engedélyezése előtt csatlakozzon az internethez, és keressen frissítéseket.",
+ "unavailable": "A biztonsági szabályzat nem ellenőrizhető. Keressen ismét frissítéseket.",
+ "malware": "Ez a bővítmény rosszindulatúnak bizonyult.",
+ "vulnerability": "A bővítmény ezen verziója biztonsági rést tartalmaz.",
+ "compromised": "A bővítmény terjesztési csatornáját feltörték.",
+ "fixedVersion": "Javítás érhető el a(z) {{version}} verzióban.",
+ "details": "Biztonsági közlemény megtekintése"
}
},
"plugin": {
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index a0d2df58..c0b88ee3 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -2672,6 +2672,16 @@
"noAccess": "Nonaktif",
"grant": "Izinkan"
}
+ },
+ "security": {
+ "blocked": "Diblokir demi keamanan",
+ "pending": "Hubungkan ke internet dan periksa pembaruan sebelum mengaktifkan plugin ini.",
+ "unavailable": "Kebijakan keamanan tidak dapat diverifikasi. Periksa pembaruan untuk mencoba lagi.",
+ "malware": "Plugin ini teridentifikasi berbahaya.",
+ "vulnerability": "Versi plugin ini memiliki kerentanan keamanan.",
+ "compromised": "Saluran distribusi plugin ini telah disusupi.",
+ "fixedVersion": "Perbaikan tersedia pada versi {{version}}.",
+ "details": "Lihat pemberitahuan keamanan"
}
},
"plugin": {
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index b4c71282..f69b6732 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -2714,6 +2714,16 @@
"noAccess": "Disattivato",
"grant": "Consenti"
}
+ },
+ "security": {
+ "blocked": "Bloccato per motivi di sicurezza",
+ "pending": "Connettiti a Internet e cerca aggiornamenti prima di attivare questo plugin.",
+ "unavailable": "Impossibile verificare la politica di sicurezza. Cerca aggiornamenti per riprovare.",
+ "malware": "Questo plugin è stato identificato come dannoso.",
+ "vulnerability": "Questa versione del plugin presenta una vulnerabilità di sicurezza.",
+ "compromised": "La distribuzione di questo plugin è stata compromessa.",
+ "fixedVersion": "Una correzione è disponibile nella versione {{version}}.",
+ "details": "Visualizza avviso di sicurezza"
}
},
"plugin": {
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 94c61f59..a36d4975 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -2672,6 +2672,16 @@
"noAccess": "オフ",
"grant": "許可"
}
+ },
+ "security": {
+ "blocked": "セキュリティ上の理由で無効",
+ "pending": "このプラグインを有効にする前に、インターネットに接続して更新を確認してください。",
+ "unavailable": "セキュリティポリシーを検証できませんでした。更新を確認して再試行してください。",
+ "malware": "このプラグインは悪意のあるものと判定されました。",
+ "vulnerability": "このバージョンにはセキュリティ上の脆弱性があります。",
+ "compromised": "このプラグインの配布元が侵害されました。",
+ "fixedVersion": "修正済みバージョン:{{version}}。",
+ "details": "セキュリティ情報を表示"
}
},
"plugin": {
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 44e7a41d..df27e0f0 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -2672,6 +2672,16 @@
"noAccess": "꺼짐",
"grant": "허용"
}
+ },
+ "security": {
+ "blocked": "보안상의 이유로 차단됨",
+ "pending": "이 플러그인을 활성화하기 전에 인터넷에 연결하여 업데이트를 확인하세요.",
+ "unavailable": "보안 정책을 확인할 수 없습니다. 업데이트를 확인하고 다시 시도하세요.",
+ "malware": "이 플러그인은 악성으로 확인되었습니다.",
+ "vulnerability": "이 플러그인 버전에 보안 취약점이 있습니다.",
+ "compromised": "이 플러그인의 배포 경로가 침해되었습니다.",
+ "fixedVersion": "수정된 버전: {{version}}.",
+ "details": "보안 공지 보기"
}
},
"plugin": {
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 9e6f4912..18521343 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -1662,6 +1662,16 @@
"optional": "Valgfri tilgang",
"review": "Krever gjennomgang",
"safe": "Ser trygt ut"
+ },
+ "security": {
+ "blocked": "Blokkert av sikkerhetsgrunner",
+ "pending": "Koble til internett og se etter oppdateringer før du aktiverer denne utvidelsen.",
+ "unavailable": "Sikkerhetspolicyen kunne ikke bekreftes. Se etter oppdateringer for å prøve igjen.",
+ "malware": "Denne utvidelsen er identifisert som skadelig.",
+ "vulnerability": "Denne versjonen av utvidelsen har en sikkerhetssårbarhet.",
+ "compromised": "Distribusjonen av denne utvidelsen er kompromittert.",
+ "fixedVersion": "En rettelse er tilgjengelig i versjon {{version}}.",
+ "details": "Vis sikkerhetsvarsel"
}
},
"quit": {
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index defb664a..519ec00f 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -1662,6 +1662,16 @@
"optional": "Optionele toegang",
"review": "Controle vereist",
"safe": "Lijkt veilig"
+ },
+ "security": {
+ "blocked": "Geblokkeerd om veiligheidsredenen",
+ "pending": "Maak verbinding met internet en controleer op updates voordat u deze plug-in inschakelt.",
+ "unavailable": "Het beveiligingsbeleid kon niet worden geverifieerd. Controleer opnieuw op updates.",
+ "malware": "Deze plug-in is als schadelijk aangemerkt.",
+ "vulnerability": "Deze versie van de plug-in bevat een beveiligingslek.",
+ "compromised": "De distributie van deze plug-in is gecompromitteerd.",
+ "fixedVersion": "Een oplossing is beschikbaar in versie {{version}}.",
+ "details": "Beveiligingsmelding bekijken"
}
},
"quit": {
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 7c202735..5ba5f2af 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -2735,6 +2735,16 @@
"noAccess": "Wyłączone",
"grant": "Zezwól"
}
+ },
+ "security": {
+ "blocked": "Zablokowano ze względów bezpieczeństwa",
+ "pending": "Połącz się z internetem i sprawdź aktualizacje przed włączeniem tej wtyczki.",
+ "unavailable": "Nie udało się zweryfikować zasad bezpieczeństwa. Sprawdź aktualizacje ponownie.",
+ "malware": "Ta wtyczka została uznana za złośliwą.",
+ "vulnerability": "Ta wersja wtyczki zawiera lukę w zabezpieczeniach.",
+ "compromised": "Kanał dystrybucji tej wtyczki został naruszony.",
+ "fixedVersion": "Poprawka jest dostępna w wersji {{version}}.",
+ "details": "Wyświetl komunikat bezpieczeństwa"
}
},
"plugin": {
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 4d3690d9..330b25d0 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -2714,6 +2714,16 @@
"noAccess": "Desativado",
"grant": "Permitir"
}
+ },
+ "security": {
+ "blocked": "Bloqueado por motivos de segurança",
+ "pending": "Conecte-se à internet e verifique se há atualizações antes de ativar este plugin.",
+ "unavailable": "Não foi possível verificar a política de segurança. Verifique se há atualizações para tentar novamente.",
+ "malware": "Este plugin foi identificado como malicioso.",
+ "vulnerability": "Esta versão do plugin tem uma vulnerabilidade de segurança.",
+ "compromised": "A distribuição deste plugin foi comprometida.",
+ "fixedVersion": "Uma correção está disponível na versão {{version}}.",
+ "details": "Ver aviso de segurança"
}
},
"plugin": {
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index a35e409c..ad0fd0d5 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -1680,6 +1680,16 @@
"optional": "Acces opțional",
"review": "Necesită verificare",
"safe": "Pare sigur"
+ },
+ "security": {
+ "blocked": "Blocat din motive de securitate",
+ "pending": "Conectați-vă la internet și căutați actualizări înainte de a activa acest plugin.",
+ "unavailable": "Politica de securitate nu a putut fi verificată. Căutați din nou actualizări.",
+ "malware": "Acest plugin a fost identificat ca fiind rău intenționat.",
+ "vulnerability": "Această versiune a pluginului are o vulnerabilitate de securitate.",
+ "compromised": "Canalul de distribuție al acestui plugin a fost compromis.",
+ "fixedVersion": "O remediere este disponibilă în versiunea {{version}}.",
+ "details": "Vedeți anunțul de securitate"
}
},
"quit": {
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index a9935bf9..91c3a01a 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -2735,6 +2735,16 @@
"noAccess": "Выключено",
"grant": "Разрешить"
}
+ },
+ "security": {
+ "blocked": "Заблокирован из соображений безопасности",
+ "pending": "Подключитесь к интернету и проверьте обновления перед включением плагина.",
+ "unavailable": "Не удалось проверить политику безопасности. Повторите проверку обновлений.",
+ "malware": "Этот плагин признан вредоносным.",
+ "vulnerability": "Эта версия плагина содержит уязвимость безопасности.",
+ "compromised": "Канал распространения этого плагина был скомпрометирован.",
+ "fixedVersion": "Исправление доступно в версии {{version}}.",
+ "details": "Открыть уведомление о безопасности"
}
},
"plugin": {
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 13815502..8bd3ca91 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -1644,6 +1644,16 @@
"optional": "การเข้าถึงที่เลือกให้ได้",
"review": "ต้องตรวจสอบ",
"safe": "ดูปลอดภัย"
+ },
+ "security": {
+ "blocked": "ถูกบล็อกด้วยเหตุผลด้านความปลอดภัย",
+ "pending": "เชื่อมต่ออินเทอร์เน็ตและตรวจสอบการอัปเดตก่อนเปิดใช้ปลั๊กอินนี้",
+ "unavailable": "ไม่สามารถยืนยันนโยบายความปลอดภัยได้ โปรดตรวจสอบการอัปเดตเพื่อลองอีกครั้ง",
+ "malware": "ปลั๊กอินนี้ถูกระบุว่าเป็นอันตราย",
+ "vulnerability": "ปลั๊กอินเวอร์ชันนี้มีช่องโหว่ด้านความปลอดภัย",
+ "compromised": "ช่องทางเผยแพร่ปลั๊กอินนี้ถูกบุกรุก",
+ "fixedVersion": "มีการแก้ไขในเวอร์ชัน {{version}}",
+ "details": "ดูประกาศความปลอดภัย"
}
},
"quit": {
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 6843b0f7..db116f05 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -2693,6 +2693,16 @@
"noAccess": "Kapalı",
"grant": "İzin ver"
}
+ },
+ "security": {
+ "blocked": "Güvenlik nedeniyle engellendi",
+ "pending": "Bu eklentiyi etkinleştirmeden önce internete bağlanıp güncellemeleri denetleyin.",
+ "unavailable": "Güvenlik ilkesi doğrulanamadı. Yeniden denemek için güncellemeleri denetleyin.",
+ "malware": "Bu eklenti kötü amaçlı olarak tanımlandı.",
+ "vulnerability": "Bu eklenti sürümünde bir güvenlik açığı var.",
+ "compromised": "Bu eklentinin dağıtım kanalı ele geçirildi.",
+ "fixedVersion": "Düzeltme {{version}} sürümünde mevcut.",
+ "details": "Güvenlik duyurusunu görüntüle"
}
},
"plugin": {
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index a610535d..d7aea017 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -1698,6 +1698,16 @@
"optional": "Необов'язковий доступ",
"review": "Потребує перевірки",
"safe": "Виглядає безпечним"
+ },
+ "security": {
+ "blocked": "Заблоковано з міркувань безпеки",
+ "pending": "Підключіться до інтернету та перевірте оновлення перед увімкненням плагіна.",
+ "unavailable": "Не вдалося перевірити політику безпеки. Повторіть перевірку оновлень.",
+ "malware": "Цей плагін визнано шкідливим.",
+ "vulnerability": "Ця версія плагіна містить вразливість безпеки.",
+ "compromised": "Канал розповсюдження цього плагіна було скомпрометовано.",
+ "fixedVersion": "Виправлення доступне у версії {{version}}.",
+ "details": "Переглянути повідомлення про безпеку"
}
},
"quit": {
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 8a5fc7f2..a83857c7 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -2672,6 +2672,16 @@
"noAccess": "Tắt",
"grant": "Cho phép"
}
+ },
+ "security": {
+ "blocked": "Bị chặn vì lý do bảo mật",
+ "pending": "Kết nối internet và kiểm tra bản cập nhật trước khi bật tiện ích này.",
+ "unavailable": "Không thể xác minh chính sách bảo mật. Hãy kiểm tra bản cập nhật để thử lại.",
+ "malware": "Tiện ích này đã được xác định là độc hại.",
+ "vulnerability": "Phiên bản tiện ích này có lỗ hổng bảo mật.",
+ "compromised": "Kênh phân phối tiện ích này đã bị xâm phạm.",
+ "fixedVersion": "Bản sửa lỗi có trong phiên bản {{version}}.",
+ "details": "Xem thông báo bảo mật"
}
},
"plugin": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 687069f3..61a02bd2 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -2672,6 +2672,16 @@
"noAccess": "关闭",
"grant": "允许"
}
+ },
+ "security": {
+ "blocked": "已因安全风险禁用",
+ "pending": "请联网检查更新后再启用此插件。",
+ "unavailable": "无法验证安全策略,请检查更新后重试。",
+ "malware": "此插件已被确认为恶意插件。",
+ "vulnerability": "此插件版本存在安全漏洞。",
+ "compromised": "此插件的分发渠道已遭入侵。",
+ "fixedVersion": "修复版本:{{version}}。",
+ "details": "查看安全公告"
}
},
"plugin": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 1053b84e..8c3e2234 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -2772,6 +2772,16 @@
"noAccess": "關閉",
"grant": "允許"
}
+ },
+ "security": {
+ "blocked": "已因安全風險停用",
+ "pending": "請連線檢查更新後再啟用此外掛。",
+ "unavailable": "無法驗證安全原則,請檢查更新後重試。",
+ "malware": "此外掛已被確認為惡意外掛。",
+ "vulnerability": "此外掛版本存在安全漏洞。",
+ "compromised": "此外掛的散布管道已遭入侵。",
+ "fixedVersion": "修復版本:{{version}}。",
+ "details": "檢視安全公告"
}
},
"applicationMenu": {
diff --git a/src/shared/plugin-security-trust.ts b/src/shared/plugin-security-trust.ts
new file mode 100644
index 00000000..4a879062
--- /dev/null
+++ b/src/shared/plugin-security-trust.ts
@@ -0,0 +1,17 @@
+/**
+ * Build-time security-policy trust. Keep these keys independent of package
+ * signing keys. Production provisioning must supply the public keys and a
+ * signed baseline before enabling the feed; runtime overrides are forbidden.
+ * No production signing key or endpoint has been provisioned in this build.
+ */
+export const PLUGIN_SECURITY_TRUST: {
+ url: string
+ publicKeys: readonly string[]
+ baseline: string | null
+} = {
+ url: 'https://dl.motrix.app/security/plugins-v1.json',
+ publicKeys: [],
+ baseline: null,
+}
+
+export const PLUGIN_SECURITY_SIGNATURE_CONTEXT = 'motrix-plugin-security-v1\n'
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index ecd8ce96..a26b5106 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -22,6 +22,7 @@ export const Events = {
PluginError: 'event:pluginError',
PluginTimeout: 'event:pluginTimeout',
PluginStatusChanged: 'event:pluginStatusChanged',
+ PluginSecurityChanged: 'event:pluginSecurityChanged',
PluginInstalled: 'event:pluginInstalled',
PluginUninstalled: 'event:pluginUninstalled',
PluginInstallConsentRequested: 'event:pluginInstallConsentRequested',
diff --git a/src/shared/protocol/forwardable-events.test.ts b/src/shared/protocol/forwardable-events.test.ts
index aa047e5f..107aa866 100644
--- a/src/shared/protocol/forwardable-events.test.ts
+++ b/src/shared/protocol/forwardable-events.test.ts
@@ -27,7 +27,7 @@ describe('ForwardableEvents', () => {
})
it('has the expected number of forwardable events', () => {
- expect(ForwardableEvents).toHaveLength(59)
+ expect(ForwardableEvents).toHaveLength(60)
})
it('includes the bridge approval events (web-shell pairing)', () => {
@@ -66,6 +66,7 @@ describe('ForwardableEvents', () => {
expect(ForwardableEvents).toContain(Events.PluginError)
expect(ForwardableEvents).toContain(Events.PluginTimeout)
expect(ForwardableEvents).toContain(Events.PluginStatusChanged)
+ expect(ForwardableEvents).toContain(Events.PluginSecurityChanged)
expect(ForwardableEvents).toContain(Events.PluginConfigChanged)
expect(ForwardableEvents).toContain(Events.PluginGrantsChanged)
expect(ForwardableEvents).toContain(Events.PluginEvicted)
diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.ts
index 8e4c8270..2d9cb4bb 100644
--- a/src/shared/protocol/forwardable-events.ts
+++ b/src/shared/protocol/forwardable-events.ts
@@ -19,6 +19,7 @@ export const ForwardableEvents = [
Events.PluginError,
Events.PluginTimeout,
Events.PluginStatusChanged,
+ Events.PluginSecurityChanged,
Events.PluginInstalled,
Events.PluginUninstalled,
Events.NatStateChanged,
diff --git a/src/shared/schemas/plugin-security.ts b/src/shared/schemas/plugin-security.ts
new file mode 100644
index 00000000..1d749e61
--- /dev/null
+++ b/src/shared/schemas/plugin-security.ts
@@ -0,0 +1,150 @@
+import { compareSemver } from '@shared/semver'
+import { z } from 'zod'
+
+export const PLUGIN_SECURITY_INTERVAL_MS = 12 * 60 * 60 * 1000
+export const PLUGIN_SECURITY_FRESHNESS_MS = 24 * 60 * 60 * 1000
+export const PLUGIN_SECURITY_MAX_BYTES = 256 * 1024
+
+// Bounds use SemVer precedence, including prereleases, with no implicit
+// prerelease exclusion or host-version normalization.
+const version = z
+ .string()
+ .max(128)
+ .regex(
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/
+ )
+const sha256 = z.string().regex(/^[a-f0-9]{64}$/)
+const pluginId = z
+ .string()
+ .min(1)
+ .max(128)
+ .regex(/^[a-zA-Z0-9_.-]+$/)
+const advisoryId = z
+ .string()
+ .min(1)
+ .max(80)
+ .regex(/^[A-Z0-9-]+$/)
+
+const versionSelector = z
+ .object({
+ kind: z.literal('plugin'),
+ pluginId,
+ fromInclusive: version.optional(),
+ beforeExclusive: version.optional(),
+ })
+ .strict()
+ .refine(
+ (value) =>
+ !value.fromInclusive ||
+ !value.beforeExclusive ||
+ compareSemver(value.fromInclusive, value.beforeExclusive) < 0,
+ 'Version bounds must describe a nonempty interval'
+ )
+
+export const PluginSecuritySelectorSchema = z.discriminatedUnion('kind', [
+ versionSelector,
+ z.object({ kind: z.literal('archive'), sha256 }).strict(),
+])
+
+export const PluginSecurityAdvisorySchema = z
+ .object({
+ id: advisoryId,
+ status: z.enum(['active', 'withdrawn']),
+ reason: z.enum(['malware', 'vulnerability', 'compromised']),
+ affected: z.array(PluginSecuritySelectorSchema).min(1).max(100),
+ fixedVersion: version.optional(),
+ // Rendered as a link, never fetched or executed by the host.
+ url: z
+ .string()
+ .max(512)
+ .url()
+ .refine((value) => {
+ const url = new URL(value)
+ return (
+ url.protocol === 'https:' &&
+ url.hostname === 'motrix.app' &&
+ !url.username &&
+ !url.password &&
+ !url.port
+ )
+ })
+ .optional(),
+ })
+ .strict()
+
+export const PluginSecurityPolicySchema = z
+ .object({
+ schemaVersion: z.literal(1),
+ revision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ issuedAt: z.iso.datetime(),
+ expiresAt: z.iso.datetime(),
+ advisories: z.array(PluginSecurityAdvisorySchema).max(1000),
+ })
+ .strict()
+ .superRefine((policy, ctx) => {
+ const issued = Date.parse(policy.issuedAt)
+ const expires = Date.parse(policy.expiresAt)
+ if (expires <= issued || expires - issued > 14 * 24 * 60 * 60 * 1000) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Policy lifetime must be at most 14 days',
+ })
+ }
+ if (
+ new Set(policy.advisories.map((entry) => entry.id)).size !==
+ policy.advisories.length
+ ) {
+ ctx.addIssue({ code: 'custom', message: 'Duplicate advisory ID' })
+ }
+ })
+
+// The signature covers the exact decoded UTF-8 payload bytes, with a domain
+// separator. No JSON canonicalization and no trust in HTTP validators.
+export const PluginSecurityEnvelopeSchema = z
+ .object({
+ payload: z
+ .string()
+ .min(1)
+ .max(PLUGIN_SECURITY_MAX_BYTES)
+ .regex(/^[A-Za-z0-9+/]+={0,2}$/),
+ signatures: z
+ .array(
+ z
+ .string()
+ .length(88)
+ .regex(/^[A-Za-z0-9+/]+={0,2}$/)
+ )
+ .min(1)
+ .max(4),
+ })
+ .strict()
+
+export const PluginSecurityDecisionSchema = z
+ .object({
+ blocked: z.literal(true),
+ reason: z.enum([
+ 'malware',
+ 'vulnerability',
+ 'compromised',
+ 'unavailable',
+ 'pending',
+ ]),
+ advisoryIds: z.array(advisoryId),
+ fixedVersion: version.optional(),
+ url: z.string().optional(),
+ })
+ .strict()
+
+export type PluginSecurityPolicy = z.infer<typeof PluginSecurityPolicySchema>
+export type PluginSecurityEnvelope = z.infer<
+ typeof PluginSecurityEnvelopeSchema
+>
+export type PluginSecurityDecision = z.infer<
+ typeof PluginSecurityDecisionSchema
+>
+
+export interface PluginSecurityIdentity {
+ pluginId: string
+ version: string
+ archiveSha256?: string
+}
diff --git a/src/shared/types/plugin-install.ts b/src/shared/types/plugin-install.ts
index 6b1367e3..7dc82e3c 100644
--- a/src/shared/types/plugin-install.ts
+++ b/src/shared/types/plugin-install.ts
@@ -32,6 +32,8 @@ export interface InstallRecordSource {
type: InstallSourceType
url: string
bundleSha256: string
+ /** Exact .moext digest, distinct from the executable entry digest. */
+ archiveSha256?: string
recordedAt: number
}
@@ -55,6 +57,8 @@ export interface InstallRecord {
consentSnapshot: ConsentSnapshot
/** Signature over the retained archive, rechecked at discovery and activation. */
official?: OfficialPackageProof
+ /** False until the first activation has a recent trusted security policy. */
+ securityReviewed?: boolean
}
export interface OfficialPackageProof {
diff --git a/src/shared/types/plugin.ts b/src/shared/types/plugin.ts
index 4b5fc953..4a0bd6fe 100644
--- a/src/shared/types/plugin.ts
+++ b/src/shared/types/plugin.ts
@@ -1,6 +1,8 @@
// src/shared/types/plugin.ts
// Phase 1A DTO-only types. Manifest schema lives in @core/plugin/manifest/schema.ts.
+import type { PluginSecurityDecision } from '@shared/schemas/plugin-security'
+
export type PluginStatus =
| 'inactive' // installed + enabled, VM not running
| 'active' // VM running
@@ -128,6 +130,7 @@ export interface PluginListDTO {
source?: PluginSource
errorCount: number
lastError?: string
+ security?: PluginSecurityDecision
}
export interface PluginManifestDTO extends PluginManifest {
diff --git a/src/test-utils/plugin-security.ts b/src/test-utils/plugin-security.ts
new file mode 100644
index 00000000..6d97cf80
--- /dev/null
+++ b/src/test-utils/plugin-security.ts
@@ -0,0 +1,54 @@
+import { generateKeyPairSync, sign } from 'node:crypto'
+import { PLUGIN_SECURITY_SIGNATURE_CONTEXT } from '@shared/plugin-security-trust'
+import type { PluginSecurityPolicy } from '@shared/schemas/plugin-security'
+
+export function securityFixture() {
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519')
+ const publicPem = publicKey.export({ type: 'spki', format: 'pem' }).toString()
+ return {
+ trust: {
+ url: 'https://security.example.test/plugins-v1.json',
+ publicKeys: [publicPem],
+ baseline: null,
+ },
+ policy: (
+ now: number,
+ patch: Partial<PluginSecurityPolicy> = {}
+ ): PluginSecurityPolicy => ({
+ schemaVersion: 1,
+ revision: 1,
+ issuedAt: new Date(now).toISOString(),
+ expiresAt: new Date(now + 7 * 24 * 60 * 60_000).toISOString(),
+ advisories: [
+ {
+ id: 'MTX-TEST-1',
+ status: 'active',
+ reason: 'malware',
+ affected: [
+ {
+ kind: 'plugin',
+ pluginId: 'alice.demo',
+ beforeExclusive: '2.0.0',
+ },
+ ],
+ },
+ ],
+ ...patch,
+ }),
+ sign: (policy: unknown): string => {
+ const payload = Buffer.from(JSON.stringify(policy))
+ const signature = sign(
+ null,
+ Buffer.concat([
+ Buffer.from(PLUGIN_SECURITY_SIGNATURE_CONTEXT),
+ payload,
+ ]),
+ privateKey
+ )
+ return JSON.stringify({
+ payload: payload.toString('base64'),
+ signatures: [signature.toString('base64')],
+ })
+ },
+ }
+}
diff --git a/tests/scripts/sign-plugin-security.test.ts b/tests/scripts/sign-plugin-security.test.ts
new file mode 100644
index 00000000..efc6b75f
--- /dev/null
+++ b/tests/scripts/sign-plugin-security.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { generateKeyPairSync } from 'node:crypto'
+import { verifySecurityPolicy } from '@core/plugin/security/policy-verifier'
+import { describe, expect, it } from 'vitest'
+// @ts-expect-error Node publishing entrypoint is a JavaScript module.
+import { signPluginSecurityPolicy } from '../../scripts/sign-plugin-security.mjs'
+
+describe('offline security-policy publisher', () => {
+ it('produces host-verifiable envelopes and refuses accidental rollback or removal', () => {
+ const keys = generateKeyPairSync('ed25519')
+ const pem = keys.privateKey
+ .export({ format: 'pem', type: 'pkcs8' })
+ .toString()
+ const publicPem = keys.publicKey
+ .export({ format: 'pem', type: 'spki' })
+ .toString()
+ const policy = {
+ schemaVersion: 1,
+ revision: 1,
+ issuedAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + 86400_000).toISOString(),
+ advisories: [
+ {
+ id: 'MTX-TEST-1',
+ status: 'active',
+ reason: 'malware',
+ affected: [{ kind: 'plugin', pluginId: 'example.test' }],
+ },
+ ],
+ }
+ const envelope = signPluginSecurityPolicy(policy, pem)
+ expect(verifySecurityPolicy(envelope, [publicPem])).toEqual(policy)
+ expect(() => signPluginSecurityPolicy(policy, pem, envelope)).toThrow(
+ 'revision'
+ )
+ expect(() =>
+ signPluginSecurityPolicy(
+ { ...policy, revision: 2, advisories: [] },
+ pem,
+ envelope
+ )
+ ).toThrow('withdrawal')
+ const withdrawn = {
+ ...policy,
+ revision: 2,
+ advisories: policy.advisories.map((entry) => ({
+ ...entry,
+ status: 'withdrawn',
+ })),
+ }
+ expect(
+ verifySecurityPolicy(signPluginSecurityPolicy(withdrawn, pem, envelope), [
+ publicPem,
+ ])
+ ).toEqual(withdrawn)
+ const rotated = generateKeyPairSync('ed25519')
+ const rotatedPrivate = rotated.privateKey
+ .export({ format: 'pem', type: 'pkcs8' })
+ .toString()
+ const rotatedPublic = rotated.publicKey
+ .export({ format: 'pem', type: 'spki' })
+ .toString()
+ expect(() =>
+ signPluginSecurityPolicy(withdrawn, rotatedPrivate, envelope)
+ ).toThrow('signature')
+ const rotatedEnvelope = signPluginSecurityPolicy(
+ withdrawn,
+ rotatedPrivate,
+ envelope,
+ publicPem
+ )
+ expect(
+ verifySecurityPolicy(rotatedEnvelope, [publicPem, rotatedPublic])
+ ).toEqual(withdrawn)
+ })
+})