A full-featured download manager.
fix(linux): restore aria2 CA trust store support (#1913)
Dr_rOotd72e68cbf69d
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.ymlindex 3a935d29..fe76e7f2 100644--- a/.github/workflows/flatpak.yml+++ b/.github/workflows/flatpak.yml@@ -299,7 +299,7 @@ jobs:-path "*/native-messaging-hosts/*" \\) -print -quit)"output="$("$aria2c" --version)"- printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.5"+ printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.6"printf "%s\n" "$output" | grep -qF "Async DNS"printf "%s\n" "$output" | grep -qF "BitTorrent"printf "%s\n" "$output" | grep -qF "HTTPS"diff --git a/Dockerfile b/Dockerfileindex c8177ad7..5630dea4 100644--- a/Dockerfile+++ b/Dockerfile@@ -7,8 +7,8 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./COPY packages/native-host/package.json ./packages/native-host/package.jsonCOPY scripts/postinstall.mjs ./scripts/postinstall.mjsCOPY scripts/fetch-engine.mjs ./scripts/fetch-engine.mjs-# The Server image uses system aria2 and never rebuilds for Electron. Electron's-# locked install script is invoked explicitly in the build stage because the+# The Server build fetches its target-specific aria2_motrix release explicitly.+# Electron's locked install script is invoked in the build stage because the# legal inventory requires its license payload.ENV MOTRIX_SKIP_ELECTRON_REBUILD=1 \MOTRIX_SKIP_ENGINE_FETCH=1@@ -40,7 +40,13 @@ WORKDIR /appCOPY . .RUN node node_modules/electron/install.jsRUN --mount=type=cache,id=motrix-builtins,target=/app/node_modules/.cache/motrix-builtins \- pnpm run check:third-party-notices \+ case "${TARGETARCH}" in \+ amd64) engine_arch=x64 ;; \+ arm64) engine_arch=arm64 ;; \+ *) echo "unsupported Docker target architecture: ${TARGETARCH}" >&2; exit 2 ;; \+ esac \+ && node scripts/fetch-engine.mjs --platform linux --arch "${engine_arch}" \+ && pnpm run check:third-party-notices \&& pnpm run build:server \&& node scripts/stage-server-app.mjs --platform linux --arch "${TARGETARCH}" --libc musl --strict \&& node scripts/verify-server-package.mjs --app-dir dist/server-app --platform linux --arch "${TARGETARCH}" --libc musl@@ -49,7 +55,7 @@ FROM scratch AS server-size-reportCOPY --from=build /app/release/size-reports/ /FROM ${NODE_IMAGE} AS server-full-root-baseline-RUN apk add --no-cache aria2 ca-certificates \+RUN apk add --no-cache ca-certificates \&& rm -rf /usr/local/lib/node_modules/npm \/usr/local/lib/node_modules/corepack \/opt/yarn-v1.22.22 \@@ -64,6 +70,7 @@ COPY --from=build --chown=node:node /app/package.json ./package.jsonCOPY --from=build --chown=node:node /app/dist/server ./dist/serverCOPY --from=build --chown=node:node /app/dist/core/plugin/host ./dist/core/plugin/hostCOPY --from=build --chown=node:node /app/dist/renderer-web ./dist/renderer-web+COPY --from=build --chown=node:node /app/dist/server-app/bin/aria2c ./bin/aria2cCOPY --from=full-root-production-deps --chown=node:node /app/node_modules ./node_modulesCOPY --from=build --chown=node:node /app/extra/aria2.conf ./extra/aria2.confCOPY --from=build --chown=node:node /app/dist/builtin-plugins ./builtin-plugins@@ -74,16 +81,18 @@ COPY --from=build --chown=node:node /app/build/legal/THIRD_PARTY_DEPENDENCIES.mdCOPY --from=build --chown=node:node /app/build/legal/THIRD_PARTY_LICENSES.txt ./legal/THIRD_PARTY_LICENSES.txtCOPY --from=build --chown=node:node /app/build/legal/sbom.spdx.json ./legal/sbom.spdx.jsonENV YARN_VERSION= \+ PATH=/app/bin:${PATH} \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_ARIA2_BIN=/app/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 \+ SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \HOME=/data/home \TMPDIR=/data/tmp \PORT=8080@@ -97,7 +106,7 @@ CMD ["node", "dist/server/index.mjs"]FROM ${NODE_IMAGE} AS runtimeARG OCI_REVISION=unknownARG OCI_VERSION=0.0.0-local-RUN apk add --no-cache aria2 ca-certificates \+RUN apk add --no-cache ca-certificates \&& rm -rf /usr/local/lib/node_modules/npm \/usr/local/lib/node_modules/corepack \/opt/yarn-v1.22.22 \@@ -118,16 +127,18 @@ LABEL org.opencontainers.image.title="Motrix Server" \org.opencontainers.image.version="${OCI_VERSION}" \org.opencontainers.image.licenses="MIT"ENV YARN_VERSION= \+ PATH=/app/bin:${PATH} \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_ARIA2_BIN=/app/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 \+ SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \HOME=/data/home \TMPDIR=/data/tmp \PORT=8080diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex ccbffedd..e91ad52c 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -83,8 +83,8 @@ must obtain permission or replace the font before distributing the build.Desktop builds bundle an `aria2c` executable pinned by`scripts/engine.lock.json`:-- **Version:** 1.37.0-motrix.5-- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.5>+- **Version:** 1.37.0-motrix.6+- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.6>- **License:** GNU General Public License v2.0 or later (`GPL-2.0-or-later`)- **Full license text:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL exception / notice:**diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.mdindex 232199a0..4a236b11 100644--- a/THIRD_PARTY_NOTICES.zh-CN.md+++ b/THIRD_PARTY_NOTICES.zh-CN.md@@ -71,8 +71,8 @@ src/renderer/routes/settings/icons/[email protected]桌面版随应用打包 `aria2c` 可执行文件,版本由 `scripts/engine.lock.json` 固定:-- **版本:** 1.37.0-motrix.5-- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.5>+- **版本:** 1.37.0-motrix.6+- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.6>- **许可证:** GNU General Public License v2.0 or later(`GPL-2.0-or-later`)- **完整许可证文本:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL 例外条款 / 声明:**diff --git a/docs/docker-server.md b/docs/docker-server.mdindex 8568b7a3..474e4dff 100644--- a/docs/docker-server.md+++ b/docs/docker-server.md@@ -1,8 +1,11 @@# Docker Server deployment-Motrix Server packages the Web UI and aria2 in a non-root, multi-architecture-container image for NAS and home-server deployments. Tagged releases publish-the same image to both registries:+Motrix Server packages the Web UI and the checksum-verified+[`motrixapp/aria2`](https://github.com/motrixapp/aria2) fork in a non-root,+multi-architecture container image for NAS and home-server deployments. The+fork provides Motrix's SQLite persistence contract; the image does not install+the distribution's generic aria2 package. Tagged releases publish the same+image to both registries:- Docker Hub: `docker.io/motrixapp/motrix-server`- GitHub Container Registry: `ghcr.io/agalwood/motrix-server`@@ -52,6 +55,18 @@ cosign verify \"docker.io/motrixapp/motrix-server@${DIGEST}"```+### TLS trust-store lifecycle++The official image installs Alpine's `ca-certificates` bundle when the image is+built and points the fork at `/etc/ssl/certs/ca-certificates.crt` through+`SSL_CERT_FILE`. Motrix therefore does not create a long-lived CA snapshot in+`/data`; recreating the container uses the trust store shipped by the new image.++An already-running immutable container cannot update that image-layer bundle.+Pull and recreate from maintained image releases as part of normal patching. A+custom deployment that needs an independent CA lifecycle may mount a refreshed+PEM bundle read-only and set `SSL_CERT_FILE` to that mounted path.+## Persistent storage contractA usable deployment has two independent writable mounts. The container root@@ -470,6 +485,6 @@ detection.| `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.+`MOTRIX_ARIA2_BIN` (`/app/bin/aria2c`), `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.mdindex 4268b5a8..a15c53a2 100644--- a/docs/docker-server.zh-CN.md+++ b/docs/docker-server.zh-CN.md@@ -1,7 +1,10 @@# Docker Server 部署-Motrix Server 将 Web 界面和 aria2 打包为非 root、多架构容器镜像,适合 NAS-与家庭服务器。带 tag 的正式发布会把同一镜像发布到两个 registry:+Motrix Server 将 Web 界面和经过 checksum 校验的+[`motrixapp/aria2`](https://github.com/motrixapp/aria2) fork 打包为非 root、+多架构容器镜像,适合 NAS 与家庭服务器。该 fork 提供 Motrix 所需的 SQLite+持久化契约;镜像不安装发行版提供的通用 aria2 软件包。带 tag 的正式发布会把+同一镜像发布到两个 registry:- Docker Hub:`docker.io/motrixapp/motrix-server`- GitHub Container Registry:`ghcr.io/agalwood/motrix-server`@@ -50,6 +53,17 @@ cosign verify \"docker.io/motrixapp/motrix-server@${DIGEST}"```+### TLS 信任库生命周期++官方镜像在构建时安装 Alpine 的 `ca-certificates`,并通过 `SSL_CERT_FILE` 让+aria2 fork 使用 `/etc/ssl/certs/ca-certificates.crt`。因此 Motrix 不会在+`/data` 中生成长期保留的 CA 快照;用新镜像重建容器时会直接使用新镜像携带的+信任库。++已经运行的不可变容器不会自动更新镜像层中的 CA bundle。请把定期拉取维护版本+并重建容器纳入日常补丁流程。如果自定义部署要求 CA 生命周期独立于镜像,也可+只读挂载定期刷新的 PEM bundle,并把 `SSL_CERT_FILE` 指向该挂载路径。+## 持久化契约可用的部署必须有两个相互独立的可写挂载;容器根文件系统可以且应当保持@@ -421,5 +435,6 @@ secret-store 状态和 FFmpeg 探测结果。| `MOTRIX_HOST_LANGUAGE` | 系统设置 | Server/插件语言覆盖值 || `LOG_LEVEL` | `info` | 输出到容器 stdout 的 Pino 日志级别 |-`MOTRIX_ARIA2_BIN`、`MOTRIX_EXTRA_DIR` 和 `MOTRIX_RENDERER_DIR` 由官方镜像-固定。只有自定义镜像同时提供对应 artifact 时才应覆盖它们。+`MOTRIX_ARIA2_BIN`(`/app/bin/aria2c`)、`MOTRIX_EXTRA_DIR` 和+`MOTRIX_RENDERER_DIR` 由官方镜像固定。只有自定义镜像同时提供对应 artifact+时才应覆盖它们。diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.ymlindex 642e4a21..21c34e21 100644--- a/flatpak/app.motrix.native.yml+++ b/flatpak/app.motrix.native.yml@@ -14,7 +14,6 @@ base: org.electronjs.Electron2.BaseAppbase-version: '25.08'sdk-extensions:- org.freedesktop.Sdk.Extension.node24- - org.freedesktop.Sdk.Extension.rust-stablecommand: start-motrix# The default destination is the user's XDG Downloads directory. Other@@ -102,7 +101,7 @@ modules:set -eoutput="$(src/aria2c --version)"printf '%s\n' "$output"- printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.5'+ printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.6'for feature in \'Async DNS' \'BitTorrent' \@@ -124,8 +123,8 @@ modules:sources:- type: giturl: https://github.com/motrixapp/aria2.git- tag: v1.37.0-motrix.5- commit: 0f30696fd4d80d456a8493c63af26b6c06429b17+ tag: v1.37.0-motrix.6+ commit: 7e3efdb0db9678efdc93cab6007125286d06bff1x-checker-data:type: gittag-pattern: ^v([\d.]+-motrix\.\d+)$@@ -137,9 +136,9 @@ modules:commands:- |sed -i -E \- 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.5]/' \+ 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.6]/' \configure.ac- grep -qF 'AC_INIT([aria2],[1.37.0-motrix.5]' configure.ac+ grep -qF 'AC_INIT([aria2],[1.37.0-motrix.6]' configure.ac- type: scriptdest-filename: autogen.shcommands:@@ -153,8 +152,8 @@ modules:- name: motrixbuildsystem: simplebuild-options:- prepend-path: /run/build/motrix/flatpak-node/pnpm-cli/bin- append-path: /usr/lib/sdk/node24/bin:/usr/lib/sdk/rust-stable/bin+ prepend-path: /run/build/motrix/flatpak-node/pnpm-cli/bin:/run/build/motrix/flatpak-rust-toolchain/bin+ append-path: /usr/lib/sdk/node24/binenv:XDG_CACHE_HOME: /run/build/motrix/flatpak-node/cachenpm_config_cache: /run/build/motrix/flatpak-node/npm-cache@@ -184,6 +183,15 @@ modules:MOTRIX_RUST_TARGET: aarch64-unknown-linux-gnubuild-commands:+ # Keep the build-only Rust toolchain content-addressed with the rest of+ # the offline sources. A floating Flathub SDK extension can briefly+ # reference objects that have not reached every repository mirror yet.+ - ./flatpak-rust/install.sh+ --prefix=/run/build/motrix/flatpak-rust-toolchain+ --without=rust-docs+ --without=rust-docs-json-preview+ --disable-ldconfig+ --verbose- npm install -g--prefix=/run/build/motrix/flatpak-node/pnpm-cli./flatpak-node/pnpm/pnpm-11.22.0.tgz@@ -219,8 +227,8 @@ modules:- install -Dm755 /app/libexec/motrix-build/aria2cextra/linux/$npm_config_target_arch/aria2c- # rust-stable//25.08 supplies native GNU targets, not musl targets.- # Build directly instead of invoking the release-oriented build.mjs.+ # The pinned Rust archive supplies the native GNU target, not a musl+ # target. Build directly instead of invoking release-oriented build.mjs.# --bins also produces the browser-facing host required transiently by# electron-builder. It is stripped before the unpacked app is copied to# $FLATPAK_DEST; the broker is the only native-host binary exported.@@ -299,8 +307,22 @@ modules:type: gittag-pattern: ^v([\d.]+)$+ # Pin the build-only Rust toolchain by architecture. Flathub fetches it+ # with every other source before the offline build phase.+ - type: archive+ only-arches:+ - x86_64+ dest: flatpak-rust+ url: https://static.rust-lang.org/dist/2026-08-20/rust-1.98.0-x86_64-unknown-linux-gnu.tar.xz+ sha256: ed8ee2df70909c88cbaf87a6cfa3920dac00b537de12a6abe6906641e0f5952f+ - type: archive+ only-arches:+ - aarch64+ dest: flatpak-rust+ url: https://static.rust-lang.org/dist/2026-08-20/rust-1.98.0-aarch64-unknown-linux-gnu.tar.xz+ sha256: ac9283184301aeed06ecc9f5aa4c1be7041e18a1b197b6cb6c5d162d98f566da+# Generated from the lockfiles in the exact application source commit.- # Flathub fetches these sources before its offline build phase.- generated-sources.json- cargo-sources.jsondiff --git a/scripts/engine.lock.json b/scripts/engine.lock.jsonindex 2137bc24..15e9b98c 100644--- a/scripts/engine.lock.json+++ b/scripts/engine.lock.json@@ -1,50 +1,50 @@{"engine": "aria2","repo": "motrixapp/aria2",- "tag": "v1.37.0-motrix.5",- "version": "1.37.0-motrix.5",+ "tag": "v1.37.0-motrix.6",+ "version": "1.37.0-motrix.6","assets": {"darwin-arm64": {- "file": "aria2c-1.37.0-motrix.5-darwin-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.6-darwin-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "19446e4f2be6522e49011aca4f3442c31a5878f0547dbefaa050fb4400368f11",- "binarySha256": "0f7c740cd2f7c242cd73afa8f34f23bd57a268832f97ae18d860c1d5babeb6fb"+ "archiveSha256": "8f47de3ea619cb635b4c7bf198569327f2c4546e5573261423b832e3cd7b9dcc",+ "binarySha256": "0b550e3f33c58131ef844c6de8c9893d7044c152a1615298acd323f64304e59c"},"darwin-x64": {- "file": "aria2c-1.37.0-motrix.5-darwin-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.6-darwin-x64.tar.gz","bin": "aria2c",- "archiveSha256": "32bc30ff12db227e075a1078276b65762b9dd523da441dac2a4f729405dd1d57",- "binarySha256": "009c877c2cf64aaf0bdea29b761ead4b1055637b29cf65e5a722af8fb621078a"+ "archiveSha256": "637a5f0568aea2f4704fdc6f008e8a08931fdcf48a3b71c19df38f69daee1440",+ "binarySha256": "8ec726fd22dc794280ead836898f2336a3e6128271f4397aec545e9e3cdc6550"},"win32-x64": {- "file": "aria2c-1.37.0-motrix.5-win32-x64.zip",+ "file": "aria2c-1.37.0-motrix.6-win32-x64.zip","bin": "aria2c.exe",- "archiveSha256": "d2b9792a5249aabc0a0054558f471eec7e5206066ce2af872ed445e9948fc5b0",- "binarySha256": "1ebb047bea9c0c3179e9a0e74a8a040352aaab45592b40c36a087015b4716f32"+ "archiveSha256": "ef83499b161fd03db86ecbf96da29732f73b6679a541951880a65957f00a4015",+ "binarySha256": "effb57cd154d07443a271aff5700f4e37abec4b44ff46f380b68d9ddb792eebb"},"win32-ia32": {- "file": "aria2c-1.37.0-motrix.5-win32-ia32.zip",+ "file": "aria2c-1.37.0-motrix.6-win32-ia32.zip","bin": "aria2c.exe",- "archiveSha256": "3031b6a4c2f211d003bf2b334e8d68f4b8abc2210515c5710187d6a97d7f2a01",- "binarySha256": "b72a705d53da7c65d57ab34fc97f88c5a0ac1dae030ad2271c2b260f00504ceb"+ "archiveSha256": "09d2ca8adac14b3345877e51e3b01a8de90f539493d1424425f2c2191f681ed9",+ "binarySha256": "003a8a2df16601b70732381a00f3ba9592d585fcf40fd06d782dced445ca4e4b"},"linux-x64": {- "file": "aria2c-1.37.0-motrix.5-linux-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.6-linux-x64.tar.gz","bin": "aria2c",- "archiveSha256": "7cd4fe027ef04d054bd1eeb95f77ab19f43b85f9a11dd6d7922f57bd8300256a",- "binarySha256": "d61eb41eb44903127808122c62b3b952eb0b9d6de17bda44762be19b4fd95c25"+ "archiveSha256": "ad40cb968223b1fcd1218713d3a49f251c15d658a3365eac35bc8faef3588d62",+ "binarySha256": "0d6ff44de65427e46f16d7d94de19e56925523600269b75a74c56c890624d21f"},"linux-arm64": {- "file": "aria2c-1.37.0-motrix.5-linux-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.6-linux-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "4a271ea8f0ce01942f14a2d8bf5fa46b2b86ede8e8f71ad21685cae4859c5b8d",- "binarySha256": "7e72db4730f920d7bf4a38367f6869de75567c3e6bbe680f32c2f19ce735be86"+ "archiveSha256": "11b11f2f8c717ab8cccb08670677ba2ae12d6d4c98a33fcaaed407d818e7c06b",+ "binarySha256": "296425c961369db3e17dc0e58cdc04f486bf345dd734fbbaf94d980531f06147"},"linux-arm": {- "file": "aria2c-1.37.0-motrix.5-linux-armv7l.tar.gz",+ "file": "aria2c-1.37.0-motrix.6-linux-armv7l.tar.gz","bin": "aria2c",- "archiveSha256": "e09b5cf155521b6344ce5464b5968dd133b3f3d9c38ba9e46ffe647efd762ef3",- "binarySha256": "9aaa9c94a451b2c8d176c0032a071500027f21b03d20623a770c54ee9c1ea916"+ "archiveSha256": "b5d4d90c09e6f5d774c19a23db731acc747ad9688d77104a7fd076fbba0277fa",+ "binarySha256": "d8872febda2f252e2111c951e273e7ca36af9ccbd2a5aa35a9c8003149582278"}}}diff --git a/scripts/server-package-size-budgets.json b/scripts/server-package-size-budgets.jsonindex 8b90e918..6045c609 100644--- a/scripts/server-package-size-budgets.json+++ b/scripts/server-package-size-budgets.json@@ -1,6 +1,6 @@{"schemaVersion": 1,- "artifactBytes": 83886080,+ "artifactBytes": 89128960,"dependencyBytes": 54525952,"packageInstances": 130,"unexpectedRuntimeRoots": 0,diff --git a/scripts/server-package-utils.mjs b/scripts/server-package-utils.mjsindex 9d1b6254..847ebf7f 100644--- a/scripts/server-package-utils.mjs+++ b/scripts/server-package-utils.mjs@@ -272,6 +272,31 @@ export function parseServerTarget(options = {}) {return { platform, arch, ...(libc ? { libc } : {}), key }}+export function resolveServerInput(input, target) {+ const replacements = {+ arch: target.arch,+ aria2Binary: target.platform === 'win32' ? 'aria2c.exe' : 'aria2c',+ platform: target.platform,+ }+ const resolveTemplate = (value, label) =>+ normalizeRelativePath(+ value.replaceAll(/\{([A-Za-z][A-Za-z0-9]*)\}/g, (token, name) => {+ const replacement = replacements[name]+ if (!replacement) {+ throw new Error(`${label} has unknown target token: ${token}`)+ }+ return replacement+ }),+ label+ )++ return {+ ...input,+ source: resolveTemplate(input.source, 'Server input source'),+ destination: resolveTemplate(input.destination, 'Server input destination'),+ }+}+export function packageNameFromSpecifier(specifier) {if (typeof specifier !== 'string' ||diff --git a/scripts/server-runtime-dependencies.json b/scripts/server-runtime-dependencies.jsonindex 0bc8d8b5..d5bd4782 100644--- a/scripts/server-runtime-dependencies.json+++ b/scripts/server-runtime-dependencies.json@@ -95,6 +95,11 @@"source": "extra/aria2.conf","destination": "extra/aria2.conf","type": "file"+ },+ {+ "source": "extra/{platform}/{arch}/{aria2Binary}",+ "destination": "bin/{aria2Binary}",+ "type": "file"}]}diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjsindex 9d66a3cd..ef44e06e 100644--- a/scripts/smoke-server-image.mjs+++ b/scripts/smoke-server-image.mjs@@ -560,6 +560,11 @@ async function assertRuntimeContract(name, url, token, identity, timeoutMs) {if (diagnostics.health?.ok !== true ||diagnostics.engine?.state !== 'ready' ||+ !/-motrix\.\d+$/.test(diagnostics.engine?.featureReport?.version ?? '') ||+ diagnostics.engine?.featureReport?.hasSqlitePersistence !== true ||+ !diagnostics.engine?.featureReport?.features?.includes(+ 'SQLite3-Persistence'+ ) ||diagnostics.process?.uid !== identity.uid ||diagnostics.storage?.dataDir !== '/data' ||diagnostics.storage?.tempDir !== '/data/tmp' ||@@ -589,9 +594,15 @@ async function assertRuntimeContract(name, url, token, identity, timeoutMs) {'test -w /data/tmp','test ! -w /app','test -s /data/motrix.db',+ 'test "$MOTRIX_ARIA2_BIN" = "/app/bin/aria2c"',+ 'test "$SSL_CERT_FILE" = "/etc/ssl/certs/ca-certificates.crt"',+ 'test -s "$SSL_CERT_FILE"',+ 'test ! -e /usr/bin/aria2c',+ "aria2c --version | grep -F -- 'SQLite3-Persistence'",'pidof aria2c',"aria2_pid=$(for pid in $(pidof aria2c); do tr '\\0' '\\n' </proc/$pid/cmdline | grep -Fxq -- '--conf-path=/data/aria2.conf' && { echo $pid; break; }; done)",'test -n "$aria2_pid"',+ 'test "$(readlink /proc/$aria2_pid/exe)" = "/app/bin/aria2c"',"tr '\\0' '\\n' </proc/$aria2_pid/cmdline | grep -Fx -- '--dht-file-path=/data/dht.dat'","tr '\\0' '\\n' </proc/$aria2_pid/cmdline | grep -Fx -- '--dht-file-path6=/data/dht6.dat'",].join('; '),@@ -805,7 +816,7 @@ function imageSmokeSummary(metadata, diagnostics, identity, startedAt) {operatorAuth: true,diagnostics: true,sqlite: true,- systemAria2: true,+ motrixAria2Fork: true,defaultSaveDir: '/downloads',shutdown: 'SIGTERM',durationMs: Date.now() - startedAt,diff --git a/scripts/smoke-server-package.mjs b/scripts/smoke-server-package.mjsindex b8b23912..3da1180b 100644--- a/scripts/smoke-server-package.mjs+++ b/scripts/smoke-server-package.mjs@@ -321,12 +321,14 @@ export async function smokeServerPackage(options) {)}const stageRoot = path.resolve(options.appDir)+ const bundledAria2 = path.join(+ stageRoot,+ 'bin',+ process.platform === 'win32' ? 'aria2c.exe' : 'aria2c'+ )const aria2Source = path.resolve(- options.aria2Bin ?? process.env.MOTRIX_ARIA2_BIN ?? ''+ options.aria2Bin ?? process.env.MOTRIX_ARIA2_BIN ?? bundledAria2)- if (!options.aria2Bin && !process.env.MOTRIX_ARIA2_BIN) {- throw new Error('--aria2-bin or MOTRIX_ARIA2_BIN is required')- }if (!(await stat(stageRoot)).isDirectory()) {throw new Error('staged Server app is not a directory')}diff --git a/scripts/stage-server-app.mjs b/scripts/stage-server-app.mjsindex 40e07727..08c2f6e5 100644--- a/scripts/stage-server-app.mjs+++ b/scripts/stage-server-app.mjs@@ -24,6 +24,7 @@ import {betterSqlite3PrebuildName,normalizeRelativePath,parseServerTarget,+ resolveServerInput,stringifySortedJson,validateServerRuntimeContract,validateServerSizeBudgets,@@ -418,6 +419,25 @@ export async function stageServerApp(options = {}) {if (!contract.supportedTargets.includes(target.key)) {throw new Error(`unsupported Server package target ${target.key}`)}+ const resolvedContract = {+ ...contract,+ buildInputs: contract.buildInputs.map((input) =>+ resolveServerInput(input, target)+ ),+ resourceInputs: contract.resourceInputs.map((input) =>+ resolveServerInput(input, target)+ ),+ }+ const inputs = [+ ...resolvedContract.buildInputs,+ ...resolvedContract.resourceInputs,+ ]+ const inputDestinations = inputs.map((input) => input.destination)+ if (new Set(inputDestinations).size !== inputDestinations.length) {+ throw new Error(+ `Server runtime contract has duplicate destinations for ${target.key}`+ )+ }const requestedStageRoot = path.resolve(options.outputDir ?? path.join(repoRoot, 'dist/server-app')@@ -436,7 +456,7 @@ export async function stageServerApp(options = {}) {const audit = await auditServerRuntime({repoRoot,- contract,+ contract: resolvedContract,budgets,})const rootManifest = await readJson(@@ -444,7 +464,6 @@ export async function stageServerApp(options = {}) {'root package manifest')const appManifest = generatedManifest(rootManifest, contract)- const inputs = [...contract.buildInputs, ...contract.resourceInputs]const inputFingerprints = []for (const input of inputs) {inputFingerprints.push(await fingerprintInput(repoRoot, input))diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjsindex 7b65c42f..e3257e38 100644--- a/scripts/verify-flatpak-packaging.mjs+++ b/scripts/verify-flatpak-packaging.mjs@@ -18,8 +18,8 @@ export const FLATPAK_BUILDER_TOOLS_COMMIT =// tag resolves to is pinned by hand (and cross-checked against the manifest).export const ARIA2_SOURCE = Object.freeze({url: 'https://github.com/motrixapp/aria2.git',- // v1.37.0-motrix.5 — performance, HTTP tail reclaim, and WinTLS fixes- commit: '0f30696fd4d80d456a8493c63af26b6c06429b17',+ // v1.37.0-motrix.6 — portable Linux OpenSSL trust-store discovery+ commit: '7e3efdb0db9678efdc93cab6007125286d06bff1',})const PNPM_SOURCE = Object.freeze({@@ -27,6 +27,17 @@ const PNPM_SOURCE = Object.freeze({sha256: '57a97e6f23a3faffc03153a4ef8c770a0552612b8640aebe39bfdd5754d0ebdc',})+const RUST_SOURCES = Object.freeze({+ x86_64: Object.freeze({+ url: 'https://static.rust-lang.org/dist/2026-08-20/rust-1.98.0-x86_64-unknown-linux-gnu.tar.xz',+ sha256: 'ed8ee2df70909c88cbaf87a6cfa3920dac00b537de12a6abe6906641e0f5952f',+ }),+ aarch64: Object.freeze({+ url: 'https://static.rust-lang.org/dist/2026-08-20/rust-1.98.0-aarch64-unknown-linux-gnu.tar.xz',+ sha256: 'ac9283184301aeed06ecc9f5aa4c1be7041e18a1b197b6cb6c5d162d98f566da',+ }),+})+const FLATPAK_BUILDER_ACTION_COMMIT = '401fe28a8384095fc1531b9d320b292f0ee45adb'const FLATPAK_BUILDER_IMAGE ='ghcr.io/flathub-infra/flatpak-github-actions:freedesktop-25.08@sha256:e3d9fbd75c7e5ce6241fb9114f59dce2156315f5977b594ea75fc97c3d364dfa'@@ -166,10 +177,10 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {'Node 24 SDK extension is required')invariant(- manifest['sdk-extensions'].includes(+ !manifest['sdk-extensions'].includes('org.freedesktop.Sdk.Extension.rust-stable'),- 'Rust SDK extension is required'+ 'Rust must use pinned archive sources, not the floating SDK extension')const finishArgs = array(manifest['finish-args'], 'finish-args')invariant(@@ -244,6 +255,23 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {'pnpm source')invariant(pnpmSource.sha256 === PNPM_SOURCE.sha256, 'pnpm digest drifted')+ for (const [arch, expected] of Object.entries(RUST_SOURCES)) {+ const rustSource = sourceByUrl(+ objectSources(motrix),+ expected.url,+ `${arch} Rust source`+ )+ invariant(rustSource.type === 'archive', `${arch} Rust must be an archive`)+ invariant(rustSource.dest === 'flatpak-rust', `${arch} Rust dest drifted`)+ invariant(+ JSON.stringify(rustSource['only-arches']) === JSON.stringify([arch]),+ `${arch} Rust source architecture drifted`+ )+ invariant(+ rustSource.sha256 === expected.sha256,+ `${arch} Rust digest drifted`+ )+ }const motrixCommands = commandText(motrix)const motrixBuildOptions = JSON.stringify(@@ -258,6 +286,17 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {),'pnpm CLI must install into a writable build prefix')+ invariant(+ motrixCommands.includes('./flatpak-rust/install.sh') &&+ motrixCommands.includes(+ '--prefix=/run/build/motrix/flatpak-rust-toolchain'+ ) &&+ motrixBuildOptions.includes(+ '/run/build/motrix/flatpak-rust-toolchain/bin'+ ) &&+ !motrixBuildOptions.includes('/usr/lib/sdk/rust-stable'),+ 'Rust must install from the pinned archive into a writable build prefix'+ )const aria2Copy = motrixCommands.indexOf('extra/linux/$npm_config_target_arch/aria2c')diff --git a/scripts/verify-server-package.mjs b/scripts/verify-server-package.mjsindex b804b717..194b38d4 100644--- a/scripts/verify-server-package.mjs+++ b/scripts/verify-server-package.mjs@@ -15,6 +15,7 @@ import {betterSqlite3PrebuildName,normalizeRelativePath,parseServerTarget,+ resolveServerInput,stringifySortedJson,validateServerRuntimeContract,validateServerSizeBudgets,@@ -213,6 +214,22 @@ export async function verifyServerPackage(options) {)))+ const resolvedResourceInputs = contract.resourceInputs.map((input) =>+ resolveServerInput(input, target)+ )+ const engineBinaryName = target.platform === 'win32' ? 'aria2c.exe' : 'aria2c'+ const engineInput = resolvedResourceInputs.find(+ (input) => input.destination === `bin/${engineBinaryName}`+ )+ const engineLock = engineInput+ ? (options.engineLock ??+ JSON.parse(+ await readFile(+ path.join(REPOSITORY_ROOT, 'scripts/engine.lock.json'),+ 'utf8'+ )+ ))+ : nullconst checks = []const errors = []let stageManifest@@ -220,6 +237,7 @@ export async function verifyServerPackage(options) {let tree = { files: [], symlinks: [] }const packageRecords = []const nativeBinaries = []+ let engineBinary = nulllet unexpectedRuntimeRoots = contract.runtimeRoots.lengthlet unresolvedExternals = 0let foreignNativeBinaries = 0@@ -305,6 +323,51 @@ export async function verifyServerPackage(options) {}return `${tree.files.length} regular files and no symlinks`})+ await check('bundled-engine', async () => {+ if (!engineInput) return 'runtime contract does not bundle an engine'+ const assetKey = `${target.platform}-${target.arch}`+ const asset = engineLock?.assets?.[assetKey]+ if (+ engineLock?.engine !== 'aria2' ||+ typeof engineLock.version !== 'string' ||+ !asset ||+ asset.bin !== engineBinaryName ||+ !/^[a-f0-9]{64}$/.test(asset.binarySha256)+ ) {+ throw new Error(`engine lock has no valid ${assetKey} aria2 asset`)+ }+ const absolute = path.join(stageRoot, ...engineInput.destination.split('/'))+ const info = await lstat(absolute)+ if (!info.isFile()) throw new Error('bundled aria2 is not a regular file')+ if (target.platform !== 'win32' && (info.mode & 0o111) === 0) {+ throw new Error('bundled aria2 is not executable')+ }+ const bytes = await readFile(absolute)+ const digest = sha256(bytes)+ if (digest !== asset.binarySha256) {+ throw new Error(+ `bundled aria2 digest mismatch; expected=${asset.binarySha256} actual=${digest}`+ )+ }+ const detected = detectNativeBinaryTarget(bytes)+ if (+ detected?.format !== FORMAT_BY_PLATFORM[target.platform] ||+ detected.arches.length !== 1 ||+ detected.arches[0] !== target.arch+ ) {+ throw new Error(+ `bundled aria2 does not match ${target.platform}-${target.arch}`+ )+ }+ engineBinary = {+ path: engineInput.destination,+ version: engineLock.version,+ sha256: digest,+ format: detected.format,+ arch: target.arch,+ }+ return `aria2 ${engineLock.version} matches the locked ${assetKey} binary`+ })await check('forbidden-payloads', () => {const paths = tree.files.map((entry) => entry.path)const forbidden = FORBIDDEN_ROOT_PATHS.filter((candidate) =>@@ -486,6 +549,7 @@ export async function verifyServerPackage(options) {checks,errors,packages: packageRecords,+ engineBinary,nativeBinaries,toolVersions: { node: process.versions.node },},diff --git a/src/core/engine/aria2/aria2-process-manager.test.ts b/src/core/engine/aria2/aria2-process-manager.test.tsindex b9bb417e..c8ee94bd 100644--- a/src/core/engine/aria2/aria2-process-manager.test.ts+++ b/src/core/engine/aria2/aria2-process-manager.test.ts@@ -268,6 +268,22 @@ describe('Aria2ProcessManager', () => {expect(manager.getPid()).toBe(12345)})+ it('passes a dedicated environment to the aria2 child', async () => {+ const mockChild = createMockChildProcess()+ mockSpawnFn.mockReturnValue(mockChild)+ const env = {+ PATH: '/usr/bin',+ SSL_CERT_FILE: '/tmp/aria2-ca-bundle.pem',+ }++ await manager.spawn('/usr/bin/aria2c', [], env)++ expect(mockSpawnFn).toHaveBeenCalledWith('/usr/bin/aria2c', [], {+ stdio: ['ignore', 'pipe', 'pipe'],+ env,+ })+ })+it('calls onExit when process exits', async () => {const mockChild = createMockChildProcess()mockSpawnFn.mockReturnValue(mockChild)diff --git a/src/core/engine/aria2/aria2-process-manager.ts b/src/core/engine/aria2/aria2-process-manager.tsindex 65f5c895..0bb6d7ee 100644--- a/src/core/engine/aria2/aria2-process-manager.ts+++ b/src/core/engine/aria2/aria2-process-manager.ts@@ -1,4 +1,4 @@-import type { ChildProcess } from 'node:child_process'+import type { ChildProcess, SpawnOptions } from 'node:child_process'import { execFile, spawn } from 'node:child_process'import { readFile, unlink } from 'node:fs/promises'import path from 'node:path'@@ -97,10 +97,16 @@ export class Aria2ProcessManager {})}- async spawn(binaryPath: string, args: string[]): Promise<void> {- const child = spawn(binaryPath, args, {+ async spawn(+ binaryPath: string,+ args: string[],+ env?: NodeJS.ProcessEnv+ ): Promise<void> {+ const options: SpawnOptions = {stdio: ['ignore', 'pipe', 'pipe'],- })+ }+ if (env) options.env = env+ const child = spawn(binaryPath, args, options)this.process = childthis.running = truediff --git a/src/core/engine/aria2/aria2-trust-store.test.ts b/src/core/engine/aria2/aria2-trust-store.test.tsnew file mode 100644index 00000000..cc2351cd--- /dev/null+++ b/src/core/engine/aria2/aria2-trust-store.test.ts@@ -0,0 +1,123 @@+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { Aria2TrustStore } from './aria2-trust-store'++const SYSTEM_CERTIFICATE = `-----BEGIN CERTIFICATE-----+system+-----END CERTIFICATE-----`+const BUNDLED_CERTIFICATE = `-----BEGIN CERTIFICATE-----+bundled+-----END CERTIFICATE-----`++describe('Aria2TrustStore', () => {+ let userConfigDir: string++ beforeEach(async () => {+ userConfigDir = await mkdtemp(path.join(tmpdir(), 'motrix-aria2-ca-'))+ })++ afterEach(async () => {+ await rm(userConfigDir, { recursive: true, force: true })+ })++ it('does nothing outside Linux', async () => {+ const getCertificates = vi.fn()+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'darwin',+ env: { PATH: '/usr/bin' },+ getCertificates,+ })++ await expect(trustStore.prepareEnvironment()).resolves.toBeUndefined()+ expect(getCertificates).not.toHaveBeenCalled()+ })++ it.each(['SSL_CERT_FILE', 'SSL_CERT_DIR'] as const)(+ 'preserves a caller-provided %s',+ async (variable) => {+ const env = { PATH: '/usr/bin', [variable]: '/custom/trust' }+ const getCertificates = vi.fn()+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'linux',+ env,+ getCertificates,+ })++ await expect(trustStore.prepareEnvironment()).resolves.toBe(env)+ expect(getCertificates).not.toHaveBeenCalled()+ }+ )++ it('writes deduplicated system certificates for the aria2 child', async () => {+ const getCertificates = vi.fn((type: string) => {+ expect(type).toBe('system')+ return [SYSTEM_CERTIFICATE, ` ${SYSTEM_CERTIFICATE} `]+ })+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'linux',+ env: { PATH: '/usr/bin' },+ getCertificates,+ })++ const env = await trustStore.prepareEnvironment()+ const bundlePath = path.join(userConfigDir, 'aria2-ca-bundle.pem')++ expect(env).toEqual({+ PATH: '/usr/bin',+ SSL_CERT_FILE: bundlePath,+ })+ expect(await readFile(bundlePath, 'utf8')).toBe(`${SYSTEM_CERTIFICATE}\n`)+ expect((await stat(bundlePath)).mode & 0o777).toBe(0o600)+ })++ it('falls back to bundled roots when the system store is empty', async () => {+ const getCertificates = vi.fn((type: string) =>+ type === 'system' ? [] : [BUNDLED_CERTIFICATE]+ )+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'linux',+ env: {},+ getCertificates,+ })++ const env = await trustStore.prepareEnvironment()++ expect(getCertificates).toHaveBeenNthCalledWith(1, 'system')+ expect(getCertificates).toHaveBeenNthCalledWith(2, 'bundled')+ expect(await readFile(env?.SSL_CERT_FILE ?? '', 'utf8')).toBe(+ `${BUNDLED_CERTIFICATE}\n`+ )+ })++ it('falls back to bundled roots when reading the system store fails', async () => {+ const getCertificates = vi.fn((type: string) => {+ if (type === 'system') throw new Error('system store unavailable')+ return [BUNDLED_CERTIFICATE]+ })+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'linux',+ env: {},+ getCertificates,+ })++ const env = await trustStore.prepareEnvironment()++ expect(await readFile(env?.SSL_CERT_FILE ?? '', 'utf8')).toBe(+ `${BUNDLED_CERTIFICATE}\n`+ )+ })++ it('fails safely when no trust anchors are available', async () => {+ const trustStore = new Aria2TrustStore(userConfigDir, {+ platform: 'linux',+ env: {},+ getCertificates: vi.fn(() => []),+ })++ await expect(trustStore.prepareEnvironment()).rejects.toThrow(+ 'No CA certificates are available for aria2 HTTPS'+ )+ })+})diff --git a/src/core/engine/aria2/aria2-trust-store.ts b/src/core/engine/aria2/aria2-trust-store.tsnew file mode 100644index 00000000..e31979d0--- /dev/null+++ b/src/core/engine/aria2/aria2-trust-store.ts@@ -0,0 +1,85 @@+import { mkdir } from 'node:fs/promises'+import path from 'node:path'+import { getCACertificates } from 'node:tls'+import { getLogger } from '@core/logger'+import writeFileAtomic from 'write-file-atomic'++const log = getLogger('aria2')++const CA_BUNDLE_FILENAME = 'aria2-ca-bundle.pem'++type Aria2CertificateSource = 'system' | 'bundled'++export interface Aria2TrustStoreOptions {+ platform?: NodeJS.Platform+ env?: NodeJS.ProcessEnv+ getCertificates?: (source: Aria2CertificateSource) => string[]+}++function normalizeCertificates(certificates: string[]): string[] {+ return [+ ...new Set(+ certificates.map((certificate) => certificate.trim()).filter(Boolean)+ ),+ ]+}++export class Aria2TrustStore {+ private readonly platform: NodeJS.Platform+ private readonly env: NodeJS.ProcessEnv+ private readonly getCertificates: (source: Aria2CertificateSource) => string[]+ private readonly bundlePath: string++ constructor(+ private readonly userConfigDir: string,+ options: Aria2TrustStoreOptions = {}+ ) {+ this.platform = options.platform ?? process.platform+ this.env = options.env ?? process.env+ this.getCertificates = options.getCertificates ?? getCACertificates+ this.bundlePath = path.join(userConfigDir, CA_BUNDLE_FILENAME)+ }++ async prepareEnvironment(): Promise<NodeJS.ProcessEnv | undefined> {+ if (this.platform !== 'linux') return undefined++ if (this.env.SSL_CERT_FILE?.trim() || this.env.SSL_CERT_DIR?.trim()) {+ log.info('using caller-provided OpenSSL trust store for aria2')+ return this.env+ }++ let certificates: string[] = []+ try {+ certificates = normalizeCertificates(this.getCertificates('system'))+ } catch (err) {+ log.warn({ err }, 'failed to read the Linux system CA trust store')+ }++ let source = 'system'+ if (certificates.length === 0) {+ certificates = normalizeCertificates(this.getCertificates('bundled'))+ source = 'bundled-fallback'+ log.warn('Linux system CA trust store is empty; using bundled roots')+ }++ if (certificates.length === 0) {+ throw new Error('No CA certificates are available for aria2 HTTPS')+ }++ await mkdir(this.userConfigDir, { recursive: true })+ await writeFileAtomic(this.bundlePath, `${certificates.join('\n')}\n`, {+ encoding: 'utf8',+ mode: 0o600,+ })++ log.info(+ { source, certificateCount: certificates.length, path: this.bundlePath },+ 'prepared aria2 CA trust store'+ )++ return {+ ...this.env,+ SSL_CERT_FILE: this.bundlePath,+ }+ }+}diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex 66d9abc3..c5e03452 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -21,6 +21,7 @@ import type { Aria2Adapter } from './aria2/aria2-adapter'import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'import type { Aria2ProcessManager } from './aria2/aria2-process-manager'import type { Aria2RpcClient } from './aria2/aria2-rpc-client'+import type { Aria2TrustStore } from './aria2/aria2-trust-store'import { EngineSupervisor } from './engine-supervisor'import { checkPort } from './port-check'@@ -123,6 +124,12 @@ function createMockRpcClient(): Aria2RpcClient {} as unknown as Aria2RpcClient}+function createMockTrustStore(): Aria2TrustStore {+ return {+ prepareEnvironment: vi.fn().mockResolvedValue(undefined),+ } as unknown as Aria2TrustStore+}+function createMockAdapter(): Aria2Adapter {return {setFeatureReport: vi.fn(),@@ -136,6 +143,7 @@ describe('EngineSupervisor', () => {let settings: SettingsManagerlet processManager: Aria2ProcessManagerlet configBuilder: Aria2ConfigBuilder+ let trustStore: Aria2TrustStorelet rpcClient: Aria2RpcClientlet adapter: Aria2Adapterlet supervisor: EngineSupervisor@@ -157,6 +165,7 @@ describe('EngineSupervisor', () => {settings = createMockSettingsManager()processManager = createMockProcessManager()configBuilder = createMockConfigBuilder()+ trustStore = createMockTrustStore()rpcClient = createMockRpcClient()adapter = createMockAdapter()@@ -165,6 +174,7 @@ describe('EngineSupervisor', () => {settings,processManager,configBuilder,+ trustStore,rpcClient,adapter)@@ -199,13 +209,32 @@ describe('EngineSupervisor', () => {expect(processManager.probe).toHaveBeenCalledWith('/usr/bin/aria2c')expect(configBuilder.ensureUserConfig).toHaveBeenCalled()+ expect(trustStore.prepareEnvironment).toHaveBeenCalled()expect(configBuilder.buildArgs).toHaveBeenCalled()- expect(processManager.spawn).toHaveBeenCalledWith('/usr/bin/aria2c', [- '--conf-path=/tmp/aria2.conf',- ])+ expect(processManager.spawn).toHaveBeenCalledWith(+ '/usr/bin/aria2c',+ ['--conf-path=/tmp/aria2.conf'],+ undefined+ )expect(rpcClient.connect).toHaveBeenCalledWith(16800)})+ it('passes the prepared trust environment only to the aria2 process', async () => {+ const env = {+ PATH: '/usr/bin',+ SSL_CERT_FILE: '/tmp/aria2-ca-bundle.pem',+ }+ vi.mocked(trustStore.prepareEnvironment).mockResolvedValue(env)++ await supervisor.start('/usr/bin/aria2c')++ expect(processManager.spawn).toHaveBeenCalledWith(+ '/usr/bin/aria2c',+ ['--conf-path=/tmp/aria2.conf'],+ env+ )+ })+it('caches feature report after successful start', async () => {await supervisor.start('/usr/bin/aria2c')expect(supervisor.getFeatureReport()).toEqual(FEATURE_REPORT)diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex a3d4c6ba..4487b507 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -25,6 +25,7 @@ import type { Aria2Adapter } from './aria2/aria2-adapter'import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'import type { Aria2ProcessManager } from './aria2/aria2-process-manager'import type { Aria2RpcClient } from './aria2/aria2-rpc-client'+import type { Aria2TrustStore } from './aria2/aria2-trust-store'import { recommend } from './aria2/aria2-tuning'import { checkPort, findAvailablePort } from './port-check'@@ -89,6 +90,7 @@ export class EngineSupervisor {private settingsManager: SettingsManager,private processManager: Aria2ProcessManager,private configBuilder: Aria2ConfigBuilder,+ private trustStore: Aria2TrustStore,private rpcClient: Aria2RpcClient,private adapter: Aria2Adapter) {@@ -299,6 +301,8 @@ export class EngineSupervisor {phase = 'config'await this.configBuilder.ensureUserConfig()if (this.stopping) return+ const processEnv = await this.trustStore.prepareEnvironment()+ if (this.stopping) returnconst configuredEngineSettings = this.settingsManager.getEngine()const engineSettings = await this.resolveRuntimeEngineSettings(@@ -342,7 +346,7 @@ export class EngineSupervisor {// Step 4: Spawn process (abort if stop() was called during earlier awaits)if (this.stopping) returnphase = 'spawn'- await this.processManager.spawn(this.binaryPath, args)+ await this.processManager.spawn(this.binaryPath, args, processEnv)// Step 5: Connect RPCif (this.stopping) {diff --git a/src/main/index.ts b/src/main/index.tsindex 08f53c4e..134b30b2 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -5,6 +5,7 @@ import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'import { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'+import { Aria2TrustStore } from '@core/engine/aria2/aria2-trust-store'import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'import { createDnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'import { JsonRpcProtocol } from '@core/engine/aria2/json-rpc-protocol'@@ -336,6 +337,7 @@ const configBuilder = new Aria2ConfigBuilder(path.join(platform.extraResourceDir, 'aria2.conf'),platform.userDataDir)+const trustStore = new Aria2TrustStore(platform.userDataDir)// ─── Database ───────────────────────────────────────────@@ -1470,6 +1472,7 @@ async function initializeMainProcess(): Promise<void> {settingsManager,processManager,configBuilder,+ trustStore,rpcClient,adapter)diff --git a/src/server/index.ts b/src/server/index.tsindex 5f26967a..36b90af1 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -7,6 +7,7 @@ import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'import { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'+import { Aria2TrustStore } from '@core/engine/aria2/aria2-trust-store'import { createDnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'import { JsonRpcProtocol } from '@core/engine/aria2/json-rpc-protocol'import {@@ -367,6 +368,7 @@ async function main() {path.join(platform.extraResourceDir, 'aria2.conf'),platform.userDataDir)+ const trustStore = new Aria2TrustStore(platform.userDataDir)// ─── Database ─────────────────────────────────────────────────const db = new MotrixDatabase(path.join(platform.userDataDir, 'motrix.db'))@@ -592,6 +594,7 @@ async function main() {settingsManager,processManager,configBuilder,+ trustStore,rpcClient,adapter)diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.tsindex 4e6a3bfe..ada803f2 100644--- a/tests/check-third-party-notices.test.ts+++ b/tests/check-third-party-notices.test.ts@@ -256,9 +256,9 @@ describe('third-party graph dependency notices', () => {expect(notice).toContain('SFNS-Regular.ttf')expect(notice).toContain('https://developer.apple.com/fonts/')- expect(notice).toContain('1.37.0-motrix.5')+ expect(notice).toContain('1.37.0-motrix.6')expect(notice).toContain(- 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.5'+ 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.6')expect(notice).toContain('GPL-2.0-or-later')expect(notice).toContain('THIRD_PARTY_LICENSES/aria2-COPYING')diff --git a/tests/generate-third-party-notices.test.ts b/tests/generate-third-party-notices.test.tsindex 55527bd8..0b91b7d7 100644--- a/tests/generate-third-party-notices.test.ts+++ b/tests/generate-third-party-notices.test.ts@@ -164,7 +164,7 @@ describe('third-party notice generator', () => {expect(bundle.packageCount).toBeGreaterThan(100)expect(inventory).toContain('| @xyflow/react | 12.11.3 |')- expect(inventory).toContain('| aria2 | 1.37.0-motrix.5 |')+ expect(inventory).toContain('| aria2 | 1.37.0-motrix.6 |')expect(inventory).toContain('| motrix.filename-template | 1.1.1 |')expect(inventory).toContain('Apple San Francisco tray font')expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')diff --git a/tests/scripts/audit-server-runtime.test.ts b/tests/scripts/audit-server-runtime.test.tsindex 43fbb154..156254f5 100644--- a/tests/scripts/audit-server-runtime.test.ts+++ b/tests/scripts/audit-server-runtime.test.ts@@ -263,6 +263,7 @@ describe('Server package contracts', () => {'build/legal/sbom.spdx.json','dist/builtin-plugins','extra/aria2.conf',+ 'extra/{platform}/{arch}/{aria2Binary}',])expect(contract.runtimeRoots).toHaveLength(21)expect(contract.runtimeRoots).not.toContain('electron-updater')diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.tsindex 52acac8f..61f842af 100644--- a/tests/scripts/docker-server-runtime.test.ts+++ b/tests/scripts/docker-server-runtime.test.ts@@ -10,6 +10,8 @@ import {const ROOT = process.cwd()const NODE_IMAGE_REFERENCE = '$' + '{NODE_IMAGE}'+const PATH_REFERENCE = '$' + '{PATH}'+const ENGINE_ARCH_REFERENCE = '$' + '{engine_arch}'describe('Docker Server runtime staging contract', () => {it('limits explicit publication smoke to supported Linux architectures', () => {@@ -64,8 +66,13 @@ describe('Docker Server runtime staging contract', () => {)expect(runtime).toContain('chmod 0755 /usr/local/bin/motrix-admin')expect(runtime.match(/^COPY /gm)).toHaveLength(1)- expect(runtime).toContain('apk add --no-cache aria2 ca-certificates')- expect(runtime).toContain('MOTRIX_ARIA2_BIN=/usr/bin/aria2c')+ expect(runtime).toContain('apk add --no-cache ca-certificates')+ expect(runtime).not.toContain('apk add --no-cache aria2')+ expect(runtime).toContain(`PATH=/app/bin:${PATH_REFERENCE}`)+ expect(runtime).toContain('MOTRIX_ARIA2_BIN=/app/bin/aria2c')+ expect(runtime).toContain(+ 'SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt'+ )expect(runtime).toContain('MOTRIX_DATA_DIR=/data')expect(runtime).toContain('MOTRIX_PLUGIN_DIR=/data/plugins')expect(runtime).toContain('MOTRIX_DEFAULT_SAVE_DIR=/downloads')@@ -182,6 +189,12 @@ describe('Docker Server runtime staging contract', () => {expect(imageSmoke).toContain("'pending'")expect(imageSmoke).toContain('Save directory is not writable: /downloads')expect(imageSmoke).toContain('did not survive container restart')+ expect(imageSmoke).toContain("'SQLite3-Persistence'")+ expect(imageSmoke).toContain("'test ! -e /usr/bin/aria2c'")+ expect(imageSmoke).toContain(+ '\'test "$(readlink /proc/$aria2_pid/exe)" = "/app/bin/aria2c"\''+ )+ expect(imageSmoke).toContain('motrixAria2Fork: true')})it('keeps a corrected full-root comparison target without changing the final target', async () => {@@ -202,6 +215,11 @@ describe('Docker Server runtime staging contract', () => {expect(dockerfile).toContain('pnpm install --prod --frozen-lockfile --ignore-scripts')+ expect(dockerfile).toContain(+ `node scripts/fetch-engine.mjs --platform linux --arch "${ENGINE_ARCH_REFERENCE}"`+ )+ expect(dockerfile).toContain('amd64) engine_arch=x64')+ expect(dockerfile).toContain('arm64) engine_arch=arm64')expect(baseline).toContain('COPY --from=full-root-production-deps --chown=node:node /app/node_modules ./node_modules')diff --git a/tests/scripts/smoke-server-package.test.ts b/tests/scripts/smoke-server-package.test.tsindex 7f42429f..42572627 100644--- a/tests/scripts/smoke-server-package.test.ts+++ b/tests/scripts/smoke-server-package.test.ts@@ -107,7 +107,11 @@ async function createFixture(): Promise<{)await writeFixtureFile(stageRoot, 'extra/aria2.conf', '')await mkdir(path.join(stageRoot, 'builtin-plugins'), { recursive: true })- const aria2Bin = await writeFixtureFile(root, 'aria2c', '#!/bin/sh\nexit 0\n')+ const aria2Bin = await writeFixtureFile(+ stageRoot,+ 'bin/aria2c',+ '#!/bin/sh\nexit 0\n'+ )await chmod(aria2Bin, 0o755)return { stageRoot, aria2Bin }}@@ -117,7 +121,6 @@ describe('smokeServerPackage', () => {const fixture = await createFixture()const result = await smokeServerPackage({appDir: fixture.stageRoot,- aria2Bin: fixture.aria2Bin,timeoutMs: 10_000,})@@ -135,7 +138,7 @@ describe('smokeServerPackage', () => {expect(result.databaseBytes).toBeGreaterThan(0)}, 20_000)- it('rejects a missing external aria2 prerequisite before startup', async () => {+ it('rejects an explicit missing aria2 override before startup', async () => {const fixture = await createFixture()await expect(smokeServerPackage({diff --git a/tests/scripts/stage-server-app.test.ts b/tests/scripts/stage-server-app.test.tsindex 4a9631e9..fec3946f 100644--- a/tests/scripts/stage-server-app.test.ts+++ b/tests/scripts/stage-server-app.test.ts@@ -477,6 +477,42 @@ describe('stageServerApp', () => {)})+ it('resolves target-specific bundled engine inputs', async () => {+ const root = await createFixture()+ const contract = fixtureContract()+ contract.resourceInputs.unshift({+ source: 'extra/{platform}/{arch}/{aria2Binary}',+ destination: 'bin/{aria2Binary}',+ type: 'file',+ })+ await writeFixtureFile(+ root,+ 'extra/linux/x64/aria2c',+ nativeHeader('linux', 'x64')+ )++ const result = await stageServerApp({+ repoRoot: root,+ platform: 'linux',+ arch: 'amd64',+ libc: 'musl',+ strict: true,+ contract,+ budgets: fixtureBudgets(),+ })++ expect(result.manifest.target.key).toBe('linux-x64-musl')+ expect(+ await readFile(path.join(root, 'dist/server-app/bin/aria2c'))+ ).toEqual(nativeHeader('linux', 'x64'))+ expect(result.manifest.inputFingerprints).toContainEqual(+ expect.objectContaining({+ destination: 'bin/aria2c',+ source: 'extra/linux/x64/aria2c',+ })+ )+ })+it('preserves the last valid stage after an input failure', async () => {const root = await createFixture()const options = {diff --git a/tests/scripts/verify-server-package.test.ts b/tests/scripts/verify-server-package.test.tsindex fc34a826..e992cbf7 100644--- a/tests/scripts/verify-server-package.test.ts+++ b/tests/scripts/verify-server-package.test.ts@@ -1,4 +1,6 @@+import { createHash } from 'node:crypto'import {+ chmod,mkdir,mkdtemp,readFile,@@ -14,6 +16,12 @@ import { verifyServerPackage } from '../../scripts/verify-server-package.mjs'const temporaryRoots: string[] = []+interface FixtureEngineLock {+ engine: string+ version: string+ assets: Record<string, { bin: string; binarySha256: string }>+}+afterEach(async () => {await Promise.all(temporaryRoots.splice(0).map((root) => rm(root, { recursive: true }))@@ -113,10 +121,14 @@ function fixtureBudgets(overrides: Record<string, number> = {}) {}}-async function createStagedFixture(): Promise<{+async function createStagedFixture(+ options: { withEngine?: boolean } = {}+): Promise<{root: stringstageRoot: stringreportPath: string+ contract: ReturnType<typeof fixtureContract>+ engineLock?: FixtureEngineLock}> {const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-server-verify-'))temporaryRoots.push(root)@@ -189,18 +201,42 @@ async function createStagedFixture(): Promise<{nativeHeader(platform, arch))}+ const contract = fixtureContract()+ let engineLock: FixtureEngineLock | undefined+ if (options.withEngine) {+ const engineBytes = nativeHeader('darwin', 'arm64')+ await writeFixtureFile(root, 'extra/darwin/arm64/aria2c', engineBytes)+ await chmod(path.join(root, 'extra/darwin/arm64/aria2c'), 0o755)+ contract.resourceInputs.unshift({+ source: 'extra/{platform}/{arch}/{aria2Binary}',+ destination: 'bin/{aria2Binary}',+ type: 'file',+ })+ engineLock = {+ engine: 'aria2',+ version: '1.37.0-motrix.test',+ assets: {+ 'darwin-arm64': {+ bin: 'aria2c',+ binarySha256: createHash('sha256').update(engineBytes).digest('hex'),+ },+ },+ }+ }await stageServerApp({repoRoot: root,platform: 'darwin',arch: 'arm64',strict: true,- contract: fixtureContract(),+ contract,budgets: fixtureBudgets(),})return {root,stageRoot: path.join(root, 'dist/server-app'),reportPath: path.join(root, 'reports/server-darwin-arm64.json'),+ contract,+ engineLock,}}@@ -212,9 +248,10 @@ async function verifyFixture(appDir: fixture.stageRoot,platform: 'darwin',arch: 'arm64',- contract: fixtureContract(),+ contract: fixture.contract,budgets,reportPath: fixture.reportPath,+ engineLock: fixture.engineLock,})}@@ -232,6 +269,25 @@ describe('verifyServerPackage', () => {expect(JSON.parse(reportJson)).toEqual(report)})+ it('accepts only the target aria2 binary pinned by the engine lock', async () => {+ const fixture = await createStagedFixture({ withEngine: true })+ const report = await verifyFixture(fixture)++ expect(report.engineBinary).toEqual(+ expect.objectContaining({+ path: 'bin/aria2c',+ version: '1.37.0-motrix.test',+ format: 'mach-o',+ arch: 'arm64',+ })+ )++ const asset = fixture.engineLock?.assets['darwin-arm64']+ if (!asset) throw new Error('fixture engine lock is missing its asset')+ asset.binarySha256 = '0'.repeat(64)+ await expect(verifyFixture(fixture)).rejects.toThrow('bundled-engine')+ })+it('fails closed on content drift and still writes the JSON report', async () => {const fixture = await createStagedFixture()await writeFixtureFile(