A full-featured download manager.
feat(server): make Docker deployments persistent and operable (#1840)
Dr_rOot1a708ee57746
diff --git a/Dockerfile b/Dockerfileindex 5adb1c3d..dc03e195 100644--- a/Dockerfile+++ b/Dockerfile@@ -54,8 +54,8 @@ RUN apk add --no-cache aria2 ca-certificates \/opt/yarn-v1.22.22 \&& rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \/usr/local/bin/pnpm /usr/local/bin/yarn /usr/local/bin/yarnpkg \- && mkdir -p /data \- && chown node:node /data+ && mkdir -p /data/home /data/tmp /downloads \+ && chown -R node:node /data /downloadsWORKDIR /appCOPY --from=build --chown=node:node /app/package.json ./package.jsonCOPY --from=build --chown=node:node /app/dist/server ./dist/server@@ -73,14 +73,22 @@ COPY --from=build --chown=node:node /app/build/legal/sbom.spdx.json ./legal/sbomENV YARN_VERSION= \NODE_ENV=production \MOTRIX_DATA_DIR=/data \+ MOTRIX_TEMP_DIR=/data/tmp \+ MOTRIX_PLUGIN_DIR=/data/plugins \MOTRIX_EXTRA_DIR=/app/extra \MOTRIX_ARIA2_BIN=/usr/bin/aria2c \+ MOTRIX_DEFAULT_SAVE_DIR=/downloads \+ MOTRIX_ALLOWED_SAVE_DIRS=/downloads \MOTRIX_RENDERER_DIR=/app/dist/renderer-web \MOTRIX_BUILTIN_PLUGIN_DIR=/app/builtin-plugins \+ HOME=/data/home \+ TMPDIR=/data/tmp \PORT=8080-VOLUME /data+VOLUME ["/data", "/downloads"]EXPOSE 8080USER node+STOPSIGNAL SIGTERM+HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'8080')+'/healthz').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]CMD ["node", "dist/server/index.mjs"]FROM node:24-alpine AS runtime@@ -90,19 +98,27 @@ RUN apk add --no-cache aria2 ca-certificates \/opt/yarn-v1.22.22 \&& rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \/usr/local/bin/pnpm /usr/local/bin/yarn /usr/local/bin/yarnpkg \- && mkdir -p /data \- && chown node:node /data+ && mkdir -p /data/home /data/tmp /downloads \+ && chown -R node:node /data /downloadsWORKDIR /appCOPY --from=build --chown=node:node /app/dist/server-app/ ./ENV YARN_VERSION= \NODE_ENV=production \MOTRIX_DATA_DIR=/data \+ MOTRIX_TEMP_DIR=/data/tmp \+ MOTRIX_PLUGIN_DIR=/data/plugins \MOTRIX_EXTRA_DIR=/app/extra \MOTRIX_ARIA2_BIN=/usr/bin/aria2c \+ MOTRIX_DEFAULT_SAVE_DIR=/downloads \+ MOTRIX_ALLOWED_SAVE_DIRS=/downloads \MOTRIX_RENDERER_DIR=/app/dist/renderer-web \MOTRIX_BUILTIN_PLUGIN_DIR=/app/builtin-plugins \+ HOME=/data/home \+ TMPDIR=/data/tmp \PORT=8080-VOLUME /data+VOLUME ["/data", "/downloads"]EXPOSE 8080USER node+STOPSIGNAL SIGTERM+HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'8080')+'/healthz').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]CMD ["node", "dist/server/index.mjs"]diff --git a/README.md b/README.mdindex 44f9a949..b5befac4 100644--- a/README.md+++ b/README.md@@ -94,13 +94,20 @@ You can also install it from Settings → Integration → Command-line tools in### Headless server with Docker-The repository includes a `Dockerfile` that builds an image with the web UI and aria2 included:+The repository includes a production `Dockerfile` and `compose.yaml` with+separate persistent mounts for Server state and downloaded resources:```bash-docker build -t motrix-turbo:dev .+mkdir -p motrix-data downloads+docker compose up --build -d```-Remote clients such as the CLI and browser extensions pair with the server through a device-code flow. See the `Dockerfile` and related documentation for details.+The runtime is non-root, supports a read-only root filesystem, validates mount+permissions before accepting work, and preserves downloads, sessions, and+installed plugins across container replacement. Remote clients such as the CLI+and browser extensions pair through a device-code flow. See the+[Docker Server deployment guide](./docs/docker-server.md) for ownership setup,+ports, environment variables, diagnostics, and backup/upgrade instructions.## 🛠 Developmentdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 8c51a3aa..70ea30db 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -94,13 +94,18 @@ npm install -g @motrix/cli### Headless server(Docker)-仓库根目录提供了 `Dockerfile`。构建得到的镜像已包含 Web 界面和 aria2:+仓库提供生产用途的 `Dockerfile` 和 `compose.yaml`,分别挂载 Server 状态与用户+下载资源:```bash-docker build -t motrix-turbo:dev .+mkdir -p motrix-data downloads+docker compose up --build -d```-CLI、浏览器扩展等远程客户端可通过 device-code 与服务器配对。详细说明请参阅 `Dockerfile` 和相关文档。+runtime 以非 root 用户运行,支持只读根文件系统,在接受任务前检查挂载权限,+并在替换容器后保留下载、session 和已安装插件。CLI、浏览器扩展等远程客户端+可通过 device-code 与服务器配对。目录所有权、端口、环境变量、诊断与备份/+升级说明见 [Docker Server 部署指南](./docs/docker-server.zh-CN.md)。## 🛠 开发与构建diff --git a/compose.yaml b/compose.yamlnew file mode 100644index 00000000..ddf99902--- /dev/null+++ b/compose.yaml@@ -0,0 +1,30 @@+name: motrix++services:+ server:+ build:+ context: .+ target: runtime+ image: motrix-turbo:local+ init: true+ read_only: true+ user: "${MOTRIX_UID:-1000}:${MOTRIX_GID:-1000}"+ security_opt:+ - no-new-privileges:true+ restart: unless-stopped+ stop_grace_period: 2m+ environment:+ MOTRIX_DATA_DIR: /data+ MOTRIX_TEMP_DIR: /data/tmp+ MOTRIX_PLUGIN_DIR: /data/plugins+ MOTRIX_DEFAULT_SAVE_DIR: /downloads+ MOTRIX_ALLOWED_SAVE_DIRS: /downloads+ MOTRIX_MDXP_HOST: 0.0.0.0+ MOTRIX_MDXP_PORT: 16801+ MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-http://localhost:8080}"+ ports:+ - "${MOTRIX_BIND_IP:-0.0.0.0}:${MOTRIX_HTTP_PORT:-8080}:8080"+ - "${MOTRIX_BIND_IP:-0.0.0.0}:${MOTRIX_MDXP_PUBLIC_PORT:-16801}:16801"+ volumes:+ - ./motrix-data:/data+ - ./downloads:/downloadsdiff --git a/docs/docker-server.md b/docs/docker-server.mdnew file mode 100644index 00000000..90580b7a--- /dev/null+++ b/docs/docker-server.md@@ -0,0 +1,204 @@+# Docker Server deployment++The Motrix Server image contains the Web UI and aria2 and runs as a non-root+user. Its root filesystem can remain read-only. A useful deployment must mount+two independent writable locations:++| Container path | Purpose | Back up? |+| --- | --- | --- |+| `/data` | SQLite database, settings, aria2 session and DHT state, torrent metadata, operator token, plugin packages/state/logs, and the plugin secret lockbox | Yes |+| `/downloads` | Completed and in-progress HTTP, BT, and magnet resources | According to your data policy |++Do not combine these paths with the container layer. Recreating an unmounted+container discards its database, plugin state, and downloaded files.++## Start with Docker Compose++The included [`compose.yaml`](../compose.yaml) builds the production runtime,+runs it without root privileges, enables a read-only root filesystem, and+publishes the Web and MDXP ports.++Create the bind-mount directories before starting. On Linux, either make them+writable by UID/GID 1000 (the image default), or run with your own non-root+UID/GID:++```bash+mkdir -p motrix-data downloads++# Option A: keep the image default user.+sudo chown 1000:1000 motrix-data downloads++# Option B: use the current non-root Linux user instead.+export MOTRIX_UID="$(id -u)"+export MOTRIX_GID="$(id -g)"+```++Docker Desktop normally handles bind-mount ownership without the Linux+`chown` step. Never set the runtime UID to `0` merely to bypass a mount+permission problem.++For access from another device, set the public Web URL before starting:++```bash+export MOTRIX_PUBLIC_URL="http://motrix.example.lan:8080"+docker compose up --build -d+docker compose ps+```++Open `MOTRIX_PUBLIC_URL` in a browser. On the first start, Motrix creates a+random operator token at `motrix-data/operator-token` with mode `0600`. Use it+on the unlock screen:++```bash+cat motrix-data/operator-token+```++You may instead set `MOTRIX_OPERATOR_TOKEN`, but environment variables are+visible in container metadata. The generated file is the safer default for a+single-host deployment.++The compose defaults publish these ports on all interfaces:++| Port | Service |+| --- | --- |+| `8080` | Web UI, operator RPC/API, and health endpoint |+| `16801` | MDXP endpoint for paired CLI and extension clients |++Set `MOTRIX_BIND_IP=127.0.0.1` when a local reverse proxy is the only intended+entry point. Terminate TLS at that proxy when crossing an untrusted network.+The operator control plane is deny-by-default, but TLS is still required to+protect credentials in transit.++## Storage and download-path contract++The image defaults to:++```text+MOTRIX_DATA_DIR=/data+MOTRIX_TEMP_DIR=/data/tmp+MOTRIX_PLUGIN_DIR=/data/plugins+MOTRIX_DEFAULT_SAVE_DIR=/downloads+MOTRIX_ALLOWED_SAVE_DIRS=/downloads+HOME=/data/home+TMPDIR=/data/tmp+```++The Server creates and write-tests its data, temporary, torrent metadata,+home, plugin, and allowed download directories before it begins accepting+requests. Startup fails with the affected absolute path when a mount is+missing, read-only, or owned by the wrong UID. Every task save directory is+validated again when the task is created.++`MOTRIX_ALLOWED_SAVE_DIRS` is a colon-separated list in the Linux image. Every+entry must be an absolute, mounted, writable directory, and+`MOTRIX_DEFAULT_SAVE_DIR` must be inside one of them. Requests outside the+configured roots are rejected. Canonical path checks also reject symlink+escapes.++To add another download root, mount it and update both variables:++```yaml+services:+ server:+ environment:+ MOTRIX_DEFAULT_SAVE_DIR: /downloads+ MOTRIX_ALLOWED_SAVE_DIRS: /downloads:/archive+ volumes:+ - ./motrix-data:/data+ - ./downloads:/downloads+ - /srv/archive:/archive+```++The Web path picker only offers allowed roots, and the Server enforces the same+policy independently of the UI.++## Plugins++Built-in plugins are read-only under `/app/builtin-plugins`. User-installed+plugins, install provenance, grants, logs, configuration, encrypted secrets,+and enablement state persist through `/data`. The install pipeline uses+transient directories below `/data/plugins`; stale upload, download, and+staging data is cleared on startup without deleting installed plugins.++The Web UI uploads a local `.moext` package to the Server before showing the+consent screen, so it does not depend on Electron's `File.path`. Installed+plugins remain available after a container replacement as long as `/data` is+preserved. Uninstall removes the package, enablement state, configuration, and+encrypted secret values.++For operator-managed sources, these options are also available:++- `MOTRIX_PLUGIN_IMPORT_DIRS`: colon-separated, read-only container roots from+ which an absolute package path may be installed. Mount every root explicitly.+- `MOTRIX_PLUGIN_INSTALL_URLS`: comma-separated or JSON-array startup sources.+ Each entry may be an HTTPS URL, `github:owner/repository`, or+ `registry:plugin.id`. Setting it is explicit operator consent; any failed+ source stops startup with its reason.+- `MOTRIX_ALLOW_UNMANAGED_PLUGINS=true`: permits manually copied plugin+ directories that have no install record. It is `false` by default and is not+ needed for normal Web, registry, URL, or bootstrap installation.++Plugin secrets use `/data/secrets.lockbox`, which Motrix creates and persists.+For orchestrated deployments, `MOTRIX_SECRETS_SEED` can supply exactly 64 hex+characters instead; keep that value in the orchestrator's secret store.++## Health and diagnostics++`GET /healthz` is public and returns success only after the Server is accepting+requests and aria2 is ready. Docker uses it for the container health check.++The detailed diagnostic endpoint is operator-protected:++```bash+TOKEN="$(cat motrix-data/operator-token)"+curl --fail http://127.0.0.1:8080/healthz+curl --fail \+ --header "Authorization: Bearer ${TOKEN}" \+ http://127.0.0.1:8080/api/diagnostics+```++It reports engine status, effective storage paths, allowed download roots,+runtime UID, plugin install/secret-store availability, and FFmpeg discovery.+The official image does not install FFmpeg. If a plugin requires it, derive a+small custom image that installs Alpine's `ffmpeg` package and set+`MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`; diagnostics will confirm the selected+binary. Media temporary files use `/data/tmp`, not the read-only image layer.++Useful operational commands:++```bash+docker compose logs --follow server+docker compose stop # sends SIGTERM and waits for clean shutdown+docker compose up --build -d # rebuild/upgrade while retaining both mounts+```++Stop the service before taking a filesystem-level backup of `/data`, so the+SQLite database and aria2 session are consistent. Preserve the operator token+and secret lockbox together with the database.++## Environment reference++| Variable | Image default | Notes |+| --- | --- | --- |+| `PORT` | `8080` | Web/API listen port inside the container |+| `MOTRIX_DATA_DIR` | `/data` | Must be absolute and writable |+| `MOTRIX_TEMP_DIR` | `/data/tmp` | Must be absolute and writable |+| `MOTRIX_DEFAULT_SAVE_DIR` | `/downloads` | Default resource destination |+| `MOTRIX_ALLOWED_SAVE_DIRS` | `/downloads` | Colon-separated server-enforced roots |+| `MOTRIX_PLUGIN_DIR` | `/data/plugins` | Writable persistent user-plugin root |+| `MOTRIX_BUILTIN_PLUGIN_DIR` | `/app/builtin-plugins` | Read-only built-in plugin root |+| `MOTRIX_PLUGIN_IMPORT_DIRS` | empty | Colon-separated mounted package roots |+| `MOTRIX_PLUGIN_INSTALL_URLS` | empty | Declarative startup plugin sources |+| `MOTRIX_ALLOW_UNMANAGED_PLUGINS` | `false` | Allow plugin directories without install provenance |+| `MOTRIX_OPERATOR_TOKEN` | generated file | Operator control-plane credential |+| `MOTRIX_SECRETS_SEED` | generated lockbox | 64-hex-character plugin secret key |+| `MOTRIX_MDXP_HOST` | `127.0.0.1` (Compose: `0.0.0.0`) | MDXP bind address |+| `MOTRIX_MDXP_PORT` | `16801` | MDXP listen port; `0` disables a stable published port |+| `MOTRIX_PUBLIC_URL` | unset | Browser URL shown during device-code pairing |+| `MOTRIX_FFMPEG_PATH` | auto-detect | Optional absolute FFmpeg path |+| `MOTRIX_HOST_LANGUAGE` | system setting | Server/plugin locale override |+| `LOG_LEVEL` | `info` | Pino log level written to container stdout |++`MOTRIX_ARIA2_BIN`, `MOTRIX_EXTRA_DIR`, and `MOTRIX_RENDERER_DIR` are fixed by+the official image. Override them only in a custom image that provides the+corresponding artifacts.diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.mdnew file mode 100644index 00000000..26acba2c--- /dev/null+++ b/docs/docker-server.zh-CN.md@@ -0,0 +1,188 @@+# Docker Server 部署++Motrix Server 镜像包含 Web 界面和 aria2,并以非 root 用户运行。容器根文件+系统可保持只读。可用的部署必须挂载两个相互独立的可写位置:++| 容器路径 | 用途 | 是否备份 |+| --- | --- | --- |+| `/data` | SQLite 数据库、设置、aria2 session 与 DHT 状态、种子元数据、operator token、插件包/状态/日志和插件 secret lockbox | 必须 |+| `/downloads` | HTTP、BT 和 magnet 任务正在下载及最终完成的用户资源 | 按数据策略决定 |++不要让这些数据只写入容器层。重新创建未挂载持久卷的容器会丢失数据库、+插件状态和下载文件。++## 使用 Docker Compose 启动++仓库提供的 [`compose.yaml`](../compose.yaml) 会构建生产 runtime,以非 root+用户运行,启用只读根文件系统,并发布 Web 与 MDXP 端口。++启动前先创建 bind mount 目录。在 Linux 上,可以把它们交给镜像默认的+UID/GID 1000,也可以让容器使用当前的非 root UID/GID:++```bash+mkdir -p motrix-data downloads++# 方案 A:保留镜像默认用户。+sudo chown 1000:1000 motrix-data downloads++# 方案 B:使用当前 Linux 非 root 用户。+export MOTRIX_UID="$(id -u)"+export MOTRIX_GID="$(id -g)"+```++Docker Desktop 通常会自动处理 bind mount 所有权,无需执行 Linux 的+`chown` 步骤。不要为了绕过权限问题把 runtime UID 设为 `0`。++如果要从其他设备访问,请在启动前配置 Web 公网/局域网地址:++```bash+export MOTRIX_PUBLIC_URL="http://motrix.example.lan:8080"+docker compose up --build -d+docker compose ps+```++在浏览器中打开 `MOTRIX_PUBLIC_URL`。首次启动时,Motrix 会生成随机的+operator token,以 `0600` 权限保存在 `motrix-data/operator-token`。在解锁+界面输入它:++```bash+cat motrix-data/operator-token+```++也可以设置 `MOTRIX_OPERATOR_TOKEN`,但环境变量可从容器元数据中看到。+对单机部署而言,自动生成并持久化的 token 文件是更安全的默认方案。++Compose 默认在所有网卡发布以下端口:++| 端口 | 服务 |+| --- | --- |+| `8080` | Web 界面、operator RPC/API 与健康检查 |+| `16801` | 已配对 CLI 和浏览器扩展使用的 MDXP endpoint |++如果只允许本机反向代理访问,设置 `MOTRIX_BIND_IP=127.0.0.1`。跨越不可信+网络时应在反向代理终止 TLS。operator 控制面虽然默认拒绝未认证请求,但仍+需用 TLS 保护传输中的凭据。++## 存储与下载路径契约++镜像默认值如下:++```text+MOTRIX_DATA_DIR=/data+MOTRIX_TEMP_DIR=/data/tmp+MOTRIX_PLUGIN_DIR=/data/plugins+MOTRIX_DEFAULT_SAVE_DIR=/downloads+MOTRIX_ALLOWED_SAVE_DIRS=/downloads+HOME=/data/home+TMPDIR=/data/tmp+```++Server 会在接受请求前创建并实际写入测试 data、临时文件、种子元数据、+home、插件和允许下载目录。挂载缺失、只读或 UID 所有权错误时,启动会失败+并指出具体绝对路径。创建每个任务时还会再次检查该任务的保存目录。++Linux 镜像中的 `MOTRIX_ALLOWED_SAVE_DIRS` 使用冒号分隔。每一项都必须是+已挂载、可写的绝对路径,且 `MOTRIX_DEFAULT_SAVE_DIR` 必须位于其中。Server+会拒绝允许根目录之外的请求,也会通过 canonical path 检查拒绝符号链接+越界。++增加另一个下载根目录时,必须同时挂载并更新变量:++```yaml+services:+ server:+ environment:+ MOTRIX_DEFAULT_SAVE_DIR: /downloads+ MOTRIX_ALLOWED_SAVE_DIRS: /downloads:/archive+ volumes:+ - ./motrix-data:/data+ - ./downloads:/downloads+ - /srv/archive:/archive+```++Web 路径选择器只提供允许根目录;Server 仍会独立执行同一套约束,不依赖+UI 保证安全。++## 插件++内置插件以只读方式存放在 `/app/builtin-plugins`。用户安装的插件、来源记录、+授权、日志、配置、加密 secret 和启用状态都通过 `/data` 持久化。安装流程在+`/data/plugins` 下使用临时目录;启动时会清除遗留的上传、下载和 staging+数据,但不会删除已安装插件。++Web 界面会先把本地 `.moext` 包上传到 Server,再显示授权界面,因此不依赖+Electron 的 `File.path`。只要保留 `/data`,替换容器后插件仍会恢复。卸载+插件会同时清除包、启用状态、配置和加密 secret 值。++还可以使用以下 operator 管理方式:++- `MOTRIX_PLUGIN_IMPORT_DIRS`:以冒号分隔的容器内只读根目录,可从中按绝对+ 路径安装包;必须显式挂载每个根目录。+- `MOTRIX_PLUGIN_INSTALL_URLS`:以逗号分隔或 JSON 数组形式提供启动安装源。+ 每项可为 HTTPS URL、`github:owner/repository` 或 `registry:plugin.id`。设置+ 此变量代表 operator 明确同意安装;任何来源失败都会携带原因终止启动。+- `MOTRIX_ALLOW_UNMANAGED_PLUGINS=true`:允许没有安装记录、由管理员手动复制+ 的插件目录。默认值为 `false`;通过 Web、registry、URL 或启动安装时不需要+ 开启。++插件 secret 默认使用 `/data/secrets.lockbox`,Motrix 会自动创建并持久化它。+编排环境也可以通过 `MOTRIX_SECRETS_SEED` 提供恰好 64 个十六进制字符;应把+该值保存在编排平台的 secret store 中。++## 健康检查与诊断++公开的 `GET /healthz` 只有在 Server 正在接受请求且 aria2 已就绪时才返回成功。+Docker 也使用此接口判断容器健康状态。++详细诊断接口受 operator 认证保护:++```bash+TOKEN="$(cat motrix-data/operator-token)"+curl --fail http://127.0.0.1:8080/healthz+curl --fail \+ --header "Authorization: Bearer ${TOKEN}" \+ http://127.0.0.1:8080/api/diagnostics+```++诊断信息包含引擎状态、生效的存储路径、允许下载根目录、runtime UID、插件+安装/secret store 可用性以及 FFmpeg 探测结果。官方镜像不安装 FFmpeg。若+插件需要它,可基于官方镜像安装 Alpine `ffmpeg` 包,并设置+`MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`;诊断接口会确认最终使用的二进制。媒体+临时文件使用 `/data/tmp`,不会写入只读镜像层。++常用运维命令:++```bash+docker compose logs --follow server+docker compose stop # 发送 SIGTERM 并等待干净退出+docker compose up --build -d # 重建/升级,同时保留两个挂载+```++对 `/data` 做文件系统级备份前应先停止服务,确保 SQLite 数据库和 aria2+session 一致。operator token、secret lockbox 与数据库应一并保留。++## 环境变量参考++| 变量 | 镜像默认值 | 说明 |+| --- | --- | --- |+| `PORT` | `8080` | 容器内 Web/API 监听端口 |+| `MOTRIX_DATA_DIR` | `/data` | 必须为可写绝对路径 |+| `MOTRIX_TEMP_DIR` | `/data/tmp` | 必须为可写绝对路径 |+| `MOTRIX_DEFAULT_SAVE_DIR` | `/downloads` | 默认用户资源目录 |+| `MOTRIX_ALLOWED_SAVE_DIRS` | `/downloads` | 以冒号分隔、由服务端强制执行的根目录 |+| `MOTRIX_PLUGIN_DIR` | `/data/plugins` | 可写且持久化的用户插件根目录 |+| `MOTRIX_BUILTIN_PLUGIN_DIR` | `/app/builtin-plugins` | 只读内置插件根目录 |+| `MOTRIX_PLUGIN_IMPORT_DIRS` | 空 | 以冒号分隔的已挂载插件包根目录 |+| `MOTRIX_PLUGIN_INSTALL_URLS` | 空 | 声明式启动插件来源 |+| `MOTRIX_ALLOW_UNMANAGED_PLUGINS` | `false` | 允许没有安装来源记录的插件目录 |+| `MOTRIX_OPERATOR_TOKEN` | 自动生成文件 | operator 控制面凭据 |+| `MOTRIX_SECRETS_SEED` | 自动生成 lockbox | 64 位十六进制插件 secret 密钥 |+| `MOTRIX_MDXP_HOST` | `127.0.0.1`(Compose 为 `0.0.0.0`) | MDXP 监听地址 |+| `MOTRIX_MDXP_PORT` | `16801` | MDXP 监听端口;`0` 表示不使用固定发布端口 |+| `MOTRIX_PUBLIC_URL` | 未设置 | device-code 配对时显示的浏览器地址 |+| `MOTRIX_FFMPEG_PATH` | 自动探测 | 可选的 FFmpeg 绝对路径 |+| `MOTRIX_HOST_LANGUAGE` | 系统设置 | Server/插件语言覆盖值 |+| `LOG_LEVEL` | `info` | 输出到容器 stdout 的 Pino 日志级别 |++`MOTRIX_ARIA2_BIN`、`MOTRIX_EXTRA_DIR` 和 `MOTRIX_RENDERER_DIR` 由官方镜像+固定。只有自定义镜像同时提供了对应 artifact 时才应覆盖它们。diff --git a/scripts/smoke-server-identity.mjs b/scripts/smoke-server-identity.mjsnew file mode 100644index 00000000..e14e64b3--- /dev/null+++ b/scripts/smoke-server-identity.mjs@@ -0,0 +1,13 @@+const DEFAULT_SMOKE_UID = 1000+const DEFAULT_SMOKE_GID = 1000++export function resolveSmokeContainerIdentity(+ hostUid = typeof process.getuid === 'function' ? process.getuid() : undefined,+ hostGid = typeof process.getgid === 'function' ? process.getgid() : undefined+) {+ const uid =+ Number.isSafeInteger(hostUid) && hostUid > 0 ? hostUid : DEFAULT_SMOKE_UID+ const gid =+ Number.isSafeInteger(hostGid) && hostGid > 0 ? hostGid : DEFAULT_SMOKE_GID+ return { uid, gid, user: `${uid}:${gid}` }+}diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjsindex 2ba5f2d4..f554b82d 100644--- a/scripts/smoke-server-image.mjs+++ b/scripts/smoke-server-image.mjs@@ -1,10 +1,45 @@import { execFile } from 'node:child_process'-import { pathToFileURL } from 'node:url'+import { createHash } from 'node:crypto'+import {+ chmod,+ cp,+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises'+import { createServer } from 'node:http'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'import { promisify } from 'node:util'+import { resolveSmokeContainerIdentity } from './smoke-server-identity.mjs'const execFileAsync = promisify(execFile)-const DEFAULT_TIMEOUT_MS = 45_000+const DEFAULT_TIMEOUT_MS = 120_000const MAX_LOG_BYTES = 256 * 1024+const PROJECT_ROOT = fileURLToPath(new URL('..', import.meta.url))+const HTTP_FIXTURE_NAME = 'motrix-http-smoke.bin'+const PLUGIN_ID = 'test.demo-config'+const PLUGIN_FIXTURE = path.join(+ PROJECT_ROOT,+ 'tests/fixtures/moext/test.demo-config-1.0.0.moext'+)+const TORRENT_FIXTURE = path.join(+ PROJECT_ROOT,+ 'scripts/poc/fixtures/sample.torrent'+)+const TORRENT_DATA_ROOT = path.join(+ PROJECT_ROOT,+ 'scripts/poc/fixtures/sample-data'+)+const TORRENT_DATA_FILE = path.join(TORRENT_DATA_ROOT, 'test.bin')+const HTTP_FIXTURE = Buffer.from(+ 'Motrix Docker Server persistent HTTP fixture\n'.repeat(16_384)+)async function docker(args, options = {}) {const result = await execFileAsync('docker', args, {@@ -15,10 +50,31 @@ async function docker(args, options = {}) {return result.stdout.trim()}+async function dockerLogs(args) {+ const result = await execFileAsync('docker', args, {+ encoding: 'utf8',+ maxBuffer: MAX_LOG_BYTES,+ })+ return `${result.stdout}${result.stderr}`.trim()+}+function delay(milliseconds) {return new Promise((resolve) => setTimeout(resolve, milliseconds))}+function sha256(bytes) {+ return createHash('sha256').update(bytes).digest('hex')+}++async function pathExists(target) {+ try {+ await stat(target)+ return true+ } catch {+ return false+ }+}+async function containerPort(name, timeoutMs) {const deadline = Date.now() + timeoutMswhile (Date.now() < deadline) {@@ -57,40 +113,221 @@ async function waitForHealth(name, url, timeoutMs) {} catch {// Container startup is still in progress.}- await delay(100)+ await delay(150)}throw new Error(`Server image did not become healthy within ${timeoutMs}ms`)}-async function assertOperatorAuth(url, token) {- const unauthenticated = await fetch(`${url}/rpc/query/image-smoke`, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ args: [] }),- })- if (unauthenticated.status !== 401) {+async function waitForDockerHealth(name, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ const value = await docker([+ 'inspect',+ '--format',+ '{{if .State.Health}}{{.State.Health.Status}}{{end}}',+ name,+ ])+ if (value === 'healthy') return+ if (value === 'unhealthy') {+ throw new Error('Docker HEALTHCHECK marked the Server unhealthy')+ }+ await delay(250)+ }+ throw new Error('Docker HEALTHCHECK did not become healthy in time')+}++async function waitForExit(name, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ const state = await containerExited(name)+ if (state) return state+ await delay(100)+ }+ throw new Error(`Container ${name} did not exit within ${timeoutMs}ms`)+}++async function requestJson(url, options = {}, expectedStatus) {+ const response = await fetch(url, options)+ const text = await response.text()+ let body+ try {+ body = text ? JSON.parse(text) : null+ } catch {+ body = text+ }+ const accepted = expectedStatus+ ? response.status === expectedStatus+ : response.ok+ if (!accepted) {throw new Error(- `unauthenticated image request returned ${unauthenticated.status}`+ `${options.method ?? 'GET'} ${url} returned ${response.status}: ${text}`)}- const status = await fetch(`${url}/rpc/auth/status`, {- headers: { authorization: `Bearer ${token}` },- })- if (!status.ok || (await status.json()).authed !== true) {- throw new Error('Docker image operator authentication failed')- }- const authenticated = await fetch(`${url}/rpc/query/image-smoke`, {+ return body+}++async function rpc(url, token, kind, channel, ...args) {+ return requestJson(`${url}/rpc/${kind}/${encodeURIComponent(channel)}`, {method: 'POST',headers: {authorization: `Bearer ${token}`,'content-type': 'application/json',},- body: JSON.stringify({ args: [] }),+ body: JSON.stringify({ args }),})- if (authenticated.status !== 404) {- throw new Error(- `authenticated image request returned ${authenticated.status}`- )+}++async function assertOperatorAuth(url, token) {+ await requestJson(+ `${url}/rpc/query/image-smoke`,+ {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ args: [] }),+ },+ 401+ )+ const status = await requestJson(`${url}/rpc/auth/status`, {+ headers: { authorization: `Bearer ${token}` },+ })+ if (status.authed !== true) {+ throw new Error('Docker image operator authentication failed')+ }+ await requestJson(+ `${url}/rpc/query/image-smoke`,+ {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify({ args: [] }),+ },+ 404+ )+}++function compactPeer(ip, port) {+ const octets = ip.split('.').map(Number)+ if (+ octets.length !== 4 ||+ octets.some((value) => !Number.isInteger(value) || value < 0 || value > 255)+ ) {+ throw new Error(`invalid Docker peer IPv4 address: ${ip}`)+ }+ const peer = Buffer.alloc(6)+ for (let index = 0; index < 4; index += 1) peer[index] = octets[index]+ peer.writeUInt16BE(port, 4)+ return peer+}++function trackerResponse(peer) {+ if (!peer) return Buffer.from('d8:intervali1e5:peers0:e')+ return Buffer.concat([+ Buffer.from('d8:intervali1e5:peers6:'),+ compactPeer(peer.ip, peer.port),+ Buffer.from('e'),+ ])+}++function rewriteTorrentAnnounce(torrent, trackerUrl) {+ const marker = Buffer.from('d8:announce')+ if (!torrent.subarray(0, marker.byteLength).equals(marker)) {+ throw new Error('BT fixture does not begin with a top-level announce key')+ }+ const colon = torrent.indexOf(0x3a, marker.byteLength)+ const previousLength = Number(+ torrent.subarray(marker.byteLength, colon).toString('ascii')+ )+ if (+ colon < 0 ||+ !Number.isSafeInteger(previousLength) ||+ previousLength < 1+ ) {+ throw new Error('BT fixture has an invalid announce value')+ }+ const nextValue = Buffer.from(trackerUrl)+ return Buffer.concat([+ marker,+ Buffer.from(`${nextValue.byteLength}:`),+ nextValue,+ torrent.subarray(colon + 1 + previousLength),+ ])+}++function parseRange(value, size) {+ const match = /^bytes=(\d+)-(\d*)$/.exec(value ?? '')+ if (!match) return null+ const start = Number(match[1])+ const end = match[2] ? Math.min(Number(match[2]), size - 1) : size - 1+ if (!Number.isSafeInteger(start) || start < 0 || start > end) return null+ return { start, end }+}++async function startFixtureServer() {+ let trackerPeer = null+ let trackerAnnounces = 0+ const trackerPeerIds = new Set()+ const server = createServer((request, response) => {+ const requestUrl = new URL(request.url ?? '/', 'http://fixture.invalid')+ if (requestUrl.pathname === '/announce') {+ trackerAnnounces += 1+ const peerId = /(?:^|[?&])peer_id=([^&]+)/.exec(request.url ?? '')?.[1]+ if (peerId) trackerPeerIds.add(peerId)+ const body = trackerResponse(trackerPeer)+ response.writeHead(200, {+ 'content-length': body.byteLength,+ 'content-type': 'text/plain',+ })+ response.end(body)+ return+ }+ if (requestUrl.pathname !== `/${HTTP_FIXTURE_NAME}`) {+ response.writeHead(404).end()+ return+ }++ const range = parseRange(request.headers.range, HTTP_FIXTURE.byteLength)+ const body = range+ ? HTTP_FIXTURE.subarray(range.start, range.end + 1)+ : HTTP_FIXTURE+ response.writeHead(range ? 206 : 200, {+ 'accept-ranges': 'bytes',+ 'content-disposition': `attachment; filename="${HTTP_FIXTURE_NAME}"`,+ 'content-length': body.byteLength,+ 'content-type': 'application/octet-stream',+ ...(range+ ? {+ 'content-range': `bytes ${range.start}-${range.end}/${HTTP_FIXTURE.byteLength}`,+ }+ : {}),+ })+ if (request.method === 'HEAD') response.end()+ else response.end(body)+ })+ await new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '0.0.0.0', resolve)+ })+ const address = server.address()+ if (!address || typeof address === 'string') {+ throw new Error('HTTP fixture server did not bind a TCP port')+ }+ return {+ port: address.port,+ setTrackerPeer(peer) {+ trackerPeer = peer+ },+ trackerAnnounces() {+ return trackerAnnounces+ },+ trackerPeerIds() {+ return trackerPeerIds+ },+ close: () =>+ new Promise((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve()))+ ),}}@@ -137,15 +374,243 @@ function parseArguments(argv) {return options}-export async function smokeServerImage(options) {- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS- if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000) {- throw new Error('Server image smoke timeout must be at least 1000ms')+async function prepareHostVolumes(root) {+ const dataDir = path.join(root, 'data')+ const downloadsDir = path.join(root, 'downloads')+ const deniedDataDir = path.join(root, 'denied-data')+ await Promise.all([mkdir(dataDir), mkdir(downloadsDir), mkdir(deniedDataDir)])+ await Promise.all([+ chmod(dataDir, 0o777),+ chmod(downloadsDir, 0o777),+ chmod(deniedDataDir, 0o777),+ ])+ return { dataDir, downloadsDir, deniedDataDir }+}++async function startServerContainer(options) {+ const {+ name,+ network,+ image,+ dataDir,+ downloadsDir,+ operatorToken,+ identity,+ } = options+ await docker([+ 'run',+ '--detach',+ '--name',+ name,+ '--network',+ network,+ '--add-host',+ 'host.docker.internal:host-gateway',+ '--read-only',+ '--security-opt',+ 'no-new-privileges:true',+ '--user',+ identity.user,+ '--env',+ `MOTRIX_OPERATOR_TOKEN=${operatorToken}`,+ '--env',+ 'MOTRIX_MDXP_PORT=0',+ '--mount',+ `type=bind,source=${dataDir},target=/data`,+ '--mount',+ `type=bind,source=${downloadsDir},target=/downloads`,+ '--publish',+ '127.0.0.1::8080',+ image,+ ])+ const port = await containerPort(name, options.timeoutMs)+ const url = `http://127.0.0.1:${port}`+ await waitForHealth(name, url, options.timeoutMs)+ return url+}++async function assertRuntimeContract(name, url, token, identity, timeoutMs) {+ await assertOperatorAuth(url, token)+ const diagnostics = await requestJson(`${url}/api/diagnostics`, {+ headers: { authorization: `Bearer ${token}` },+ })+ if (+ diagnostics.health?.ok !== true ||+ diagnostics.engine?.state !== 'ready' ||+ diagnostics.process?.uid !== identity.uid ||+ diagnostics.storage?.dataDir !== '/data' ||+ diagnostics.storage?.tempDir !== '/data/tmp' ||+ diagnostics.storage?.homeDir !== '/data/home' ||+ diagnostics.storage?.defaultSaveDir !== '/downloads' ||+ !diagnostics.storage?.allowedSaveDirs?.includes('/downloads') ||+ diagnostics.plugins?.directory !== '/data/plugins' ||+ diagnostics.plugins?.installAvailable !== true ||+ diagnostics.plugins?.secretStoreAvailable !== true ||+ diagnostics.media?.tempDir !== '/data/tmp' ||+ !Array.isArray(diagnostics.media?.ffmpeg?.candidates)+ ) {+ throw new Error(+ `unexpected Server diagnostics: ${JSON.stringify(diagnostics)}`+ )}- const image = options.image- const name = `motrix-server-smoke-${process.pid}-${Date.now()}`- const operatorToken = 'motrix-image-smoke-operator-token'- const startedAt = Date.now()+ await docker([+ 'exec',+ name,+ 'sh',+ '-ec',+ [+ `[ "$(id -u)" = "${identity.uid}" ]`,+ `[ "$(id -g)" = "${identity.gid}" ]`,+ 'test -w /data',+ 'test -w /downloads',+ 'test -w /data/tmp',+ 'test ! -w /app',+ 'test -s /data/motrix.db',+ 'pidof aria2c',+ "tr '\\0' '\\n' </proc/$(pidof aria2c)/cmdline | grep -Fx -- '--dht-file-path=/data/dht.dat'",+ "tr '\\0' '\\n' </proc/$(pidof aria2c)/cmdline | grep -Fx -- '--dht-file-path6=/data/dht6.dat'",+ ].join('; '),+ ])+ const hostConfig = JSON.parse(+ await docker(['inspect', '--format', '{{json .HostConfig}}', name])+ )+ if (hostConfig.ReadonlyRootfs !== true) {+ throw new Error('Server container did not use a read-only root filesystem')+ }+ await docker([+ 'exec',+ name,+ 'node',+ '--input-type=module',+ '--eval',+ RUNTIME_PROBE,+ ])+ await waitForDockerHealth(name, timeoutMs)+ return diagnostics+}++async function waitForTask(url, token, taskId, accepted, timeoutMs) {+ const deadline = Date.now() + timeoutMs+ while (Date.now() < deadline) {+ const tasks = await rpc(url, token, 'query', 'query:listTasks')+ const task = tasks.find((candidate) => candidate.id === taskId)+ if (task?.status === 'error') {+ throw new Error(+ `task ${taskId} failed: ${task.errorMessage ?? task.errorCode ?? 'unknown'}`+ )+ }+ if (task && accepted.has(task.status)) return task+ await delay(250)+ }+ throw new Error(`task ${taskId} did not reach ${[...accepted].join('/')}`)+}++async function assertHostFile(target, expected) {+ const actual = await readFile(target)+ if (!actual.equals(expected)) {+ throw new Error(`downloaded file content mismatch: ${target}`)+ }+}++async function assertDirectoryEmpty(target) {+ let entries+ try {+ entries = await readdir(target)+ } catch (error) {+ if (error?.code === 'ENOENT') return+ throw error+ }+ if (entries.length > 0) {+ throw new Error(`temporary plugin directory is not empty: ${target}`)+ }+}++async function installPlugin(url, token) {+ const initialPlugins = await rpc(url, token, 'query', 'query:listPlugins')+ if (!initialPlugins.some((plugin) => plugin.source?.type === 'builtin')) {+ throw new Error(+ 'Server image did not discover its read-only builtin plugins'+ )+ }+ const bytes = await readFile(PLUGIN_FIXTURE)+ const fileHash = sha256(bytes)+ const reference = await requestJson(+ `${url}/api/plugins/uploads`,+ {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/vnd.motrix.moext',+ 'x-motrix-file-name': encodeURIComponent(path.basename(PLUGIN_FIXTURE)),+ 'x-motrix-file-sha256': fileHash,+ },+ body: bytes,+ },+ 201+ )+ const staged = await rpc(url, token, 'command', 'command:installPlugin', {+ sourceType: 'upload',+ uploadId: reference.uploadId,+ fileHash,+ })+ if (staged.committed !== false || !staged.stagingId) {+ throw new Error(+ `plugin did not enter consent staging: ${JSON.stringify(staged)}`+ )+ }+ const committed = await rpc(+ url,+ token,+ 'command',+ 'command:confirmPluginInstall',+ { stagingId: staged.stagingId, grants: { notify: 'denied' } }+ )+ if (committed.pluginId !== PLUGIN_ID) {+ throw new Error(`unexpected committed plugin: ${JSON.stringify(committed)}`)+ }+ await rpc(url, token, 'command', 'command:disablePlugin', PLUGIN_ID)+ await rpc(url, token, 'command', 'command:enablePlugin', PLUGIN_ID)+ const secret = 'docker-smoke-secret-value'+ await rpc(url, token, 'command', 'command:updatePluginConfig', {+ pluginId: PLUGIN_ID,+ patch: { apiKey: secret, quality: '720p' },+ })+ const plugins = await rpc(url, token, 'query', 'query:listPlugins')+ const plugin = plugins.find((candidate) => candidate.id === PLUGIN_ID)+ if (!plugin?.enabled) {+ throw new Error(+ `installed plugin is not enabled: ${JSON.stringify(plugin)}`+ )+ }+ const config = await rpc(+ url,+ token,+ 'query',+ 'query:getPluginConfig',+ PLUGIN_ID+ )+ if (config.quality !== '720p' || !config.apiKey?.startsWith('box:')) {+ throw new Error(+ `plugin configuration was not encrypted: ${JSON.stringify(config)}`+ )+ }+ return { fileHash, secret }+}++async function stopServer(name, timeoutMs) {+ await docker(['stop', '--time', String(Math.ceil(timeoutMs / 1000)), name])+ const state = JSON.parse(+ await docker(['inspect', '--format', '{{json .State}}', name])+ )+ if (state.Running || state.ExitCode !== 0 || state.OOMKilled) {+ throw new Error(+ `Server image shutdown failed: running=${state.Running} code=${state.ExitCode} oom=${state.OOMKilled}`+ )+ }+}++async function assertPermissionFailure(options) {+ const name = `${options.name}-permission`let created = falsetry {await docker([@@ -153,44 +618,354 @@ export async function smokeServerImage(options) {'--detach','--name',name,+ '--read-only',+ '--user',+ options.identity.user,'--env',- `MOTRIX_OPERATOR_TOKEN=${operatorToken}`,+ 'MOTRIX_OPERATOR_TOKEN=permission-smoke-token','--env','MOTRIX_MDXP_PORT=0',- '--publish',- '127.0.0.1::8080',- image,+ '--mount',+ `type=bind,source=${options.dataDir},target=/data`,+ '--mount',+ `type=bind,source=${options.downloadsDir},target=/downloads,readonly`,+ options.image,])created = true- const port = await containerPort(name, timeoutMs)- const url = `http://127.0.0.1:${port}`- await waitForHealth(name, url, timeoutMs)- await assertOperatorAuth(url, operatorToken)+ const state = await waitForExit(name, Math.min(options.timeoutMs, 20_000))+ const logs = await dockerLogs(['logs', name])+ if (+ state.ExitCode === 0 ||+ !logs.includes('Save directory is not writable: /downloads')+ ) {+ throw new Error(+ `read-only downloads mount did not fail clearly: code=${state.ExitCode}\n${logs}`+ )+ }+ } finally {+ if (created) await docker(['rm', '--force', name]).catch(() => undefined)+ }+}++export async function smokeServerImage(options) {+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 30_000) {+ throw new Error('Server image smoke timeout must be at least 30000ms')+ }+ const image = options.image+ const identity = resolveSmokeContainerIdentity()+ const prefix = `motrix-server-smoke-${process.pid}-${Date.now()}`+ const appName = `${prefix}-app`+ const seedName = `${prefix}-seed`+ const network = `${prefix}-net`+ const operatorToken = 'motrix-image-smoke-operator-token'+ const startedAt = Date.now()+ const tempRoot = await mkdtemp(path.join(tmpdir(), 'motrix-image-smoke-'))+ const fixtureServer = await startFixtureServer()+ const volumes = await prepareHostVolumes(tempRoot)+ let appCreated = false+ let seedCreated = false+ let networkCreated = false+ try {+ const metadata = JSON.parse(await docker(['image', 'inspect', image]))[0]+ if (metadata.Config.User !== 'node') {+ throw new Error(+ `Server image default user is ${metadata.Config.User || 'root'}`+ )+ }+ if (!metadata.Config.Healthcheck) {+ throw new Error('Server image has no Docker HEALTHCHECK')+ }++ await docker(['network', 'create', network])+ networkCreated = true+ const trackerUrl = `http://host.docker.internal:${fixtureServer.port}/announce`+ const torrentBytes = rewriteTorrentAnnounce(+ await readFile(TORRENT_FIXTURE),+ trackerUrl+ )+ const seedRoot = path.join(tempRoot, 'seed')+ await mkdir(seedRoot)+ await cp(TORRENT_DATA_ROOT, path.join(seedRoot, 'sample-data'), {+ recursive: true,+ })+ const localTorrentPath = path.join(seedRoot, 'sample.torrent')+ await writeFile(localTorrentPath, torrentBytes)await docker([- 'exec',- name,- 'sh',- '-ec',- 'test -s /data/motrix.db; pidof aria2c',+ 'run',+ '--detach',+ '--name',+ seedName,+ '--network',+ network,+ '--add-host',+ 'host.docker.internal:host-gateway',+ '--mount',+ `type=bind,source=${seedRoot},target=/seed,readonly`,+ image,+ 'aria2c',+ '--no-conf=true',+ '--enable-dht=false',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ '--enable-peer-exchange=false',+ '--allow-overwrite=true',+ '--check-integrity=true',+ '--file-allocation=none',+ `--bt-tracker=${trackerUrl}`,+ '--listen-port=6881',+ '--seed-time=120',+ '--seed-ratio=0.0',+ '--dir=/seed',+ '/seed/sample.torrent',])- await docker([- 'exec',- name,- 'node',- '--input-type=module',- '--eval',- RUNTIME_PROBE,+ seedCreated = true+ const seedIp = await docker([+ 'inspect',+ '--format',+ `{{(index .NetworkSettings.Networks "${network}").IPAddress}}`,+ seedName,])- await docker(['stop', '--time', String(Math.ceil(timeoutMs / 1000)), name])- const state = JSON.parse(- await docker(['inspect', '--format', '{{json .State}}', name])+ fixtureServer.setTrackerPeer({ ip: seedIp, port: 6881 })++ let url = await startServerContainer({+ name: appName,+ network,+ image,+ ...volumes,+ operatorToken,+ identity,+ timeoutMs,+ })+ appCreated = true+ const diagnostics = await assertRuntimeContract(+ appName,+ url,+ operatorToken,+ identity,+ timeoutMs+ )++ const settings = await rpc(url, operatorToken, 'query', 'query:getSettings')+ const allowed = await rpc(+ url,+ operatorToken,+ 'query',+ 'query:listAllowedSaveDirs')- if (state.Running || state.ExitCode !== 0 || state.OOMKilled) {+ if (+ settings.app?.defaultSaveDir !== '/downloads' ||+ allowed.defaultPath !== '/downloads' ||+ allowed.paths?.[0]?.path !== '/downloads' ||+ allowed.allowCustom !== false+ ) {throw new Error(- `Server image shutdown failed: running=${state.Running} code=${state.ExitCode} oom=${state.OOMKilled}`+ `Docker default save contract is wrong: ${JSON.stringify(allowed)}`)}- const metadata = JSON.parse(await docker(['image', 'inspect', image]))[0]++ const httpTask = await rpc(+ url,+ operatorToken,+ 'command',+ 'command:createTask',+ {+ type: 'http',+ uris: [+ `http://host.docker.internal:${fixtureServer.port}/${HTTP_FIXTURE_NAME}`,+ ],+ saveDir: settings.app.defaultSaveDir,+ filename: HTTP_FIXTURE_NAME,+ headers: [],+ }+ )+ await waitForTask(+ url,+ operatorToken,+ httpTask.taskId,+ new Set(['completed']),+ timeoutMs+ )+ await assertHostFile(+ path.join(volumes.downloadsDir, HTTP_FIXTURE_NAME),+ HTTP_FIXTURE+ )++ const btTask = await rpc(+ url,+ operatorToken,+ 'command',+ 'command:createTask',+ {+ type: 'bt',+ payload: {+ kind: 'torrent-base64',+ base64: torrentBytes.toString('base64'),+ },+ selectedFiles: [0],+ saveDir: '/downloads',+ displayName: 'sample-data',+ }+ )+ await rpc(url, operatorToken, 'command', 'command:setTaskBtTracker', {+ engineGid: btTask.gid,+ trackers: [trackerUrl],+ })+ await waitForTask(+ url,+ operatorToken,+ btTask.taskId,+ new Set(['seeding', 'completed']),+ timeoutMs+ )+ await assertHostFile(+ path.join(volumes.downloadsDir, 'sample-data', 'sample-data', 'test.bin'),+ await readFile(TORRENT_DATA_FILE)+ )+ if (+ fixtureServer.trackerAnnounces() < 2 ||+ fixtureServer.trackerPeerIds().size < 2+ ) {+ throw new Error('Motrix BT task never announced to the fixture tracker')+ }++ const pluginInstall = await installPlugin(url, operatorToken)+ const installRecord = JSON.parse(+ await readFile(+ path.join(volumes.dataDir, 'plugins', PLUGIN_ID, '_install.json'),+ 'utf8'+ )+ )+ if (+ installRecord.pluginId !== PLUGIN_ID ||+ installRecord.source?.type !== 'local' ||+ installRecord.source?.url !== `local:${pluginInstall.fileHash}`+ ) {+ throw new Error(+ `plugin install provenance was not persisted: ${JSON.stringify(installRecord)}`+ )+ }+ await Promise.all(+ ['_uploads', '_downloads', '_staging'].map((directory) =>+ assertDirectoryEmpty(path.join(volumes.dataDir, 'plugins', directory))+ )+ )+ const settingsRaw = await readFile(+ path.join(volumes.dataDir, 'settings.json'),+ 'utf8'+ )+ if (+ settingsRaw.includes(pluginInstall.secret) ||+ !settingsRaw.includes('box:')+ ) {+ throw new Error('plugin secret was not encrypted at rest')+ }+ const lockbox = await readFile(+ path.join(volumes.dataDir, 'secrets.lockbox')+ )+ if (lockbox.byteLength !== 32) {+ throw new Error('plugin lockbox is invalid')+ }++ await stopServer(appName, timeoutMs)+ await docker(['rm', appName])+ appCreated = false+ for (const durable of [+ 'motrix.db',+ 'settings.json',+ 'secrets.lockbox',+ 'aria2.session',+ 'aria2.conf',+ ]) {+ if (!(await pathExists(path.join(volumes.dataDir, durable)))) {+ throw new Error(+ `missing durable Server state after shutdown: ${durable}`+ )+ }+ }++ url = await startServerContainer({+ name: appName,+ network,+ image,+ ...volumes,+ operatorToken,+ identity,+ timeoutMs,+ })+ appCreated = true+ const restoredTasks = await rpc(+ url,+ operatorToken,+ 'query',+ 'query:listTasks'+ )+ for (const taskId of [httpTask.taskId, btTask.taskId]) {+ if (!restoredTasks.some((task) => task.id === taskId)) {+ throw new Error(`task ${taskId} did not survive container restart`)+ }+ }+ const restoredPlugins = await rpc(+ url,+ operatorToken,+ 'query',+ 'query:listPlugins'+ )+ const restoredPlugin = restoredPlugins.find(+ (plugin) => plugin.id === PLUGIN_ID+ )+ if (!restoredPlugin?.enabled) {+ throw new Error(+ `plugin did not survive restart: ${JSON.stringify(restoredPlugin)}`+ )+ }+ const restoredConfig = await rpc(+ url,+ operatorToken,+ 'query',+ 'query:getPluginConfig',+ PLUGIN_ID+ )+ if (+ !restoredConfig.apiKey?.startsWith('box:') ||+ restoredConfig.quality !== '720p'+ ) {+ throw new Error('plugin configuration did not survive restart')+ }+ await rpc(url, operatorToken, 'command', 'command:uninstallPlugin', {+ pluginId: PLUGIN_ID,+ })+ const afterUninstall = await rpc(+ url,+ operatorToken,+ 'query',+ 'query:listPlugins'+ )+ if (afterUninstall.some((plugin) => plugin.id === PLUGIN_ID)) {+ throw new Error('plugin remained discoverable after uninstall')+ }+ if (await pathExists(path.join(volumes.dataDir, 'plugins', PLUGIN_ID))) {+ throw new Error('plugin directory remained after uninstall')+ }+ const afterUninstallSettings = JSON.parse(+ await readFile(path.join(volumes.dataDir, 'settings.json'), 'utf8')+ )+ if (Object.hasOwn(afterUninstallSettings.plugins ?? {}, PLUGIN_ID)) {+ throw new Error('plugin configuration remained after uninstall')+ }++ await stopServer(appName, timeoutMs)+ await docker(['rm', appName])+ appCreated = false+ await assertPermissionFailure({+ name: prefix,+ image,+ dataDir: volumes.deniedDataDir,+ downloadsDir: volumes.downloadsDir,+ identity,+ timeoutMs,+ })+return {imageId: metadata.Id,imageBytes: metadata.Size,@@ -198,26 +973,54 @@ export async function smokeServerImage(options) {node: metadata.Config.Env.find((entry) =>entry.startsWith('NODE_VERSION='))?.slice('NODE_VERSION='.length),+ nonRootUid: diagnostics.process.uid,+ nonRootGid: identity.gid,+ readOnlyRootfs: true,health: true,operatorAuth: true,+ diagnostics: true,sqlite: true,systemAria2: true,+ defaultSaveDir: '/downloads',+ httpDownload: sha256(HTTP_FIXTURE),+ btDownload: sha256(await readFile(TORRENT_DATA_FILE)),+ restartPersistence: true,+ pluginLifecycle: 'install-enable-restart-uninstall',+ pluginSecretLockbox: true,+ permissionFailure: true,shutdown: 'SIGTERM',durationMs: Date.now() - startedAt,}} catch (error) {- const logs = created- ? await docker(['logs', '--tail', '200', name]).catch(() => '')+ const appLogs = appCreated+ ? await dockerLogs(['logs', '--tail', '200', appName]).catch(() => '')+ : ''+ const seedLogs = seedCreated+ ? await dockerLogs(['logs', '--tail', '100', seedName]).catch(() => ''): ''const message = error instanceof Error ? error.message : String(error)+ const logs = [+ appLogs && `Server logs:\n${appLogs}`,+ seedLogs && `Seeder logs:\n${seedLogs}`,+ ]+ .filter(Boolean)+ .join('\n')throw new Error(- logs- ? `${message}\nContainer logs:\n${logs.slice(-MAX_LOG_BYTES)}`- : message,+ logs ? `${message}\n${logs.slice(-MAX_LOG_BYTES)}` : message,{ cause: error })} finally {- if (created) await docker(['rm', '--force', name]).catch(() => undefined)+ if (appCreated) {+ await docker(['rm', '--force', appName]).catch(() => undefined)+ }+ if (seedCreated) {+ await docker(['rm', '--force', seedName]).catch(() => undefined)+ }+ if (networkCreated) {+ await docker(['network', 'rm', network]).catch(() => undefined)+ }+ await fixtureServer.close().catch(() => undefined)+ await rm(tempRoot, { recursive: true, force: true })}}diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.tsindex 34f078d8..6faee4a0 100644--- a/src/core/engine/aria2/aria2-config-builder.test.ts+++ b/src/core/engine/aria2/aria2-config-builder.test.ts@@ -123,6 +123,19 @@ describe('Aria2ConfigBuilder', () => {)})+ it('keeps DHT state inside the writable user config directory', () => {+ const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ download: 0,+ upload: 0,+ })+ expect(args).toContain(+ '--dht-file-path=/home/user/.config/motrix/dht.dat'+ )+ expect(args).toContain(+ '--dht-file-path6=/home/user/.config/motrix/dht6.dat'+ )+ })+it('uses custom settings values', () => {const custom: EngineSettings = {...DEFAULT_ENGINE_SETTINGS,diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.tsindex 10af3a8a..7c5b3838 100644--- a/src/core/engine/aria2/aria2-config-builder.ts+++ b/src/core/engine/aria2/aria2-config-builder.ts@@ -7,6 +7,8 @@ export class Aria2ConfigBuilder {private readonly userConfPath: stringprivate readonly defaultDbPath: stringprivate readonly saveSessionPath: string+ private readonly dhtFilePath: string+ private readonly dht6FilePath: stringconstructor(private templatePath: string,@@ -15,6 +17,8 @@ export class Aria2ConfigBuilder {this.userConfPath = path.join(userConfigDir, 'aria2.conf')this.defaultDbPath = path.join(userConfigDir, 'aria2.db')this.saveSessionPath = path.join(userConfigDir, 'aria2.session')+ this.dhtFilePath = path.join(userConfigDir, 'dht.dat')+ this.dht6FilePath = path.join(userConfigDir, 'dht6.dat')}async ensureUserConfig(): Promise<string> {@@ -74,6 +78,8 @@ export class Aria2ConfigBuilder {`--dht-listen-port=${settings.dhtListenPort}`,`--enable-dht=${settings.dhtEnabled}`,`--enable-dht6=${settings.dhtEnabled}`,+ `--dht-file-path=${this.dhtFilePath}`,+ `--dht-file-path6=${this.dht6FilePath}`,`--save-session=${this.saveSessionPath}`)if (hasSqlitePersistence) {diff --git a/src/core/plugin/configuration-schema.test.ts b/src/core/plugin/configuration-schema.test.tsnew file mode 100644index 00000000..7358359f--- /dev/null+++ b/src/core/plugin/configuration-schema.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest'+import { pluginSecretFields } from './configuration-schema'++describe('pluginSecretFields', () => {+ it('returns only top-level fields marked secret', () => {+ const fields = pluginSecretFields({+ contributes: {+ configuration: {+ schema: {+ type: 'object',+ properties: {+ apiKey: { type: 'string', secret: true },+ quality: { type: 'string' },+ },+ },+ },+ },+ } as never)++ expect([...fields]).toEqual(['apiKey'])+ })++ it('is empty for a missing or malformed configuration schema', () => {+ expect(pluginSecretFields(undefined).size).toBe(0)+ expect(+ pluginSecretFields({+ contributes: { configuration: { schema: null } },+ } as never).size+ ).toBe(0)+ })+})diff --git a/src/core/plugin/configuration-schema.ts b/src/core/plugin/configuration-schema.tsnew file mode 100644index 00000000..cb5e995d--- /dev/null+++ b/src/core/plugin/configuration-schema.ts@@ -0,0 +1,26 @@+import type { PluginManifest } from '@shared/types/plugin'++export function pluginSecretFields(+ manifest: Pick<PluginManifest, 'contributes'> | undefined+): ReadonlySet<string> {+ const schema = manifest?.contributes.configuration?.schema+ const properties =+ schema &&+ typeof schema === 'object' &&+ 'properties' in schema &&+ schema.properties &&+ typeof schema.properties === 'object'+ ? (schema.properties as Record<string, unknown>)+ : {}+ const secretFields = new Set<string>()+ for (const [key, property] of Object.entries(properties)) {+ if (+ property &&+ typeof property === 'object' &&+ (property as { secret?: boolean }).secret === true+ ) {+ secretFields.add(key)+ }+ }+ return secretFields+}diff --git a/src/core/plugin/install/e2e-install.test.ts b/src/core/plugin/install/e2e-install.test.tsindex 34795ee8..89473521 100644--- a/src/core/plugin/install/e2e-install.test.ts+++ b/src/core/plugin/install/e2e-install.test.ts@@ -269,10 +269,11 @@ describe('PluginInstaller e2e', () => {manifestJSON())- const { stagingId, consent } = await installer.stage(moext, {+ const { stagingId, consent, committed } = await installer.stage(moext, {type: 'github',spec: 'example/test',})+ expect(committed).toBe(false)expect(consent.manifest.id).toBe('example.test')expect(consent.diff).toBeNull()@@ -303,7 +304,14 @@ describe('PluginInstaller e2e', () => {manifestJSON({ version: '1.0.1' }),Buffer.from('console.log(2);', 'utf8'))- await installer.stage(v2, { type: 'github', spec: 'example/test' })+ const staged = await installer.stage(v2, {+ type: 'github',+ spec: 'example/test',+ })+ expect(staged).toMatchObject({+ committed: true,+ pluginId: 'example.test',+ })const onDisk = await readFile(path.join(pluginsDir, 'example.test', 'dist/plugin.js'),@@ -432,6 +440,23 @@ describe('PluginInstaller e2e', () => {void readdir})+ it('rejects a local package when the claimed file hash differs', async () => {+ const moext = await writeMoext(+ path.join(inputDir, 'hash-mismatch.moext'),+ manifestJSON()+ )++ await expect(+ installer.stage(moext, {+ type: 'local',+ absPath: moext,+ fileHash: '0'.repeat(64),+ })+ ).rejects.toMatchObject({+ message: 'plugin.install.local_file_hash_mismatch',+ })+ })+it('id immutable: stage with a different prior pluginId rejected', async () => {const v1 = await writeMoext(path.join(inputDir, 'v1.moext'),diff --git a/src/core/plugin/install/github-fetcher.ts b/src/core/plugin/install/github-fetcher.tsindex 874c62b3..31cfb4d0 100644--- a/src/core/plugin/install/github-fetcher.ts+++ b/src/core/plugin/install/github-fetcher.ts@@ -4,8 +4,7 @@// We don't read the manifest here — that happens later in `extractMoext`.// We just provide a clean tarball-style "bring me the bytes" boundary.-import { createWriteStream } from 'node:fs'-import { mkdir } from 'node:fs/promises'+import { mkdir, rm, writeFile } from 'node:fs/promises'import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'import { Agent, interceptors, request } from 'undici'@@ -39,6 +38,7 @@ export interface DownloadResult {}const USER_AGENT = 'motrix-plugin-installer'+const MAX_MOEXT_BYTES = 5 * 1024 * 1024export async function downloadGithubMoext(spec: GhReleaseSpec,@@ -87,12 +87,24 @@ export async function downloadGithubMoext(`plugin.install.gh_asset_download_failed: ${dl.statusCode}`)}- await new Promise<void>((res, rej) => {- const ws = createWriteStream(destFile)- dl.body.on('error', rej)- ws.on('error', rej)- ws.on('finish', () => res())- dl.body.pipe(ws)- })+ const chunks: Buffer[] = []+ let total = 0+ try {+ for await (const chunk of dl.body) {+ const bytes = Buffer.from(chunk)+ total += bytes.byteLength+ if (total > MAX_MOEXT_BYTES) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.package_too_large'+ )+ }+ chunks.push(bytes)+ }+ await writeFile(destFile, Buffer.concat(chunks, total), { mode: 0o600 })+ } catch (cause) {+ await rm(destFile, { force: true }).catch(() => undefined)+ throw cause+ }return { tag: body.tag_name, assetName: asset.name }}diff --git a/src/core/plugin/install/plugin-installer.i18n.test.ts b/src/core/plugin/install/plugin-installer.i18n.test.tsindex 675c794e..6bbd6fc1 100644--- a/src/core/plugin/install/plugin-installer.i18n.test.ts+++ b/src/core/plugin/install/plugin-installer.i18n.test.ts@@ -1,5 +1,6 @@import { Buffer } from 'node:buffer'-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { createHash } from 'node:crypto'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'@@ -121,7 +122,9 @@ describe('PluginInstaller manifest i18n', () => {const staged = await installer.stage(moext, {type: 'local',absPath: moext,- fileHash: 'a'.repeat(64),+ fileHash: createHash('sha256')+ .update(await readFile(moext))+ .digest('hex'),})expect(staged.consent.manifest.name).toBe('Localized Plugin')diff --git a/src/core/plugin/install/plugin-installer.ts b/src/core/plugin/install/plugin-installer.tsindex 8012bb46..84cd6759 100644--- a/src/core/plugin/install/plugin-installer.ts+++ b/src/core/plugin/install/plugin-installer.ts@@ -14,6 +14,7 @@// row → purge plugin_storage + plugin_task_metadata + plugin_cookie_jar →// remove the install directory → refresh registry.+import { createHash } from 'node:crypto'import { mkdir, readFile, rename, rm } from 'node:fs/promises'import path from 'node:path'import { FALLBACK_LOCALE } from '@shared/constants/locales'@@ -110,6 +111,10 @@ interface StagedInstall {export interface StageResult {stagingId: stringconsent: ConsentPayload+ /** True when a trust-equivalent upgrade committed without another prompt. */+ committed: boolean+ /** Present when `committed` is true. */+ pluginId?: string}export interface StageOptions {@@ -169,6 +174,22 @@ export class PluginInstaller {moextPath,stagingDir)+ const localFileHash =+ sourceInput.type === 'local'+ ? createHash('sha256')+ .update(await readFile(moextPath))+ .digest('hex')+ : null+ if (+ sourceInput.type === 'local' &&+ sourceInput.fileHash !== localFileHash+ ) {+ await rm(stagingDir, { recursive: true, force: true })+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_file_hash_mismatch'+ )+ }let parsedManifest: PluginManifesttry {@@ -305,9 +326,15 @@ export class PluginInstaller {this.pending.set(stagingId, staged)if (!needConsent) {- await this.commit(stagingId, prev?.grants ?? {})+ const committed = await this.commit(stagingId, prev?.grants ?? {})+ return {+ stagingId,+ consent,+ committed: true,+ pluginId: committed.pluginId,+ }}- return { stagingId, consent }+ return { stagingId, consent, committed: false }}async commit(diff --git a/src/core/plugin/plugin-registry.test.ts b/src/core/plugin/plugin-registry.test.tsindex c4bd4e28..1f8609e5 100644--- a/src/core/plugin/plugin-registry.test.ts+++ b/src/core/plugin/plugin-registry.test.ts@@ -72,6 +72,33 @@ describe('PluginRegistry', () => {expect(reg.list().map((p) => p.id)).toEqual(['alice.one'])})+ it('applies the host community-directory policy before indexing', async () => {+ plant(path.join(dir, 'community'), 'alice.one')+ const policy = vi.fn(async () => ({+ ok: false,+ reason: 'plugin.lifecycle.install_record_required',+ }))+ const guarded = new PluginRegistry({+ pluginsDir: path.join(dir, 'community'),+ builtinDir: path.join(dir, 'builtin'),+ stateStore: store,+ hostVersion: '2.5.0',+ communityDirectoryPolicy: policy,+ })++ await guarded.discover()++ expect(guarded.list()).toEqual([])+ expect(guarded.loadErrors()).toEqual([+ expect.objectContaining({+ message: 'plugin.lifecycle.install_record_required',+ }),+ ])+ expect(policy).toHaveBeenCalledWith(+ path.join(dir, 'community', 'alice.one')+ )+ })+it('discover() removes orphan ffmpeg staging dirs before scanning plugins', async () => {// Seed an orphan staging dir from a previous (crashed) run.const orphanRoot = path.join(dir, 'community', 'alice', 'staging', 't-old')diff --git a/src/core/plugin/plugin-registry.ts b/src/core/plugin/plugin-registry.tsindex 1bc7abfb..fd54fa00 100644--- a/src/core/plugin/plugin-registry.ts+++ b/src/core/plugin/plugin-registry.ts@@ -44,6 +44,10 @@ export interface PluginRegistryOptions {signingPubkeys?: ReadonlyArray<string>/** Injectable locale reader for deterministic prepare/commit race tests. */readLocaleFile?: (filePath: string) => Promise<string>+ /** Host-owned gate for writable community plugin directories. */+ communityDirectoryPolicy?: (+ pluginDir: string+ ) => Promise<{ ok: boolean; reason?: string }>/** Shell-provided plugin development directory; omitted outside dev mode. */devPath?: string}@@ -457,8 +461,20 @@ export class PluginRegistry {throw e}for (const name of entries) {+ if (origin === 'community' && name.startsWith('_')) continueconst dir = path.join(root, name)try {+ if (origin === 'community' && this.opts.communityDirectoryPolicy) {+ const policy = await this.opts.communityDirectoryPolicy(dir)+ if (!policy.ok) {+ this.errors.push({+ pluginDir: dir,+ code: ErrorCode.PluginManifestInvalid,+ message: policy.reason ?? 'plugin.lifecycle.unsigned_not_allowed',+ })+ continue+ }+ }const raw = await readFile(path.join(dir, 'motrix-plugin.json'), 'utf8')const { manifest } = parseManifest(raw, {hostVersion: this.opts.hostVersion,diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.tsindex dfdbdccc..ff09bb00 100644--- a/src/core/settings/settings-manager.test.ts+++ b/src/core/settings/settings-manager.test.ts@@ -776,6 +776,34 @@ describe('SettingsManager', () => {// Other tracker fields retain defaultsexpect(manager.get().tracker.autoSync).toBe(true)})++ it('atomically removes only the uninstalled plugin configuration', async () => {+ await manager.update({+ plugins: {+ 'plugin.remove': { apiKey: 'box:encrypted-secret' },+ 'plugin.keep': { quality: '1080p' },+ },+ })++ const result = await manager.removePluginConfig('plugin.remove')++ expect(result.saved).toBe(true)+ expect(manager.get().plugins).toEqual({+ 'plugin.keep': { quality: '1080p' },+ })+ const persisted = JSON.parse(+ mockedFs.writeFile.mock.calls.at(-1)?.[1] as string+ )+ expect(persisted.plugins).toEqual({+ 'plugin.keep': { quality: '1080p' },+ })++ const writes = mockedFs.writeFile.mock.calls.length+ await expect(+ manager.removePluginConfig('plugin.remove')+ ).resolves.toMatchObject({ saved: false })+ expect(mockedFs.writeFile).toHaveBeenCalledTimes(writes)+ })})describe('save', () => {diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.tsindex e49910b7..60136d8d 100644--- a/src/core/settings/settings-manager.ts+++ b/src/core/settings/settings-manager.ts@@ -324,6 +324,35 @@ export class SettingsManager {return this.enqueueMutation(() => this.persistUpdate(patch))}+ /**+ * Remove the durable configuration namespace owned by an uninstalled+ * plugin. A normal partial update cannot express deletion because plugin+ * settings are merge-patched, so uninstall uses this explicit atomic+ * operation instead of leaving encrypted secrets and stale configuration+ * behind forever.+ */+ async removePluginConfig(pluginId: string): Promise<UpdateResult> {+ return this.enqueueMutation(async () => {+ if (!Object.hasOwn(this.settings.plugins, pluginId)) {+ return this.unchangedResult()+ }++ const old = structuredClone(this.settings)+ const next = structuredClone(this.settings)+ delete next.plugins[pluginId]+ await this.saveSettings(next)+ this.settings = next+ this.onChange?.(old, this.settings)+ return {+ saved: true,+ requiresRestart: false,+ changedRestartKeys: [],+ requiresAppRestart: false,+ changedAppRestartKeys: [],+ }+ })+ }+private async persistUpdate(partial: DeepPartial<AppSettings>): Promise<UpdateResult> {diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 3a2d342f..d73261ad 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -75,6 +75,7 @@ interface DepOverrides {persist?: (id: string, bytes: Uint8Array) => Promise<string>defaultSaveDir?: stringwaitForEngineReady?: () => Promise<void>+ prepareSaveDir?: (requested: string) => Promise<string>}function httpRequest() {@@ -208,6 +209,7 @@ function makeDeps(overrides: DepOverrides = {}): Deps & {}if (overrides.waitForEngineReady)deps.waitForEngineReady = overrides.waitForEngineReady+ if (overrides.prepareSaveDir) deps.prepareSaveDir = overrides.prepareSaveDirreturn deps}@@ -244,6 +246,21 @@ describe('handleCreateTask', () => {)})+ it('uses the host-prepared save directory for task and aria2 paths', async () => {+ const prepareSaveDir = vi.fn(async () => '/downloads/canonical')+ const deps = makeDeps({ prepareSaveDir })++ await handleCreateTask(httpRequest(), deps)++ expect(prepareSaveDir).toHaveBeenCalledWith('/d')+ expect(deps.pick).toHaveBeenCalledWith('/downloads/canonical', 'b')+ expect(deps.addUri).toHaveBeenCalledWith(+ ['https://a/b'],+ expect.objectContaining({ dir: '/downloads/canonical' })+ )+ expect(lastAddedTask(deps).saveDir).toBe('/downloads/canonical')+ })+it('records one submitted event after canonical registration and before TaskUpdated', async () => {const deps = makeDeps({ addUriGid: 'gid-activity' })diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 85425c73..400da2e9 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -70,6 +70,12 @@ export interface CreateTaskDeps {* adapter call so a cold-start request waits for aria2 instead of hitting* a not-yet-connected RPC socket. Absent ⇒ no gate (back-compat / tests). */waitForEngineReady?: () => Promise<void>+ /**+ * Host-owned save-directory preflight. Server injects containment and+ * writability enforcement; Electron may omit it because its native picker+ * and shell own that policy.+ */+ prepareSaveDir?: (requested: string) => Promise<string>/** Rejecting parent-row durability barrier, invoked before publication. */persistTask?: (task: DownloadTask) => Promise<void>/**@@ -164,7 +170,10 @@ export async function handleCreateTask(const appSettings = deps.settingsManager.getApp()const engineSettings = deps.settingsManager.getEngine()- const effectiveSaveDir = req.saveDir || appSettings.defaultSaveDir+ const requestedSaveDir = req.saveDir || appSettings.defaultSaveDir+ const effectiveSaveDir = deps.prepareSaveDir+ ? await deps.prepareSaveDir(requestedSaveDir)+ : requestedSaveDirlog.info({diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 46fa3bca..2a8585c3 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -90,6 +90,7 @@ function fakeCtx() {settingsManager: {getApp: () => ({ defaultSaveDir: '/tmp', magnetFileSelection: true }),getEngine: () => ({ maxConnectionPerServer: 5 }),+ removePluginConfig: vi.fn().mockResolvedValue(undefined),update: vi.fn().mockResolvedValue({ok: true,requiresRestart: false,diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 7b3cb61a..83ee0858 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -1256,10 +1256,14 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {toSourceInput(parsed),{ expect })- eventBus.emit(Events.PluginInstallConsentRequested, {- stagingId: result.stagingId,- consent: result.consent,- })+ if (result.committed && result.pluginId) {+ eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })+ } else {+ eventBus.emit(Events.PluginInstallConsentRequested, {+ stagingId: result.stagingId,+ consent: result.consent,+ })+ }return result},@@ -1367,6 +1371,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {[Commands.UninstallPlugin]: async (payload: unknown) => {const parsed = z.object({ pluginId: z.string().min(1) }).parse(payload)await pluginInstaller.uninstall(parsed.pluginId)+ await settingsManager.removePluginConfig(parsed.pluginId)eventBus.emit(Events.PluginUninstalled, { pluginId: parsed.pluginId })return { ok: true }},diff --git a/src/renderer/platform/electron-services.test.ts b/src/renderer/platform/electron-services.test.tsindex bee0a715..e5cc1b04 100644--- a/src/renderer/platform/electron-services.test.ts+++ b/src/renderer/platform/electron-services.test.ts@@ -2,14 +2,34 @@ import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { beforeEach, describe, expect, it, vi } from 'vitest'import { electronServices } from './electron-services'+import { sha256File } from './plugin-install-file'vi.mock('@renderer/lib/transport', () => ({transport: { invoke: vi.fn() },}))+vi.mock('./plugin-install-file', () => ({+ sha256File: vi.fn(async () => 'a'.repeat(64)),+}))describe('electronServices', () => {beforeEach(() => {vi.clearAllMocks()+ window.motrix = {+ getPathForFile: vi.fn(() => '/host/plugin.moext'),+ } as never+ })++ it('converts a selected file through the Electron host capability', async () => {+ const file = new File(['plugin'], 'plugin.moext')+ await expect(+ electronServices.pluginInstallFile?.prepare(file)+ ).resolves.toEqual({+ sourceType: 'local',+ absPath: '/host/plugin.moext',+ fileHash: 'a'.repeat(64),+ })+ expect(window.motrix?.getPathForFile).toHaveBeenCalledWith(file)+ expect(sha256File).toHaveBeenCalledWith(file)})it('pickSaveDir returns path on user confirm', async () => {diff --git a/src/renderer/platform/electron-services.ts b/src/renderer/platform/electron-services.tsindex be29a17a..e5702c2b 100644--- a/src/renderer/platform/electron-services.ts+++ b/src/renderer/platform/electron-services.ts@@ -2,11 +2,27 @@ import { toast } from '@renderer/components/ui/toast'import { i18n } from '@renderer/lib/i18n'import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'+import { sha256File } from './plugin-install-file'import type { PlatformServices } from './services'export const electronServices: PlatformServices = {kind: 'electron',+ pluginInstallFile: {+ mode: 'local-path',+ async prepare(file) {+ const absPath = window.motrix?.getPathForFile?.(file)+ if (!absPath) {+ throw new Error('Desktop file path capability is unavailable')+ }+ return {+ sourceType: 'local',+ absPath,+ fileHash: await sha256File(file),+ }+ },+ },+async pickSaveDir(defaultPath) {const res = await transport.invoke(Commands.PickSaveDir, { defaultPath })if (res && typeof res === 'object' && 'path' in res) {diff --git a/src/renderer/platform/plugin-install-file.ts b/src/renderer/platform/plugin-install-file.tsnew file mode 100644index 00000000..51e49b1e--- /dev/null+++ b/src/renderer/platform/plugin-install-file.ts@@ -0,0 +1,6 @@+export async function sha256File(file: File): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer())+ return Array.from(new Uint8Array(digest))+ .map((byte) => byte.toString(16).padStart(2, '0'))+ .join('')+}diff --git a/src/renderer/platform/services.tsx b/src/renderer/platform/services.tsxindex 0b3ff026..ad6ec872 100644--- a/src/renderer/platform/services.tsx+++ b/src/renderer/platform/services.tsx@@ -1,7 +1,17 @@import { createContext, type ReactNode, useContext } from 'react'+export type PluginInstallFileReference =+ | { sourceType: 'local'; absPath: string; fileHash: string }+ | { sourceType: 'upload'; uploadId: string; fileHash: string }++export interface PluginInstallFileCapability {+ readonly mode: 'local-path' | 'upload'+ prepare(file: File): Promise<PluginInstallFileReference>+}+export interface PlatformServices {readonly kind: 'electron' | 'web'+ readonly pluginInstallFile?: PluginInstallFileCapabilitypickSaveDir(defaultPath?: string): Promise<string | null>closeHost(options?: {showMain?: boolean@@ -47,3 +57,7 @@ export function usePlatformServices(): PlatformServices {}return ctx}++export function useOptionalPlatformServices(): PlatformServices | null {+ return useContext(PlatformServicesContext)+}diff --git a/src/renderer/platform/web-services.test.ts b/src/renderer/platform/web-services.test.tsindex a9c519c0..19bcb531 100644--- a/src/renderer/platform/web-services.test.ts+++ b/src/renderer/platform/web-services.test.ts@@ -1,6 +1,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest'+import { sha256File } from './plugin-install-file'import { __webPathPickerBus, createWebServices } from './web-services'+vi.mock('./plugin-install-file', () => ({+ sha256File: vi.fn(async () => 'b'.repeat(64)),+}))+describe('createWebServices', () => {let services: ReturnType<typeof createWebServices>@@ -34,4 +39,52 @@ describe('createWebServices', () => {})expect(await services.readClipboard()).toBe('')})++ it('uploads a selected plugin and returns an opaque Server reference', async () => {+ const fetchImpl = vi.fn(async () =>+ Promise.resolve(+ new Response(+ JSON.stringify({+ uploadId: '123e4567-e89b-42d3-a456-426614174000',+ fileHash: 'b'.repeat(64),+ }),+ { status: 201, headers: { 'content-type': 'application/json' } }+ )+ )+ ) as unknown as typeof fetch+ services = createWebServices({+ fetchImpl,+ baseUrl: 'https://motrix.example',+ })+ const file = new File(['plugin'], '插件.moext')++ await expect(services.pluginInstallFile?.prepare(file)).resolves.toEqual({+ sourceType: 'upload',+ uploadId: '123e4567-e89b-42d3-a456-426614174000',+ fileHash: 'b'.repeat(64),+ })+ expect(sha256File).toHaveBeenCalledWith(file)+ expect(fetchImpl).toHaveBeenCalledWith(+ 'https://motrix.example/api/plugins/uploads',+ expect.objectContaining({+ method: 'POST',+ credentials: 'same-origin',+ body: file,+ headers: expect.objectContaining({+ 'x-motrix-file-name': encodeURIComponent('插件.moext'),+ 'x-motrix-file-sha256': 'b'.repeat(64),+ }),+ })+ )+ })++ it('surfaces a rejected upload instead of fabricating a path', async () => {+ const fetchImpl = vi.fn(async () =>+ Promise.resolve(new Response('too large', { status: 413 }))+ ) as unknown as typeof fetch+ services = createWebServices({ fetchImpl, baseUrl: '' })+ await expect(+ services.pluginInstallFile?.prepare(new File(['x'], 'x.moext'))+ ).rejects.toThrow('Plugin upload failed (413)')+ })})diff --git a/src/renderer/platform/web-services.ts b/src/renderer/platform/web-services.tsindex c89baa06..c688610f 100644--- a/src/renderer/platform/web-services.ts+++ b/src/renderer/platform/web-services.ts@@ -1,5 +1,6 @@import { toast } from '@renderer/components/ui/toast'import { i18n } from '@renderer/lib/i18n'+import { sha256File } from './plugin-install-file'import type { PlatformServices } from './services'type PickRequest = { defaultPath?: string }@@ -44,10 +45,57 @@ export function __setWebCloseHandler(fn: (() => void) | null): void {__webCloseHandler = fn}-export function createWebServices(): PlatformServices {+export interface WebServicesOptions {+ fetchImpl?: typeof fetch+ baseUrl?: string+}++export function createWebServices(+ options: WebServicesOptions = {}+): PlatformServices {+ const fetchImpl = options.fetchImpl ?? fetch.bind(globalThis)+ const baseUrl = options.baseUrl ?? globalThis.location?.origin ?? ''return {kind: 'web',+ pluginInstallFile: {+ mode: 'upload',+ async prepare(file) {+ const fileHash = await sha256File(file)+ const response = await fetchImpl(`${baseUrl}/api/plugins/uploads`, {+ method: 'POST',+ credentials: 'same-origin',+ headers: {+ 'content-type': 'application/vnd.motrix.moext',+ 'x-motrix-file-name': encodeURIComponent(file.name),+ 'x-motrix-file-sha256': fileHash,+ },+ body: file,+ })+ if (!response.ok) {+ const detail = await response.text()+ throw new Error(+ `Plugin upload failed (${response.status}): ${detail}`+ )+ }+ const reference = (await response.json()) as {+ uploadId?: unknown+ fileHash?: unknown+ }+ if (+ typeof reference.uploadId !== 'string' ||+ reference.fileHash !== fileHash+ ) {+ throw new Error('Plugin upload returned an invalid reference')+ }+ return {+ sourceType: 'upload',+ uploadId: reference.uploadId,+ fileHash,+ }+ },+ },+pickSaveDir(defaultPath) {return __webPathPickerBus.request({ defaultPath })},diff --git a/src/renderer/routes/plugins/components/plugin-input-group.test.tsx b/src/renderer/routes/plugins/components/plugin-input-group.test.tsxindex e9f916ac..48e6e153 100644--- a/src/renderer/routes/plugins/components/plugin-input-group.test.tsx+++ b/src/renderer/routes/plugins/components/plugin-input-group.test.tsx@@ -1,28 +1,55 @@import '@renderer/lib/i18n'import '@testing-library/jest-dom/vitest'+import {+ type PlatformServices,+ PlatformServicesProvider,+} from '@renderer/platform/services'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'import { PluginInputGroup } from './plugin-input-group'-interface MotrixBridge {- getPathForFile?: (file: File) => string+const prepareFile = vi.fn()++function services(withFiles = true): PlatformServices {+ return {+ kind: 'electron',+ ...(withFiles+ ? {+ pluginInstallFile: {+ mode: 'local-path' as const,+ prepare: prepareFile,+ },+ }+ : {}),+ pickSaveDir: vi.fn(),+ closeHost: vi.fn(),+ readClipboard: vi.fn(),+ openExternal: vi.fn(),+ notify: vi.fn(),+ }+}++function renderGroup(onCheck = vi.fn(), checking = false, withFiles = true) {+ return render(+ <PlatformServicesProvider services={services(withFiles)}>+ <PluginInputGroup onCheck={onCheck} checking={checking} />+ </PlatformServicesProvider>+ )}-const originalMotrix = (window as unknown as { motrix?: MotrixBridge }).motrixdescribe('PluginInputGroup', () => {beforeEach(() => {- ;(window as unknown as { motrix?: MotrixBridge }).motrix = {- getPathForFile: vi.fn().mockReturnValue('/abs/foo.moext'),- }- })-- afterAll(() => {- ;(window as unknown as { motrix?: MotrixBridge }).motrix = originalMotrix+ prepareFile.mockReset()+ prepareFile.mockResolvedValue({+ sourceType: 'local',+ absPath: '/abs/foo.moext',+ fileHash: 'a'.repeat(64),+ })})it('detects github shorthand and enables Check', () => {const onCheck = vi.fn()- render(<PluginInputGroup onCheck={onCheck} checking={false} />)+ renderGroup(onCheck)const input = screen.getByPlaceholderText(/Paste a GitHub/i)fireEvent.change(input, { target: { value: 'motrix/plugin-video' } })expect(screen.getAllByText('GitHub').length).toBeGreaterThan(0)@@ -34,7 +61,7 @@ describe('PluginInputGroup', () => {})it('uses a multiline prompt input like the shadcn InputGroup reference', () => {- render(<PluginInputGroup onCheck={vi.fn()} checking={false} />)+ renderGroup()expect(screen.getByPlaceholderText(/Paste a GitHub/i).tagName).toBe('TEXTAREA')@@ -42,7 +69,7 @@ describe('PluginInputGroup', () => {it('detects URL and shows the URL chip', () => {const onCheck = vi.fn()- render(<PluginInputGroup onCheck={onCheck} checking={false} />)+ renderGroup(onCheck)fireEvent.change(screen.getByPlaceholderText(/Paste a GitHub/i), {target: { value: 'https://example.com/p.zip' },})@@ -50,29 +77,26 @@ describe('PluginInputGroup', () => {})it('disables Check button for empty/invalid input', () => {- render(<PluginInputGroup onCheck={vi.fn()} checking={false} />)+ renderGroup()expect(screen.getByLabelText('Check this plugin')).toBeDisabled()})- it('disables file picker button on web (no getPathForFile bridge)', () => {- delete (window as unknown as { motrix?: MotrixBridge }).motrix- render(<PluginInputGroup onCheck={vi.fn()} checking={false} />)+ it('disables file picker when the host omits the file capability', () => {+ renderGroup(vi.fn(), false, false)const fileBtn = screen.getByLabelText(- /Local file install is only available in the desktop app/+ /Local file install is unavailable in this host/)expect(fileBtn).toBeDisabled()})it('disables Check while pending', () => {- render(<PluginInputGroup onCheck={vi.fn()} checking={true} />)+ renderGroup(vi.fn(), true)expect(screen.getByLabelText('Check this plugin')).toBeDisabled()})it('auto-triggers onCheck when a local moext file is picked', async () => {const onCheck = vi.fn()- const { container } = render(- <PluginInputGroup onCheck={onCheck} checking={false} />- )+ const { container } = renderGroup(onCheck)const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement@@ -85,13 +109,49 @@ describe('PluginInputGroup', () => {expect.objectContaining({sourceType: 'local',absPath: '/abs/foo.moext',- fileHash: expect.stringMatching(/^[0-9a-f]{64}$/),+ fileHash: 'a'.repeat(64),}))})+ it('passes an uploaded Web reference without inventing a local path', async () => {+ prepareFile.mockResolvedValue({+ sourceType: 'upload',+ uploadId: '123e4567-e89b-42d3-a456-426614174000',+ fileHash: 'b'.repeat(64),+ })+ const onCheck = vi.fn()+ const { container } = renderGroup(onCheck)+ const fileInput = container.querySelector(+ 'input[type="file"]'+ ) as HTMLInputElement+ fireEvent.change(fileInput, {+ target: { files: [new File(['x'], 'foo.moext')] },+ })+ await waitFor(() => expect(onCheck).toHaveBeenCalledTimes(1))+ expect(onCheck).toHaveBeenCalledWith({+ sourceType: 'upload',+ uploadId: '123e4567-e89b-42d3-a456-426614174000',+ fileHash: 'b'.repeat(64),+ })+ })++ it('shows a host capability error instead of failing silently', async () => {+ prepareFile.mockRejectedValue(new Error('upload is unavailable'))+ const { container } = renderGroup()+ const fileInput = container.querySelector(+ 'input[type="file"]'+ ) as HTMLInputElement+ fireEvent.change(fileInput, {+ target: { files: [new File(['x'], 'foo.moext')] },+ })+ expect(await screen.findByRole('alert')).toHaveTextContent(+ /upload is unavailable/+ )+ })+it('hides the Check button when input is a local moext', () => {- render(<PluginInputGroup onCheck={vi.fn()} checking={false} />)+ renderGroup()fireEvent.change(screen.getByPlaceholderText(/Paste a GitHub/i), {target: { value: 'plugin.moext' },})diff --git a/src/renderer/routes/plugins/components/plugin-input-group.tsx b/src/renderer/routes/plugins/components/plugin-input-group.tsxindex c4917f50..2b117a2c 100644--- a/src/renderer/routes/plugins/components/plugin-input-group.tsx+++ b/src/renderer/routes/plugins/components/plugin-input-group.tsx@@ -13,6 +13,10 @@ import {} from '@renderer/components/ui/tooltip'import { useDragDepth } from '@renderer/hooks/use-drag-depth'import { cn } from '@renderer/lib/utils'+import {+ type PluginInstallFileReference,+ useOptionalPlatformServices,+} from '@renderer/platform/services'import { Paperclip, Search } from 'lucide-react'import { type ChangeEvent, useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -28,64 +32,49 @@ const OPTIONAL_TONE = getAudienceTone('optional')export type CheckArgs =| { sourceType: 'github'; spec: string }| { sourceType: 'url'; url: string }- | { sourceType: 'local'; absPath: string; fileHash: string }+ | PluginInstallFileReferenceinterface Props {onCheck: (args: CheckArgs) => void | Promise<void>checking: boolean}-async function sha256Hex(file: File): Promise<string> {- const buf = await file.arrayBuffer()- const digest = await crypto.subtle.digest('SHA-256', buf)- return Array.from(new Uint8Array(digest))- .map((b) => b.toString(16).padStart(2, '0'))- .join('')-}-export function PluginInputGroup({ onCheck, checking }: Props) {const { t } = useTranslation()+ const platform = useOptionalPlatformServices()+ const fileCapability = platform?.pluginInstallFileconst [input, setInput] = useState('')- const [localPath, setLocalPath] = useState<string | null>(null)- const [localFile, setLocalFile] = useState<File | null>(null)+ const [fileError, setFileError] = useState<string | null>(null)const fileInputRef = useRef<HTMLInputElement>(null)const detected: DetectedSource = detectInstallSource(input)- const isElectron = typeof window.motrix?.getPathForFile === 'function'- const canCheck =- !!detected &&- !checking &&- (detected !== 'local' || (!!localPath && !!localFile))+ const canCheck = !!detected && !checking && detected !== 'local'const acceptFile = useCallback(async (file: File) => {- if (checking) return- const resolved = window.motrix?.getPathForFile?.(file)- if (!resolved) return- setLocalPath(resolved)- setLocalFile(file)+ if (checking || !fileCapability) return+ setFileError(null)setInput(file.name)- const fileHash = await sha256Hex(file)- await onCheck({- sourceType: 'local',- absPath: resolved,- fileHash,- })+ try {+ await onCheck(await fileCapability.prepare(file))+ } catch (cause) {+ setFileError(cause instanceof Error ? cause.message : String(cause))+ }},- [onCheck, checking]+ [onCheck, checking, fileCapability])const onFilesDrop = useCallback((files: FileList) => {- if (!isElectron || checking) return+ if (!fileCapability || checking) returnconst file = files[0]if (file) void acceptFile(file)},- [isElectron, acceptFile, checking]+ [fileCapability, acceptFile, checking])const { isDragging, dragHandlers } = useDragDepth<HTMLElement>(onFilesDrop)- const showDragOverlay = isDragging && isElectron+ const showDragOverlay = isDragging && Boolean(fileCapability)function onLocalChange(e: ChangeEvent<HTMLInputElement>) {const file = e.target.files?.[0]@@ -98,13 +87,6 @@ export function PluginInputGroup({ onCheck, checking }: Props) {await onCheck({ sourceType: 'github', spec: input.trim() })} else if (detected === 'url') {await onCheck({ sourceType: 'url', url: input.trim() })- } else if (detected === 'local' && localPath && localFile) {- const fileHash = await sha256Hex(localFile)- await onCheck({- sourceType: 'local',- absPath: localPath,- fileHash,- })}}@@ -147,16 +129,20 @@ export function PluginInputGroup({ onCheck, checking }: Props) {variant="ghost"size="icon-xs"className="rounded-full"- disabled={!isElectron || checking}+ disabled={!fileCapability || checking}onClick={() => fileInputRef.current?.click()}- aria-label={t('plugins.install.localUnavailable')}+ aria-label={t(+ fileCapability+ ? 'plugins.install.pickLocal'+ : 'plugins.install.localUnavailable'+ )}><Paperclip className="size-4" /></Button></span>}/>- {!isElectron && (+ {!fileCapability && (<TooltipContent>{t('plugins.install.localUnavailable')}</TooltipContent>@@ -207,7 +193,7 @@ export function PluginInputGroup({ onCheck, checking }: Props) {type: t(`plugins.install.detected.${detected}`),})}</Badge>- {isElectron && (+ {fileCapability && (<Badgevariant="outline"className={cn(@@ -221,6 +207,11 @@ export function PluginInputGroup({ onCheck, checking }: Props) {)}</div>)}+ {fileError && (+ <p role="alert" className="mt-2 text-xs text-destructive">+ {t('plugins.install.localPrepareFailed', { detail: fileError })}+ </p>+ )}</section>)}diff --git a/src/renderer/routes/plugins/hooks/use-plugin-install.ts b/src/renderer/routes/plugins/hooks/use-plugin-install.tsindex 21dbde4c..41b29af4 100644--- a/src/renderer/routes/plugins/hooks/use-plugin-install.ts+++ b/src/renderer/routes/plugins/hooks/use-plugin-install.ts@@ -11,11 +11,14 @@ export type InstallSource =| { sourceType: 'github'; spec: string }| { sourceType: 'url'; url: string }| { sourceType: 'local'; absPath: string; fileHash: string }+ | { sourceType: 'upload'; uploadId: string; fileHash: string }| { sourceType: 'registry'; pluginId: string }interface InstallResult {stagingId: stringconsent: ConsentPayload+ committed: boolean+ pluginId?: string}export function usePluginInstall() {@@ -32,8 +35,13 @@ export function usePluginInstall() {Commands.InstallPlugin,input)) as InstallResult- setStagingId(r.stagingId)- setConsent(r.consent)+ if (r.committed) {+ setStagingId(null)+ setConsent(null)+ } else {+ setStagingId(r.stagingId)+ setConsent(r.consent)+ }} catch (e) {setError(e instanceof Error ? e.message : String(e))} finally {diff --git a/src/server/download-path-policy.test.ts b/src/server/download-path-policy.test.tsnew file mode 100644index 00000000..db8b0926--- /dev/null+++ b/src/server/download-path-policy.test.ts@@ -0,0 +1,138 @@+import { chmod, mkdir, mkdtemp, realpath, rm, symlink } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import {+ createServerDownloadPathPolicy,+ resolveServerDefaultSaveDir,+} from './download-path-policy'++const roots: string[] = []++async function tempRoot(): Promise<string> {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-save-policy-'))+ roots.push(root)+ return root+}++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map(async (root) => {+ await chmod(root, 0o700).catch(() => undefined)+ await rm(root, { recursive: true, force: true })+ })+ )+})++describe('resolveServerDefaultSaveDir', () => {+ it('uses and normalizes MOTRIX_DEFAULT_SAVE_DIR', () => {+ expect(+ resolveServerDefaultSaveDir(+ { MOTRIX_DEFAULT_SAVE_DIR: '/downloads/../downloads' },+ '/fallback'+ )+ ).toBe('/downloads')+ })++ it('rejects a relative MOTRIX_DEFAULT_SAVE_DIR', () => {+ expect(() =>+ resolveServerDefaultSaveDir(+ { MOTRIX_DEFAULT_SAVE_DIR: 'downloads' },+ '/fallback'+ )+ ).toThrow('MOTRIX_DEFAULT_SAVE_DIR must be an absolute path')+ })+})++describe('ServerDownloadPathPolicy', () => {+ it('creates and prepares the default and allowed roots', async () => {+ const root = await tempRoot()+ const downloads = path.join(root, 'downloads')+ const media = path.join(root, 'media')+ const policy = await createServerDownloadPathPolicy({+ defaultSaveDir: downloads,+ allowedSaveDirsValue: [downloads, media].join(path.delimiter),+ })++ expect(policy.allowedSaveDirs).toEqual([downloads, media])+ await expect(policy.prepareSaveDir('')).resolves.toBe(+ await realpath(downloads)+ )+ const nested = await policy.prepareSaveDir(path.join(media, 'nested'))+ expect(nested).toBe(await realpath(path.join(media, 'nested')))+ })++ it('rejects an allowed root that does not contain the default', async () => {+ const root = await tempRoot()+ await expect(+ createServerDownloadPathPolicy({+ defaultSaveDir: path.join(root, 'downloads'),+ allowedSaveDirsValue: path.join(root, 'media'),+ })+ ).rejects.toThrow(+ 'MOTRIX_DEFAULT_SAVE_DIR must be inside MOTRIX_ALLOWED_SAVE_DIRS'+ )+ })++ it('rejects relative and out-of-root task paths before creating them', async () => {+ const root = await tempRoot()+ const downloads = path.join(root, 'downloads')+ const escaped = path.join(root, 'escaped')+ const policy = await createServerDownloadPathPolicy({+ defaultSaveDir: downloads,+ allowedSaveDirsValue: downloads,+ })++ await expect(policy.prepareSaveDir('relative')).rejects.toThrow(+ 'Save directory must be an absolute path'+ )+ await expect(policy.prepareSaveDir(escaped)).rejects.toThrow(+ 'Save directory is outside MOTRIX_ALLOWED_SAVE_DIRS'+ )+ await expect(realpath(escaped)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('rejects a symlink that escapes an allowed root', async () => {+ const root = await tempRoot()+ const downloads = path.join(root, 'downloads')+ const outside = path.join(root, 'outside')+ await Promise.all([+ mkdir(downloads, { recursive: true }),+ mkdir(outside, { recursive: true }),+ ])+ await symlink(outside, path.join(downloads, 'escape'))+ const policy = await createServerDownloadPathPolicy({+ defaultSaveDir: downloads,+ allowedSaveDirsValue: downloads,+ })++ await expect(+ policy.prepareSaveDir(path.join(downloads, 'escape', 'nested'))+ ).rejects.toThrow('Save directory resolves outside the allowed root')+ })++ it('permits any absolute writable path when no allowlist is configured', async () => {+ const root = await tempRoot()+ const downloads = path.join(root, 'downloads')+ const custom = path.join(root, 'custom')+ const policy = await createServerDownloadPathPolicy({+ defaultSaveDir: downloads,+ })++ expect(policy.allowedSaveDirs).toEqual([])+ const prepared = await policy.prepareSaveDir(custom)+ expect(prepared).toBe(await realpath(custom))+ })++ it('surfaces an unwritable save directory clearly', async () => {+ const root = await tempRoot()+ const downloads = path.join(root, 'downloads')+ await mkdir(downloads, { recursive: true })+ await chmod(downloads, 0o500)++ await expect(+ createServerDownloadPathPolicy({ defaultSaveDir: downloads })+ ).rejects.toThrow('Save directory is not writable')+ await chmod(downloads, 0o700)+ })+})diff --git a/src/server/download-path-policy.ts b/src/server/download-path-policy.tsnew file mode 100644index 00000000..87aae6eb--- /dev/null+++ b/src/server/download-path-policy.ts@@ -0,0 +1,211 @@+import { lstat, mkdir, open, realpath, stat, unlink } from 'node:fs/promises'+import path from 'node:path'+import { AppError, ErrorCode } from '@shared/errors'++interface DownloadPathEnvironment {+ MOTRIX_DEFAULT_SAVE_DIR?: string+}++export interface ServerDownloadPathPolicyOptions {+ defaultSaveDir: string+ allowedSaveDirsValue?: string+ pathDelimiter?: string+}++export interface ServerDownloadPathPolicy {+ readonly allowedSaveDirs: readonly string[]+ prepareSaveDir(requested: string | undefined): Promise<string>+}++interface AllowedRoot {+ configured: string+ canonical: string+}++function pathIsInside(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate)+ return (+ relative === '' ||+ (relative !== '..' &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative))+ )+}++function absolutePath(value: string, label: string): string {+ const trimmed = value.trim()+ if (!trimmed || !path.isAbsolute(trimmed)) {+ throw new AppError(+ ErrorCode.SettingsInvalid,+ `${label} must be an absolute path`+ )+ }+ return path.resolve(trimmed)+}++function parseAllowedSaveDirs(+ value: string | undefined,+ delimiter: string+): string[] {+ if (!value?.trim()) return []+ const seen = new Set<string>()+ const roots: string[] = []+ for (const raw of value.split(delimiter)) {+ if (!raw.trim()) continue+ const root = absolutePath(raw, 'MOTRIX_ALLOWED_SAVE_DIRS entry')+ if (!seen.has(root)) {+ seen.add(root)+ roots.push(root)+ }+ }+ return roots+}++function pathFailure(message: string, cause?: unknown): AppError {+ return new AppError(ErrorCode.TaskCreateFailed, message, cause)+}++async function ensureDirectory(candidate: string): Promise<void> {+ try {+ await mkdir(candidate, { recursive: true })+ const info = await stat(candidate)+ if (!info.isDirectory()) {+ throw pathFailure(`Save directory is not a directory: ${candidate}`)+ }+ } catch (cause) {+ if (cause instanceof AppError) throw cause+ throw pathFailure(`Save directory cannot be created: ${candidate}`, cause)+ }+}++async function ensureWritable(candidate: string): Promise<void> {+ const probe = path.join(+ candidate,+ `.motrix-write-test-${process.pid}-${Date.now()}-${Math.random()+ .toString(36)+ .slice(2)}`+ )+ let handle: Awaited<ReturnType<typeof open>> | undefined+ try {+ handle = await open(probe, 'wx', 0o600)+ await handle.close()+ handle = undefined+ await unlink(probe)+ } catch (cause) {+ await handle?.close().catch(() => undefined)+ await unlink(probe).catch(() => undefined)+ throw pathFailure(`Save directory is not writable: ${candidate}`, cause)+ }+}++async function deepestExistingAncestor(candidate: string): Promise<string> {+ let current = candidate+ for (;;) {+ try {+ await lstat(current)+ return current+ } catch (cause) {+ if ((cause as NodeJS.ErrnoException).code !== 'ENOENT') throw cause+ const parent = path.dirname(current)+ if (parent === current) throw cause+ current = parent+ }+ }+}++class DownloadPathPolicy implements ServerDownloadPathPolicy {+ readonly allowedSaveDirs: readonly string[]++ constructor(+ private readonly defaultSaveDir: string,+ private readonly allowedRoots: readonly AllowedRoot[]+ ) {+ this.allowedSaveDirs = allowedRoots.map((root) => root.configured)+ }++ async prepareSaveDir(requested: string | undefined): Promise<string> {+ const raw = requested?.trim() || this.defaultSaveDir+ const candidate = absolutePath(raw, 'Save directory')+ const matchingRoots = this.allowedRoots.filter((root) =>+ pathIsInside(root.configured, candidate)+ )+ if (this.allowedRoots.length > 0 && matchingRoots.length === 0) {+ throw pathFailure(+ `Save directory is outside MOTRIX_ALLOWED_SAVE_DIRS: ${candidate}`+ )+ }++ if (matchingRoots.length > 0) {+ const ancestor = await deepestExistingAncestor(candidate)+ const canonicalAncestor = await realpath(ancestor)+ if (+ !matchingRoots.some((root) =>+ pathIsInside(root.canonical, canonicalAncestor)+ )+ ) {+ throw pathFailure(+ `Save directory resolves outside the allowed root: ${candidate}`+ )+ }+ }++ await ensureDirectory(candidate)+ const canonical = await realpath(candidate)+ if (+ matchingRoots.length > 0 &&+ !matchingRoots.some((root) => pathIsInside(root.canonical, canonical))+ ) {+ throw pathFailure(+ `Save directory resolves outside the allowed root: ${candidate}`+ )+ }+ await ensureWritable(canonical)+ return canonical+ }+}++export function resolveServerDefaultSaveDir(+ env: DownloadPathEnvironment,+ fallback: string+): string {+ return absolutePath(+ env.MOTRIX_DEFAULT_SAVE_DIR?.trim() || fallback,+ env.MOTRIX_DEFAULT_SAVE_DIR?.trim()+ ? 'MOTRIX_DEFAULT_SAVE_DIR'+ : 'Server default save directory'+ )+}++export async function createServerDownloadPathPolicy(+ options: ServerDownloadPathPolicyOptions+): Promise<ServerDownloadPathPolicy> {+ const defaultSaveDir = absolutePath(+ options.defaultSaveDir,+ 'MOTRIX_DEFAULT_SAVE_DIR'+ )+ const configuredRoots = parseAllowedSaveDirs(+ options.allowedSaveDirsValue,+ options.pathDelimiter ?? path.delimiter+ )+ if (+ configuredRoots.length > 0 &&+ !configuredRoots.some((root) => pathIsInside(root, defaultSaveDir))+ ) {+ throw new AppError(+ ErrorCode.SettingsInvalid,+ 'MOTRIX_DEFAULT_SAVE_DIR must be inside MOTRIX_ALLOWED_SAVE_DIRS'+ )+ }++ const allowedRoots: AllowedRoot[] = []+ for (const configured of configuredRoots) {+ await ensureDirectory(configured)+ const canonical = await realpath(configured)+ await ensureWritable(canonical)+ allowedRoots.push({ configured, canonical })+ }++ const policy = new DownloadPathPolicy(defaultSaveDir, allowedRoots)+ await policy.prepareSaveDir(defaultSaveDir)+ return policy+}diff --git a/src/server/environment.test.ts b/src/server/environment.test.tsnew file mode 100644index 00000000..13f14aea--- /dev/null+++ b/src/server/environment.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest'+import { parseServerPort } from './environment'++describe('parseServerPort', () => {+ it('uses the fallback only when the variable is unset', () => {+ expect(parseServerPort(undefined, 'PORT', 8080)).toBe(8080)+ expect(parseServerPort('', 'PORT', 8080)).toBe(8080)+ })++ it('validates the complete listen-port range', () => {+ expect(parseServerPort('8443', 'PORT', 8080)).toBe(8443)+ expect(() => parseServerPort('not-a-port', 'PORT', 8080)).toThrow('PORT')+ expect(() => parseServerPort('0', 'PORT', 8080)).toThrow('PORT')+ expect(+ parseServerPort('0', 'MOTRIX_MDXP_PORT', 16801, { allowZero: true })+ ).toBe(0)+ })+})diff --git a/src/server/environment.ts b/src/server/environment.tsnew file mode 100644index 00000000..3d465685--- /dev/null+++ b/src/server/environment.ts@@ -0,0 +1,14 @@+export function parseServerPort(+ value: string | undefined,+ name: string,+ fallback: number,+ options: { allowZero?: boolean } = {}+): number {+ if (value === undefined || value.trim() === '') return fallback+ const port = Number(value)+ const minimum = options.allowZero ? 0 : 1+ if (!Number.isInteger(port) || port < minimum || port > 65_535) {+ throw new Error(`${name} must be an integer between ${minimum} and 65535`)+ }+ return port+}diff --git a/src/server/http/app.test.ts b/src/server/http/app.test.tsindex bf3bf4b2..52e84784 100644--- a/src/server/http/app.test.ts+++ b/src/server/http/app.test.ts@@ -9,4 +9,22 @@ describe('createApp', () => {expect(res.json()).toEqual({ ok: true })await app.close()})++ it('returns 503 when the runtime health callback is not ready', async () => {+ const app = await createApp({+ healthCheck: () => ({+ ok: false,+ status: 'degraded',+ engine: { state: 'failed' },+ }),+ })+ const res = await app.inject({ method: 'GET', url: '/healthz' })+ expect(res.statusCode).toBe(503)+ expect(res.json()).toEqual({+ ok: false,+ status: 'degraded',+ engine: { state: 'failed' },+ })+ await app.close()+ })})diff --git a/src/server/http/app.ts b/src/server/http/app.tsindex f069f2b6..d96cf938 100644--- a/src/server/http/app.ts+++ b/src/server/http/app.ts@@ -36,6 +36,7 @@ export interface AppOptions {bridgeQueryHandlers?: Record<string, Handler>eventBus?: EventBusrendererDir?: string+ healthCheck?: () => { ok: boolean } | Promise<{ ok: boolean }>}export async function createApp(@@ -51,7 +52,10 @@ export async function createApp(const bridgeCommands = opts.bridgeCommandHandlers ?? {}const bridgeQueries = opts.bridgeQueryHandlers ?? {}- app.get('/healthz', async () => ({ ok: true }))+ app.get('/healthz', async (_request, reply) => {+ const health = opts.healthCheck ? await opts.healthCheck() : { ok: true }+ return reply.code(health.ok ? 200 : 503).send(health)+ })app.post<{ Params: { channel: string }; Body: { args?: unknown[] } }>('/rpc/command/:channel',diff --git a/src/server/index.ts b/src/server/index.tsindex fd674258..fa088dcf 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -1,4 +1,5 @@import fs from 'node:fs/promises'+import os from 'node:os'import path from 'node:path'import { fileURLToPath } from 'node:url'import { TaskActivityService, TaskActivityStore } from '@core/activity'@@ -34,12 +35,16 @@ import { getLogger, initLogger } from '@core/logger'import { registerEngineFailureSubscriber } from '@core/notifications/engine-failure-subscriber'import { NotificationCenter } from '@core/notifications/notification-center'import { createNotificationOccurrenceConsumer } from '@core/notifications/occurrence-consumer'+import { projectActiveToLegacy } from '@core/plugin/capabilities/ffmpeg-detect'import { wireCommandSystem } from '@core/plugin/commands/wire'+import { pluginSecretFields } from '@core/plugin/configuration-schema'+import { GrantsManager } from '@core/plugin/grants/grants-manager'import { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'import {PluginHost,parsePluginIdleDisposeMs,} from '@core/plugin/host/plugin-host'+import { PluginInstaller } from '@core/plugin/install/plugin-installer'import { PluginRegistry } from '@core/plugin/plugin-registry'import { RegistryClient } from '@core/plugin/registry/registry-client'import { PluginStateStore } from '@core/plugin/state/plugin-state-store'@@ -99,16 +104,33 @@ import {bootstrapBridgeForServer,type ServerBridgeRuntime,} from './bridge/bootstrap'+import {+ createServerDownloadPathPolicy,+ resolveServerDefaultSaveDir,+} from './download-path-policy'+import { parseServerPort } from './environment'import { createApp } from './http/app'import { buildServerCommandHandlers } from './ipc/commands'import { buildServerQueryHandlers } from './ipc/queries'import { provisionOperatorToken } from './operator-token'import { createNodePlatformServices } from './platform/services'import { createServerCapabilityHost } from './plugin/capability-host'+import {+ createServerCommunityPluginPolicy,+ parseAllowUnmanagedPlugins,+} from './plugin/community-policy'import { startDevWatcher } from './plugin/dev-watcher'+import { makeServerFfmpegDetect } from './plugin/ffmpeg-detect-server'+import { ServerPluginInstallService } from './plugin/install-service'import { resolveServerPluginsDir } from './plugin/plugins-dir'+import { serverBootstrapInstall } from './plugin/server-bootstrap-installer'+import { PluginUploadStore } from './plugin/upload-store'import { createServerProxyApplier } from './proxy/wiring'+import { registerServerDiagnosticsRoute } from './routes/diagnostics'+import { registerPluginUploadRoute } from './routes/plugin-uploads'import { registerTasksBulkRoutes } from './routes/tasks-bulk'+import { prepareServerRuntimeDirectories } from './runtime-directories'+import { serverHealthSnapshot } from './runtime-health'import {createServerExitCoordinator,createServerShutdown,@@ -129,7 +151,15 @@ async function main() {// ─── Platform ─────────────────────────────────────────────────const platform = createNodePlatformServices()- log.info({ platform }, 'boot')+ const runtimeDirectories = await prepareServerRuntimeDirectories({+ dataDir: platform.userDataDir,+ tempDirValue: process.env.MOTRIX_TEMP_DIR,+ })+ process.env.TMPDIR = runtimeDirectories.tempDir+ log.info(+ { platform, tempDir: runtimeDirectories.tempDir },+ 'runtime directories ready'+ )// The cleanup coordinator exists before the first fallible acquisition.// Each resource replaces its no-op slot immediately when ownership is@@ -229,9 +259,14 @@ async function main() {// are visible here.let speedLimitController: SpeedLimitController | undefined+ const configuredDefaultSaveDir = resolveServerDefaultSaveDir(+ process.env,+ path.join(os.homedir(), 'Downloads')+ )const settingsManager = new SettingsManager(path.join(platform.userDataDir, 'settings.json'),{+ defaultSaveDir: configuredDefaultSaveDir,onChange: (old, updated) => {eventBus.emit(Events.SettingsChanged, { old, updated })if (@@ -245,6 +280,32 @@ async function main() {)await settingsManager.load()if (!shellAsyncWork.isAccepting()) return+ const hasDefaultSaveDirOverride = Boolean(+ process.env.MOTRIX_DEFAULT_SAVE_DIR?.trim()+ )+ const effectiveDefaultSaveDir = hasDefaultSaveDirOverride+ ? configuredDefaultSaveDir+ : settingsManager.getApp().defaultSaveDir+ const downloadPathPolicy = await createServerDownloadPathPolicy({+ defaultSaveDir: effectiveDefaultSaveDir,+ allowedSaveDirsValue: process.env.MOTRIX_ALLOWED_SAVE_DIRS,+ })+ if (+ hasDefaultSaveDirOverride &&+ settingsManager.getApp().defaultSaveDir !== effectiveDefaultSaveDir+ ) {+ await settingsManager.update({+ app: { defaultSaveDir: effectiveDefaultSaveDir },+ })+ }+ log.info(+ {+ defaultSaveDir: settingsManager.getApp().defaultSaveDir,+ allowedSaveDirs: downloadPathPolicy.allowedSaveDirs,+ },+ 'download path contract ready'+ )+ if (!shellAsyncWork.isAccepting()) returnconst resolveServerLocale = (settingsLanguage: string) =>resolveSupportedLocale(settingsLanguage,@@ -357,9 +418,8 @@ async function main() {}// ─── Plugin runtime ─────────────────────────────────────────- const { pluginsDir, builtinDir } = await resolveServerPluginsDir(- platform.userDataDir- )+ const { pluginsDir, builtinDir, pluginImportRoots } =+ await resolveServerPluginsDir(platform.userDataDir)if (!shellAsyncWork.isAccepting()) returnconst pluginStateStore = new PluginStateStore(db.database)const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH@@ -370,6 +430,11 @@ async function main() {hostVersion: process.env.MOTRIX_APP_VERSION ?? '2.0.0',hostLanguage,devPath,+ communityDirectoryPolicy: createServerCommunityPluginPolicy({+ allowUnmanagedPlugins: parseAllowUnmanagedPlugins(+ process.env.MOTRIX_ALLOW_UNMANAGED_PLUGINS+ ),+ }),})await pluginRegistry.discover()if (!shellAsyncWork.isAccepting()) return@@ -380,10 +445,9 @@ async function main() {userDataDir: platform.userDataDir,pluginsDir,settingsManager,- // TODO Task 22: wire settingsManager config lookup- configReader: (_pluginId) => ({}),- // TODO Plan F: derive from manifest contributes.configuration schema- secretFieldsFor: (_pluginId) => new Set(),+ configReader: (pluginId) => settingsManager.get().plugins[pluginId] ?? {},+ secretFieldsFor: (pluginId) =>+ pluginSecretFields(pluginRegistry.get(pluginId)?.manifest),manifestCommandIdsFor: (pluginId) => {const cmds = pluginRegistry.get(pluginId)?.manifest.contributes.commandsreturn new Set(cmds?.map((c) => c.id) ?? [])@@ -391,6 +455,10 @@ async function main() {localeSnapshotFor: (pluginId) =>pluginRegistry.getLocaleDictionaries(pluginId),})+ const pluginGrants = new GrantsManager({+ registry: pluginRegistry,+ eventBus,+ })pluginLocaleTargets = {registry: pluginRegistry,capabilityHost: pluginCapHost,@@ -409,22 +477,79 @@ async function main() {appVersion: process.env.MOTRIX_APP_VERSION ?? '2.0.0',runtime: 'server',hostLanguage,+ pluginGrants,idleDisposeMs: parsePluginIdleDisposeMs(process.env.MOTRIX_PLUGIN_IDLE_DISPOSE_MS),})shutdownActions.drainPluginHost = () => pluginHost.shutdown()+ eventBus.on(Events.PluginGrantsChanged, (...args: unknown[]) => {+ const payload = args[0] as { pluginId?: string } | undefined+ if (payload?.pluginId && pluginHost.isActive(payload.pluginId)) {+ void pluginHost.deactivate(payload.pluginId)+ }+ })// Wire Plan D: cross-plugin command safeguards (schema cache + rate limit// + caller throttle + chain depth + audit) and bind the invoker to the// capability host. Must run AFTER registry.discover() so manifest schemas// can be compiled at install time.- wireCommandSystem({+ const commandSystem = wireCommandSystem({registry: pluginRegistry,host: pluginHost,capabilityHost: pluginCapHost,pluginsDir,})+ const hostVersion = process.env.MOTRIX_APP_VERSION ?? '2.0.0'+ const registryClient = new RegistryClient({+ cachePath: path.join(platform.userDataDir, REGISTRY_CACHE_FILENAME),+ })+ const pluginInstaller = new PluginInstaller({+ pluginsDir,+ registry: pluginRegistry,+ stateStore: pluginStateStore,+ capabilityHost: pluginCapHost,+ hostVersion,+ schemaCache: commandSystem.schemas,+ ffmpegDetect: async () =>+ projectActiveToLegacy(+ await makeServerFfmpegDetect({+ settingsManager,+ userDataDir: platform.userDataDir,+ })()+ ),+ })+ const pluginUploadStore = new PluginUploadStore(+ path.join(pluginsDir, '_uploads')+ )+ const pluginInstallService = new ServerPluginInstallService({+ installer: pluginInstaller,+ registryClient,+ hostVersion,+ pluginsDir,+ allowedLocalRoots: pluginImportRoots,+ uploadStore: pluginUploadStore,+ })+ const bootstrapInstalls = await serverBootstrapInstall(+ pluginInstallService,+ pluginInstaller,+ process.env+ )+ if (bootstrapInstalls.rejected.length > 0) {+ throw new Error(+ `Declarative plugin installation failed: ${bootstrapInstalls.rejected+ .map(({ source, reason }) => `${source}: ${reason}`)+ .join('; ')}`+ )+ }+ if (bootstrapInstalls.accepted.length > 0) {+ log.info(+ { pluginIds: bootstrapInstalls.accepted },+ 'declarative plugin installation complete'+ )+ }+ if (!shellAsyncWork.isAccepting()) return+const pluginActivation = new ActivationDispatcher(pluginRegistry, pluginHost)let devWatcherHandle: { close(): Promise<void> } | null = nullshutdownActions.drainDevWatcher = () => devWatcherHandle?.close()@@ -650,7 +775,7 @@ async function main() {exists: pathExists,})const torrentMetaStore = new TorrentMetaStoreImpl(- path.join(platform.userDataDir, 'torrents')+ runtimeDirectories.torrentsDir)const fileCleanupService = new FileCleanupServiceImpl({async removePathRecursive(absPath: string): Promise<void> {@@ -679,7 +804,7 @@ async function main() {taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),runExclusivePersistence: (operation) =>sessionManager.runExclusivePersistence(operation),- torrentMetaDir: path.join(platform.userDataDir, 'torrents'),+ torrentMetaDir: runtimeDirectories.torrentsDir,occurrenceDispatcher,})@@ -717,6 +842,9 @@ async function main() {pluginRegistry,pluginStateStore,pluginHost,+ pluginInstaller,+ pluginInstallService,+ pluginGrants,capabilityHost: pluginCapHost,userDataDir: platform.userDataDir,pluginsDir,@@ -736,9 +864,7 @@ async function main() {taskInspectorActivityRuntime.parentTaskCreated(task, persistParent),publishTaskUpdate,publishTaskUpdateNow,- })- const registryClient = new RegistryClient({- cachePath: path.join(platform.userDataDir, REGISTRY_CACHE_FILENAME),+ downloadPathPolicy,})const queryHandlers = buildServerQueryHandlers({taskManager,@@ -754,11 +880,13 @@ async function main() {engineAdapter: adapter,notificationCenter,pluginRegistry,+ pluginGrants,registryClient,pluginsDir,- hostVersion: process.env.MOTRIX_APP_VERSION ?? '2.0.0',+ hostVersion,userDataDir: platform.userDataDir,speedLimitController,+ downloadPathPolicy,})const rendererDir =@@ -792,6 +920,11 @@ async function main() {eventBus,rendererDir,operatorAuth: { operatorToken: operator.token },+ healthCheck: () =>+ serverHealthSnapshot({+ accepting: shellAsyncWork.isAccepting(),+ engine: supervisor.getStatus(),+ }),})shutdownActions.closeIngress = () => app.close()if (!shellAsyncWork.isAccepting()) {@@ -799,6 +932,48 @@ async function main() {return}+ registerPluginUploadRoute(app, pluginUploadStore)+ registerServerDiagnosticsRoute(app, async () => ({+ generatedAt: Date.now(),+ health: serverHealthSnapshot({+ accepting: shellAsyncWork.isAccepting(),+ engine: supervisor.getStatus(),+ }),+ engine: await supervisor.diagnose(),+ media: {+ ffmpeg: await makeServerFfmpegDetect({+ settingsManager,+ userDataDir: runtimeDirectories.dataDir,+ })(),+ tempDir: runtimeDirectories.tempDir,+ },+ process: {+ node: process.version,+ platform: process.platform,+ arch: process.arch,+ uid: process.getuid?.() ?? null,+ },+ storage: {+ dataDir: runtimeDirectories.dataDir,+ tempDir: runtimeDirectories.tempDir,+ torrentsDir: runtimeDirectories.torrentsDir,+ homeDir: runtimeDirectories.homeDir,+ settingsFile: path.join(runtimeDirectories.dataDir, 'settings.json'),+ databaseFile: path.join(runtimeDirectories.dataDir, 'motrix.db'),+ aria2SessionFile: path.join(runtimeDirectories.dataDir, 'aria2.session'),+ defaultSaveDir: settingsManager.getApp().defaultSaveDir,+ allowedSaveDirs: downloadPathPolicy.allowedSaveDirs,+ },+ plugins: {+ directory: pluginsDir,+ builtinDirectory: builtinDir,+ importRoots: pluginImportRoots,+ secretStoreAvailable: pluginCapHost.secrets.available(),+ installAvailable: true,+ },+ operatorAuth: { source: operator.source },+ }))+registerTasksBulkRoutes(app, {taskManager,adapter,@@ -1113,7 +1288,7 @@ async function main() {// Do not expose command/query ingress until restore, transition recovery,// and recovered Activity anchors have settled. Otherwise an early request// can observe an empty/partial TaskManager or a false TaskNotFound.- const port = Number(process.env.PORT ?? 8080)+ const port = parseServerPort(process.env.PORT, 'PORT', 8080)try {await app.listen({ port, host: '0.0.0.0' })} catch (err) {@@ -1187,6 +1362,8 @@ async function main() {) => taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),waitForEngineReady: () =>supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),+ prepareSaveDir: (requested: string) =>+ downloadPathPolicy.prepareSaveDir(requested),}const taskActionDeps = {taskManager,@@ -1205,21 +1382,12 @@ async function main() {publishTaskUpdate,publishTaskUpdateNow,}- // Validate the port so a typo in MOTRIX_MDXP_PORT falls back loudly to the- // default rather than NaN → ERR_SOCKET_BAD_PORT → swallowed by the catch- // below (silently no bridge on a headless host).- const rawPort = process.env.MOTRIX_MDXP_PORT- const parsedPort = rawPort === undefined ? 16801 : Number(rawPort)- const mdxpPort =- Number.isInteger(parsedPort) && parsedPort >= 0 && parsedPort < 65536- ? parsedPort- : 16801- if (parsedPort !== mdxpPort) {- log.warn(- { MOTRIX_MDXP_PORT: rawPort },- 'invalid MOTRIX_MDXP_PORT — falling back to 16801'- )- }+ const mdxpPort = parseServerPort(+ process.env.MOTRIX_MDXP_PORT,+ 'MOTRIX_MDXP_PORT',+ 16801,+ { allowZero: true }+ )const candidateBridgeRuntime = await bootstrapBridgeForServer({userDataDir: platform.userDataDir,host: process.env.MOTRIX_MDXP_HOST ?? '127.0.0.1',diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex 25d918e9..a825c719 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -5,8 +5,10 @@ import type { EngineSupervisor } from '@core/engine/engine-supervisor'import type { EventBus } from '@core/events/event-bus'import { NotificationCenter } from '@core/notifications/notification-center'import type { CapabilityHost } from '@core/plugin/capabilities/interface'+import type { GrantsManager } from '@core/plugin/grants/grants-manager'import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'import type { PluginHost } from '@core/plugin/host/plugin-host'+import type { PluginInstaller } from '@core/plugin/install/plugin-installer'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'import { MotrixDatabase } from '@core/session/motrix-database'@@ -21,6 +23,7 @@ import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ServerPluginInstallService } from '../plugin/install-service'import type { ServerCommandContext } from './commands'import { buildServerCommandHandlers } from './commands'@@ -45,6 +48,7 @@ function makeFakeCtx() {settingsManager: {get: vi.fn(),update: vi.fn(),+ removePluginConfig: vi.fn().mockResolvedValue(undefined),getApp: vi.fn(() => ({defaultSaveDir: '/tmp',magnetFileSelection: true,@@ -92,12 +96,23 @@ function makeFakeCtx() {pluginHost: {deactivate: vi.fn().mockResolvedValue(undefined),} as unknown as PluginHost,+ pluginInstaller: {+ commit: vi.fn(),+ cancel: vi.fn(),+ uninstall: vi.fn(),+ } as unknown as PluginInstaller,+ pluginInstallService: {+ stage: vi.fn(),+ } as unknown as ServerPluginInstallService,+ pluginGrants: { updateGrants: vi.fn() } as unknown as GrantsManager,capabilityHost: {secrets: {available: vi.fn(() => false),encrypt: vi.fn(),},configFor: vi.fn(() => ({ applyExternalChange: vi.fn() })),+ clearLog: vi.fn(),+ setLogVerbose: vi.fn(),} as unknown as CapabilityHost,userDataDir: '/tmp/userdata',pluginsDir: '/tmp/userdata/plugins',@@ -118,6 +133,10 @@ function makeFakeCtx() {async (_taskIds: readonly string[], operation: () => Promise<unknown>) =>operation()),+ downloadPathPolicy: {+ allowedSaveDirs: ['/downloads'],+ prepareSaveDir: vi.fn(async (requested: string) => requested),+ },}}@@ -283,6 +302,33 @@ describe('server Commands.UpdateSettings', () => {expect(ctx.trackerManager.applySourcesChange).not.toHaveBeenCalled()expect(ctx.trackerManager.applyBlacklistChange).not.toHaveBeenCalled()})++ it('validates a default save directory before persisting settings', async () => {+ const ctx = makeFakeCtx()+ ;(+ ctx.downloadPathPolicy.prepareSaveDir as ReturnType<typeof vi.fn>+ ).mockResolvedValue('/downloads/media-canonical')+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>).mockReturnValue(+ makeSettings(PROXY_OFF)+ )+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(+ { ok: true, requiresRestart: false, changedRestartKeys: [] }+ )+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )++ await handlers[Commands.UpdateSettings]?.({+ app: { defaultSaveDir: '/downloads/media' },+ })++ expect(ctx.downloadPathPolicy.prepareSaveDir).toHaveBeenCalledWith(+ '/downloads/media'+ )+ expect(ctx.settingsManager.update).toHaveBeenCalledWith({+ app: { defaultSaveDir: '/downloads/media-canonical' },+ })+ })})describe('server Commands.CreateTask magnet metadata selection', () => {@@ -304,6 +350,9 @@ describe('server Commands.CreateTask magnet metadata selection', () => {'magnet:?xt=urn:btih:abc','/downloads')+ expect(ctx.downloadPathPolicy.prepareSaveDir).toHaveBeenCalledWith(+ '/downloads'+ )})it('admits a selection swap through the canonical task lock', async () => {@@ -706,6 +755,84 @@ describe('server plugin enable/disable commands', () => {})})+describe('server plugin lifecycle commands', () => {+ it('stages an install and publishes the consent request', async () => {+ const ctx = makeFakeCtx()+ ;(+ ctx.pluginInstallService.stage as ReturnType<typeof vi.fn>+ ).mockResolvedValue({+ stagingId: 's1',+ consent: { manifest: { id: 'test.plugin' } },+ committed: false,+ })+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )++ await expect(+ handlers[Commands.InstallPlugin]?.({+ sourceType: 'registry',+ pluginId: 'test.plugin',+ })+ ).resolves.toMatchObject({ stagingId: 's1', committed: false })+ expect(ctx.eventBus.emit).toHaveBeenCalledWith(+ Events.PluginInstallConsentRequested,+ expect.objectContaining({ stagingId: 's1' })+ )+ })++ it('commits consent grants and publishes installation', async () => {+ const ctx = makeFakeCtx()+ ;(ctx.pluginInstaller.commit as ReturnType<typeof vi.fn>).mockResolvedValue(+ { pluginId: 'test.plugin' }+ )+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )++ await expect(+ handlers[Commands.ConfirmPluginInstall]?.({+ stagingId: 's1',+ grants: { notify: 'denied' },+ })+ ).resolves.toEqual({ ok: true, pluginId: 'test.plugin' })+ expect(ctx.pluginInstaller.commit).toHaveBeenCalledWith('s1', {+ notify: 'denied',+ })+ expect(ctx.eventBus.emit).toHaveBeenCalledWith(Events.PluginInstalled, {+ pluginId: 'test.plugin',+ })+ })++ it('cancels staging, updates grants, and uninstalls through the installer', async () => {+ const ctx = makeFakeCtx()+ ;(+ ctx.pluginGrants.updateGrants as ReturnType<typeof vi.fn>+ ).mockResolvedValue({ notify: 'granted' })+ const handlers = buildServerCommandHandlers(+ ctx as Parameters<typeof buildServerCommandHandlers>[0]+ )++ await handlers[Commands.CancelPluginInstall]?.({ stagingId: 's1' })+ await expect(+ handlers[Commands.UpdatePluginGrants]?.({+ pluginId: 'test.plugin',+ patch: { notify: 'granted' },+ })+ ).resolves.toEqual({ ok: true, grants: { notify: 'granted' } })+ await handlers[Commands.UninstallPlugin]?.({ pluginId: 'test.plugin' })++ expect(ctx.pluginInstaller.cancel).toHaveBeenCalledWith('s1')+ expect(ctx.pluginInstaller.uninstall).toHaveBeenCalledWith('test.plugin')+ expect(ctx.settingsManager.removePluginConfig).toHaveBeenCalledWith(+ 'test.plugin'+ )+ expect(ctx.eventBus.emit).toHaveBeenCalledWith(Events.PluginUninstalled, {+ pluginId: 'test.plugin',+ })+ })+})+describe('buildServerCommandHandlers — notification center', () => {let db: MotrixDatabaselet notificationCenter: NotificationCenterdiff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 23f9be99..a0f7c392 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -7,10 +7,13 @@ import type { EventBus } from '@core/events/event-bus'import { getLogger } from '@core/logger'import type { NotificationCenter } from '@core/notifications/notification-center'import type { CapabilityHost } from '@core/plugin/capabilities/interface'+import { pluginSecretFields } from '@core/plugin/configuration-schema'+import type { GrantsManager } from '@core/plugin/grants/grants-manager'import { HookAuditLog } from '@core/plugin/hooks/audit-log'import { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'import type { PluginHost } from '@core/plugin/host/plugin-host'+import type { PluginInstaller } from '@core/plugin/install/plugin-installer'import type { PluginRegistry } from '@core/plugin/plugin-registry'import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'import type { MotrixDatabase } from '@core/session/motrix-database'@@ -54,6 +57,8 @@ import type { DownloadTask } from '@shared/types/task'import type { TaskActivityRecorder } from '@shared/types/task-activity'import type { TaskOccurrence } from '@shared/types/task-occurrence'import { z } from 'zod'+import type { ServerDownloadPathPolicy } from '../download-path-policy'+import type { ServerPluginInstallService } from '../plugin/install-service'import type { createServerProxyApplier } from '../proxy/wiring'export interface ServerCommandContext {@@ -75,6 +80,9 @@ export interface ServerCommandContext {pluginRegistry: PluginRegistrypluginStateStore: PluginStateStorepluginHost: PluginHost+ pluginInstaller: PluginInstaller+ pluginInstallService: ServerPluginInstallService+ pluginGrants: GrantsManagercapabilityHost: CapabilityHostuserDataDir: stringpluginsDir: string@@ -104,6 +112,7 @@ export interface ServerCommandContext {/** Coalesced / immediate TaskUpdated publication (TaskUpdatePublisher). */publishTaskUpdate: TaskActionDeps['publishTaskUpdate']publishTaskUpdateNow: TaskActionDeps['publishTaskUpdateNow']+ downloadPathPolicy: ServerDownloadPathPolicy}export function buildServerCommandHandlers(@@ -127,6 +136,9 @@ export function buildServerCommandHandlers(pluginRegistry,pluginStateStore,pluginHost,+ pluginInstaller,+ pluginInstallService,+ pluginGrants,capabilityHost,userDataDir,pluginsDir,@@ -142,6 +154,7 @@ export function buildServerCommandHandlers(parentTaskCreated: injectedParentTaskCreated,publishTaskUpdate,publishTaskUpdateNow,+ downloadPathPolicy,} = ctxconst persistTask =@@ -199,6 +212,8 @@ export function buildServerCommandHandlers(runTaskMutation,waitForEngineReady: () =>supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),+ prepareSaveDir: (requested: string) =>+ downloadPathPolicy.prepareSaveDir(requested),}const log = getLogger('server:commands')@@ -337,10 +352,10 @@ export function buildServerCommandHandlers(req.selectedFiles.length === 0 &&settingsManager.getApp().magnetFileSelection) {- await magnetTracker.submit(- req.payload.uri,+ const saveDir = await downloadPathPolicy.prepareSaveDir(req.saveDir || settingsManager.getApp().defaultSaveDir)+ await magnetTracker.submit(req.payload.uri, saveDir)return { ok: true }}} else {@@ -351,12 +366,13 @@ export function buildServerCommandHandlers(// instance in place so task identity / Downloads list slot// survive (no duplicate row appears).if (req.payload.kind === 'torrent-base64' && req.existingTaskId) {+ const saveDir = await downloadPathPolicy.prepareSaveDir(req.saveDir)return swapMagnetMetadataForBt({taskId: req.existingTaskId,base64: req.payload.base64,selectedFiles: req.selectedFiles,- saveDir: req.saveDir,+ saveDir,name: req.displayName,},{@@ -461,9 +477,31 @@ export function buildServerCommandHandlers(},[Commands.UpdateSettings]: async (partial: unknown) => {+ const saveDirPatch = z+ .object({+ app: z+ .object({ defaultSaveDir: z.string().optional() })+ .passthrough()+ .optional(),+ })+ .passthrough()+ .safeParse(partial)+ let validatedPartial = partial+ if (+ saveDirPatch.success &&+ saveDirPatch.data.app?.defaultSaveDir !== undefined+ ) {+ const defaultSaveDir = await downloadPathPolicy.prepareSaveDir(+ saveDirPatch.data.app.defaultSaveDir+ )+ validatedPartial = {+ ...saveDirPatch.data,+ app: { ...saveDirPatch.data.app, defaultSaveDir },+ }+ }const oldFull = settingsManager.get()const result = await settingsManager.update(- partial as Parameters<typeof settingsManager.update>[0]+ validatedPartial as Parameters<typeof settingsManager.update>[0])const newFull = settingsManager.get()@@ -561,26 +599,7 @@ export function buildServerCommandHandlers()}- // Walk schema to collect secret-flagged field names.- const schema = indexed.manifest.contributes?.configuration?.schema- const properties =- schema &&- typeof schema === 'object' &&- 'properties' in schema &&- schema.properties &&- typeof schema.properties === 'object'- ? (schema.properties as Record<string, unknown>)- : {}- const secretFields = new Set<string>()- for (const [key, prop] of Object.entries(properties)) {- if (- prop &&- typeof prop === 'object' &&- (prop as { secret?: boolean }).secret === true- ) {- secretFields.add(key)- }- }+ const secretFields = pluginSecretFields(indexed.manifest)// Build effective patch with secrets encrypted.const prior = settingsManager.get().plugins[parsed.pluginId] ?? {}@@ -617,6 +636,76 @@ export function buildServerCommandHandlers(return { ok: true }},+ [Commands.InstallPlugin]: async (payload: unknown) => {+ const result = await pluginInstallService.stage(payload)+ if (result.committed && result.pluginId) {+ eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })+ } else {+ eventBus.emit(Events.PluginInstallConsentRequested, {+ stagingId: result.stagingId,+ consent: result.consent,+ })+ }+ return result+ },++ [Commands.ConfirmPluginInstall]: async (payload: unknown) => {+ const parsed = z+ .object({+ stagingId: z.string().min(1),+ grants: z.record(z.string(), z.enum(['granted', 'denied'])),+ })+ .parse(payload)+ const { pluginId } = await pluginInstaller.commit(+ parsed.stagingId,+ parsed.grants+ )+ eventBus.emit(Events.PluginInstalled, { pluginId })+ return { ok: true, pluginId }+ },++ [Commands.CancelPluginInstall]: async (payload: unknown) => {+ const parsed = z.object({ stagingId: z.string().min(1) }).parse(payload)+ await pluginInstaller.cancel(parsed.stagingId)+ return { ok: true }+ },++ [Commands.UpdatePluginGrants]: async (payload: unknown) => {+ const parsed = z+ .object({+ pluginId: z.string().min(1),+ patch: z.record(z.string(), z.enum(['granted', 'denied'])),+ })+ .parse(payload)+ const grants = await pluginGrants.updateGrants(+ parsed.pluginId,+ parsed.patch+ )+ return { ok: true, grants }+ },++ [Commands.UninstallPlugin]: async (payload: unknown) => {+ const parsed = z.object({ pluginId: z.string().min(1) }).parse(payload)+ await pluginInstaller.uninstall(parsed.pluginId)+ await settingsManager.removePluginConfig(parsed.pluginId)+ eventBus.emit(Events.PluginUninstalled, { pluginId: parsed.pluginId })+ return { ok: true }+ },++ [Commands.ClearPluginLogs]: async (payload: unknown) => {+ const parsed = z.object({ pluginId: z.string().min(1) }).parse(payload)+ capabilityHost.clearLog(parsed.pluginId)+ return { ok: true }+ },++ [Commands.SetPluginLogVerbose]: async (payload: unknown) => {+ const parsed = z+ .object({ pluginId: z.string().min(1), verbose: z.boolean() })+ .parse(payload)+ capabilityHost.setLogVerbose(parsed.pluginId, parsed.verbose)+ return { ok: true }+ },+[Commands.MarkNotificationRead]: async (id: string) =>notificationCenter.markRead(id),diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.tsindex 089e1d5f..e46167ed 100644--- a/src/server/ipc/queries.test.ts+++ b/src/server/ipc/queries.test.ts@@ -121,14 +121,45 @@ function makeCtx(over: Record<string, unknown> = {}) {unreadCount: vi.fn(() => 0),},pluginRegistry: { list: vi.fn(() => []), entries: vi.fn(() => []) },+ pluginGrants: {+ getGrants: vi.fn(async () => ({})),+ listAllGrants: vi.fn(async () => ({})),+ },pluginsDir: '',hostVersion: '2.0',userDataDir: '',speedLimitController: { getState: vi.fn() },+ downloadPathPolicy: {+ allowedSaveDirs: [],+ prepareSaveDir: vi.fn(),+ },...over,}}+describe('buildServerQueryHandlers — allowed save directories', () => {+ it('publishes the validated path policy instead of reparsing the environment', async () => {+ const handlers = buildServerQueryHandlers(+ makeCtx({+ settingsManager: {+ get: vi.fn(() => ({ tracker: { sources: [] } })),+ getApp: vi.fn(() => ({ defaultSaveDir: '/downloads' })),+ },+ downloadPathPolicy: {+ allowedSaveDirs: ['/downloads', '/media'],+ prepareSaveDir: vi.fn(),+ },+ }) as never+ )++ await expect(handlers[Queries.ListAllowedSaveDirs]?.()).resolves.toEqual({+ paths: [{ path: '/downloads' }, { path: '/media' }],+ defaultPath: '/downloads',+ allowCustom: false,+ })+ })+})+describe('buildServerQueryHandlers — GetTransferStats parity', () => {it('exposes CLI installation as an unsupported web query', async () => {const handlers = buildServerQueryHandlers(makeCtx() as never)@@ -330,6 +361,27 @@ describe('buildServerQueryHandlers — notification center', () => {})})+describe('buildServerQueryHandlers — plugin grants', () => {+ it('exposes persisted grants through both query shapes', async () => {+ const pluginGrants = {+ getGrants: vi.fn(async () => ({ notify: 'granted' })),+ listAllGrants: vi.fn(async () => ({+ 'test.plugin': { notify: 'granted' },+ })),+ }+ const handlers = buildServerQueryHandlers(+ makeCtx({ pluginGrants }) as unknown as ServerQueryContext+ )++ await expect(+ handlers[Queries.GetPluginGrants]?.('test.plugin')+ ).resolves.toEqual({ notify: 'granted' })+ await expect(handlers[Queries.ListPluginGrants]?.()).resolves.toEqual({+ 'test.plugin': { notify: 'granted' },+ })+ })+})+describe('GetPluginCommandGraph handler', () => {let pluginsDir: stringdiff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.tsindex 325ccab7..bc61e7d9 100644--- a/src/server/ipc/queries.ts+++ b/src/server/ipc/queries.ts@@ -4,6 +4,7 @@ import type { EngineAdapter } from '@core/engine/engine-adapter'import type { EngineSupervisor } from '@core/engine/engine-supervisor'import type { NotificationCenter } from '@core/notifications/notification-center'import { readCommandGraph } from '@core/plugin/commands/command-graph'+import type { GrantsManager } from '@core/plugin/grants/grants-manager'import type { PluginRegistry } from '@core/plugin/plugin-registry'import {buildContributionIndex,@@ -34,6 +35,7 @@ import {} from '@shared/types/cli-tool'import type { GetTransferStatsParams } from '@shared/types/stats'import type { GetTaskActivityParams } from '@shared/types/task-activity'+import type { ServerDownloadPathPolicy } from '../download-path-policy'import { makeServerFfmpegDetect } from '../plugin/ffmpeg-detect-server'const UNSUPPORTED_WEB_CLI_STATUS: CliToolStatus = {@@ -91,11 +93,13 @@ export interface ServerQueryContext {engineAdapter: EngineAdapternotificationCenter: NotificationCenterpluginRegistry: PluginRegistry+ pluginGrants: GrantsManagerregistryClient: RegistryClientpluginsDir: stringhostVersion: stringuserDataDir: stringspeedLimitController: SpeedLimitController+ downloadPathPolicy: ServerDownloadPathPolicy}export function buildServerQueryHandlers(@@ -115,11 +119,13 @@ export function buildServerQueryHandlers(engineAdapter,notificationCenter,pluginRegistry,+ pluginGrants,registryClient,pluginsDir,hostVersion,userDataDir,speedLimitController,+ downloadPathPolicy,} = ctxconst detectFfmpeg = makeServerFfmpegDetect({@@ -173,12 +179,7 @@ export function buildServerQueryHandlers(settingsManager.get().tracker.sources,[Queries.ListAllowedSaveDirs]: async () => {- const raw = process.env.MOTRIX_ALLOWED_SAVE_DIRS ?? ''- const paths = raw- .split(':')- .map((p) => p.trim())- .filter(Boolean)- .map((path) => ({ path }))+ const paths = downloadPathPolicy.allowedSaveDirs.map((path) => ({ path }))return {paths,defaultPath: settingsManager.getApp().defaultSaveDir,@@ -210,6 +211,11 @@ export function buildServerQueryHandlers([Queries.GetPluginConfig]: async (pluginId: string) =>readPluginConfig(settingsManager.get(), pluginId),+ [Queries.GetPluginGrants]: async (pluginId: string) =>+ pluginGrants.getGrants(pluginId),++ [Queries.ListPluginGrants]: async () => pluginGrants.listAllGrants(),+[Queries.GetContributionIndex]: async () =>buildContributionIndex(pluginRegistry.entries()),diff --git a/src/server/plugin/community-policy.test.ts b/src/server/plugin/community-policy.test.tsnew file mode 100644index 00000000..da89b25e--- /dev/null+++ b/src/server/plugin/community-policy.test.ts@@ -0,0 +1,76 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import {+ createServerCommunityPluginPolicy,+ parseAllowUnmanagedPlugins,+} from './community-policy'++const cleanup: string[] = []++afterEach(async () => {+ await Promise.all(+ cleanup.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))+ )+})++describe('Server community plugin policy', () => {+ it('parses the explicit unmanaged-plugin override strictly', () => {+ expect(parseAllowUnmanagedPlugins(undefined)).toBe(false)+ expect(parseAllowUnmanagedPlugins('true')).toBe(true)+ expect(parseAllowUnmanagedPlugins('0')).toBe(false)+ expect(() => parseAllowUnmanagedPlugins('yes')).toThrow(+ 'MOTRIX_ALLOW_UNMANAGED_PLUGINS'+ )+ })++ it('requires a valid installer record by default', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-policy-'))+ cleanup.push(dir)+ const policy = createServerCommunityPluginPolicy({+ allowUnmanagedPlugins: false,+ })++ await expect(policy(dir)).resolves.toEqual({+ ok: false,+ reason: 'plugin.lifecycle.install_record_required',+ })++ await writeFile(+ path.join(dir, '_install.json'),+ JSON.stringify({+ version: 1,+ pluginId: 'test.plugin',+ source: {+ type: 'local',+ url: `local:${'a'.repeat(64)}`,+ bundleSha256: 'b'.repeat(64),+ recordedAt: 1,+ },+ grants: {},+ consentSnapshot: {+ permissions: [],+ optionalPermissions: [],+ invokesCommands: [],+ publicCommands: {},+ requestedHeapMB: 32,+ enginesMotrix: '>=2.0.0',+ hostPermissions: [],+ },+ })+ )+ await expect(policy(dir)).resolves.toEqual({ ok: true })+ })++ it('allows explicitly managed unpacked plugin directories', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-policy-'))+ cleanup.push(root)+ const dir = path.join(root, 'test.plugin')+ await mkdir(dir)+ const policy = createServerCommunityPluginPolicy({+ allowUnmanagedPlugins: true,+ })+ await expect(policy(dir)).resolves.toEqual({ ok: true })+ })+})diff --git a/src/server/plugin/community-policy.ts b/src/server/plugin/community-policy.tsnew file mode 100644index 00000000..467861e8--- /dev/null+++ b/src/server/plugin/community-policy.ts@@ -0,0 +1,25 @@+import { readInstallRecord } from '@core/plugin/install/install-record'++export interface ServerCommunityPluginPolicyOptions {+ allowUnmanagedPlugins: boolean+}++export function parseAllowUnmanagedPlugins(value: string | undefined): boolean {+ if (value === undefined || value.trim() === '') return false+ const normalized = value.trim().toLowerCase()+ if (normalized === 'true' || normalized === '1') return true+ if (normalized === 'false' || normalized === '0') return false+ throw new Error('MOTRIX_ALLOW_UNMANAGED_PLUGINS must be true, false, 1, or 0')+}++export function createServerCommunityPluginPolicy(+ options: ServerCommunityPluginPolicyOptions+): (pluginDir: string) => Promise<{ ok: boolean; reason?: string }> {+ return async (pluginDir) => {+ if (options.allowUnmanagedPlugins) return { ok: true }+ const record = await readInstallRecord(pluginDir)+ return record+ ? { ok: true }+ : { ok: false, reason: 'plugin.lifecycle.install_record_required' }+ }+}diff --git a/src/server/plugin/install-service.integration.test.ts b/src/server/plugin/install-service.integration.test.tsnew file mode 100644index 00000000..7e6d62a3--- /dev/null+++ b/src/server/plugin/install-service.integration.test.ts@@ -0,0 +1,110 @@+import { createHash } from 'node:crypto'+import { existsSync } from 'node:fs'+import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import type { CapabilityHost } from '@core/plugin/capabilities/interface'+import { PluginInstaller } from '@core/plugin/install/plugin-installer'+import { PluginRegistry } from '@core/plugin/plugin-registry'+import { PluginStateStore } from '@core/plugin/state/plugin-state-store'+import { migrate } from '@core/session/migrations'+import Database from 'better-sqlite3'+import { afterEach, describe, expect, it } from 'vitest'+import { createServerCommunityPluginPolicy } from './community-policy'+import { ServerPluginInstallService } from './install-service'++const fixture = path.resolve(+ 'tests/fixtures/moext/test.demo-config-1.0.0.moext'+)+const cleanup: string[] = []++afterEach(async () => {+ await Promise.all(+ cleanup.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))+ )+})++function capabilityHost(): CapabilityHost {+ return {+ lifecycle: { runDeactivate: async () => undefined },+ storage: { deleteAll: async () => undefined },+ metadata: { deleteAllForPlugin: async () => undefined },+ cookieJarFor: () => ({ clear: () => undefined }),+ } as unknown as CapabilityHost+}++describe('Server plugin install lifecycle integration', () => {+ it('installs, persists enablement across rediscovery, and uninstalls', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-server-plugin-e2e-'))+ cleanup.push(root)+ const pluginsDir = path.join(root, 'plugins')+ const builtinDir = path.join(root, 'builtins')+ await Promise.all([mkdir(pluginsDir), mkdir(builtinDir)])+ const database = new Database(path.join(root, 'motrix.db'))+ migrate(database)+ const stateStore = new PluginStateStore(database)+ const policy = createServerCommunityPluginPolicy({+ allowUnmanagedPlugins: false,+ })+ const registry = new PluginRegistry({+ pluginsDir,+ builtinDir,+ stateStore,+ hostVersion: '2.0.0',+ communityDirectoryPolicy: policy,+ })+ await registry.discover()+ const installer = new PluginInstaller({+ pluginsDir,+ registry,+ stateStore,+ capabilityHost: capabilityHost(),+ hostVersion: '2.0.0',+ })+ const service = new ServerPluginInstallService({+ installer,+ registryClient: {} as never,+ hostVersion: '2.0.0',+ pluginsDir,+ allowedLocalRoots: [path.dirname(fixture)],+ })+ const fileHash = createHash('sha256')+ .update(await readFile(fixture))+ .digest('hex')++ const staged = await service.stage({+ sourceType: 'local',+ absPath: fixture,+ fileHash,+ })+ expect(staged.committed).toBe(false)+ await installer.commit(staged.stagingId, { notify: 'denied' })+ expect(+ existsSync(path.join(pluginsDir, 'test.demo-config', '_install.json'))+ ).toBe(true)+ expect(registry.get('test.demo-config')?.state.enabled).toBe(true)++ stateStore.setEnabled('test.demo-config', false)+ const restartedRegistry = new PluginRegistry({+ pluginsDir,+ builtinDir,+ stateStore: new PluginStateStore(database),+ hostVersion: '2.0.0',+ communityDirectoryPolicy: policy,+ })+ await restartedRegistry.discover()+ expect(restartedRegistry.get('test.demo-config')?.state.enabled).toBe(false)++ const restartedInstaller = new PluginInstaller({+ pluginsDir,+ registry: restartedRegistry,+ stateStore: new PluginStateStore(database),+ capabilityHost: capabilityHost(),+ hostVersion: '2.0.0',+ })+ await restartedInstaller.uninstall('test.demo-config')+ expect(restartedRegistry.get('test.demo-config')).toBeUndefined()+ expect(existsSync(path.join(pluginsDir, 'test.demo-config'))).toBe(false)+ database.close()+ })+})diff --git a/src/server/plugin/install-service.test.ts b/src/server/plugin/install-service.test.tsnew file mode 100644index 00000000..14e9466b--- /dev/null+++ b/src/server/plugin/install-service.test.ts@@ -0,0 +1,141 @@+import {+ mkdir,+ mkdtemp,+ readdir,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ServerPluginInstallService } from './install-service'++let root: string+let pluginsDir: string+let incomingDir: string++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'motrix-server-install-'))+ pluginsDir = path.join(root, 'plugins')+ incomingDir = path.join(root, 'incoming')+ await Promise.all([mkdir(pluginsDir), mkdir(incomingDir)])+})++afterEach(async () => {+ await rm(root, { recursive: true, force: true })+})++function makeService(overrides: Record<string, unknown> = {}) {+ const stage = vi.fn(+ async (_moextPath: string, _source: unknown, _options: unknown) => ({+ stagingId: 's1',+ consent: {} as never,+ committed: false,+ })+ )+ const service = new ServerPluginInstallService({+ installer: { stage } as never,+ registryClient: { get: vi.fn() } as never,+ hostVersion: '2.0.0',+ pluginsDir,+ allowedLocalRoots: [incomingDir],+ ...overrides,+ })+ return { service, stage }+}++describe('ServerPluginInstallService', () => {+ it('accepts a local package only from an allowed import root', async () => {+ const packagePath = path.join(incomingDir, 'fixture.moext')+ await writeFile(packagePath, 'fixture')+ const { service, stage } = makeService()+ const canonicalPackagePath = await realpath(packagePath)++ await service.stage({+ sourceType: 'local',+ absPath: packagePath,+ fileHash: 'a'.repeat(64),+ })++ expect(stage).toHaveBeenCalledWith(+ canonicalPackagePath,+ {+ type: 'local',+ absPath: canonicalPackagePath,+ fileHash: 'a'.repeat(64),+ },+ { expect: undefined }+ )+ })++ it('rejects local paths outside the configured import roots', async () => {+ const packagePath = path.join(root, 'outside.moext')+ await writeFile(packagePath, 'fixture')+ const { service } = makeService()++ await expect(+ service.stage({+ sourceType: 'local',+ absPath: packagePath,+ fileHash: 'a'.repeat(64),+ })+ ).rejects.toMatchObject({+ message: 'plugin.install.local_path_not_allowed',+ })+ })++ it('resolves an opaque upload reference and removes it after staging', async () => {+ const uploadedPath = path.join(pluginsDir, '_uploads', 'u.moext')+ await mkdir(path.dirname(uploadedPath), { recursive: true })+ await writeFile(uploadedPath, 'fixture')+ const uploadStore = {+ resolve: vi.fn(async () => uploadedPath),+ }+ const { service, stage } = makeService({ uploadStore })++ await service.stage({+ sourceType: 'upload',+ uploadId: '123e4567-e89b-42d3-a456-426614174000',+ fileHash: 'a'.repeat(64),+ })++ expect(uploadStore.resolve).toHaveBeenCalledWith(+ '123e4567-e89b-42d3-a456-426614174000',+ 'a'.repeat(64)+ )+ expect(stage).toHaveBeenCalledWith(+ uploadedPath,+ expect.objectContaining({ type: 'local', fileHash: 'a'.repeat(64) }),+ { expect: undefined }+ )+ await expect(readdir(path.dirname(uploadedPath))).resolves.toEqual([])+ })++ it('downloads a URL package into the persistent work root and cleans it after staging', async () => {+ const fetchImpl = vi.fn(async () =>+ Promise.resolve(new Response('plugin-bytes', { status: 200 }))+ ) as unknown as typeof fetch+ const { service, stage } = makeService({ fetchImpl })++ await service.stage({+ sourceType: 'url',+ url: 'https://plugins.example/test.moext',+ })++ const stagedPath = stage.mock.calls[0]?.[0] as string+ expect(stagedPath).toContain(path.join(pluginsDir, '_downloads'))+ await expect(readdir(path.join(pluginsDir, '_downloads'))).resolves.toEqual(+ []+ )+ })++ it('rejects non-http URL sources before fetching', async () => {+ const fetchImpl = vi.fn() as unknown as typeof fetch+ const { service } = makeService({ fetchImpl })+ await expect(+ service.stage({ sourceType: 'url', url: 'file:///tmp/plugin.moext' })+ ).rejects.toMatchObject({ message: 'plugin.install.invalid_url' })+ expect(fetchImpl).not.toHaveBeenCalled()+ })+})diff --git a/src/server/plugin/install-service.ts b/src/server/plugin/install-service.tsnew file mode 100644index 00000000..a3440413--- /dev/null+++ b/src/server/plugin/install-service.ts@@ -0,0 +1,291 @@+import { randomUUID } from 'node:crypto'+import { mkdir, realpath, rm, stat, writeFile } from 'node:fs/promises'+import path from 'node:path'+import {+ downloadGithubMoext,+ parseGithubSpec,+} from '@core/plugin/install/github-fetcher'+import type {+ PluginInstaller,+ StageResult,+} from '@core/plugin/install/plugin-installer'+import {+ buildRegistryExpectation,+ type RegistryExpectation,+} from '@core/plugin/install/registry-expectation'+import type { SourceInput } from '@core/plugin/install/source-resolver'+import type { RegistryClient } from '@core/plugin/registry/registry-client'+import { downloadRegistryMoext } from '@core/plugin/registry/registry-fetcher'+import { AppError, ErrorCode } from '@shared/errors'+import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'+import { z } from 'zod'+import type { PluginUploadStore } from './upload-store'++const MAX_PLUGIN_PACKAGE_BYTES = 5 * 1024 * 1024++export const serverInstallPluginPayloadSchema = z.discriminatedUnion(+ 'sourceType',+ [+ z.object({ sourceType: z.literal('github'), spec: z.string().min(1) }),+ z.object({ sourceType: z.literal('url'), url: z.string().min(1) }),+ z.object({+ sourceType: z.literal('local'),+ absPath: z.string().min(1),+ fileHash: z.string().regex(/^[0-9a-f]{64}$/),+ }),+ z.object({+ sourceType: z.literal('upload'),+ uploadId: z.string().uuid(),+ fileHash: z.string().regex(/^[0-9a-f]{64}$/),+ }),+ z.object({+ sourceType: z.literal('registry'),+ pluginId: z.string().regex(REGISTRY_PLUGIN_ID_RE),+ }),+ ]+)++export type ServerInstallPluginPayload = z.infer<+ typeof serverInstallPluginPayloadSchema+>++export interface ServerPluginInstallServiceOptions {+ installer: PluginInstaller+ registryClient: RegistryClient+ hostVersion: string+ pluginsDir: string+ allowedLocalRoots?: readonly string[]+ uploadStore?: PluginUploadStore+ fetchImpl?: typeof fetch+}++function pathIsInside(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate)+ return (+ relative === '' ||+ (relative !== '..' &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative))+ )+}++async function readResponseBounded(response: Response): Promise<Buffer> {+ const declaredLength = Number(response.headers.get('content-length'))+ if (+ Number.isFinite(declaredLength) &&+ declaredLength > MAX_PLUGIN_PACKAGE_BYTES+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.package_too_large'+ )+ }+ if (!response.body) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.url_download_failed: empty body'+ )+ }++ const chunks: Uint8Array[] = []+ let total = 0+ const reader = response.body.getReader()+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ total += value.byteLength+ if (total > MAX_PLUGIN_PACKAGE_BYTES) {+ await reader.cancel()+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.package_too_large'+ )+ }+ chunks.push(value)+ }+ return Buffer.concat(chunks, total)+}++export class ServerPluginInstallService {+ private readonly downloadsDir: string+ private readonly allowedLocalRoots: readonly string[]+ private readonly fetchImpl: typeof fetch++ constructor(private readonly options: ServerPluginInstallServiceOptions) {+ this.downloadsDir = path.join(options.pluginsDir, '_downloads')+ this.allowedLocalRoots = [+ path.join(options.pluginsDir, '_uploads'),+ ...(options.allowedLocalRoots ?? []),+ ].map((root) => path.resolve(root))+ this.fetchImpl = options.fetchImpl ?? fetch+ }++ async stage(rawPayload: unknown): Promise<StageResult> {+ const payload = serverInstallPluginPayloadSchema.parse(rawPayload)+ const materialized = await this.materialize(payload)+ try {+ return await this.options.installer.stage(+ materialized.moextPath,+ materialized.source,+ { expect: materialized.expect }+ )+ } finally {+ if (materialized.temporary) {+ await rm(materialized.moextPath, { force: true }).catch(() => undefined)+ }+ }+ }++ private async materialize(payload: ServerInstallPluginPayload): Promise<{+ moextPath: string+ source: SourceInput+ expect?: RegistryExpectation+ temporary: boolean+ }> {+ await mkdir(this.downloadsDir, { recursive: true })+ switch (payload.sourceType) {+ case 'github': {+ const spec = parseGithubSpec(payload.spec)+ const target = this.downloadPath('github')+ await downloadGithubMoext(spec, target)+ return {+ moextPath: target,+ source: { type: 'github', spec: payload.spec },+ temporary: true,+ }+ }+ case 'url': {+ const url = this.parseHttpUrl(payload.url)+ const response = await this.fetchImpl(url, { redirect: 'follow' })+ if (!response.ok) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ `plugin.install.url_download_failed: ${response.status}`+ )+ }+ const target = this.downloadPath('url')+ await writeFile(target, await readResponseBounded(response), {+ mode: 0o600,+ })+ return {+ moextPath: target,+ source: { type: 'url', url: payload.url },+ temporary: true,+ }+ }+ case 'local': {+ const moextPath = await this.resolveAllowedLocalPath(payload.absPath)+ return {+ moextPath,+ source: {+ type: 'local',+ absPath: moextPath,+ fileHash: payload.fileHash,+ },+ temporary: false,+ }+ }+ case 'upload': {+ if (!this.options.uploadStore) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_unavailable'+ )+ }+ const moextPath = await this.options.uploadStore.resolve(+ payload.uploadId,+ payload.fileHash+ )+ return {+ moextPath,+ source: {+ type: 'local',+ absPath: moextPath,+ fileHash: payload.fileHash,+ },+ temporary: true,+ }+ }+ case 'registry': {+ const entry = await this.options.registryClient.get(+ payload.pluginId,+ this.options.hostVersion+ )+ if (!entry) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.registry_entry_missing'+ )+ }+ if (!entry.compatible) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.registry_incompatible'+ )+ }+ const target = this.downloadPath('registry')+ await downloadRegistryMoext(entry, target, this.fetchImpl)+ return {+ moextPath: target,+ source: { type: 'registry', pluginId: payload.pluginId },+ expect: buildRegistryExpectation(entry),+ temporary: true,+ }+ }+ }+ }++ private downloadPath(kind: string): string {+ return path.join(this.downloadsDir, `${kind}-${randomUUID()}.moext`)+ }++ private parseHttpUrl(raw: string): URL {+ let url: URL+ try {+ url = new URL(raw)+ } catch {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.invalid_url'+ )+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.invalid_url'+ )+ }+ return url+ }++ private async resolveAllowedLocalPath(rawPath: string): Promise<string> {+ if (!path.isAbsolute(rawPath)) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_path_must_be_absolute'+ )+ }+ let candidate: string+ try {+ candidate = await realpath(rawPath)+ const info = await stat(candidate)+ if (!info.isFile()) throw new Error('not a regular file')+ } catch (cause) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_file_unreadable',+ cause+ )+ }+ const roots = await Promise.all(+ this.allowedLocalRoots.map((root) => realpath(root).catch(() => root))+ )+ if (!roots.some((root) => pathIsInside(root, candidate))) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_path_not_allowed'+ )+ }+ return candidate+ }+}diff --git a/src/server/plugin/plugins-dir.test.ts b/src/server/plugin/plugins-dir.test.tsnew file mode 100644index 00000000..64537b4a--- /dev/null+++ b/src/server/plugin/plugins-dir.test.ts@@ -0,0 +1,74 @@+import {+ chmod,+ mkdir,+ mkdtemp,+ realpath,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { resolveServerPluginsDir } from './plugins-dir'++const cleanup: string[] = []++afterEach(async () => {+ for (const dir of cleanup.splice(0)) {+ await chmod(dir, 0o700).catch(() => undefined)+ await rm(dir, { recursive: true, force: true })+ }+})++describe('resolveServerPluginsDir', () => {+ it('creates the persistent plugin working directories', async () => {+ const dataDir = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-dir-'))+ cleanup.push(dataDir)+ const result = await resolveServerPluginsDir(dataDir, {})++ expect(result.pluginsDir).toBe(path.join(dataDir, 'plugins'))+ expect(result.pluginImportRoots).toEqual([])+ await expect(+ Promise.all(+ ['_downloads', '_logs', '_staging', '_uploads'].map((name) =>+ stat(path.join(result.pluginsDir, name))+ )+ )+ ).resolves.toHaveLength(4)+ })++ it('removes abandoned package and extraction staging at startup', async () => {+ const dataDir = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-dir-'))+ cleanup.push(dataDir)+ const stale = path.join(dataDir, 'plugins', '_staging', 'abandoned')+ await mkdir(stale, { recursive: true })+ await writeFile(path.join(stale, 'partial'), 'partial')++ const result = await resolveServerPluginsDir(dataDir, {})++ await expect(stat(stale)).rejects.toMatchObject({ code: 'ENOENT' })+ await expect(+ stat(path.join(result.pluginsDir, '_staging'))+ ).resolves.toBeDefined()+ })++ it('rejects relative configured directories', async () => {+ const dataDir = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-dir-'))+ cleanup.push(dataDir)+ await expect(+ resolveServerPluginsDir(dataDir, { MOTRIX_PLUGIN_DIR: 'plugins' })+ ).rejects.toThrow('MOTRIX_PLUGIN_DIR must be an absolute path')+ })++ it('resolves existing import roots', async () => {+ const dataDir = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-dir-'))+ cleanup.push(dataDir)+ const incoming = path.join(dataDir, 'incoming')+ await mkdir(incoming)+ const result = await resolveServerPluginsDir(dataDir, {+ MOTRIX_PLUGIN_IMPORT_DIRS: incoming,+ })+ expect(result.pluginImportRoots).toEqual([await realpath(incoming)])+ })+})diff --git a/src/server/plugin/plugins-dir.ts b/src/server/plugin/plugins-dir.tsindex 7cac8d38..1218aae4 100644--- a/src/server/plugin/plugins-dir.ts+++ b/src/server/plugin/plugins-dir.ts@@ -1,15 +1,89 @@-import { mkdir } from 'node:fs/promises'+import { mkdir, open, realpath, rm, stat, unlink } from 'node:fs/promises'import path from 'node:path'-export async function resolveServerPluginsDir(userDataDir: string): Promise<{+interface ServerPluginDirectoryEnvironment {+ MOTRIX_PLUGIN_DIR?: string+ MOTRIX_BUILTIN_PLUGIN_DIR?: string+ MOTRIX_PLUGIN_IMPORT_DIRS?: string+}++function absolutePath(value: string, label: string): string {+ const trimmed = value.trim()+ if (!path.isAbsolute(trimmed)) {+ throw new Error(`${label} must be an absolute path`)+ }+ return path.resolve(trimmed)+}++async function requireWritableDirectory(dir: string): Promise<void> {+ await mkdir(dir, { recursive: true })+ const probe = path.join(+ dir,+ `.motrix-plugin-write-test-${process.pid}-${Date.now()}`+ )+ let handle: Awaited<ReturnType<typeof open>> | undefined+ try {+ handle = await open(probe, 'wx', 0o600)+ await handle.close()+ handle = undefined+ await unlink(probe)+ } catch (cause) {+ await handle?.close().catch(() => undefined)+ await unlink(probe).catch(() => undefined)+ throw new Error(`Plugin directory is not writable: ${dir}`, {+ cause,+ })+ }+}++async function resolveImportRoots(raw: string | undefined): Promise<string[]> {+ if (!raw?.trim()) return []+ const roots: string[] = []+ for (const value of raw.split(path.delimiter)) {+ if (!value.trim()) continue+ const configured = absolutePath(value, 'MOTRIX_PLUGIN_IMPORT_DIRS entry')+ const info = await stat(configured).catch((cause) => {+ throw new Error(`Plugin import directory is unavailable: ${configured}`, {+ cause,+ })+ })+ if (!info.isDirectory()) {+ throw new Error(`Plugin import path is not a directory: ${configured}`)+ }+ roots.push(await realpath(configured))+ }+ return [...new Set(roots)]+}++export async function resolveServerPluginsDir(+ userDataDir: string,+ env: ServerPluginDirectoryEnvironment = process.env+): Promise<{pluginsDir: stringbuiltinDir: string+ pluginImportRoots: readonly string[]}> {- const pluginsDir =- process.env.MOTRIX_PLUGIN_DIR ?? path.join(userDataDir, 'plugins')- await mkdir(pluginsDir, { recursive: true })- const builtinDir =- process.env.MOTRIX_BUILTIN_PLUGIN_DIR ??- path.join(userDataDir, 'builtin-plugins')- return { pluginsDir, builtinDir }+ const pluginsDir = absolutePath(+ env.MOTRIX_PLUGIN_DIR ?? path.join(userDataDir, 'plugins'),+ env.MOTRIX_PLUGIN_DIR ? 'MOTRIX_PLUGIN_DIR' : 'Server plugin directory'+ )+ await requireWritableDirectory(pluginsDir)+ await Promise.all(+ ['_downloads', '_staging', '_uploads'].map(async (name) => {+ const transientDir = path.join(pluginsDir, name)+ await rm(transientDir, { recursive: true, force: true })+ await requireWritableDirectory(transientDir)+ })+ )+ await requireWritableDirectory(path.join(pluginsDir, '_logs'))+ const builtinDir = absolutePath(+ env.MOTRIX_BUILTIN_PLUGIN_DIR ?? path.join(userDataDir, 'builtin-plugins'),+ env.MOTRIX_BUILTIN_PLUGIN_DIR+ ? 'MOTRIX_BUILTIN_PLUGIN_DIR'+ : 'Server builtin plugin directory'+ )+ const pluginImportRoots = await resolveImportRoots(+ env.MOTRIX_PLUGIN_IMPORT_DIRS+ )+ return { pluginsDir, builtinDir, pluginImportRoots }}diff --git a/src/server/plugin/server-bootstrap-installer.test.ts b/src/server/plugin/server-bootstrap-installer.test.tsindex 0237eba3..8f5fcb98 100644--- a/src/server/plugin/server-bootstrap-installer.test.ts+++ b/src/server/plugin/server-bootstrap-installer.test.ts@@ -1,168 +1,109 @@-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import path from 'node:path'-import type { PluginInstaller } from '@core/plugin/install/plugin-installer'-import type { InstallRecord } from '@shared/types/plugin-install'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { serverBootstrapInstall } from './server-bootstrap-installer'-let tmp: string-let pluginsDir: string--beforeEach(async () => {- tmp = await mkdtemp(path.join(tmpdir(), 'motrix-srv-bootstrap-'))- pluginsDir = path.join(tmp, 'plugins')- await mkdir(pluginsDir, { recursive: true })-})--afterEach(async () => {- await rm(tmp, { recursive: true, force: true })-})--function stubInstaller(): PluginInstaller {- return {- stage: vi.fn().mockResolvedValue({- stagingId: 'sx',- consent: {} as never,- }),- } as unknown as PluginInstaller-}--function makeRecord(id: string, sourceUrl: string): InstallRecord {- return {- version: 1,- pluginId: id,- source: {- type: 'github',- url: sourceUrl,- bundleSha256: 'a'.repeat(64),- recordedAt: 0,- },- grants: {},- consentSnapshot: {- permissions: [],- optionalPermissions: [],- invokesCommands: [],- publicCommands: {},- requestedHeapMB: 32,- enginesMotrix: '^2.0.0',- hostPermissions: [],- },- }+const consent = {+ trustSurface: {+ optionalPermissions: [{ name: 'notify' }, { name: 'ffmpeg' }],+ },}describe('serverBootstrapInstall', () => {- it('returns {accepted:[], rejected:[]} when pluginsDir is missing', async () => {- const installer = stubInstaller()- const result = await serverBootstrapInstall(- installer,- path.join(tmp, 'does-not-exist'),- {},- { blanketBypass: false }- )- expect(result).toEqual({ accepted: [], rejected: [] })- })-- it('accepts a volume-mounted plugin whose source URL is on the allowlist', async () => {- const dir = path.join(pluginsDir, 'example.widget')- await mkdir(dir, { recursive: true })- const rec = makeRecord(- 'example.widget',- 'https://github.com/example/widget'- )- await writeFile(- path.join(dir, '_install.json'),- JSON.stringify(rec, null, 2)- )-- const result = await serverBootstrapInstall(- stubInstaller(),- pluginsDir,- { MOTRIX_PLUGIN_ALLOWLIST: 'https://github.com/example' },- { blanketBypass: false }- )- expect(result.accepted).toContain('example.widget')- expect(result.rejected).toEqual([])+ it('returns an empty result when no declarative sources are configured', async () => {+ const service = { stage: vi.fn() }+ const installer = { commit: vi.fn() }+ await expect(+ serverBootstrapInstall(service as never, installer as never, {})+ ).resolves.toEqual({ accepted: [], rejected: [] })})- it('rejects a volume-mounted plugin missing an install record under default policy', async () => {- const dir = path.join(pluginsDir, 'shady.plugin')- await mkdir(dir, { recursive: true })- const result = await serverBootstrapInstall(- stubInstaller(),- pluginsDir,- {},- { blanketBypass: false }- )- expect(result.rejected).toEqual([- { id: 'shady.plugin', reason: 'plugin.lifecycle.unsigned_not_allowed' },- ])- expect(result.accepted).toEqual([])- })+ it('routes GitHub, registry, and URL sources through the install service', async () => {+ const service = {+ stage: vi+ .fn()+ .mockResolvedValueOnce({+ stagingId: 's1',+ consent,+ committed: false,+ })+ .mockResolvedValueOnce({+ stagingId: 's2',+ consent,+ committed: true,+ pluginId: 'registry.plugin',+ })+ .mockResolvedValueOnce({+ stagingId: 's3',+ consent,+ committed: false,+ }),+ }+ const installer = {+ commit: vi+ .fn()+ .mockResolvedValueOnce({ pluginId: 'github.plugin' })+ .mockResolvedValueOnce({ pluginId: 'url.plugin' }),+ }- it('accepts everything under --allow-unsigned-plugins blanket bypass', async () => {- const dir = path.join(pluginsDir, 'shady.plugin')- await mkdir(dir, { recursive: true })const result = await serverBootstrapInstall(- stubInstaller(),- pluginsDir,- {},- { blanketBypass: true }+ service as never,+ installer as never,+ {+ MOTRIX_PLUGIN_INSTALL_URLS:+ 'github:acme/widget,registry:acme.registry,https://example.com/widget.moext',+ })- expect(result.accepted).toEqual(['shady.plugin'])- expect(result.rejected).toEqual([])- })- it('skips entries prefixed with _ (staging, downloads)', async () => {- await mkdir(path.join(pluginsDir, '_staging'), { recursive: true })- await mkdir(path.join(pluginsDir, '_dl'), { recursive: true })- const result = await serverBootstrapInstall(- stubInstaller(),- pluginsDir,- {},- { blanketBypass: true }- )- expect(result.accepted).toEqual([])- expect(result.rejected).toEqual([])+ expect(service.stage).toHaveBeenNthCalledWith(1, {+ sourceType: 'github',+ spec: 'acme/widget',+ })+ expect(service.stage).toHaveBeenNthCalledWith(2, {+ sourceType: 'registry',+ pluginId: 'acme.registry',+ })+ expect(service.stage).toHaveBeenNthCalledWith(3, {+ sourceType: 'url',+ url: 'https://example.com/widget.moext',+ })+ expect(installer.commit).toHaveBeenNthCalledWith(1, 's1', {+ notify: 'denied',+ ffmpeg: 'denied',+ })+ expect(installer.commit).toHaveBeenCalledTimes(2)+ expect(result).toEqual({+ accepted: ['github.plugin', 'registry.plugin', 'url.plugin'],+ rejected: [],+ })})- it('rejects an env URL that is neither github: nor a .moext URL', async () => {- const result = await serverBootstrapInstall(- stubInstaller(),- pluginsDir,- { MOTRIX_PLUGIN_INSTALL_URLS: 'https://example.com/index.html' },- { blanketBypass: false }- )- expect(result.rejected).toEqual([- {- id: 'https://example.com/index.html',- reason: 'plugin.install.invalid_env_url',- },- ])- })+ it('reports every rejected source without hiding successful installs', async () => {+ const service = {+ stage: vi+ .fn()+ .mockRejectedValueOnce(new Error('download failed'))+ .mockResolvedValueOnce({+ stagingId: 's2',+ consent,+ committed: false,+ }),+ }+ const installer = {+ commit: vi.fn().mockResolvedValue({ pluginId: 'good.plugin' }),+ }- it('threads a github: env URL through stage() unattended', async () => {- const installer = stubInstaller()- // Bypass the actual download by mocking github-fetcher.- const { downloadGithubMoext } = await import(- '@core/plugin/install/github-fetcher'- )- vi.spyOn(- { downloadGithubMoext } as {- downloadGithubMoext: typeof downloadGithubMoext- },- 'downloadGithubMoext'- ).mockResolvedValue({ tag: 'v1', assetName: 'x.moext' })- // Note: we can't easily intercept the dynamic import; instead, accept that- // the test will reject when the download fails. We assert the env URL is- // attempted (i.e. ended up in rejected) — proves the dispatcher routes it.- const result = await serverBootstrapInstall(- installer,- pluginsDir,- { MOTRIX_PLUGIN_INSTALL_URLS: 'github:acme/widget' },- { blanketBypass: false }- )- const ids = [...result.accepted, ...result.rejected.map((r) => r.id)]- expect(ids).toContain('github:acme/widget')+ await expect(+ serverBootstrapInstall(service as never, installer as never, {+ MOTRIX_PLUGIN_INSTALL_URLS:+ '["https://bad.example/a.moext","https://good.example/b.moext"]',+ })+ ).resolves.toEqual({+ accepted: ['good.plugin'],+ rejected: [+ {+ source: 'https://bad.example/a.moext',+ reason: 'download failed',+ },+ ],+ })})})diff --git a/src/server/plugin/server-bootstrap-installer.ts b/src/server/plugin/server-bootstrap-installer.tsindex 1a109b99..425a769d 100644--- a/src/server/plugin/server-bootstrap-installer.ts+++ b/src/server/plugin/server-bootstrap-installer.ts@@ -1,117 +1,63 @@-// Server-runtime bootstrap install path (I27).-//-// Runs once at server startup. Two install vectors:-//-// 1. `MOTRIX_PLUGIN_INSTALL_URLS` — comma- or JSON-array-of- declarative-// install specs (github: or https://) the operator wants applied at boot.-// Each entry is fetched, staged, and committed unattended (operator-// already consented by setting the env var).-//-// 2. Volume-mounted plugin dirs already on disk under `pluginsDir`. Each-// directory is checked against `isServerAckSatisfied` (existing-// `_install.json` OR allowlist hit OR blanket bypass). Mismatched dirs-// are rejected and reported; they do NOT get registered.-//-// Default is fail-closed.--import { readdir } from 'node:fs/promises'-import path from 'node:path'-import {- downloadGithubMoext,- parseGithubSpec,-} from '@core/plugin/install/github-fetcher'-import { readInstallRecord } from '@core/plugin/install/install-record'import type { PluginInstaller } from '@core/plugin/install/plugin-installer'-import {- isServerAckSatisfied,- parseAllowlist,-} from '@core/plugin/install/server-ack'-import type {- InstallRecord,- InstallSourceType,-} from '@shared/types/plugin-install'+import { parseAllowlist } from '@core/plugin/install/server-ack'+import type { GrantsMap } from '@shared/types/plugin-install'+import type { ServerPluginInstallService } from './install-service'export interface BootstrapInstallResult {accepted: string[]- rejected: Array<{ id: string; reason: string }>+ rejected: Array<{ source: string; reason: string }>}export interface ServerBootstrapEnv {- MOTRIX_PLUGIN_ALLOWLIST?: stringMOTRIX_PLUGIN_INSTALL_URLS?: string}-export interface ServerBootstrapFlags {- blanketBypass: boolean+function installPayload(source: string): unknown {+ if (source.startsWith('github:')) {+ return { sourceType: 'github', spec: source.slice('github:'.length) }+ }+ if (source.startsWith('registry:')) {+ return {+ sourceType: 'registry',+ pluginId: source.slice('registry:'.length),+ }+ }+ return { sourceType: 'url', url: source }}+/**+ * Reconciles explicit startup install sources before plugin activation.+ * Setting the environment variable is the operator consent boundary; required+ * permissions are inherent and optional permissions start denied.+ */export async function serverBootstrapInstall(- installer: PluginInstaller,- pluginsDir: string,- env: ServerBootstrapEnv,- flags: ServerBootstrapFlags+ service: Pick<ServerPluginInstallService, 'stage'>,+ installer: Pick<PluginInstaller, 'commit'>,+ env: ServerBootstrapEnv): Promise<BootstrapInstallResult> {- const ackCtx = {- allowlist: parseAllowlist(env.MOTRIX_PLUGIN_ALLOWLIST),- blanketBypass: flags.blanketBypass,- }const accepted: string[] = []const rejected: BootstrapInstallResult['rejected'] = []-- // 1) declarative install: env URLs- const urls = parseAllowlist(env.MOTRIX_PLUGIN_INSTALL_URLS)- for (const url of urls) {+ for (const source of parseAllowlist(env.MOTRIX_PLUGIN_INSTALL_URLS)) {try {- let moextPath: string- if (url.startsWith('github:')) {- const spec = parseGithubSpec(url.slice('github:'.length))- moextPath = path.join(- pluginsDir,- '_dl',- `${spec.owner}-${spec.repo}-${Date.now()}.moext`- )- await downloadGithubMoext(spec, moextPath)- } else if (url.endsWith('.moext')) {- moextPath = url- } else {- rejected.push({ id: url, reason: 'plugin.install.invalid_env_url' })+ const staged = await service.stage(installPayload(source))+ if (staged.committed && staged.pluginId) {+ accepted.push(staged.pluginId)continue}- await installer.stage(moextPath, { type: 'env', url })- accepted.push(url)- } catch (e) {- rejected.push({ id: url, reason: (e as Error).message })- }- }-- // 2) volume-mounted plugins (existing dirs under pluginsDir)- let entries: string[] = []- try {- entries = await readdir(pluginsDir)- } catch {- // pluginsDir does not exist — nothing mounted, fine.- return { accepted, rejected }- }- for (const id of entries) {- if (id.startsWith('_')) continue // skip _staging, _dl- const dir = path.join(pluginsDir, id)- const rec = await readInstallRecord(dir)- const source: InstallRecord['source'] = rec?.source ?? {- type: 'volume' as InstallSourceType,- url: `volume:${dir}`,- bundleSha256: '0'.repeat(64),- recordedAt: 0,- }- const ack = isServerAckSatisfied(source, rec, ackCtx)- if (!ack.ok) {+ const grants: GrantsMap = Object.fromEntries(+ staged.consent.trustSurface.optionalPermissions.map(({ name }) => [+ name,+ 'denied',+ ])+ )+ const committed = await installer.commit(staged.stagingId, grants)+ accepted.push(committed.pluginId)+ } catch (cause) {rejected.push({- id,- reason: ack.reason ?? 'plugin.lifecycle.unsigned_not_allowed',+ source,+ reason: cause instanceof Error ? cause.message : String(cause),})- } else {- accepted.push(id)}}-return { accepted, rejected }}diff --git a/src/server/plugin/upload-store.test.ts b/src/server/plugin/upload-store.test.tsnew file mode 100644index 00000000..c72f7a41--- /dev/null+++ b/src/server/plugin/upload-store.test.ts@@ -0,0 +1,54 @@+import { createHash } from 'node:crypto'+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { PluginUploadStore } from './upload-store'++let root: string+let store: PluginUploadStore++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-upload-'))+ store = new PluginUploadStore(root)+})++afterEach(async () => {+ await rm(root, { recursive: true, force: true })+})++describe('PluginUploadStore', () => {+ it('stores an opaque reference and verifies it again on resolve', async () => {+ const bytes = Buffer.from('plugin bytes')+ const fileHash = createHash('sha256').update(bytes).digest('hex')+ const reference = await store.put(bytes, fileHash, 'test.moext')++ const resolved = await store.resolve(reference.uploadId, fileHash)+ await expect(readFile(resolved)).resolves.toEqual(bytes)+ await store.remove(reference.uploadId)+ await expect(+ store.resolve(reference.uploadId, fileHash)+ ).rejects.toMatchObject({ message: 'plugin.install.upload_not_found' })+ })++ it('rejects a mismatched hash and a non-moext filename', async () => {+ const bytes = Buffer.from('plugin bytes')+ await expect(+ store.put(bytes, '0'.repeat(64), 'test.moext')+ ).rejects.toMatchObject({+ message: 'plugin.install.local_file_hash_mismatch',+ })+ const fileHash = createHash('sha256').update(bytes).digest('hex')+ await expect(store.put(bytes, fileHash, 'test.zip')).rejects.toMatchObject({+ message: 'plugin.install.upload_extension_invalid',+ })+ })++ it('rejects traversal-shaped upload identifiers', async () => {+ await expect(+ store.resolve('../../etc/passwd', '0'.repeat(64))+ ).rejects.toMatchObject({+ message: 'plugin.install.upload_reference_invalid',+ })+ })+})diff --git a/src/server/plugin/upload-store.ts b/src/server/plugin/upload-store.tsnew file mode 100644index 00000000..2c70b8b2--- /dev/null+++ b/src/server/plugin/upload-store.ts@@ -0,0 +1,93 @@+import { createHash, randomUUID } from 'node:crypto'+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'+import path from 'node:path'+import { AppError, ErrorCode } from '@shared/errors'++export const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024+const SHA256_RE = /^[0-9a-f]{64}$/+const UPLOAD_ID_RE =+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/++function sha256(bytes: Uint8Array): string {+ return createHash('sha256').update(bytes).digest('hex')+}++export interface PluginUploadReference {+ uploadId: string+ fileHash: string+}++export class PluginUploadStore {+ constructor(private readonly uploadsDir: string) {}++ async put(+ bytes: Buffer,+ claimedHash: string,+ originalName: string+ ): Promise<PluginUploadReference> {+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_PLUGIN_UPLOAD_BYTES) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_size_invalid'+ )+ }+ if (!originalName.toLowerCase().endsWith('.moext')) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_extension_invalid'+ )+ }+ const fileHash = sha256(bytes)+ if (!SHA256_RE.test(claimedHash) || claimedHash !== fileHash) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_file_hash_mismatch'+ )+ }+ await mkdir(this.uploadsDir, { recursive: true })+ const uploadId = randomUUID()+ await writeFile(this.pathFor(uploadId), bytes, {+ flag: 'wx',+ mode: 0o600,+ })+ return { uploadId, fileHash }+ }++ async resolve(uploadId: string, expectedHash: string): Promise<string> {+ if (!UPLOAD_ID_RE.test(uploadId) || !SHA256_RE.test(expectedHash)) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_reference_invalid'+ )+ }+ let bytes: Buffer+ try {+ bytes = await readFile(this.pathFor(uploadId))+ } catch (cause) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_not_found',+ cause+ )+ }+ if (+ bytes.byteLength > MAX_PLUGIN_UPLOAD_BYTES ||+ sha256(bytes) !== expectedHash+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_file_hash_mismatch'+ )+ }+ return this.pathFor(uploadId)+ }++ async remove(uploadId: string): Promise<void> {+ if (!UPLOAD_ID_RE.test(uploadId)) return+ await rm(this.pathFor(uploadId), { force: true })+ }++ private pathFor(uploadId: string): string {+ return path.join(this.uploadsDir, `${uploadId}.moext`)+ }+}diff --git a/src/server/routes/diagnostics.test.ts b/src/server/routes/diagnostics.test.tsnew file mode 100644index 00000000..002d0918--- /dev/null+++ b/src/server/routes/diagnostics.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'+import { createApp } from '../http/app'+import { registerServerDiagnosticsRoute } from './diagnostics'++describe('server diagnostics route', () => {+ it('requires operator authentication and returns the runtime snapshot', async () => {+ const app = await createApp({+ operatorAuth: { operatorToken: 'operator-secret' },+ })+ registerServerDiagnosticsRoute(app, async () => ({+ health: { ok: true },+ storage: { dataDir: '/data', downloads: ['/downloads'] },+ }))++ expect(+ (await app.inject({ method: 'GET', url: '/api/diagnostics' })).statusCode+ ).toBe(401)+ const response = await app.inject({+ method: 'GET',+ url: '/api/diagnostics',+ headers: { authorization: 'Bearer operator-secret' },+ })+ expect(response.statusCode).toBe(200)+ expect(response.json()).toEqual({+ health: { ok: true },+ storage: { dataDir: '/data', downloads: ['/downloads'] },+ })+ await app.close()+ })++ it('returns a clear error when a diagnostic probe fails', async () => {+ const app = await createApp()+ registerServerDiagnosticsRoute(app, () => {+ throw new Error('aria2 probe failed')+ })+ const response = await app.inject({+ method: 'GET',+ url: '/api/diagnostics',+ })+ expect(response.statusCode).toBe(500)+ expect(response.json()).toEqual({ error: 'aria2 probe failed' })+ await app.close()+ })+})diff --git a/src/server/routes/diagnostics.ts b/src/server/routes/diagnostics.tsnew file mode 100644index 00000000..c938b346--- /dev/null+++ b/src/server/routes/diagnostics.ts@@ -0,0 +1,16 @@+import type { FastifyInstance } from 'fastify'++export function registerServerDiagnosticsRoute(+ app: FastifyInstance,+ snapshot: () => unknown | Promise<unknown>+): void {+ app.get('/api/diagnostics', async (_request, reply) => {+ try {+ return await snapshot()+ } catch (cause) {+ return reply.code(500).send({+ error: cause instanceof Error ? cause.message : String(cause),+ })+ }+ })+}diff --git a/src/server/routes/plugin-uploads.test.ts b/src/server/routes/plugin-uploads.test.tsnew file mode 100644index 00000000..a7af7d17--- /dev/null+++ b/src/server/routes/plugin-uploads.test.ts@@ -0,0 +1,102 @@+import { createHash } from 'node:crypto'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import Fastify from 'fastify'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createApp } from '../http/app'+import { PluginUploadStore } from '../plugin/upload-store'+import {+ PLUGIN_UPLOAD_CONTENT_TYPE,+ registerPluginUploadRoute,+} from './plugin-uploads'++let root: string++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), 'motrix-plugin-upload-route-'))+})++afterEach(async () => {+ await rm(root, { recursive: true, force: true })+})++describe('plugin upload route', () => {+ it('returns an opaque upload reference for a verified package', async () => {+ const app = Fastify()+ registerPluginUploadRoute(app, new PluginUploadStore(root))+ const bytes = Buffer.from('plugin bytes')+ const fileHash = createHash('sha256').update(bytes).digest('hex')++ const response = await app.inject({+ method: 'POST',+ url: '/api/plugins/uploads',+ headers: {+ 'content-type': PLUGIN_UPLOAD_CONTENT_TYPE,+ 'x-motrix-file-name': encodeURIComponent('test.moext'),+ 'x-motrix-file-sha256': fileHash,+ },+ payload: bytes,+ })++ expect(response.statusCode).toBe(201)+ expect(response.json()).toMatchObject({+ uploadId: expect.stringMatching(/^[0-9a-f-]+$/),+ fileHash,+ })+ await app.close()+ })++ it('rejects an upload whose claimed hash is false', async () => {+ const app = Fastify()+ registerPluginUploadRoute(app, new PluginUploadStore(root))+ const response = await app.inject({+ method: 'POST',+ url: '/api/plugins/uploads',+ headers: {+ 'content-type': PLUGIN_UPLOAD_CONTENT_TYPE,+ 'x-motrix-file-name': encodeURIComponent('test.moext'),+ 'x-motrix-file-sha256': '0'.repeat(64),+ },+ payload: Buffer.from('plugin bytes'),+ })+ expect(response.statusCode).toBe(400)+ expect(response.json()).toEqual({+ error: 'plugin.install.local_file_hash_mismatch',+ })+ await app.close()+ })++ it('is covered by the operator control-plane authentication gate', async () => {+ const app = await createApp({+ operatorAuth: { operatorToken: 'operator-secret' },+ })+ registerPluginUploadRoute(app, new PluginUploadStore(root))+ const bytes = Buffer.from('plugin bytes')+ const fileHash = createHash('sha256').update(bytes).digest('hex')+ const request = {+ method: 'POST' as const,+ url: '/api/plugins/uploads',+ headers: {+ 'content-type': PLUGIN_UPLOAD_CONTENT_TYPE,+ 'x-motrix-file-name': encodeURIComponent('test.moext'),+ 'x-motrix-file-sha256': fileHash,+ },+ payload: bytes,+ }++ expect((await app.inject(request)).statusCode).toBe(401)+ expect(+ (+ await app.inject({+ ...request,+ headers: {+ ...request.headers,+ authorization: 'Bearer operator-secret',+ },+ })+ ).statusCode+ ).toBe(201)+ await app.close()+ })+})diff --git a/src/server/routes/plugin-uploads.ts b/src/server/routes/plugin-uploads.tsnew file mode 100644index 00000000..fbd0ad56--- /dev/null+++ b/src/server/routes/plugin-uploads.ts@@ -0,0 +1,43 @@+import type { FastifyInstance } from 'fastify'+import {+ MAX_PLUGIN_UPLOAD_BYTES,+ type PluginUploadStore,+} from '../plugin/upload-store'++export const PLUGIN_UPLOAD_CONTENT_TYPE = 'application/vnd.motrix.moext'++function headerValue(value: string | string[] | undefined): string {+ return Array.isArray(value) ? (value[0] ?? '') : (value ?? '')+}++export function registerPluginUploadRoute(+ app: FastifyInstance,+ store: PluginUploadStore+): void {+ if (!app.hasContentTypeParser(PLUGIN_UPLOAD_CONTENT_TYPE)) {+ app.addContentTypeParser(+ PLUGIN_UPLOAD_CONTENT_TYPE,+ { parseAs: 'buffer' },+ (_request, body, done) => done(null, body)+ )+ }++ app.post<{ Body: Buffer }>(+ '/api/plugins/uploads',+ { bodyLimit: MAX_PLUGIN_UPLOAD_BYTES },+ async (request, reply) => {+ try {+ const encodedName = headerValue(request.headers['x-motrix-file-name'])+ const fileName = decodeURIComponent(encodedName)+ const fileHash = headerValue(request.headers['x-motrix-file-sha256'])+ const reference = await store.put(request.body, fileHash, fileName)+ return reply.code(201).send(reference)+ } catch (cause) {+ request.log.warn({ err: cause }, 'plugin upload rejected')+ return reply.code(400).send({+ error: cause instanceof Error ? cause.message : String(cause),+ })+ }+ }+ )+}diff --git a/src/server/runtime-directories.test.ts b/src/server/runtime-directories.test.tsnew file mode 100644index 00000000..56f1566e--- /dev/null+++ b/src/server/runtime-directories.test.ts@@ -0,0 +1,48 @@+import { chmod, mkdtemp, rm, stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { prepareServerRuntimeDirectories } from './runtime-directories'++const cleanup: string[] = []++afterEach(async () => {+ for (const dir of cleanup.splice(0)) {+ await chmod(dir, 0o700).catch(() => undefined)+ await rm(dir, { recursive: true, force: true })+ }+})++describe('prepareServerRuntimeDirectories', () => {+ it('creates writable persistent data, temp, and torrent roots', async () => {+ const parent = await mkdtemp(path.join(tmpdir(), 'motrix-runtime-dir-'))+ cleanup.push(parent)+ const dataDir = path.join(parent, 'data')++ const result = await prepareServerRuntimeDirectories({ dataDir })++ expect(result).toEqual({+ dataDir,+ tempDir: path.join(dataDir, 'tmp'),+ torrentsDir: path.join(dataDir, 'torrents'),+ homeDir: path.join(dataDir, 'home'),+ })+ await expect(stat(result.tempDir)).resolves.toBeDefined()+ await expect(stat(result.torrentsDir)).resolves.toBeDefined()+ await expect(stat(result.homeDir)).resolves.toBeDefined()+ })++ it('rejects relative data and temp configuration', async () => {+ await expect(+ prepareServerRuntimeDirectories({ dataDir: 'data' })+ ).rejects.toThrow('MOTRIX_DATA_DIR must be an absolute path')+ const parent = await mkdtemp(path.join(tmpdir(), 'motrix-runtime-dir-'))+ cleanup.push(parent)+ await expect(+ prepareServerRuntimeDirectories({+ dataDir: parent,+ tempDirValue: 'tmp',+ })+ ).rejects.toThrow('MOTRIX_TEMP_DIR must be an absolute path')+ })+})diff --git a/src/server/runtime-directories.ts b/src/server/runtime-directories.tsnew file mode 100644index 00000000..013a9e3b--- /dev/null+++ b/src/server/runtime-directories.ts@@ -0,0 +1,65 @@+import { mkdir, open, stat, unlink } from 'node:fs/promises'+import path from 'node:path'++export interface ServerRuntimeDirectoryOptions {+ dataDir: string+ tempDirValue?: string+}++export interface ServerRuntimeDirectories {+ dataDir: string+ tempDir: string+ torrentsDir: string+ homeDir: string+}++function absolutePath(value: string, label: string): string {+ const trimmed = value.trim()+ if (!trimmed || !path.isAbsolute(trimmed)) {+ throw new Error(`${label} must be an absolute path`)+ }+ return path.resolve(trimmed)+}++async function requireWritableDirectory(dir: string, label: string) {+ await mkdir(dir, { recursive: true }).catch((cause) => {+ throw new Error(`${label} cannot be created: ${dir}`, { cause })+ })+ const info = await stat(dir)+ if (!info.isDirectory())+ throw new Error(`${label} is not a directory: ${dir}`)+ const probe = path.join(+ dir,+ `.motrix-runtime-write-test-${process.pid}-${Date.now()}`+ )+ let handle: Awaited<ReturnType<typeof open>> | undefined+ try {+ handle = await open(probe, 'wx', 0o600)+ await handle.close()+ handle = undefined+ await unlink(probe)+ } catch (cause) {+ await handle?.close().catch(() => undefined)+ await unlink(probe).catch(() => undefined)+ throw new Error(`${label} is not writable: ${dir}`, { cause })+ }+}++export async function prepareServerRuntimeDirectories(+ options: ServerRuntimeDirectoryOptions+): Promise<ServerRuntimeDirectories> {+ const dataDir = absolutePath(options.dataDir, 'MOTRIX_DATA_DIR')+ const tempDir = absolutePath(+ options.tempDirValue?.trim() || path.join(dataDir, 'tmp'),+ options.tempDirValue?.trim() ? 'MOTRIX_TEMP_DIR' : 'Server temp directory'+ )+ const torrentsDir = path.join(dataDir, 'torrents')+ const homeDir = path.join(dataDir, 'home')+ await requireWritableDirectory(dataDir, 'Server data directory')+ await Promise.all([+ requireWritableDirectory(tempDir, 'Server temp directory'),+ requireWritableDirectory(torrentsDir, 'Torrent metadata directory'),+ requireWritableDirectory(homeDir, 'Server runtime home directory'),+ ])+ return { dataDir, tempDir, torrentsDir, homeDir }+}diff --git a/src/server/runtime-health.test.ts b/src/server/runtime-health.test.tsnew file mode 100644index 00000000..ec5393c3--- /dev/null+++ b/src/server/runtime-health.test.ts@@ -0,0 +1,56 @@+import { EngineFailureReason, EngineState } from '@shared/types/engine'+import { describe, expect, it } from 'vitest'+import { serverHealthSnapshot } from './runtime-health'++describe('serverHealthSnapshot', () => {+ it('is ready only while ingress is accepting and aria2 is ready', () => {+ expect(+ serverHealthSnapshot({+ accepting: true,+ engine: {+ state: EngineState.Ready,+ featureReport: null,+ failure: null,+ managedPid: 42,+ },+ })+ ).toEqual({+ ok: true,+ status: 'ready',+ engine: { state: EngineState.Ready, failureReason: null },+ })+ })++ it('reports engine failure and shutdown as unhealthy', () => {+ expect(+ serverHealthSnapshot({+ accepting: true,+ engine: {+ state: EngineState.Failed,+ featureReport: null,+ failure: {+ reason: EngineFailureReason.SpawnFailed,+ occurredAt: 1,+ technicalMessage: 'spawn failed',+ },+ managedPid: null,+ },+ })+ ).toMatchObject({+ ok: false,+ status: 'degraded',+ engine: { failureReason: EngineFailureReason.SpawnFailed },+ })+ expect(+ serverHealthSnapshot({+ accepting: false,+ engine: {+ state: EngineState.Ready,+ featureReport: null,+ failure: null,+ managedPid: 42,+ },+ }).status+ ).toBe('stopping')+ })+})diff --git a/src/server/runtime-health.ts b/src/server/runtime-health.tsnew file mode 100644index 00000000..05ebeb8a--- /dev/null+++ b/src/server/runtime-health.ts@@ -0,0 +1,29 @@+import { EngineState, type EngineStatusSnapshot } from '@shared/types/engine'++export interface ServerHealthSnapshot {+ ok: boolean+ status: 'ready' | 'degraded' | 'stopping'+ engine: {+ state: EngineState+ failureReason: string | null+ }+}++export function serverHealthSnapshot(options: {+ accepting: boolean+ engine: EngineStatusSnapshot+}): ServerHealthSnapshot {+ const engineReady = options.engine.state === EngineState.Ready+ return {+ ok: options.accepting && engineReady,+ status: !options.accepting+ ? 'stopping'+ : engineReady+ ? 'ready'+ : 'degraded',+ engine: {+ state: options.engine.state,+ failureReason: options.engine.failure?.reason ?? null,+ },+ }+}diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 4096a2ab..bef48be8 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1596,7 +1596,9 @@},"checkAriaLabel": "Check this plugin","install": "Install plugin",- "localUnavailable": "Local file install is only available in the desktop app.",+ "pickLocal": "Choose a local .moext file",+ "localUnavailable": "Local file install is unavailable in this host.",+ "localPrepareFailed": "Could not prepare this plugin file: {{detail}}","dropHint": "Drop a .moext file here to check this plugin","dragDisabledHint": "Drag-and-drop is not supported in this environment. Use a GitHub address or a URL.","warning": "Before installing: only continue if you trust the author and expect it to use the access listed above."diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex f4013c2e..452460ff 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1581,7 +1581,9 @@},"checkAriaLabel": "检查该插件","install": "安装插件",- "localUnavailable": "本地文件安装仅在桌面应用中可用。",+ "pickLocal": "选择本地 .moext 文件",+ "localUnavailable": "当前宿主不支持本地文件安装。",+ "localPrepareFailed": "无法准备此插件文件:{{detail}}","dropHint": "将 .moext 文件拖至此处以检查该插件","dragDisabledHint": "当前环境不支持拖拽。请使用 GitHub 地址或链接。","warning": "安装前请注意:只有信任作者并预期它会使用上述权限时,才继续安装。"diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.tsindex 858e3605..5ef18313 100644--- a/tests/scripts/docker-server-runtime.test.ts+++ b/tests/scripts/docker-server-runtime.test.ts@@ -1,10 +1,29 @@import { readFile } from 'node:fs/promises'import path from 'node:path'import { describe, expect, it } from 'vitest'+import { resolveSmokeContainerIdentity } from '../../scripts/smoke-server-identity.mjs'const ROOT = process.cwd()describe('Docker Server runtime staging contract', () => {+ it('maps smoke containers to a portable non-root host identity', () => {+ expect(resolveSmokeContainerIdentity(1001, 121)).toEqual({+ uid: 1001,+ gid: 121,+ user: '1001:121',+ })+ expect(resolveSmokeContainerIdentity(0, 0)).toEqual({+ uid: 1000,+ gid: 1000,+ user: '1000:1000',+ })+ expect(resolveSmokeContainerIdentity(Number.NaN, Number.NaN)).toEqual({+ uid: 1000,+ gid: 1000,+ user: '1000:1000',+ })+ })+it('copies only the verified stage into a non-root Node 24 runtime', async () => {const dockerfile = await readFile(path.join(ROOT, 'Dockerfile'), 'utf8')const runtime = dockerfile.slice(@@ -18,7 +37,18 @@ describe('Docker Server runtime staging contract', () => {expect(runtime).toContain('apk add --no-cache aria2 ca-certificates')expect(runtime).toContain('MOTRIX_ARIA2_BIN=/usr/bin/aria2c')expect(runtime).toContain('MOTRIX_DATA_DIR=/data')+ expect(runtime).toContain('MOTRIX_PLUGIN_DIR=/data/plugins')+ expect(runtime).toContain('MOTRIX_DEFAULT_SAVE_DIR=/downloads')+ expect(runtime).toContain('MOTRIX_ALLOWED_SAVE_DIRS=/downloads')+ expect(runtime).toContain('mkdir -p /data/home /data/tmp /downloads')+ expect(runtime).toContain('chown -R node:node /data /downloads')+ expect(runtime).toContain('VOLUME ["/data", "/downloads"]')+ expect(runtime).toContain('MOTRIX_TEMP_DIR=/data/tmp')+ expect(runtime).toContain('TMPDIR=/data/tmp')+ expect(runtime).toContain('HOME=/data/home')expect(runtime).toContain('USER node')+ expect(runtime).toContain('STOPSIGNAL SIGTERM')+ expect(runtime).toContain('HEALTHCHECK --interval=30s')expect(runtime).toContain('CMD ["node", "dist/server/index.mjs"]')expect(runtime).toContain('rm -rf /usr/local/lib/node_modules/npm')expect(runtime).toContain('/usr/local/lib/node_modules/corepack')@@ -54,6 +84,22 @@ describe('Docker Server runtime staging contract', () => {)})+ it('exercises deployment behavior instead of only process startup', async () => {+ const imageSmoke = await readFile(+ path.join(ROOT, 'scripts/smoke-server-image.mjs'),+ 'utf8'+ )++ expect(imageSmoke).toContain("'--read-only'")+ expect(imageSmoke).toContain('identity.user')+ expect(imageSmoke).toContain("'command:createTask'")+ expect(imageSmoke).toContain("'command:setTaskBtTracker'")+ expect(imageSmoke).toContain("'command:installPlugin'")+ expect(imageSmoke).toContain("'command:uninstallPlugin'")+ expect(imageSmoke).toContain('Save directory is not writable: /downloads')+ expect(imageSmoke).toContain('did not survive container restart')+ })+it('keeps a corrected full-root comparison target without changing the final target', async () => {const dockerfile = await readFile(path.join(ROOT, 'Dockerfile'), 'utf8')const baselineStart = dockerfile.indexOf(