A full-featured download manager.
feat(deploy): publish installable Motrix Server containers (#1845)
Dr_rOot333c8f0a6cc0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9d82e8d8..a35609a1 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -134,6 +134,10 @@ jobs:src/main/bridge/snap-environment.test.tstests/scripts/assemble-release-artifacts.test.tstests/scripts/before-pack-verify.test.ts+ tests/scripts/compose-server.test.ts+ tests/scripts/container-publication-state.test.ts+ tests/scripts/container-release-metadata.test.ts+ tests/scripts/docker-server-docs.test.tstests/scripts/electron-package-contract.test.tstests/scripts/flatpak-native-host.test.tstests/scripts/native-binary-target.test.ts@@ -149,6 +153,7 @@ jobs:tests/scripts/smoke-server-package.test.tstests/scripts/stage-server-app.test.tstests/scripts/verify-electron-package.test.ts+ tests/scripts/verify-container-publication.test.tstests/scripts/verify-server-package.test.tstests/scripts/verify-update-artifacts.test.tstests/scripts/workflow-release-matrix.test.tsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 92dc4805..4faf962b 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -41,6 +41,13 @@ jobs:version: ${{ steps.metadata.outputs.version }}prerelease: ${{ steps.metadata.outputs.prerelease }}channel: ${{ steps.metadata.outputs.channel }}+ container_version: ${{ steps.container.outputs.container_version }}+ container_prerelease: ${{ steps.container.outputs.container_prerelease }}+ container_dockerhub_repository: ${{ steps.container.outputs.container_dockerhub_repository }}+ container_ghcr_repository: ${{ steps.container.outputs.container_ghcr_repository }}+ container_immutable_tags: ${{ steps.container.outputs.container_immutable_tags }}+ container_floating_tags: ${{ steps.container.outputs.container_floating_tags }}+ container_labels: ${{ steps.container.outputs.container_labels }}steps:- name: Checkout release sourceuses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1@@ -58,6 +65,17 @@ jobs:--package-json package.json--github-output "$GITHUB_OUTPUT"+ - name: Resolve container release metadata+ id: container+ env:+ RELEASE_VERSION: ${{ steps.metadata.outputs.version }}+ RELEASE_REVISION: ${{ github.sha }}+ run: >-+ node scripts/container-release-metadata.mjs+ --version "$RELEASE_VERSION"+ --revision "$RELEASE_REVISION"+ --github-output "$GITHUB_OUTPUT"+- name: Verify tag commit is on mainif: github.event_name == 'push'shell: bash@@ -606,6 +624,343 @@ jobs:prerelease: ${{ needs.preflight.outputs.prerelease }}files: release/*+ publish-container:+ name: Publish verified Server container+ needs: [preflight, publish]+ if: >-+ github.event_name == 'push' &&+ startsWith(github.ref, 'refs/tags/v')+ runs-on: ubuntu-22.04+ timeout-minutes: 90+ environment: container-release+ permissions:+ contents: read+ id-token: write+ packages: write+ env:+ CONTAINER_VERSION: ${{ needs.preflight.outputs.container_version }}+ DOCKERHUB_REPOSITORY: ${{ needs.preflight.outputs.container_dockerhub_repository }}+ GHCR_REPOSITORY: ${{ needs.preflight.outputs.container_ghcr_repository }}+ steps:+ - name: Checkout release source+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1++ - name: Validate container release credentials+ shell: bash+ env:+ DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}+ DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}+ run: |+ set -euo pipefail+ missing=()+ for name in DOCKERHUB_USERNAME DOCKERHUB_TOKEN; do+ if [[ -z "${!name:-}" ]]; then+ missing+=("$name")+ fi+ done+ if (( ${#missing[@]} > 0 )); then+ echo "Missing required container-release secrets: ${missing[*]}" >&2+ exit 1+ fi+ curl --fail --silent --show-error \+ https://hub.docker.com/v2/repositories/motrixapp/motrix-server/ \+ > /dev/null++ - name: Login to Docker Hub+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}++ - name: Login to GHCR+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - name: Set up pinned QEMU+ uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0+ with:+ image: tonistiigi/binfmt@sha256:400a4873b838d1b89194d982c45e5fb3cda4593fbfd7e08a02e76b03b21166f0+ platforms: arm64++ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0++ - name: Inspect existing immutable tags+ shell: bash+ env:+ DOCKERHUB_SNAPSHOT: ${{ runner.temp }}/dockerhub-immutable.json+ GHCR_SNAPSHOT: ${{ runner.temp }}/ghcr-immutable.json+ run: |+ set -euo pipefail+ inspect_tag() {+ local ref="$1"+ local target="$2"+ local detail+ if detail="$(docker buildx imagetools inspect \+ "$ref" --format '{{json .}}' 2>&1)"; then+ printf '%s\n' "$detail" > "$target"+ return+ fi+ if grep -Eiq \+ 'not found|manifest unknown|name unknown|does not exist' \+ <<< "$detail"; then+ printf 'null\n' > "$target"+ return+ fi+ printf '%s\n' "$detail" >&2+ exit 1+ }+ inspect_tag \+ "${DOCKERHUB_REPOSITORY}:${CONTAINER_VERSION}" \+ "$DOCKERHUB_SNAPSHOT"+ inspect_tag \+ "${GHCR_REPOSITORY}:${CONTAINER_VERSION}" \+ "$GHCR_SNAPSHOT"++ - name: Resolve immutable publication state+ id: publication-state+ env:+ DOCKERHUB_SNAPSHOT: ${{ runner.temp }}/dockerhub-immutable.json+ GHCR_SNAPSHOT: ${{ runner.temp }}/ghcr-immutable.json+ run: >-+ node scripts/container-publication-state.mjs+ --docker-hub-snapshot "$DOCKERHUB_SNAPSHOT"+ --ghcr-snapshot "$GHCR_SNAPSHOT"+ --version "$CONTAINER_VERSION"+ --revision "$GITHUB_SHA"+ --github-output "$GITHUB_OUTPUT"++ - name: Build and stage immutable multi-architecture image+ id: container-build+ if: steps.publication-state.outputs.publication_action == 'build'+ uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0+ with:+ context: .+ target: runtime+ platforms: linux/amd64,linux/arm64+ push: true+ tags: ${{ needs.preflight.outputs.container_immutable_tags }}+ labels: ${{ needs.preflight.outputs.container_labels }}+ build-args: |+ OCI_REVISION=${{ github.sha }}+ OCI_VERSION=${{ needs.preflight.outputs.container_version }}+ cache-from: type=gha,scope=motrix-server-release+ cache-to: type=gha,mode=max,scope=motrix-server-release+ provenance: mode=max+ sbom: true++ - name: Repair partial immutable publication+ if: steps.publication-state.outputs.publication_action == 'copy'+ shell: bash+ env:+ COPY_SOURCE: ${{ steps.publication-state.outputs.copy_source }}+ COPY_TARGET: ${{ steps.publication-state.outputs.copy_target }}+ run: >-+ docker buildx imagetools create+ --tag "$COPY_TARGET"+ "$COPY_SOURCE"++ - name: Reinspect immutable tags+ shell: bash+ env:+ DOCKERHUB_SNAPSHOT: ${{ runner.temp }}/dockerhub-immutable.json+ GHCR_SNAPSHOT: ${{ runner.temp }}/ghcr-immutable.json+ run: |+ set -euo pipefail+ docker buildx imagetools inspect \+ "${DOCKERHUB_REPOSITORY}:${CONTAINER_VERSION}" \+ --format '{{json .}}' > "$DOCKERHUB_SNAPSHOT"+ docker buildx imagetools inspect \+ "${GHCR_REPOSITORY}:${CONTAINER_VERSION}" \+ --format '{{json .}}' > "$GHCR_SNAPSHOT"++ - name: Verify immutable publication state+ id: immutable-publication+ env:+ DOCKERHUB_SNAPSHOT: ${{ runner.temp }}/dockerhub-immutable.json+ GHCR_SNAPSHOT: ${{ runner.temp }}/ghcr-immutable.json+ run: >-+ node scripts/container-publication-state.mjs+ --docker-hub-snapshot "$DOCKERHUB_SNAPSHOT"+ --ghcr-snapshot "$GHCR_SNAPSHOT"+ --version "$CONTAINER_VERSION"+ --revision "$GITHUB_SHA"+ --github-output "$GITHUB_OUTPUT"++ - name: Refuse a non-resumable immutable result+ shell: bash+ env:+ EXPECTED_ACTION: ${{ steps.immutable-publication.outputs.publication_action }}+ PUBLISHED_DIGEST: ${{ steps.immutable-publication.outputs.publication_digest }}+ BUILD_DIGEST: ${{ steps.container-build.outputs.digest }}+ run: |+ set -euo pipefail+ if [[ "$EXPECTED_ACTION" != 'resume' ]]; then+ echo "Immutable publication did not converge: $EXPECTED_ACTION" >&2+ exit 1+ fi+ if [[ -n "$BUILD_DIGEST" && "$BUILD_DIGEST" != "$PUBLISHED_DIGEST" ]]; then+ echo "Build digest differs from published digest" >&2+ exit 1+ fi++ - name: Install Cosign+ uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2++ - name: Sign immutable digests with GitHub OIDC+ shell: bash+ env:+ PUBLISHED_DIGEST: ${{ steps.immutable-publication.outputs.publication_digest }}+ run: |+ set -euo pipefail+ for repository in "$DOCKERHUB_REPOSITORY" "$GHCR_REPOSITORY"; do+ cosign sign --yes "${repository}@${PUBLISHED_DIGEST}"+ done++ - name: Prepare anonymous registry client+ shell: bash+ env:+ ANONYMOUS_DOCKER_CONFIG: ${{ runner.temp }}/anonymous-docker+ run: |+ set -euo pipefail+ mkdir -p "$ANONYMOUS_DOCKER_CONFIG"+ printf '{"auths":{}}\n' > "$ANONYMOUS_DOCKER_CONFIG/config.json"++ - name: Verify immutable signatures+ shell: bash+ env:+ DOCKER_CONFIG: ${{ runner.temp }}/anonymous-docker+ PUBLISHED_DIGEST: ${{ steps.immutable-publication.outputs.publication_digest }}+ run: |+ set -euo pipefail+ identity="https://github.com/agalwood/Motrix/.github/workflows/release.yml@refs/tags/${GITHUB_REF_NAME}"+ for repository in "$DOCKERHUB_REPOSITORY" "$GHCR_REPOSITORY"; do+ cosign verify \+ --certificate-identity "$identity" \+ --certificate-oidc-issuer \+ 'https://token.actions.githubusercontent.com' \+ "${repository}@${PUBLISHED_DIGEST}" > /dev/null+ done++ - name: Verify anonymous multi-architecture artifacts+ shell: bash+ env:+ DOCKER_CONFIG: ${{ runner.temp }}/anonymous-docker+ PUBLISHED_DIGEST: ${{ steps.immutable-publication.outputs.publication_digest }}+ SNAPSHOT_DIRECTORY: ${{ runner.temp }}/container-publication+ run: |+ set -euo pipefail+ mkdir -p "$SNAPSHOT_DIRECTORY"+ snapshot_artifact() {+ local name="$1"+ local reference="$2"+ docker buildx imagetools inspect "$reference" \+ --format '{{json .}}' \+ > "$SNAPSHOT_DIRECTORY/${name}-inspect.json"+ docker buildx imagetools inspect "$reference" --raw \+ > "$SNAPSHOT_DIRECTORY/${name}-index.json"+ docker buildx imagetools inspect "$reference" \+ --format '{{json .SBOM}}' \+ > "$SNAPSHOT_DIRECTORY/${name}-sbom.json"+ docker buildx imagetools inspect "$reference" \+ --format '{{json .Provenance}}' \+ > "$SNAPSHOT_DIRECTORY/${name}-provenance.json"+ }+ snapshot_artifact \+ docker-hub "${DOCKERHUB_REPOSITORY}@${PUBLISHED_DIGEST}"+ snapshot_artifact ghcr "${GHCR_REPOSITORY}@${PUBLISHED_DIGEST}"+ node scripts/verify-container-publication.mjs \+ --docker-hub-inspect \+ "$SNAPSHOT_DIRECTORY/docker-hub-inspect.json" \+ --docker-hub-index \+ "$SNAPSHOT_DIRECTORY/docker-hub-index.json" \+ --docker-hub-sbom \+ "$SNAPSHOT_DIRECTORY/docker-hub-sbom.json" \+ --docker-hub-provenance \+ "$SNAPSHOT_DIRECTORY/docker-hub-provenance.json" \+ --ghcr-inspect "$SNAPSHOT_DIRECTORY/ghcr-inspect.json" \+ --ghcr-index "$SNAPSHOT_DIRECTORY/ghcr-index.json" \+ --ghcr-sbom "$SNAPSHOT_DIRECTORY/ghcr-sbom.json" \+ --ghcr-provenance "$SNAPSHOT_DIRECTORY/ghcr-provenance.json" \+ --builder-id-prefix \+ 'https://github.com/docker/buildx/actions/runs/' \+ --version "$CONTAINER_VERSION" \+ --revision "$GITHUB_SHA"++ - name: Smoke anonymous published architectures+ shell: bash+ env:+ DOCKER_CONFIG: ${{ runner.temp }}/anonymous-docker+ PUBLISHED_DIGEST: ${{ steps.immutable-publication.outputs.publication_digest }}+ run: |+ set -euo pipefail+ public_image="${DOCKERHUB_REPOSITORY}@${PUBLISHED_DIGEST}"+ node scripts/smoke-server-image.mjs \+ --image "$public_image" \+ --platform linux/amd64 \+ --timeout-ms 180000+ node scripts/smoke-server-image.mjs \+ --image "$public_image" \+ --platform linux/arm64 \+ --mode health \+ --timeout-ms 180000++ - name: Promote stable container aliases+ if: needs.preflight.outputs.container_prerelease != 'true'+ shell: bash+ env:+ FLOATING_TAGS: ${{ needs.preflight.outputs.container_floating_tags }}+ PUBLISHED_DIGEST: ${{ steps.immutable-publication.outputs.publication_digest }}+ run: |+ set -euo pipefail+ dockerhub_tags=()+ ghcr_tags=()+ while IFS= read -r tag; do+ [[ -z "$tag" ]] && continue+ case "$tag" in+ docker.io/*) dockerhub_tags+=(--tag "$tag") ;;+ ghcr.io/*) ghcr_tags+=(--tag "$tag") ;;+ *) echo "Unexpected container tag: $tag" >&2; exit 1 ;;+ esac+ done <<< "$FLOATING_TAGS"+ docker buildx imagetools create \+ "${dockerhub_tags[@]}" \+ "${DOCKERHUB_REPOSITORY}@${PUBLISHED_DIGEST}"+ docker buildx imagetools create \+ "${ghcr_tags[@]}" \+ "${GHCR_REPOSITORY}@${PUBLISHED_DIGEST}"++ - name: Update Docker Hub description+ shell: bash+ env:+ DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}+ DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}+ run: |+ set -euo pipefail+ dockerhub_login_payload="$(jq -cn \+ --arg username "$DOCKERHUB_USERNAME" \+ --arg password "$DOCKERHUB_TOKEN" \+ '{username: $username, password: $password}')"+ dockerhub_jwt="$(curl --fail --silent --show-error \+ --header 'Content-Type: application/json' \+ --data "$dockerhub_login_payload" \+ https://hub.docker.com/v2/users/login/ | jq -er '.token')"+ dockerhub_description="$(jq -cn \+ --arg description \+ 'Motrix Server for persistent Docker and NAS deployments' \+ --rawfile full_description docs/docker-server.md \+ '{description: $description, full_description: $full_description}')"+ curl --fail --silent --show-error \+ --request PATCH \+ --header "Authorization: JWT ${dockerhub_jwt}" \+ --header 'Content-Type: application/json' \+ --data "$dockerhub_description" \+ https://hub.docker.com/v2/repositories/motrixapp/motrix-server/ \+ > /dev/null+publish-feed:name: Publish dl.motrix.app update feedneeds: [preflight, assemble, publish]diff --git a/Dockerfile b/Dockerfileindex dc03e195..71eccc60 100644--- a/Dockerfile+++ b/Dockerfile@@ -1,5 +1,6 @@-# syntax=docker/dockerfile:1.7-FROM node:24-alpine AS deps+# syntax=docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e+ARG NODE_IMAGE=node:24-alpine@sha256:d32cdf619f63fe0471182d08996dd516c6275bb5fd31ae06e55a570bd9e1ad43+FROM ${NODE_IMAGE} AS depsRUN apk add --no-cache python3 make g++WORKDIR /appCOPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./@@ -17,7 +18,7 @@ RUN --mount=type=cache,id=motrix-pnpm-store,target=/pnpm/store \&& pnpm config set store-dir /pnpm/store \&& pnpm install --frozen-lockfile-FROM node:24-alpine AS full-root-production-deps+FROM ${NODE_IMAGE} AS full-root-production-depsRUN apk add --no-cache python3 make g++WORKDIR /appCOPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./@@ -47,7 +48,7 @@ RUN --mount=type=cache,id=motrix-builtins,target=/app/node_modules/.cache/motrixFROM scratch AS server-size-reportCOPY --from=build /app/release/size-reports/ /-FROM node:24-alpine AS server-full-root-baseline+FROM ${NODE_IMAGE} AS server-full-root-baselineRUN apk add --no-cache aria2 ca-certificates \&& rm -rf /usr/local/lib/node_modules/npm \/usr/local/lib/node_modules/corepack \@@ -91,7 +92,9 @@ STOPSIGNAL SIGTERMHEALTHCHECK --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+FROM ${NODE_IMAGE} AS runtime+ARG OCI_REVISION=unknown+ARG OCI_VERSION=0.0.0-localRUN apk add --no-cache aria2 ca-certificates \&& rm -rf /usr/local/lib/node_modules/npm \/usr/local/lib/node_modules/corepack \@@ -102,6 +105,14 @@ RUN apk add --no-cache aria2 ca-certificates \&& chown -R node:node /data /downloadsWORKDIR /appCOPY --from=build --chown=node:node /app/dist/server-app/ ./+LABEL org.opencontainers.image.title="Motrix Server" \+ org.opencontainers.image.description="Motrix Server web download manager for persistent NAS deployments" \+ org.opencontainers.image.url="https://motrix.app" \+ org.opencontainers.image.documentation="https://github.com/agalwood/Motrix/blob/main/docs/docker-server.md" \+ org.opencontainers.image.source="https://github.com/agalwood/Motrix" \+ org.opencontainers.image.revision="${OCI_REVISION}" \+ org.opencontainers.image.version="${OCI_VERSION}" \+ org.opencontainers.image.licenses="MIT"ENV YARN_VERSION= \NODE_ENV=production \MOTRIX_DATA_DIR=/data \diff --git a/README.md b/README.mdindex b5befac4..8b68dd86 100644--- a/README.md+++ b/README.md@@ -94,12 +94,16 @@ You can also install it from Settings → Integration → Command-line tools in### Headless server with Docker-The repository includes a production `Dockerfile` and `compose.yaml` with-separate persistent mounts for Server state and downloaded resources:+Tagged releases publish a multi-architecture Server image to Docker Hub and+GHCR. The included `compose.yaml` pulls Docker Hub by default and keeps Server+state separate from downloaded resources:```bashmkdir -p motrix-data downloads-docker compose up --build -d+sudo chown 1000:1000 motrix-data downloads+export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+docker compose pull server+docker compose up -d --wait```The runtime is non-root, supports a read-only root filesystem, validates mount@@ -107,7 +111,8 @@ permissions before accepting work, and preserves downloads, sessions, andinstalled plugins across container replacement. Remote clients such as the CLIand 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.+Docker Hub/GHCR image and tag selection, DSM 7 and fnOS installation, ports,+diagnostics, and backup/upgrade instructions.## 🛠 Developmentdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 70ea30db..49b9a233 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -94,18 +94,23 @@ npm install -g @motrix/cli### Headless server(Docker)-仓库提供生产用途的 `Dockerfile` 和 `compose.yaml`,分别挂载 Server 状态与用户-下载资源:+带 tag 的正式版本会把多架构 Server 镜像发布到 Docker Hub 和 GHCR。仓库的+`compose.yaml` 默认从 Docker Hub 拉取,并分别持久化 Server 状态与用户下载+资源:```bashmkdir -p motrix-data downloads-docker compose up --build -d+sudo chown 1000:1000 motrix-data downloads+export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+docker compose pull server+docker compose up -d --wait```runtime 以非 root 用户运行,支持只读根文件系统,在接受任务前检查挂载权限,并在替换容器后保留下载、session 和已安装插件。CLI、浏览器扩展等远程客户端-可通过 device-code 与服务器配对。目录所有权、端口、环境变量、诊断与备份/-升级说明见 [Docker Server 部署指南](./docs/docker-server.zh-CN.md)。+可通过 device-code 与服务器配对。Docker Hub/GHCR 镜像与 tag 选择、群晖+DSM 7 和飞牛 fnOS 安装、目录所有权、端口、诊断与备份/升级说明见+[Docker Server 部署指南](./docs/docker-server.zh-CN.md)。## 🛠 开发与构建diff --git a/compose.named-volumes.yaml b/compose.named-volumes.yamlnew file mode 100644index 00000000..909c8f97--- /dev/null+++ b/compose.named-volumes.yaml@@ -0,0 +1,33 @@+name: motrix++services:+ server:+ image: "${MOTRIX_IMAGE:-motrixapp/motrix-server:latest}"+ init: true+ read_only: true+ user: "1000:1000"+ security_opt:+ - no-new-privileges:true+ restart: unless-stopped+ stop_grace_period: 2m+ tmpfs:+ - /tmp:rw,noexec,nosuid,size=64m,mode=1777+ 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+ - motrix-downloads:/downloads++volumes:+ motrix-data:+ motrix-downloads:diff --git a/compose.yaml b/compose.yamlindex ddf99902..3f896a01 100644--- a/compose.yaml+++ b/compose.yaml@@ -2,10 +2,7 @@ name: motrixservices:server:- build:- context: .- target: runtime- image: motrix-turbo:local+ image: "${MOTRIX_IMAGE:-motrixapp/motrix-server:latest}"init: trueread_only: trueuser: "${MOTRIX_UID:-1000}:${MOTRIX_GID:-1000}"@@ -13,6 +10,8 @@ services:- no-new-privileges:truerestart: unless-stoppedstop_grace_period: 2m+ tmpfs:+ - /tmp:rw,noexec,nosuid,size=64m,mode=1777environment:MOTRIX_DATA_DIR: /dataMOTRIX_TEMP_DIR: /data/tmpdiff --git a/docs/docker-server.md b/docs/docker-server.mdindex 90580b7a..192c990b 100644--- a/docs/docker-server.md+++ b/docs/docker-server.md@@ -1,77 +1,241 @@# 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:+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:++- Docker Hub: `docker.io/motrixapp/motrix-server`+- GitHub Container Registry: `ghcr.io/agalwood/motrix-server`++Docker Hub is the default in the included Compose files because NAS interfaces+usually discover and pull it with the least configuration. GHCR is an+equivalent GitHub-native mirror and a useful fallback. A `manifest unknown` or+404 before the first image-bearing release means that no public image has been+published yet; it is not a reason to build an unverified image from a fork.++## Image, architecture, and tag selection++Every release image includes `linux/amd64` and `linux/arm64`. Docker selects the+matching manifest automatically. Intel and AMD NAS devices use `amd64`; ARMv8+NAS devices use `arm64`. The image does not support 32-bit ARM.++| Reference | Behavior | Recommended use |+| --- | --- | --- |+| `:2.3.4` | Immutable release | Production and rollback |+| `:2.3` | Newest stable patch in 2.3 | Automatic patch upgrades |+| `:2` | Newest stable release in major 2 | Automatic minor and patch upgrades |+| `:stable` | Newest stable release | Users who explicitly want the stable channel |+| `:latest` | Same digest as `stable` | NAS UI default |+| `:2.3.4-beta.2` | Immutable prerelease | Evaluation only |++Prereleases never update `2.3`, `2`, `stable`, or `latest`. There are no+`edge` or `nightly` images. Both registries receive the same immutable manifest+digest before any floating tag is advanced.++For maximum reproducibility, pin the digest shown by the release or registry:++```bash+export MOTRIX_IMAGE='motrixapp/motrix-server@sha256:<manifest-digest>'+docker buildx imagetools inspect "$MOTRIX_IMAGE"+```++The manifest includes OCI source, revision, version, license, and documentation+labels, plus an SPDX SBOM and SLSA provenance. Tagged digests are signed through+GitHub Actions OIDC. For example:++```bash+VERSION=2.3.4+DIGEST='sha256:<manifest-digest>'+cosign verify \+ --certificate-identity "https://github.com/agalwood/Motrix/.github/workflows/release.yml@refs/tags/v${VERSION}" \+ --certificate-oidc-issuer https://token.actions.githubusercontent.com \+ "docker.io/motrixapp/motrix-server@${DIGEST}"+```++## Persistent storage contract++A usable deployment has two independent writable mounts. The container root+filesystem can and should remain read-only.| 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 |+| `/data` | SQLite database, settings, aria2 session and DHT state, torrent metadata, operator token, plugin packages/state/logs, and 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.+Do not combine these paths with the container layer. Recreating a container+without both mounts loses state or downloaded data. Keeping them separate lets+you back up the small, consistency-sensitive `/data` tree independently of+large downloads.-## Start with Docker Compose+## Generic Docker Compose: bind mounts-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.+The included [`compose.yaml`](../compose.yaml) pulls the Docker Hub image. It is+suitable for Docker Compose and NAS "Project" import: it has no local build,+fixed container name, privileged mode, or host-specific Docker behavior.-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:+Create the directories and make their numeric owner match the non-root user+that the container will run as:```bashmkdir -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.+# Use a dedicated non-root account. These commands use the current user.export MOTRIX_UID="$(id -u)"export MOTRIX_GID="$(id -g)"+chown "$MOTRIX_UID:$MOTRIX_GID" motrix-data downloads++export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+docker compose pull server+docker compose up -d --wait+docker compose ps```-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.+Use `sudo chown` if the current administrator does not own the directories.+Never set the runtime UID to `0` or enable privileged mode just to bypass a+mount permission error. Docker Desktop generally handles bind-mount ownership+without an explicit `chown`.-For access from another device, set the public Web URL before starting:+`MOTRIX_IMAGE` may select GHCR, a SemVer tag, or a digest without editing the+Compose file:```bash-export MOTRIX_PUBLIC_URL="http://motrix.example.lan:8080"-docker compose up --build -d-docker compose ps+export MOTRIX_IMAGE='ghcr.io/agalwood/motrix-server:2.3.4'+docker compose up -d --wait```-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:+## Generic Docker Compose: named volumes++Use [`compose.named-volumes.yaml`](../compose.named-volumes.yaml) when the NAS+should manage storage locations and backups. Docker initializes both volumes+with the image's UID/GID 1000 ownership:```bash-cat motrix-data/operator-token+export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+docker compose -f compose.named-volumes.yaml pull server+docker compose -f compose.named-volumes.yaml up -d --wait+```++Do not add `--volumes` to `docker compose down`: that option deletes the named+volumes. Bind mounts are usually easier when downloads must also appear in a+NAS shared folder.++## Synology DSM 7 Container Manager++DSM labels can vary slightly between Container Manager updates, but the+deployment model is the same:++1. Install **Container Manager** from Package Center.+2. In File Station, create a project directory such as+ `/volume1/docker/motrix`, with `motrix-data` and `downloads` below it. You may+ instead make `downloads` a separate shared folder and replace the left side+ of that bind mount in `compose.yaml` with its absolute path.+3. Choose a dedicated, non-administrator DSM account. Determine its numeric+ UID/GID with `id <account>` over an administrator SSH session, then give that+ numeric owner write access to both directories. Set `MOTRIX_UID` and+ `MOTRIX_GID` to the same values. DSM ACL access alone does not repair a+ mismatched Unix owner inside every container setup.+4. In **Container Manager > Project**, create a project using that directory+ and import or paste `compose.yaml`. Set `MOTRIX_PUBLIC_URL` to the browser URL+ that other devices will use, for example `http://nas-name:8080`. Set any+ changed ports or UID/GID values in the Project environment or substitute+ literal values before import.+5. Build/start the Project. Container Manager should pull+ `motrixapp/motrix-server:latest`; it must not display a local image build.+6. Wait for the service to become healthy, open the Web URL, and read+ `motrix-data/operator-token` from an administrator shell to unlock it.++Do not enable "high privilege", mount the Docker socket, or grant access to the+whole NAS filesystem. If DSM's reverse proxy is the only Web entry point, set+`MOTRIX_BIND_IP=127.0.0.1` only when that address is reachable from the proxy's+network context; otherwise bind the NAS address and restrict the port with the+DSM firewall.++## fnOS Docker/Compose++On fnOS, install Docker from the app store, then use its Compose/Project view:++1. Create an application directory with separate `motrix-data` and `downloads`+ directories in Files. Do not put either directory on temporary container+ storage.+2. Give both directories to a dedicated non-root numeric UID/GID. Use those+ numbers for `MOTRIX_UID` and `MOTRIX_GID`; do not work around a mismatch by+ running as root.+3. Create a Compose project from [`compose.yaml`](../compose.yaml). The relative+ mounts resolve below the selected project directory. If fnOS only accepts+ pasted YAML, replace `${...}` entries with the desired literal values or add+ the same values through its environment editor.+4. Use `motrixapp/motrix-server:latest` for stable automatic upgrades, or an+ immutable SemVer tag for controlled upgrades. Docker chooses `amd64` or+ `arm64` from the manifest.+5. Set `MOTRIX_PUBLIC_URL`, verify ports 8080 and 16801 are not already used,+ start the project, and wait for the health status before opening the Web UI.++fnOS share permissions and the container's Unix UID/GID must both allow writes.+If downloads appear in the container but not in Files, inspect the left-hand+bind path and confirm it points to the intended fnOS storage pool.++## Docker run++This is equivalent to the bind-mount Compose deployment:++```bash+mkdir -p motrix-data downloads+MOTRIX_UID="$(id -u)"+MOTRIX_GID="$(id -g)"+chown "$MOTRIX_UID:$MOTRIX_GID" motrix-data downloads++docker run -d \+ --name motrix-server \+ --init \+ --restart unless-stopped \+ --stop-timeout 120 \+ --read-only \+ --tmpfs /tmp:rw,noexec,nosuid,size=64m,mode=1777 \+ --security-opt no-new-privileges:true \+ --user "$MOTRIX_UID:$MOTRIX_GID" \+ -e MOTRIX_PUBLIC_URL='http://nas.example.lan:8080' \+ -e MOTRIX_MDXP_HOST=0.0.0.0 \+ -p 8080:8080 \+ -p 16801:16801 \+ -v "$PWD/motrix-data:/data" \+ -v "$PWD/downloads:/downloads" \+ motrixapp/motrix-server:latest```-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 image already defines its health check, non-root user, data paths, and+graceful `SIGTERM` behavior.++## Web, MDXP, token, and HTTPS boundaries-The compose defaults publish these ports on all interfaces:+The default addresses are different services:-| Port | Service |+| Address | Purpose || --- | --- |-| `8080` | Web UI, operator RPC/API, and health endpoint |-| `16801` | MDXP endpoint for paired CLI and extension clients |+| `http://NAS_HOST:8080` | Web UI, operator RPC/API, and `GET /healthz` |+| `http://NAS_HOST:16801` | MDXP client base; unary `POST /mdxp`, event stream `GET /mdxp/events`, and device-code pairing |++`MOTRIX_PUBLIC_URL` is the externally reachable **Web approval URL** returned to+device-code clients. Do not set it to the MDXP port. On first start, Motrix+generates `/data/operator-token` at mode `0600`. With bind mounts, read it with:++```bash+cat motrix-data/operator-token+```-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.+The same token is reused across restart and image replacement. You may set+`MOTRIX_OPERATOR_TOKEN` instead, but environment variables are visible in+container metadata; the generated file is the safer single-host default.-## Storage and download-path contract+Do not expose plaintext HTTP directly to the Internet. Terminate HTTPS at a+trusted reverse proxy and firewall the origin ports. Proxy port 8080 as the Web+origin and preserve cookies, authorization headers, and streaming responses.+MDXP is a separate HTTP/SSE service: clients that access it remotely need a+separate TLS-enabled proxy/upstream to port 16801. Forwarding only port 8080 does+not publish MDXP, and forwarding only 16801 does not serve the approval UI.-The image defaults to:+## Download paths and plugins++The image defaults are:```textMOTRIX_DATA_DIR=/data@@ -83,19 +247,14 @@ HOME=/data/homeTMPDIR=/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+Startup creates and write-tests the data, temporary, torrent, home, plugin, and+download directories. A missing, read-only, or wrongly owned mount fails with+the affected absolute path. Every task save directory is checked again when+the task is created. `MOTRIX_ALLOWED_SAVE_DIRS` is a colon-separated list of+absolute, mounted roots; canonical path checks reject traversal and symlinkescapes.-To add another download root, mount it and update both variables:+To add an archive root, mount and allow it together:```yamlservices:@@ -109,45 +268,63 @@ services:- /srv/archive:/archive```-The Web path picker only offers allowed roots, and the Server enforces the same-policy independently of the UI.+Built-in plugins are read-only under `/app/builtin-plugins`. User-installed+packages, provenance, grants, configuration, logs, encrypted secrets, and+enablement state persist under `/data`. Web uploads of `.moext` packages and+normal registry/URL installs therefore survive a container replacement.-## Plugins+Operator-managed options are:-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+- `MOTRIX_PLUGIN_IMPORT_DIRS`: colon-separated, explicitly mounted read-only+ roots containing local packages.+- `MOTRIX_PLUGIN_INSTALL_URLS`: comma-separated or JSON-array HTTPS,+ `github:owner/repository`, or `registry:plugin.id` startup sources. Any failedsource 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.+- `MOTRIX_ALLOW_UNMANAGED_PLUGINS=true`: allows manually copied plugin folders;+ it is off by default and unnecessary for normal installation.+- `MOTRIX_SECRETS_SEED`: optional 64-hex secret from an orchestrator secret+ store. Otherwise `/data/secrets.lockbox` is generated and persisted.-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.+The official image does not include FFmpeg. A plugin that requires it needs a+derived image with Alpine's `ffmpeg` package and+`MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`.-## Health and diagnostics+## Upgrade, rollback, backup, and restore-`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.+Before an upgrade, record the current image digest and back up `/data`. Stop the+service for a filesystem-level backup so SQLite and the aria2 session are+consistent:++```bash+docker compose stop server+tar -C . -czf "motrix-data-$(date +%Y%m%d).tar.gz" motrix-data+docker compose start server+```-The detailed diagnostic endpoint is operator-protected:+Then pull and replace only the container:++```bash+docker compose pull server+docker compose up -d --wait+docker compose ps+```++The two mounts, generated operator token, downloads, aria2 state, and installed+plugins remain. For controlled upgrades, set `MOTRIX_IMAGE` to an immutable+SemVer tag or digest before pulling. Treat a new major version as a compatibility+boundary and read its release notes.++To roll back, select the previous immutable tag/digest and recreate the service.+If the newer version migrated persistent state, stop Motrix and restore the+matching `/data` backup before starting the older image; do not assume an older+binary can read state written by a newer release. Restore `/downloads` only when+your download backup policy requires it. Keep the database, operator token, and+`secrets.lockbox` from the same backup generation.++## Health, diagnostics, and troubleshooting++`GET /healthz` is public and succeeds only after the HTTP service and aria2 are+ready. Detailed diagnostics require the operator token:```bashTOKEN="$(cat motrix-data/operator-token)"@@ -155,26 +332,23 @@ curl --fail http://127.0.0.1:8080/healthzcurl --fail \--header "Authorization: Bearer ${TOKEN}" \http://127.0.0.1:8080/api/diagnostics+docker compose logs --tail=200 server```-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-```+Diagnostics report engine status, effective storage paths, allowed download+roots, runtime UID, plugin installation/secret-store status, and FFmpeg+detection.-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.+| Symptom | Check and correction |+| --- | --- |+| Pull returns 404 or `manifest unknown` | Confirm the repository/tag spelling and that an image-bearing release exists. Try the same immutable tag on the other registry; do not substitute a similarly named third-party image. |+| `no matching manifest` | Confirm the NAS is 64-bit `amd64` or `arm64` with `docker info`; 32-bit ARM is unsupported. |+| Startup reports `EACCES`, read-only, or a path failure | Compare `docker inspect ... .Config.User` with numeric ownership of both mounts. Correct ownership/ACLs; do not run privileged or as root. |+| Port is already allocated | Change `MOTRIX_HTTP_PORT` or `MOTRIX_MDXP_PUBLIC_PORT`, and update `MOTRIX_PUBLIC_URL` if the Web port changes. |+| Web UI opens but unlock fails | Read the current persistent `/data/operator-token`; do not use a token copied from another deployment. Verify the file is regular, base64url text, and mode `0600`. |+| Download directory is rejected or files are missing from the NAS share | Use an absolute container path below `MOTRIX_ALLOWED_SAVE_DIRS`; verify the intended host directory is mounted at that exact path and writable by the runtime UID/GID. |+| Plugin install fails | Inspect `/api/diagnostics` and logs, retain `/data`, confirm package/source trust and network/TLS access, and mount any `MOTRIX_PLUGIN_IMPORT_DIRS` explicitly. Do not enable unmanaged plugins for a normal `.moext`, URL, or registry install. |+| Container is unhealthy after an upgrade | Inspect logs and diagnostics, verify both mounts, then roll back to the recorded immutable image and matching `/data` backup. |## Environment reference@@ -194,7 +368,7 @@ and secret lockbox together with the database.| `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_PUBLIC_URL` | unset | Externally reachable Web approval URL, not the MDXP URL || `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 |diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.mdindex 26acba2c..3bed9ccf 100644--- a/docs/docker-server.zh-CN.md+++ b/docs/docker-server.zh-CN.md@@ -1,69 +1,217 @@# Docker Server 部署-Motrix Server 镜像包含 Web 界面和 aria2,并以非 root 用户运行。容器根文件-系统可保持只读。可用的部署必须挂载两个相互独立的可写位置:+Motrix Server 将 Web 界面和 aria2 打包为非 root、多架构容器镜像,适合 NAS+与家庭服务器。带 tag 的正式发布会把同一镜像发布到两个 registry:++- Docker Hub:`docker.io/motrixapp/motrix-server`+- GitHub Container Registry:`ghcr.io/agalwood/motrix-server`++仓库 Compose 默认使用 Docker Hub,因为多数 NAS 界面无需额外配置即可搜索和+拉取;GHCR 是内容相同的 GitHub 原生镜像源,也可作为备用。首个包含容器镜像+的版本发布前若返回 404 或 `manifest unknown`,表示公开镜像尚未发布;不要因此+改用 fork 提供的未验证镜像。++## 镜像、架构与 tag 选择++每个发布镜像均包含 `linux/amd64` 和 `linux/arm64`,Docker 会自动选择匹配的+manifest。Intel/AMD NAS 使用 `amd64`,ARMv8 NAS 使用 `arm64`;不支持 32 位+ARM。++| 引用 | 行为 | 建议用途 |+| --- | --- | --- |+| `:2.3.4` | 不可变正式版本 | 生产与回滚 |+| `:2.3` | 2.3 系列最新稳定补丁 | 自动接收补丁升级 |+| `:2` | 主版本 2 的最新稳定版本 | 自动接收次版本和补丁升级 |+| `:stable` | 最新稳定版本 | 明确选择稳定通道的用户 |+| `:latest` | 与 `stable` 指向同一 digest | NAS 界面默认值 |+| `:2.3.4-beta.2` | 不可变预发布版本 | 仅用于评估 |++预发布版本不会更新 `2.3`、`2`、`stable` 或 `latest`。项目不发布 `edge` 或+`nightly` 镜像。只有两个 registry 的不可变 manifest digest 一致后,发布流程+才会推进 floating tag。++如需最高可复现性,请使用 release 或 registry 显示的 digest:++```bash+export MOTRIX_IMAGE='motrixapp/motrix-server@sha256:<manifest-digest>'+docker buildx imagetools inspect "$MOTRIX_IMAGE"+```++manifest 包含 OCI source、revision、version、license、documentation labels,+以及 SPDX SBOM 和 SLSA provenance。带 tag 的 digest 使用 GitHub Actions OIDC+签名,例如:++```bash+VERSION=2.3.4+DIGEST='sha256:<manifest-digest>'+cosign verify \+ --certificate-identity "https://github.com/agalwood/Motrix/.github/workflows/release.yml@refs/tags/v${VERSION}" \+ --certificate-oidc-issuer https://token.actions.githubusercontent.com \+ "docker.io/motrixapp/motrix-server@${DIGEST}"+```++## 持久化契约++可用的部署必须有两个相互独立的可写挂载;容器根文件系统可以且应当保持+只读。| 容器路径 | 用途 | 是否备份 || --- | --- | --- || `/data` | SQLite 数据库、设置、aria2 session 与 DHT 状态、种子元数据、operator token、插件包/状态/日志和插件 secret lockbox | 必须 || `/downloads` | HTTP、BT 和 magnet 任务正在下载及最终完成的用户资源 | 按数据策略决定 |-不要让这些数据只写入容器层。重新创建未挂载持久卷的容器会丢失数据库、-插件状态和下载文件。+不要让这些数据只写入容器层。重新创建没有这两个挂载的容器会丢失状态或下载+文件。分开挂载还能让体积小、要求一致性的 `/data` 独立于大量下载内容备份。-## 使用 Docker Compose 启动+## 通用 Docker Compose:bind mount-仓库提供的 [`compose.yaml`](../compose.yaml) 会构建生产 runtime,以非 root-用户运行,启用只读根文件系统,并发布 Web 与 MDXP 端口。+仓库的 [`compose.yaml`](../compose.yaml) 直接拉取 Docker Hub 镜像,适用于标准+Docker Compose 和 NAS 的“项目”导入。它不包含本地 build、固定 container+name、privileged 模式或特定主机行为。-启动前先创建 bind mount 目录。在 Linux 上,可以把它们交给镜像默认的-UID/GID 1000,也可以让容器使用当前的非 root UID/GID:+先创建目录,并让它们的数字 owner 与容器使用的非 root 用户一致:```bashmkdir -p motrix-data downloads-# 方案 A:保留镜像默认用户。-sudo chown 1000:1000 motrix-data downloads--# 方案 B:使用当前 Linux 非 root 用户。+# 使用专用非 root 账户;以下命令使用当前账户。export MOTRIX_UID="$(id -u)"export MOTRIX_GID="$(id -g)"+chown "$MOTRIX_UID:$MOTRIX_GID" motrix-data downloads++export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+docker compose pull server+docker compose up -d --wait+docker compose ps```-Docker Desktop 通常会自动处理 bind mount 所有权,无需执行 Linux 的-`chown` 步骤。不要为了绕过权限问题把 runtime UID 设为 `0`。+若当前管理员不是目录 owner,可使用 `sudo chown`。不要为了绕过挂载权限错误而+把 runtime UID 设为 `0` 或开启 privileged 模式。Docker Desktop 通常会自动+处理 bind mount 所有权,不需要显式 `chown`。-如果要从其他设备访问,请在启动前配置 Web 公网/局域网地址:+无需修改 Compose 文件即可用 `MOTRIX_IMAGE` 选择 GHCR、SemVer tag 或 digest:```bash-export MOTRIX_PUBLIC_URL="http://motrix.example.lan:8080"-docker compose up --build -d-docker compose ps+export MOTRIX_IMAGE='ghcr.io/agalwood/motrix-server:2.3.4'+docker compose up -d --wait```-在浏览器中打开 `MOTRIX_PUBLIC_URL`。首次启动时,Motrix 会生成随机的-operator token,以 `0600` 权限保存在 `motrix-data/operator-token`。在解锁-界面输入它:+## 通用 Docker Compose:named volume++如果希望由 NAS 管理存储位置和备份,可使用+[`compose.named-volumes.yaml`](../compose.named-volumes.yaml)。Docker 会按镜像+UID/GID 1000 的所有权初始化两个 volume:```bash-cat motrix-data/operator-token+export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+docker compose -f compose.named-volumes.yaml pull server+docker compose -f compose.named-volumes.yaml up -d --wait```-也可以设置 `MOTRIX_OPERATOR_TOKEN`,但环境变量可从容器元数据中看到。-对单机部署而言,自动生成并持久化的 token 文件是更安全的默认方案。+执行 `docker compose down` 时不要添加 `--volumes`,该参数会删除 named+volumes。需要让下载文件同时出现在 NAS 共享文件夹时,bind mount 通常更合适。++## 群晖 DSM 7 Container Manager++不同版本的 Container Manager 界面名称可能略有区别,但部署模型相同:++1. 从套件中心安装 **Container Manager**。+2. 在 File Station 中创建项目目录,例如 `/volume1/docker/motrix`,并在其下+ 分别创建 `motrix-data` 和 `downloads`。也可把 `downloads` 建成独立共享+ 文件夹,并在 `compose.yaml` 中把该挂载左侧改成绝对路径。+3. 选择专用的非管理员 DSM 账户。在管理员 SSH 会话中用 `id <账户>` 获取其+ 数字 UID/GID,然后让这两个目录的数字 owner 拥有写权限,并把相同数字设置+ 为 `MOTRIX_UID` 与 `MOTRIX_GID`。仅有 DSM ACL 并不保证所有容器环境都能+ 绕过 Unix owner 不匹配。+4. 在 **Container Manager > 项目** 中,使用该目录新建项目并导入或粘贴+ `compose.yaml`。把 `MOTRIX_PUBLIC_URL` 设为其他设备实际访问的浏览器 URL,+ 例如 `http://nas-name:8080`。端口或 UID/GID 有变化时,可在项目环境变量中+ 设置,或在导入前把对应值替换为字面量。+5. 构建/启动项目。Container Manager 应直接拉取+ `motrixapp/motrix-server:latest`,不应显示本地镜像 build。+6. 等服务变为 healthy 后打开 Web URL,并在管理员 shell 中读取+ `motrix-data/operator-token` 解锁。++不要启用“高权限”、挂载 Docker socket 或授权访问整个 NAS 文件系统。若 DSM+反向代理是 Web 的唯一入口,仅当代理的网络环境可访问主机 loopback 时才设置+`MOTRIX_BIND_IP=127.0.0.1`;否则监听 NAS 地址,并通过 DSM 防火墙限制端口。++## 飞牛 fnOS Docker/Compose++在 fnOS 应用商店安装 Docker,然后使用 Compose/项目视图:++1. 在文件管理中创建应用目录,并分别创建 `motrix-data` 与 `downloads`;不要+ 把它们放在容器临时存储中。+2. 让两个目录属于专用非 root 数字 UID/GID,并把相同数字用于+ `MOTRIX_UID` 与 `MOTRIX_GID`;不要用 root 运行来掩盖 owner 不匹配。+3. 使用 [`compose.yaml`](../compose.yaml) 新建 Compose 项目。相对挂载会解析到+ 选定的项目目录。如果 fnOS 只接受粘贴 YAML,可把 `${...}` 替换为实际字面+ 值,或在环境变量编辑器中添加同名值。+4. 如需自动接收稳定升级,使用 `motrixapp/motrix-server:latest`;如需受控升级,+ 使用不可变 SemVer tag。Docker 会从 manifest 中自动选择 `amd64` 或 `arm64`。+5. 设置 `MOTRIX_PUBLIC_URL`,确认 8080 和 16801 未被占用,启动项目,并等待+ health 状态正常后再打开 Web 界面。++fnOS 的共享目录权限和容器 Unix UID/GID 必须同时允许写入。如果容器中能看到+下载、文件管理中却没有,请检查 bind mount 左侧是否确实指向目标存储池。++## Docker run++以下命令与 bind-mount Compose 部署等价:-Compose 默认在所有网卡发布以下端口:+```bash+mkdir -p motrix-data downloads+MOTRIX_UID="$(id -u)"+MOTRIX_GID="$(id -g)"+chown "$MOTRIX_UID:$MOTRIX_GID" motrix-data downloads++docker run -d \+ --name motrix-server \+ --init \+ --restart unless-stopped \+ --stop-timeout 120 \+ --read-only \+ --tmpfs /tmp:rw,noexec,nosuid,size=64m,mode=1777 \+ --security-opt no-new-privileges:true \+ --user "$MOTRIX_UID:$MOTRIX_GID" \+ -e MOTRIX_PUBLIC_URL='http://nas.example.lan:8080' \+ -e MOTRIX_MDXP_HOST=0.0.0.0 \+ -p 8080:8080 \+ -p 16801:16801 \+ -v "$PWD/motrix-data:/data" \+ -v "$PWD/downloads:/downloads" \+ motrixapp/motrix-server:latest+```++镜像已经定义 healthcheck、非 root 用户、数据路径和优雅 `SIGTERM` 行为。++## Web、MDXP、token 与 HTTPS 边界-| 端口 | 服务 |+以下默认地址属于两个不同服务:++| 地址 | 用途 || --- | --- |-| `8080` | Web 界面、operator RPC/API 与健康检查 |-| `16801` | 已配对 CLI 和浏览器扩展使用的 MDXP endpoint |+| `http://NAS_HOST:8080` | Web 界面、operator RPC/API 与 `GET /healthz` |+| `http://NAS_HOST:16801` | MDXP 客户端基址;单次调用 `POST /mdxp`、事件流 `GET /mdxp/events` 与 device-code 配对 |++`MOTRIX_PUBLIC_URL` 是 device-code 客户端收到的、外部可访问的 **Web 审批+URL**,不要把它设置为 MDXP 端口。首次启动时,Motrix 会以 `0600` 权限生成+`/data/operator-token`。使用 bind mount 时可这样读取:++```bash+cat motrix-data/operator-token+```-如果只允许本机反向代理访问,设置 `MOTRIX_BIND_IP=127.0.0.1`。跨越不可信-网络时应在反向代理终止 TLS。operator 控制面虽然默认拒绝未认证请求,但仍-需用 TLS 保护传输中的凭据。+重启或替换镜像时会继续使用同一 token。也可以设置 `MOTRIX_OPERATOR_TOKEN`,+但环境变量能从容器元数据中看到;单机部署默认使用生成文件更安全。-## 存储与下载路径契约+不要把明文 HTTP 直接暴露到公网。应在可信反向代理终止 HTTPS,并用防火墙+限制源端口。把 8080 作为 Web upstream,并保留 cookie、Authorization header+和流式响应。MDXP 是独立的 HTTP/SSE 服务:远程 MDXP 客户端需要另一个启用+TLS、指向 16801 的代理/upstream。只转发 8080 不会发布 MDXP,只转发 16801+也不会提供审批界面。++## 下载路径与插件镜像默认值如下:@@ -77,16 +225,12 @@ HOME=/data/homeTMPDIR=/data/tmp```-Server 会在接受请求前创建并实际写入测试 data、临时文件、种子元数据、-home、插件和允许下载目录。挂载缺失、只读或 UID 所有权错误时,启动会失败-并指出具体绝对路径。创建每个任务时还会再次检查该任务的保存目录。--Linux 镜像中的 `MOTRIX_ALLOWED_SAVE_DIRS` 使用冒号分隔。每一项都必须是-已挂载、可写的绝对路径,且 `MOTRIX_DEFAULT_SAVE_DIR` 必须位于其中。Server-会拒绝允许根目录之外的请求,也会通过 canonical path 检查拒绝符号链接-越界。+启动过程会创建并实际写入测试 data、临时文件、种子、home、插件和下载目录。+挂载缺失、只读或 owner 错误时会携带受影响的绝对路径启动失败。创建每个任务+时还会再次检查保存目录。`MOTRIX_ALLOWED_SAVE_DIRS` 是以冒号分隔的已挂载绝对+根目录;canonical path 检查会拒绝路径穿越和符号链接越界。-增加另一个下载根目录时,必须同时挂载并更新变量:+增加 archive 根目录时,必须同时挂载并允许:```yamlservices:@@ -100,41 +244,56 @@ services:- /srv/archive:/archive```-Web 路径选择器只提供允许根目录;Server 仍会独立执行同一套约束,不依赖-UI 保证安全。+内置插件以只读方式存放在 `/app/builtin-plugins`。用户安装的包、来源记录、+授权、配置、日志、加密 secret 和启用状态都持久化在 `/data`;通过 Web 上传+`.moext`,以及正常的 registry/URL 安装都会在替换容器后保留。++operator 可用的管理选项包括:-## 插件+- `MOTRIX_PLUGIN_IMPORT_DIRS`:以冒号分隔、显式挂载为只读的本地包根目录。+- `MOTRIX_PLUGIN_INSTALL_URLS`:以逗号分隔或 JSON 数组形式提供 HTTPS、+ `github:owner/repository` 或 `registry:plugin.id` 启动安装源;任一来源失败都会+ 携带原因终止启动。+- `MOTRIX_ALLOW_UNMANAGED_PLUGINS=true`:允许手动复制的插件目录;默认关闭,+ 正常 `.moext`、URL 或 registry 安装不需要开启。+- `MOTRIX_SECRETS_SEED`:可选的 64 位十六进制 secret,应来自编排器 secret+ store;否则会生成并持久化 `/data/secrets.lockbox`。-内置插件以只读方式存放在 `/app/builtin-plugins`。用户安装的插件、来源记录、-授权、日志、配置、加密 secret 和启用状态都通过 `/data` 持久化。安装流程在-`/data/plugins` 下使用临时目录;启动时会清除遗留的上传、下载和 staging-数据,但不会删除已安装插件。+官方镜像不包含 FFmpeg。依赖 FFmpeg 的插件需要基于官方镜像安装 Alpine+`ffmpeg` 包,并设置 `MOTRIX_FFMPEG_PATH=/usr/bin/ffmpeg`。-Web 界面会先把本地 `.moext` 包上传到 Server,再显示授权界面,因此不依赖-Electron 的 `File.path`。只要保留 `/data`,替换容器后插件仍会恢复。卸载-插件会同时清除包、启用状态、配置和加密 secret 值。+## 升级、回滚、备份与恢复-还可以使用以下 operator 管理方式:+升级前记录当前镜像 digest 并备份 `/data`。做文件系统级备份前先停止服务,+确保 SQLite 与 aria2 session 一致:-- `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 或启动安装时不需要- 开启。+```bash+docker compose stop server+tar -C . -czf "motrix-data-$(date +%Y%m%d).tar.gz" motrix-data+docker compose start server+```++然后只拉取并替换容器:++```bash+docker compose pull server+docker compose up -d --wait+docker compose ps+```-插件 secret 默认使用 `/data/secrets.lockbox`,Motrix 会自动创建并持久化它。-编排环境也可以通过 `MOTRIX_SECRETS_SEED` 提供恰好 64 个十六进制字符;应把-该值保存在编排平台的 secret store 中。+两个挂载、生成的 operator token、下载、aria2 状态和已安装插件都会保留。如需+受控升级,拉取前把 `MOTRIX_IMAGE` 设置为不可变 SemVer tag 或 digest。新的+主版本属于兼容性边界,应先阅读 release notes。-## 健康检查与诊断+回滚时选择之前的不可变 tag/digest 并重建服务。如果新版本迁移过持久状态,+应停止 Motrix,并在启动旧镜像前恢复与其匹配的 `/data` 备份;不要假定旧二进制+一定能读取新版本写入的状态。只有下载备份策略要求时才恢复 `/downloads`。+数据库、operator token 与 `secrets.lockbox` 应来自同一代备份。-公开的 `GET /healthz` 只有在 Server 正在接受请求且 aria2 已就绪时才返回成功。-Docker 也使用此接口判断容器健康状态。+## 健康检查、诊断与故障排查-详细诊断接口受 operator 认证保护:+公开的 `GET /healthz` 只有在 HTTP 服务和 aria2 均就绪时才成功。详细诊断需要+operator token:```bashTOKEN="$(cat motrix-data/operator-token)"@@ -142,24 +301,22 @@ curl --fail http://127.0.0.1:8080/healthzcurl --fail \--header "Authorization: Bearer ${TOKEN}" \http://127.0.0.1:8080/api/diagnostics+docker compose logs --tail=200 server```-诊断信息包含引擎状态、生效的存储路径、允许下载根目录、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 # 重建/升级,同时保留两个挂载-```+诊断信息包含引擎状态、生效存储路径、允许下载根目录、runtime UID、插件安装/+secret-store 状态和 FFmpeg 探测结果。-对 `/data` 做文件系统级备份前应先停止服务,确保 SQLite 数据库和 aria2-session 一致。operator token、secret lockbox 与数据库应一并保留。+| 现象 | 检查与修复 |+| --- | --- |+| 拉取返回 404 或 `manifest unknown` | 检查 repository/tag 拼写以及是否已经有包含镜像的 release。可在另一个 registry 尝试相同不可变 tag;不要改用名称相似的第三方镜像。 |+| `no matching manifest` | 用 `docker info` 确认 NAS 是 64 位 `amd64` 或 `arm64`;不支持 32 位 ARM。 |+| 启动报告 `EACCES`、只读或路径失败 | 对比 `docker inspect ... .Config.User` 与两个挂载的数字 owner。修正 owner/ACL;不要改用 privileged 或 root。 |+| 端口已分配 | 修改 `MOTRIX_HTTP_PORT` 或 `MOTRIX_MDXP_PUBLIC_PORT`;Web 端口变化时同步更新 `MOTRIX_PUBLIC_URL`。 |+| Web 能打开但无法解锁 | 读取当前持久化 `/data/operator-token`,不要使用另一套部署的 token。确认它是普通文件、内容为 base64url 文本且权限为 `0600`。 |+| 下载目录被拒绝或 NAS 共享目录中没有文件 | 使用 `MOTRIX_ALLOWED_SAVE_DIRS` 下的绝对容器路径;确认目标宿主目录正好挂载到该路径,并允许 runtime UID/GID 写入。 |+| 插件安装失败 | 检查 `/api/diagnostics` 与日志,保留 `/data`,核实包/来源可信且网络/TLS 可达;显式挂载所有 `MOTRIX_PLUGIN_IMPORT_DIRS`。正常 `.moext`、URL 或 registry 安装不要开启 unmanaged plugins。 |+| 升级后容器 unhealthy | 检查日志、诊断和两个挂载,然后回滚到已记录的不可变镜像及其配套 `/data` 备份。 |## 环境变量参考@@ -179,10 +336,10 @@ session 一致。operator token、secret lockbox 与数据库应一并保留。| `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_PUBLIC_URL` | 未设置 | 外部可访问的 Web 审批 URL,不是 MDXP URL || `MOTRIX_FFMPEG_PATH` | 自动探测 | 可选的 FFmpeg 绝对路径 || `MOTRIX_HOST_LANGUAGE` | 系统设置 | Server/插件语言覆盖值 || `LOG_LEVEL` | `info` | 输出到容器 stdout 的 Pino 日志级别 |`MOTRIX_ARIA2_BIN`、`MOTRIX_EXTRA_DIR` 和 `MOTRIX_RENDERER_DIR` 由官方镜像-固定。只有自定义镜像同时提供了对应 artifact 时才应覆盖它们。+固定。只有自定义镜像同时提供对应 artifact 时才应覆盖它们。diff --git a/scripts/container-publication-state.mjs b/scripts/container-publication-state.mjsnew file mode 100644index 00000000..3f3a50a5--- /dev/null+++ b/scripts/container-publication-state.mjs@@ -0,0 +1,165 @@+import { appendFileSync, readFileSync } from 'node:fs'+import { pathToFileURL } from 'node:url'+import {+ CONTAINER_REPOSITORIES,+ resolveContainerLabels,+ resolveContainerReleaseMetadata,+} from './container-release-metadata.mjs'++const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/+export const REQUIRED_CONTAINER_PLATFORMS = Object.freeze([+ 'linux/amd64',+ 'linux/arm64',+])++function inspectedImage(snapshot, repository, revision, version) {+ if (snapshot === null || snapshot === undefined) return undefined+ if (typeof snapshot !== 'object' || Array.isArray(snapshot)) {+ throw new Error(`${repository} inspection must be an object or null`)+ }++ const digest = snapshot.manifest?.digest+ if (typeof digest !== 'string' || !DIGEST_PATTERN.test(digest)) {+ throw new Error(`${repository} immutable tag has no valid index digest`)+ }+ for (const platform of REQUIRED_CONTAINER_PLATFORMS) {+ const image = snapshot.image?.[platform]+ if (!image || typeof image !== 'object') {+ throw new Error(`${repository} immutable tag is missing ${platform}`)+ }+ const labels = image.config?.Labels+ if (!labels || typeof labels !== 'object') {+ throw new Error(`${repository} ${platform} has no OCI labels`)+ }+ const expectedLabels = resolveContainerLabels({ revision, version })+ for (const [key, expected] of Object.entries(expectedLabels)) {+ if (labels[key] !== expected) {+ throw new Error(+ `${repository} immutable tag conflicts at ${platform} label ${key}`+ )+ }+ }+ if (image.config?.User !== 'node') {+ throw new Error(`${repository} ${platform} default user is not node`)+ }+ }+ return { digest, repository }+}++export function resolveContainerPublicationState({+ dockerHubSnapshot,+ ghcrSnapshot,+ revision,+ version,+}) {+ resolveContainerReleaseMetadata(version)+ const dockerHub = inspectedImage(+ dockerHubSnapshot,+ CONTAINER_REPOSITORIES.dockerHub,+ revision,+ version+ )+ const ghcr = inspectedImage(+ ghcrSnapshot,+ CONTAINER_REPOSITORIES.ghcr,+ revision,+ version+ )++ if (!dockerHub && !ghcr) {+ return { action: 'build', digest: '', copySource: '', copyTarget: '' }+ }+ if (dockerHub && ghcr) {+ if (dockerHub.digest !== ghcr.digest) {+ throw new Error(+ `Immutable container tags disagree: ${dockerHub.digest} != ${ghcr.digest}`+ )+ }+ return {+ action: 'resume',+ digest: dockerHub.digest,+ copySource: '',+ copyTarget: '',+ }+ }++ const existing = dockerHub ?? ghcr+ const missingRepository = dockerHub+ ? CONTAINER_REPOSITORIES.ghcr+ : CONTAINER_REPOSITORIES.dockerHub+ return {+ action: 'copy',+ digest: existing.digest,+ copySource: `${existing.repository}@${existing.digest}`,+ copyTarget: `${missingRepository}:${version}`,+ }+}++function parseArgs(argv) {+ const options = { githubOutput: process.env.GITHUB_OUTPUT }+ for (let index = 0; index < argv.length; index += 1) {+ const argument = argv[index]+ const value = argv[index + 1]+ if (+ ![+ '--docker-hub-snapshot',+ '--ghcr-snapshot',+ '--version',+ '--revision',+ '--github-output',+ ].includes(argument)+ ) {+ throw new Error(`Unknown argument: ${argument}`)+ }+ if (!value || value.startsWith('--')) {+ throw new Error(`${argument} requires a value`)+ }+ if (argument === '--docker-hub-snapshot') options.dockerHubSnapshot = value+ else if (argument === '--ghcr-snapshot') options.ghcrSnapshot = value+ else if (argument === '--github-output') options.githubOutput = value+ else options[argument.slice(2)] = value+ index += 1+ }+ return options+}++function readSnapshot(target) {+ return JSON.parse(readFileSync(target, 'utf8'))+}++function appendOutput(target, key, value) {+ appendFileSync(target, `${key}=${value}\n`, 'utf8')+}++function main() {+ const options = parseArgs(process.argv.slice(2))+ for (const key of [+ 'dockerHubSnapshot',+ 'ghcrSnapshot',+ 'version',+ 'revision',+ ]) {+ if (!options[key]) throw new Error(`${key} is required`)+ }+ const state = resolveContainerPublicationState({+ dockerHubSnapshot: readSnapshot(options.dockerHubSnapshot),+ ghcrSnapshot: readSnapshot(options.ghcrSnapshot),+ revision: options.revision,+ version: options.version,+ })+ if (!options.githubOutput) {+ process.stdout.write(`${JSON.stringify(state)}\n`)+ return+ }+ appendOutput(options.githubOutput, 'publication_action', state.action)+ appendOutput(options.githubOutput, 'publication_digest', state.digest)+ appendOutput(options.githubOutput, 'copy_source', state.copySource)+ appendOutput(options.githubOutput, 'copy_target', state.copyTarget)+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ main()+}diff --git a/scripts/container-release-metadata.mjs b/scripts/container-release-metadata.mjsnew file mode 100644index 00000000..5c598bba--- /dev/null+++ b/scripts/container-release-metadata.mjs@@ -0,0 +1,157 @@+import { appendFileSync } from 'node:fs'+import { pathToFileURL } from 'node:url'+import { parseStrictSemVer } from './release-metadata.mjs'++export const CONTAINER_REPOSITORIES = Object.freeze({+ dockerHub: 'docker.io/motrixapp/motrix-server',+ ghcr: 'ghcr.io/agalwood/motrix-server',+})++export const CONTAINER_LABELS = Object.freeze({+ 'org.opencontainers.image.description':+ 'Motrix Server web download manager for persistent NAS deployments',+ 'org.opencontainers.image.documentation':+ 'https://github.com/agalwood/Motrix/blob/main/docs/docker-server.md',+ 'org.opencontainers.image.licenses': 'MIT',+ 'org.opencontainers.image.source': 'https://github.com/agalwood/Motrix',+ 'org.opencontainers.image.title': 'Motrix Server',+ 'org.opencontainers.image.url': 'https://motrix.app',+})++const GIT_REVISION_PATTERN = /^[0-9a-f]{40}$/++export function resolveContainerReleaseMetadata(version) {+ const semver = parseStrictSemVer(version, 'container release version')+ if (version.includes('+')) {+ throw new Error(+ `container release version must not contain build metadata: ${version}`+ )+ }+ if (semver.prerelease && semver.channel !== 'beta') {+ throw new Error(+ `Container prerelease channel must be beta: ${semver.version}`+ )+ }++ const [major, minor] = version.split('-', 1)[0].split('.')+ const floatingTags = semver.prerelease+ ? []+ : [`${major}.${minor}`, major, 'stable', 'latest']++ return {+ version,+ prerelease: semver.prerelease,+ immutableTag: version,+ floatingTags,+ }+}++export function resolveContainerLabels({ revision, version }) {+ if (!GIT_REVISION_PATTERN.test(revision)) {+ throw new Error(+ `container revision must be a full lowercase SHA: ${revision}`+ )+ }+ const release = resolveContainerReleaseMetadata(version)+ return {+ ...CONTAINER_LABELS,+ 'org.opencontainers.image.revision': revision,+ 'org.opencontainers.image.version': release.version,+ }+}++export function containerImageTags(tags) {+ return Object.values(CONTAINER_REPOSITORIES).flatMap((repository) =>+ tags.map((tag) => `${repository}:${tag}`)+ )+}++function parseArgs(argv) {+ const options = { githubOutput: process.env.GITHUB_OUTPUT }+ for (let index = 0; index < argv.length; index += 1) {+ const argument = argv[index]+ const value = argv[index + 1]+ if (!['--version', '--revision', '--github-output'].includes(argument)) {+ throw new Error(`Unknown argument: ${argument}`)+ }+ if (!value || value.startsWith('--')) {+ throw new Error(`${argument} requires a value`)+ }+ if (argument === '--github-output') options.githubOutput = value+ else options[argument.slice(2)] = value+ index += 1+ }+ return options+}++function appendOutput(target, key, value) {+ const text = String(value)+ if (text.includes('\n')) {+ const delimiter = 'MOTRIX_CONTAINER_OUTPUT'+ if (text.includes(delimiter)) {+ throw new Error(`${key} contains the GitHub output delimiter`)+ }+ appendFileSync(+ target,+ `${key}<<${delimiter}\n${text}\n${delimiter}\n`,+ 'utf8'+ )+ return+ }+ appendFileSync(target, `${key}=${text}\n`, 'utf8')+}++function main() {+ const options = parseArgs(process.argv.slice(2))+ if (!options.version) throw new Error('--version is required')+ if (!options.revision) throw new Error('--revision is required')+ if (!options.githubOutput) {+ throw new Error('Expected --github-output or GITHUB_OUTPUT')+ }++ const metadata = resolveContainerReleaseMetadata(options.version)+ const labels = resolveContainerLabels({+ revision: options.revision,+ version: metadata.version,+ })+ appendOutput(options.githubOutput, 'container_version', metadata.version)+ appendOutput(+ options.githubOutput,+ 'container_dockerhub_repository',+ CONTAINER_REPOSITORIES.dockerHub+ )+ appendOutput(+ options.githubOutput,+ 'container_ghcr_repository',+ CONTAINER_REPOSITORIES.ghcr+ )+ appendOutput(+ options.githubOutput,+ 'container_prerelease',+ metadata.prerelease+ )+ appendOutput(+ options.githubOutput,+ 'container_immutable_tags',+ containerImageTags([metadata.immutableTag]).join('\n')+ )+ appendOutput(+ options.githubOutput,+ 'container_floating_tags',+ containerImageTags(metadata.floatingTags).join('\n')+ )+ appendOutput(+ options.githubOutput,+ 'container_labels',+ Object.entries(labels)+ .map(([key, value]) => `${key}=${value}`)+ .join('\n')+ )+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ main()+}diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjsindex f554b82d..2f2eeb36 100644--- a/scripts/smoke-server-image.mjs+++ b/scripts/smoke-server-image.mjs@@ -17,6 +17,10 @@ import path from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'import { promisify } from 'node:util'import { resolveSmokeContainerIdentity } from './smoke-server-identity.mjs'+import {+ resolveSmokeMode,+ resolveSmokePlatform,+} from './smoke-server-platform.mjs'const execFileAsync = promisify(execFile)const DEFAULT_TIMEOUT_MS = 120_000@@ -41,6 +45,10 @@ const HTTP_FIXTURE = Buffer.from('Motrix Docker Server persistent HTTP fixture\n'.repeat(16_384))+function platformArgs(platform) {+ return platform ? ['--platform', platform] : []+}+async function docker(args, options = {}) {const result = await execFileAsync('docker', args, {encoding: 'utf8',@@ -360,7 +368,7 @@ function parseArguments(argv) {if (!argument.startsWith('--'))throw new Error(`unknown argument: ${argument}`)const key = argument.slice(2)- if (!['image', 'timeout-ms'].includes(key)) {+ if (!['image', 'mode', 'platform', 'timeout-ms'].includes(key)) {throw new Error(`unknown option: --${key}`)}const value = argv[index + 1]@@ -371,6 +379,8 @@ function parseArguments(argv) {index += 1}if (!options.image) throw new Error('--image is required')+ resolveSmokeMode(options.mode)+ resolveSmokePlatform(options.platform)return options}@@ -396,9 +406,11 @@ async function startServerContainer(options) {downloadsDir,operatorToken,identity,+ platform,} = optionsawait docker(['run',+ ...platformArgs(platform),'--detach','--name',name,@@ -407,6 +419,8 @@ async function startServerContainer(options) {'--add-host','host.docker.internal:host-gateway','--read-only',+ '--tmpfs',+ '/tmp:rw,noexec,nosuid,size=64m','--security-opt','no-new-privileges:true','--user',@@ -467,8 +481,10 @@ async function assertRuntimeContract(name, url, token, identity, timeoutMs) {'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'",+ "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"',+ "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('; '),])const hostConfig = JSON.parse(@@ -615,10 +631,13 @@ async function assertPermissionFailure(options) {try {await docker(['run',+ ...platformArgs(options.platform),'--detach','--name',name,'--read-only',+ '--tmpfs',+ '/tmp:rw,noexec,nosuid,size=64m','--user',options.identity.user,'--env',@@ -647,12 +666,36 @@ async function assertPermissionFailure(options) {}}+function imageSmokeSummary(metadata, diagnostics, identity, startedAt) {+ return {+ imageId: metadata.Id,+ imageBytes: metadata.Size,+ architecture: metadata.Architecture,+ 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',+ shutdown: 'SIGTERM',+ durationMs: Date.now() - startedAt,+ }+}+export async function smokeServerImage(options) {const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MSif (!Number.isSafeInteger(timeoutMs) || timeoutMs < 30_000) {throw new Error('Server image smoke timeout must be at least 30000ms')}const image = options.image+ const mode = resolveSmokeMode(options.mode)+ const platform = resolveSmokePlatform(options.platform)const identity = resolveSmokeContainerIdentity()const prefix = `motrix-server-smoke-${process.pid}-${Date.now()}`const appName = `${prefix}-app`@@ -667,7 +710,10 @@ export async function smokeServerImage(options) {let seedCreated = falselet networkCreated = falsetry {- const metadata = JSON.parse(await docker(['image', 'inspect', image]))[0]+ if (platform) await docker(['pull', '--platform', platform, image])+ const metadata = JSON.parse(+ await docker(['image', 'inspect', ...platformArgs(platform), image])+ )[0]if (metadata.Config.User !== 'node') {throw new Error(`Server image default user is ${metadata.Config.User || 'root'}`@@ -676,6 +722,11 @@ export async function smokeServerImage(options) {if (!metadata.Config.Healthcheck) {throw new Error('Server image has no Docker HEALTHCHECK')}+ if (platform && metadata.Architecture !== platform.split('/')[1]) {+ throw new Error(+ `Server image architecture is ${metadata.Architecture}, expected ${platform}`+ )+ }await docker(['network', 'create', network])networkCreated = true@@ -693,6 +744,7 @@ export async function smokeServerImage(options) {await writeFile(localTorrentPath, torrentBytes)await docker(['run',+ ...platformArgs(platform),'--detach','--name',seedName,@@ -700,6 +752,8 @@ export async function smokeServerImage(options) {network,'--add-host','host.docker.internal:host-gateway',+ '--tmpfs',+ '/tmp:rw,noexec,nosuid,size=64m','--mount',`type=bind,source=${seedRoot},target=/seed,readonly`,image,@@ -735,6 +789,7 @@ export async function smokeServerImage(options) {...volumes,operatorToken,identity,+ platform,timeoutMs,})appCreated = true@@ -746,6 +801,16 @@ export async function smokeServerImage(options) {timeoutMs)+ if (mode === 'health') {+ await stopServer(appName, timeoutMs)+ await docker(['rm', appName])+ appCreated = false+ return {+ ...imageSmokeSummary(metadata, diagnostics, identity, startedAt),+ mode,+ }+ }+const settings = await rpc(url, operatorToken, 'query', 'query:getSettings')const allowed = await rpc(url,@@ -891,6 +956,7 @@ export async function smokeServerImage(options) {...volumes,operatorToken,identity,+ platform,timeoutMs,})appCreated = true@@ -963,33 +1029,19 @@ export async function smokeServerImage(options) {dataDir: volumes.deniedDataDir,downloadsDir: volumes.downloadsDir,identity,+ platform,timeoutMs,})return {- imageId: metadata.Id,- imageBytes: metadata.Size,- architecture: metadata.Architecture,- 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',+ ...imageSmokeSummary(metadata, diagnostics, identity, startedAt),+ mode,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 appLogs = appCreated@@ -1031,6 +1083,8 @@ if (const raw = parseArguments(process.argv.slice(2))smokeServerImage({image: raw.image,+ mode: raw.mode,+ platform: raw.platform,timeoutMs: raw['timeout-ms']? Number.parseInt(raw['timeout-ms'], 10): undefined,diff --git a/scripts/smoke-server-platform.mjs b/scripts/smoke-server-platform.mjsnew file mode 100644index 00000000..139be796--- /dev/null+++ b/scripts/smoke-server-platform.mjs@@ -0,0 +1,15 @@+export function resolveSmokePlatform(value) {+ if (value === undefined) return undefined+ if (!['linux/amd64', 'linux/arm64'].includes(value)) {+ throw new Error(`unsupported Server image smoke platform: ${value}`)+ }+ return value+}++export function resolveSmokeMode(value) {+ if (value === undefined) return 'full'+ if (!['full', 'health'].includes(value)) {+ throw new Error(`unsupported Server image smoke mode: ${value}`)+ }+ return value+}diff --git a/scripts/verify-container-publication.mjs b/scripts/verify-container-publication.mjsnew file mode 100644index 00000000..7d1c315a--- /dev/null+++ b/scripts/verify-container-publication.mjs@@ -0,0 +1,337 @@+import { readFileSync } from 'node:fs'+import { pathToFileURL } from 'node:url'+import {+ REQUIRED_CONTAINER_PLATFORMS,+ resolveContainerPublicationState,+} from './container-publication-state.mjs'++const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/+const INDEX_MEDIA_TYPES = new Set([+ 'application/vnd.docker.distribution.manifest.list.v2+json',+ 'application/vnd.oci.image.index.v1+json',+])+const LEGACY_BUILD_TYPE = 'https://mobyproject.org/buildkit@v1'+const BUILD_TYPE =+ 'https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md'++function record(value, label) {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new Error(`${label} must be an object`)+ }+ return value+}++function array(value, label) {+ if (!Array.isArray(value)) throw new Error(`${label} must be an array`)+ return value+}++function string(value, label) {+ if (typeof value !== 'string' || !value) {+ throw new Error(`${label} must be a non-empty string`)+ }+ return value+}++function digest(value, label) {+ const result = string(value, label)+ if (!DIGEST_PATTERN.test(result)) {+ throw new Error(`${label} must be a sha256 digest`)+ }+ return result+}++function verifyIndex(index, repository) {+ const document = record(index, `${repository} index`)+ if (document.schemaVersion !== 2) {+ throw new Error(`${repository} index must use schemaVersion 2`)+ }+ if (!INDEX_MEDIA_TYPES.has(document.mediaType)) {+ throw new Error(`${repository} is not a multi-architecture image index`)+ }+ const descriptors = array(document.manifests, `${repository} manifests`)+ const platformDigests = new Map()+ for (const descriptorValue of descriptors) {+ const descriptor = record(descriptorValue, `${repository} descriptor`)+ const platform = record(+ descriptor.platform,+ `${repository} descriptor platform`+ )+ const key = `${platform.os}/${platform.architecture}`+ if (!REQUIRED_CONTAINER_PLATFORMS.includes(key)) continue+ if (platformDigests.has(key)) {+ throw new Error(`${repository} has duplicate ${key} image manifests`)+ }+ platformDigests.set(+ key,+ digest(descriptor.digest, `${repository} ${key} manifest digest`)+ )+ }++ for (const platform of REQUIRED_CONTAINER_PLATFORMS) {+ const subjectDigest = platformDigests.get(platform)+ if (!subjectDigest) {+ throw new Error(`${repository} index is missing ${platform}`)+ }+ const attestations = descriptors.filter((descriptorValue) => {+ const descriptor = record(descriptorValue, `${repository} descriptor`)+ const annotations = descriptor.annotations+ return (+ annotations?.['vnd.docker.reference.type'] === 'attestation-manifest' &&+ annotations?.['vnd.docker.reference.digest'] === subjectDigest+ )+ })+ if (attestations.length !== 1) {+ throw new Error(+ `${repository} ${platform} must have exactly one attestation manifest`+ )+ }+ digest(+ attestations[0].digest,+ `${repository} ${platform} attestation digest`+ )+ }+ return Object.fromEntries(platformDigests)+}++function verifySbom(sbom, repository) {+ const document = record(sbom, `${repository} SBOM result`)+ for (const platform of REQUIRED_CONTAINER_PLATFORMS) {+ const platformResult = record(+ document[platform],+ `${repository} ${platform} SBOM result`+ )+ const spdx = record(platformResult.SPDX, `${repository} ${platform} SPDX`)+ if (spdx.SPDXID !== 'SPDXRef-DOCUMENT') {+ throw new Error(`${repository} ${platform} has no SPDX document root`)+ }+ if (!/^SPDX-2\.[0-9]+$/.test(spdx.spdxVersion)) {+ throw new Error(`${repository} ${platform} has no SPDX 2.x version`)+ }+ string(+ spdx.documentNamespace,+ `${repository} ${platform} SPDX document namespace`+ )+ if (+ array(spdx.packages, `${repository} ${platform} SPDX packages`).length < 1+ ) {+ throw new Error(`${repository} ${platform} SPDX package list is empty`)+ }+ }+}++function verifyProvenance(provenance, repository, revision, builderIdPrefix) {+ const document = record(provenance, `${repository} provenance result`)+ for (const platform of REQUIRED_CONTAINER_PLATFORMS) {+ const platformResult = record(+ document[platform],+ `${repository} ${platform} provenance result`+ )+ const slsa = record(+ platformResult.SLSA,+ `${repository} ${platform} SLSA provenance`+ )+ let builderId+ if (slsa.buildDefinition) {+ const definition = record(+ slsa.buildDefinition,+ `${repository} ${platform} build definition`+ )+ if (definition.buildType !== BUILD_TYPE) {+ throw new Error(+ `${repository} ${platform} has an unexpected build type`+ )+ }+ record(+ definition.externalParameters,+ `${repository} ${platform} external parameters`+ )+ record(+ definition.internalParameters,+ `${repository} ${platform} internal parameters`+ )+ if (+ array(+ definition.resolvedDependencies,+ `${repository} ${platform} resolved dependencies`+ ).length < 1+ ) {+ throw new Error(+ `${repository} ${platform} provenance has no resolved dependencies`+ )+ }+ const runDetails = record(+ slsa.runDetails,+ `${repository} ${platform} run details`+ )+ const rawBuilderId = record(+ runDetails.builder,+ `${repository} ${platform} builder`+ ).id+ if (typeof rawBuilderId !== 'string') {+ throw new Error(`${repository} ${platform} builder id must be a string`)+ }+ builderId = rawBuilderId+ const metadata = record(+ runDetails.metadata,+ `${repository} ${platform} metadata`+ )+ const completeness = record(+ metadata.buildkit_completeness,+ `${repository} ${platform} BuildKit completeness`+ )+ if (completeness.request !== true) {+ throw new Error(`${repository} ${platform} build request is incomplete`)+ }+ const vcs = record(+ record(+ metadata.buildkit_metadata,+ `${repository} ${platform} BuildKit metadata`+ ).vcs,+ `${repository} ${platform} VCS metadata`+ )+ if (vcs.revision !== revision) {+ throw new Error(+ `${repository} ${platform} provenance revision conflicts`+ )+ }+ if (+ !string(vcs.source, `${repository} ${platform} VCS source`).includes(+ 'agalwood/Motrix'+ )+ ) {+ throw new Error(`${repository} ${platform} provenance source conflicts`)+ }+ } else {+ if (slsa.buildType !== LEGACY_BUILD_TYPE) {+ throw new Error(+ `${repository} ${platform} has an unexpected build type`+ )+ }+ builderId = string(+ record(slsa.builder, `${repository} ${platform} builder`).id,+ `${repository} ${platform} builder id`+ )+ record(slsa.invocation, `${repository} ${platform} invocation`)+ record(slsa.buildConfig, `${repository} ${platform} build config`)+ if (+ array(slsa.materials, `${repository} ${platform} materials`).length < 1+ ) {+ throw new Error(`${repository} ${platform} provenance has no materials`)+ }+ const completeness = record(+ record(slsa.metadata, `${repository} ${platform} metadata`)+ .completeness,+ `${repository} ${platform} completeness`+ )+ for (const field of ['parameters', 'environment', 'materials']) {+ if (completeness[field] !== true) {+ throw new Error(+ `${repository} ${platform} provenance is incomplete at ${field}`+ )+ }+ }+ }+ if (builderIdPrefix && !builderId.startsWith(builderIdPrefix)) {+ throw new Error(`${repository} ${platform} builder identity conflicts`)+ }+ }+}++function verifyArtifact(artifact, repository, revision, builderIdPrefix) {+ const platformDigests = verifyIndex(artifact.index, repository)+ verifySbom(artifact.sbom, repository)+ verifyProvenance(artifact.provenance, repository, revision, builderIdPrefix)+ return platformDigests+}++export function verifyContainerPublication({+ builderIdPrefix,+ dockerHub,+ ghcr,+ revision,+ version,+}) {+ const publication = resolveContainerPublicationState({+ dockerHubSnapshot: dockerHub.inspect,+ ghcrSnapshot: ghcr.inspect,+ revision,+ version,+ })+ if (publication.action !== 'resume') {+ throw new Error(+ `Container publication is incomplete: ${publication.action}`+ )+ }+ return {+ digest: publication.digest,+ platforms: REQUIRED_CONTAINER_PLATFORMS,+ dockerHub: verifyArtifact(+ dockerHub,+ 'Docker Hub',+ revision,+ builderIdPrefix+ ),+ ghcr: verifyArtifact(ghcr, 'GHCR', revision, builderIdPrefix),+ sbom: 'SPDX-2.x',+ provenance: 'SLSA BuildKit',+ }+}++function parseArgs(argv) {+ const options = {}+ const allowed = new Set([+ '--docker-hub-inspect',+ '--docker-hub-index',+ '--docker-hub-sbom',+ '--docker-hub-provenance',+ '--ghcr-inspect',+ '--ghcr-index',+ '--ghcr-sbom',+ '--ghcr-provenance',+ '--builder-id-prefix',+ '--version',+ '--revision',+ ])+ for (let index = 0; index < argv.length; index += 2) {+ const argument = argv[index]+ const value = argv[index + 1]+ if (!allowed.has(argument)) throw new Error(`Unknown argument: ${argument}`)+ if (!value || value.startsWith('--')) {+ throw new Error(`${argument} requires a value`)+ }+ options[argument.slice(2)] = value+ }+ return options+}++function readArtifact(options, prefix) {+ const artifact = {}+ for (const field of ['inspect', 'index', 'sbom', 'provenance']) {+ const path = options[`${prefix}-${field}`]+ if (!path) throw new Error(`--${prefix}-${field} is required`)+ artifact[field] = JSON.parse(readFileSync(path, 'utf8'))+ }+ return artifact+}++function main() {+ const options = parseArgs(process.argv.slice(2))+ if (!options.version) throw new Error('--version is required')+ if (!options.revision) throw new Error('--revision is required')+ const result = verifyContainerPublication({+ builderIdPrefix: options['builder-id-prefix'],+ dockerHub: readArtifact(options, 'docker-hub'),+ ghcr: readArtifact(options, 'ghcr'),+ revision: options.revision,+ version: options.version,+ })+ process.stdout.write(`${JSON.stringify(result)}\n`)+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ main()+}diff --git a/src/server/operator-token.test.ts b/src/server/operator-token.test.tsindex a682db66..4ba26938 100644--- a/src/server/operator-token.test.ts+++ b/src/server/operator-token.test.ts@@ -1,4 +1,4 @@-import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'+import { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'@@ -34,4 +34,39 @@ describe('provisionOperatorToken', () => {// …and only the owner can.expect((await stat(r.path as string)).mode & 0o777).toBe(0o600)})++ it('reuses the generated file across restarts and repairs its mode', async () => {+ const path = join(dir, 'operator-token')+ const token = 'a'.repeat(43)+ await writeFile(path, token, { mode: 0o644 })+ await chmod(path, 0o644)++ await expect(+ provisionOperatorToken({ dataDir: dir, env: {} })+ ).resolves.toEqual({ token, source: 'file', path })+ expect(await readFile(path, 'utf8')).toBe(token)+ expect((await stat(path)).mode & 0o777).toBe(0o600)+ })++ it('converges concurrent first-start provisioning on one token', async () => {+ const results = await Promise.all(+ Array.from({ length: 8 }, () =>+ provisionOperatorToken({ dataDir: dir, env: {} })+ )+ )+ expect(new Set(results.map((result) => result.token)).size).toBe(1)+ expect(await readFile(join(dir, 'operator-token'), 'utf8')).toBe(+ results[0]?.token+ )+ })++ it('refuses to rotate an invalid persistent token silently', async () => {+ const path = join(dir, 'operator-token')+ await writeFile(path, 'not-a-valid-generated-token', { mode: 0o600 })++ await expect(+ provisionOperatorToken({ dataDir: dir, env: {} })+ ).rejects.toThrow(/Operator token file is invalid/)+ expect(await readFile(path, 'utf8')).toBe('not-a-valid-generated-token')+ })})diff --git a/src/server/operator-token.ts b/src/server/operator-token.tsindex 3a73f382..c388c4dd 100644--- a/src/server/operator-token.ts+++ b/src/server/operator-token.ts@@ -1,7 +1,9 @@import { randomBytes } from 'node:crypto'-import { chmod, mkdir, writeFile } from 'node:fs/promises'+import { chmod, lstat, mkdir, readFile, writeFile } from 'node:fs/promises'import { dirname, join } from 'node:path'+const FILE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43,128}$/+export interface ProvisionedOperatorToken {token: stringsource: 'env' | 'file'@@ -31,10 +33,39 @@ export async function provisionOperatorToken(opts: {if (typeof fromEnv === 'string' && fromEnv.length > 0) {return { token: fromEnv, source: 'env' }}- const token = randomBytes(32).toString('base64url')const path = join(opts.dataDir, 'operator-token')await mkdir(dirname(path), { recursive: true })- await writeFile(path, token, { mode: 0o600 })+ const existing = await readExistingToken(path)+ if (existing) return { token: existing, source: 'file', path }++ const token = randomBytes(32).toString('base64url')+ try {+ await writeFile(path, token, { flag: 'wx', mode: 0o600 })+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error+ const concurrent = await readExistingToken(path)+ if (concurrent) return { token: concurrent, source: 'file', path }+ throw error+ }await chmod(path, 0o600)return { token, source: 'file', path }}++async function readExistingToken(path: string): Promise<string | undefined> {+ let metadata: Awaited<ReturnType<typeof lstat>>+ try {+ metadata = await lstat(path)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined+ throw error+ }+ if (!metadata.isFile()) {+ throw new Error(`Operator token path is not a regular file: ${path}`)+ }+ const token = await readFile(path, 'utf8')+ if (!FILE_TOKEN_PATTERN.test(token)) {+ throw new Error(`Operator token file is invalid: ${path}`)+ }+ await chmod(path, 0o600)+ return token+}diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.tsindex de166069..5c72db62 100644--- a/tests/check-third-party-notices.test.ts+++ b/tests/check-third-party-notices.test.ts@@ -419,8 +419,8 @@ describe('third-party graph dependency notices', () => {expect(manifest.devDependencies?.vitest).toBeDefined()expect(installCommand).toBeDefined()expect(isProductionOnlyInstall(installCommand ?? '')).toBe(false)- expect(dockerfile).toContain('FROM node:24-alpine AS deps')- expect(dockerfile).toContain('FROM node:24-alpine AS runtime')+ expect(dockerfile).toContain('FROM ${' + 'NODE_IMAGE} AS deps')+ expect(dockerfile).toContain('FROM ${' + 'NODE_IMAGE} AS runtime')expect(electronInstallIndex).toBeGreaterThanOrEqual(0)expect(gateIndex).toBeGreaterThan(electronInstallIndex)expect(buildIndex).toBeGreaterThan(gateIndex)diff --git a/tests/scripts/compose-server.test.ts b/tests/scripts/compose-server.test.tsnew file mode 100644index 00000000..b68d3b30--- /dev/null+++ b/tests/scripts/compose-server.test.ts@@ -0,0 +1,94 @@+import { readFile } from 'node:fs/promises'+import { createRequire } from 'node:module'+import path from 'node:path'+import { describe, expect, it } from 'vitest'++interface LooseRecord {+ [key: string]: unknown+}++const ROOT = process.cwd()+const require = createRequire(import.meta.url)+const parseYaml = require('js-yaml').load as (source: string) => unknown+const interpolation = (value: string) => ['$', `{${value}}`].join('')+const IMAGE = interpolation('MOTRIX_IMAGE:-motrixapp/motrix-server:latest')+const BIND_IP = interpolation('MOTRIX_BIND_IP:-0.0.0.0')+const HTTP_PORT = interpolation('MOTRIX_HTTP_PORT:-8080')+const MDXP_PORT = interpolation('MOTRIX_MDXP_PUBLIC_PORT:-16801')+const PUBLIC_URL = interpolation('MOTRIX_PUBLIC_URL:-http://localhost:8080')++function record(value: unknown, label: string): LooseRecord {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new TypeError(`${label} must be an object`)+ }+ return value as LooseRecord+}++async function compose(file: string) {+ return record(parseYaml(await readFile(path.join(ROOT, file), 'utf8')), file)+}++function server(document: LooseRecord) {+ return record(record(document.services, 'services').server, 'server')+}++describe('NAS-importable Compose contract', () => {+ it.each(['compose.yaml', 'compose.named-volumes.yaml'])(+ '%s pulls the official image and retains the hardened runtime',+ async (file) => {+ const service = server(await compose(file))++ expect(service).not.toHaveProperty('build')+ expect(service).not.toHaveProperty('container_name')+ expect(service).not.toHaveProperty('privileged')+ expect(service.image).toBe(IMAGE)+ expect(service.init).toBe(true)+ expect(service.read_only).toBe(true)+ expect(service.restart).toBe('unless-stopped')+ expect(service.stop_grace_period).toBe('2m')+ expect(service.security_opt).toEqual(['no-new-privileges:true'])+ expect(service.tmpfs).toEqual([+ '/tmp:rw,noexec,nosuid,size=64m,mode=1777',+ ])+ expect(service.ports).toEqual([+ `${BIND_IP}:${HTTP_PORT}:8080`,+ `${BIND_IP}:${MDXP_PORT}:16801`,+ ])+ expect(service.environment).toEqual({+ MOTRIX_ALLOWED_SAVE_DIRS: '/downloads',+ MOTRIX_DATA_DIR: '/data',+ MOTRIX_DEFAULT_SAVE_DIR: '/downloads',+ MOTRIX_MDXP_HOST: '0.0.0.0',+ MOTRIX_MDXP_PORT: 16801,+ MOTRIX_PLUGIN_DIR: '/data/plugins',+ MOTRIX_PUBLIC_URL: PUBLIC_URL,+ MOTRIX_TEMP_DIR: '/data/tmp',+ })+ }+ )++ it('uses two independent relative bind mounts in the NAS project', async () => {+ const service = server(await compose('compose.yaml'))+ expect(service.user).toBe(+ `${interpolation('MOTRIX_UID:-1000')}:${interpolation('MOTRIX_GID:-1000')}`+ )+ expect(service.volumes).toEqual([+ './motrix-data:/data',+ './downloads:/downloads',+ ])+ })++ it('offers an independent named-volume variant without changing service behavior', async () => {+ const document = await compose('compose.named-volumes.yaml')+ const service = server(document)+ expect(service.user).toBe('1000:1000')+ expect(service.volumes).toEqual([+ 'motrix-data:/data',+ 'motrix-downloads:/downloads',+ ])+ expect(document.volumes).toEqual({+ 'motrix-data': null,+ 'motrix-downloads': null,+ })+ })+})diff --git a/tests/scripts/container-publication-state.test.ts b/tests/scripts/container-publication-state.test.tsnew file mode 100644index 00000000..f32207b6--- /dev/null+++ b/tests/scripts/container-publication-state.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import { resolveContainerPublicationState } from '../../scripts/container-publication-state.mjs'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import {+ CONTAINER_LABELS,+ CONTAINER_REPOSITORIES,+} from '../../scripts/container-release-metadata.mjs'++const VERSION = '2.3.4'+const REVISION = 'a'.repeat(40)+const DIGEST = `sha256:${'b'.repeat(64)}`++function snapshot(options?: {+ digest?: string+ revision?: string+ user?: string+ platforms?: string[]+}) {+ const platforms = options?.platforms ?? ['linux/amd64', 'linux/arm64']+ return {+ manifest: { digest: options?.digest ?? DIGEST },+ image: Object.fromEntries(+ platforms.map((platform) => [+ platform,+ {+ config: {+ User: options?.user ?? 'node',+ Labels: {+ ...CONTAINER_LABELS,+ 'org.opencontainers.image.revision':+ options?.revision ?? REVISION,+ 'org.opencontainers.image.version': VERSION,+ },+ },+ },+ ])+ ),+ }+}++describe('container publication state', () => {+ it('builds only when neither immutable tag exists', () => {+ expect(+ resolveContainerPublicationState({+ dockerHubSnapshot: null,+ ghcrSnapshot: null,+ revision: REVISION,+ version: VERSION,+ })+ ).toEqual({ action: 'build', digest: '', copySource: '', copyTarget: '' })+ })++ it('resumes an identical complete publication', () => {+ expect(+ resolveContainerPublicationState({+ dockerHubSnapshot: snapshot(),+ ghcrSnapshot: snapshot(),+ revision: REVISION,+ version: VERSION,+ })+ ).toEqual({+ action: 'resume',+ digest: DIGEST,+ copySource: '',+ copyTarget: '',+ })+ })++ it.each([+ [+ 'Docker Hub to GHCR',+ snapshot(),+ null,+ `${CONTAINER_REPOSITORIES.dockerHub}@${DIGEST}`,+ `${CONTAINER_REPOSITORIES.ghcr}:${VERSION}`,+ ],+ [+ 'GHCR to Docker Hub',+ null,+ snapshot(),+ `${CONTAINER_REPOSITORIES.ghcr}@${DIGEST}`,+ `${CONTAINER_REPOSITORIES.dockerHub}:${VERSION}`,+ ],+ ])(+ 'repairs a partial %s publication without rebuilding',+ (_, dockerHubSnapshot, ghcrSnapshot, copySource, copyTarget) => {+ expect(+ resolveContainerPublicationState({+ dockerHubSnapshot,+ ghcrSnapshot,+ revision: REVISION,+ version: VERSION,+ })+ ).toEqual({ action: 'copy', digest: DIGEST, copySource, copyTarget })+ }+ )++ it('refuses to replace disagreeing immutable tags', () => {+ expect(() =>+ resolveContainerPublicationState({+ dockerHubSnapshot: snapshot(),+ ghcrSnapshot: snapshot({ digest: `sha256:${'c'.repeat(64)}` }),+ revision: REVISION,+ version: VERSION,+ })+ ).toThrow(/Immutable container tags disagree/)+ })++ it.each([+ ['wrong revision', snapshot({ revision: 'c'.repeat(40) }), /conflicts/],+ ['root user', snapshot({ user: 'root' }), /default user is not node/],+ [+ 'missing architecture',+ snapshot({ platforms: ['linux/amd64'] }),+ /missing linux\/arm64/,+ ],+ ])('refuses %s on an existing immutable tag', (_, dockerHub, error) => {+ expect(() =>+ resolveContainerPublicationState({+ dockerHubSnapshot: dockerHub,+ ghcrSnapshot: null,+ revision: REVISION,+ version: VERSION,+ })+ ).toThrow(error)+ })++ it('rejects malformed release revisions before publication', () => {+ expect(() =>+ resolveContainerPublicationState({+ dockerHubSnapshot: snapshot(),+ ghcrSnapshot: null,+ revision: 'abc123',+ version: VERSION,+ })+ ).toThrow(/full lowercase SHA/)+ })+})diff --git a/tests/scripts/container-release-metadata.test.ts b/tests/scripts/container-release-metadata.test.tsnew file mode 100644index 00000000..e4fe37f9--- /dev/null+++ b/tests/scripts/container-release-metadata.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import {+ CONTAINER_LABELS,+ CONTAINER_REPOSITORIES,+ containerImageTags,+ resolveContainerLabels,+ resolveContainerReleaseMetadata,+} from '../../scripts/container-release-metadata.mjs'++describe('container release metadata', () => {+ it('promotes a stable SemVer release through the documented aliases', () => {+ expect(resolveContainerReleaseMetadata('2.3.4')).toEqual({+ version: '2.3.4',+ prerelease: false,+ immutableTag: '2.3.4',+ floatingTags: ['2.3', '2', 'stable', 'latest'],+ })+ })++ it('keeps prereleases off every stable floating alias', () => {+ expect(resolveContainerReleaseMetadata('2.3.4-beta.2')).toEqual({+ version: '2.3.4-beta.2',+ prerelease: true,+ immutableTag: '2.3.4-beta.2',+ floatingTags: [],+ })+ })++ it.each(['2.3.4+build.1', '2.3.4-rc.1', '2.3.4-nightly.1'])(+ 'rejects image version %s outside the release contract',+ (version) => {+ expect(() => resolveContainerReleaseMetadata(version)).toThrow()+ }+ )++ it('expands the same immutable tag for Docker Hub and GHCR', () => {+ expect(containerImageTags(['2.3.4'])).toEqual([+ `${CONTAINER_REPOSITORIES.dockerHub}:2.3.4`,+ `${CONTAINER_REPOSITORIES.ghcr}:2.3.4`,+ ])+ })++ it('publishes Docker Hub images from the Motrix project namespace', () => {+ expect(CONTAINER_REPOSITORIES.dockerHub).toBe(+ 'docker.io/motrixapp/motrix-server'+ )+ expect(CONTAINER_REPOSITORIES.ghcr).toBe('ghcr.io/agalwood/motrix-server')+ })++ it('emits complete OCI source identity labels', () => {+ const revision = 'a'.repeat(40)+ expect(resolveContainerLabels({ revision, version: '2.3.4' })).toEqual({+ ...CONTAINER_LABELS,+ 'org.opencontainers.image.revision': revision,+ 'org.opencontainers.image.version': '2.3.4',+ })+ })++ it.each(['abc123', 'A'.repeat(40), 'a'.repeat(39), `${'a'.repeat(40)}\n`])(+ 'rejects unsafe revision %j',+ (revision) => {+ expect(() =>+ resolveContainerLabels({ revision, version: '2.3.4' })+ ).toThrow(/full lowercase SHA/)+ }+ )+})diff --git a/tests/scripts/docker-server-docs.test.ts b/tests/scripts/docker-server-docs.test.tsnew file mode 100644index 00000000..e19bf802--- /dev/null+++ b/tests/scripts/docker-server-docs.test.ts@@ -0,0 +1,56 @@+import { readFile } from 'node:fs/promises'+import path from 'node:path'+import { describe, expect, it } from 'vitest'++const ROOT = process.cwd()++async function text(file: string) {+ return readFile(path.join(ROOT, file), 'utf8')+}++describe('public Docker Server documentation', () => {+ it.each(['docs/docker-server.md', 'docs/docker-server.zh-CN.md'])(+ '%s covers the public NAS installation and lifecycle contract',+ async (file) => {+ const document = await text(file)++ for (const required of [+ 'docker.io/motrixapp/motrix-server',+ 'ghcr.io/agalwood/motrix-server',+ 'linux/amd64',+ 'linux/arm64',+ 'stable',+ 'latest',+ 'compose.yaml',+ 'compose.named-volumes.yaml',+ '/data',+ '/downloads',+ 'MOTRIX_UID',+ 'MOTRIX_GID',+ 'operator-token',+ 'MOTRIX_PUBLIC_URL',+ '/mdxp/events',+ '/healthz',+ '/api/diagnostics',+ 'DSM 7',+ 'fnOS',+ 'read-only',+ 'HTTPS',+ 'digest',+ ]) {+ expect(document, `${file} must mention ${required}`).toContain(required)+ }+ expect(document).not.toContain('docker compose up --build')+ }+ )++ it.each(['README.md', 'README.zh-CN.md'])(+ '%s uses the registry-first quick start',+ async (file) => {+ const document = await text(file)+ expect(document).toContain('docker compose pull server')+ expect(document).toContain('docker compose up -d --wait')+ expect(document).not.toContain('docker compose up --build')+ }+ )+})diff --git a/tests/scripts/docker-server-runtime.test.ts b/tests/scripts/docker-server-runtime.test.tsindex 5ef18313..36c49010 100644--- a/tests/scripts/docker-server-runtime.test.ts+++ b/tests/scripts/docker-server-runtime.test.ts@@ -2,10 +2,30 @@ 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'+// @ts-expect-error -- JavaScript smoke helper intentionally has no declarations+import {+ resolveSmokeMode,+ resolveSmokePlatform,+} from '../../scripts/smoke-server-platform.mjs'const ROOT = process.cwd()+const NODE_IMAGE_REFERENCE = '$' + '{NODE_IMAGE}'describe('Docker Server runtime staging contract', () => {+ it('limits explicit publication smoke to supported Linux architectures', () => {+ expect(resolveSmokePlatform(undefined)).toBeUndefined()+ expect(resolveSmokePlatform('linux/amd64')).toBe('linux/amd64')+ expect(resolveSmokePlatform('linux/arm64')).toBe('linux/arm64')+ expect(() => resolveSmokePlatform('linux/386')).toThrow(/unsupported/)+ })++ it('defaults image smoke to full and accepts a cross-architecture health mode', () => {+ expect(resolveSmokeMode(undefined)).toBe('full')+ expect(resolveSmokeMode('full')).toBe('full')+ expect(resolveSmokeMode('health')).toBe('health')+ expect(() => resolveSmokeMode('package-only')).toThrow(/unsupported/)+ })+it('maps smoke containers to a portable non-root host identity', () => {expect(resolveSmokeContainerIdentity(1001, 121)).toEqual({uid: 1001,@@ -27,9 +47,15 @@ describe('Docker Server runtime staging contract', () => {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(- dockerfile.indexOf('FROM node:24-alpine AS runtime')+ dockerfile.indexOf(`FROM ${NODE_IMAGE_REFERENCE} AS runtime`))+ expect(dockerfile).toMatch(+ /^# syntax=docker\/dockerfile:1\.7@sha256:[0-9a-f]{64}$/m+ )+ expect(dockerfile).toMatch(+ /^ARG NODE_IMAGE=node:24-alpine@sha256:[0-9a-f]{64}$/m+ )expect(runtime).toContain('COPY --from=build --chown=node:node /app/dist/server-app/ ./')@@ -50,6 +76,20 @@ describe('Docker Server runtime staging contract', () => {expect(runtime).toContain('STOPSIGNAL SIGTERM')expect(runtime).toContain('HEALTHCHECK --interval=30s')expect(runtime).toContain('CMD ["node", "dist/server/index.mjs"]')+ expect(runtime).toContain('ARG OCI_REVISION=unknown')+ expect(runtime).toContain('ARG OCI_VERSION=0.0.0-local')+ for (const label of [+ 'org.opencontainers.image.title',+ 'org.opencontainers.image.description',+ 'org.opencontainers.image.url',+ 'org.opencontainers.image.documentation',+ 'org.opencontainers.image.source',+ 'org.opencontainers.image.revision',+ 'org.opencontainers.image.version',+ 'org.opencontainers.image.licenses',+ ]) {+ expect(runtime).toContain(label)+ }expect(runtime).toContain('rm -rf /usr/local/lib/node_modules/npm')expect(runtime).toContain('/usr/local/lib/node_modules/corepack')expect(runtime).toContain('/opt/yarn-v1.22.22')@@ -103,15 +143,17 @@ describe('Docker Server runtime staging contract', () => {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(- 'FROM node:24-alpine AS server-full-root-baseline'+ `FROM ${NODE_IMAGE_REFERENCE} AS server-full-root-baseline`+ )+ const runtimeStart = dockerfile.indexOf(+ `FROM ${NODE_IMAGE_REFERENCE} AS runtime`)- const runtimeStart = dockerfile.indexOf('FROM node:24-alpine AS runtime')const baseline = dockerfile.slice(baselineStart, runtimeStart)expect(baselineStart).toBeGreaterThanOrEqual(0)expect(runtimeStart).toBeGreaterThan(baselineStart)expect(dockerfile).toContain(- 'FROM node:24-alpine AS full-root-production-deps'+ `FROM ${NODE_IMAGE_REFERENCE} AS full-root-production-deps`)expect(dockerfile).toContain('pnpm install --prod --frozen-lockfile --ignore-scripts'diff --git a/tests/scripts/verify-container-publication.test.ts b/tests/scripts/verify-container-publication.test.tsnew file mode 100644index 00000000..a04cb666--- /dev/null+++ b/tests/scripts/verify-container-publication.test.ts@@ -0,0 +1,255 @@+import { describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import {+ CONTAINER_LABELS,+ CONTAINER_REPOSITORIES,+} from '../../scripts/container-release-metadata.mjs'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import { verifyContainerPublication } from '../../scripts/verify-container-publication.mjs'++const VERSION = '2.3.4'+const REVISION = 'a'.repeat(40)+const INDEX_DIGEST = `sha256:${'b'.repeat(64)}`+const AMD64_DIGEST = `sha256:${'c'.repeat(64)}`+const ARM64_DIGEST = `sha256:${'d'.repeat(64)}`++function inspect() {+ const platform = (architecture: string) => ({+ config: {+ User: 'node',+ Labels: {+ ...CONTAINER_LABELS,+ 'org.opencontainers.image.revision': REVISION,+ 'org.opencontainers.image.version': VERSION,+ },+ },+ platform: { architecture, os: 'linux' },+ })+ return {+ manifest: { digest: INDEX_DIGEST },+ image: {+ 'linux/amd64': platform('amd64'),+ 'linux/arm64': platform('arm64'),+ },+ }+}++function index(options?: { omitArmAttestation?: boolean }) {+ const manifest = (architecture: string, digest: string) => ({+ mediaType: 'application/vnd.oci.image.manifest.v1+json',+ digest,+ size: 1024,+ platform: { architecture, os: 'linux' },+ })+ const attestation = (subject: string, digest: string) => ({+ mediaType: 'application/vnd.oci.image.manifest.v1+json',+ digest,+ size: 512,+ annotations: {+ 'vnd.docker.reference.digest': subject,+ 'vnd.docker.reference.type': 'attestation-manifest',+ },+ platform: { architecture: 'unknown', os: 'unknown' },+ })+ return {+ schemaVersion: 2,+ mediaType: 'application/vnd.oci.image.index.v1+json',+ manifests: [+ manifest('amd64', AMD64_DIGEST),+ attestation(AMD64_DIGEST, `sha256:${'e'.repeat(64)}`),+ manifest('arm64', ARM64_DIGEST),+ ...(options?.omitArmAttestation+ ? []+ : [attestation(ARM64_DIGEST, `sha256:${'f'.repeat(64)}`)]),+ ],+ }+}++function sbom(options?: { emptyArmPackages?: boolean }) {+ const result = (platform: string) => ({+ SPDX: {+ SPDXID: 'SPDXRef-DOCUMENT',+ documentNamespace: `https://example.invalid/${platform}`,+ packages: platform === 'arm64' && options?.emptyArmPackages ? [] : [{}],+ spdxVersion: 'SPDX-2.3',+ },+ })+ return {+ 'linux/amd64': result('amd64'),+ 'linux/arm64': result('arm64'),+ }+}++function provenance(options?: { incompleteArmMaterials?: boolean }) {+ const result = (platform: string) => ({+ SLSA: {+ buildConfig: {},+ buildType: 'https://mobyproject.org/buildkit@v1',+ builder: { id: 'https://github.com/agalwood/Motrix/actions/runs/1' },+ invocation: {},+ materials: [{}],+ metadata: {+ completeness: {+ environment: true,+ materials: platform !== 'arm64' || !options?.incompleteArmMaterials,+ parameters: true,+ },+ },+ },+ })+ return {+ 'linux/amd64': result('amd64'),+ 'linux/arm64': result('arm64'),+ }+}++function currentProvenance(options?: {+ builderId?: string+ revision?: string+}) {+ const result = () => ({+ SLSA: {+ buildDefinition: {+ buildType:+ 'https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md',+ externalParameters: {},+ internalParameters: {},+ resolvedDependencies: [{}],+ },+ runDetails: {+ builder: {+ id:+ options?.builderId ??+ 'https://github.com/docker/buildx/actions/runs/123',+ },+ metadata: {+ buildkit_completeness: { request: true },+ buildkit_metadata: {+ vcs: {+ revision: options?.revision ?? REVISION,+ source: 'https://github.com/agalwood/Motrix.git',+ },+ },+ },+ },+ },+ })+ return {+ 'linux/amd64': result(),+ 'linux/arm64': result(),+ }+}++function artifact(overrides: Record<string, unknown> = {}) {+ return {+ inspect: inspect(),+ index: index(),+ provenance: provenance(),+ sbom: sbom(),+ ...overrides,+ }+}++function verify(+ overrides: {+ builderIdPrefix?: string+ dockerHub?: ReturnType<typeof artifact>+ ghcr?: ReturnType<typeof artifact>+ } = {}+) {+ return verifyContainerPublication({+ builderIdPrefix: overrides.builderIdPrefix,+ dockerHub: overrides.dockerHub ?? artifact(),+ ghcr: overrides.ghcr ?? artifact(),+ revision: REVISION,+ version: VERSION,+ })+}++describe('container publication verifier', () => {+ it('accepts identical dual-registry indexes with both attestations', () => {+ expect(verify()).toEqual({+ digest: INDEX_DIGEST,+ platforms: ['linux/amd64', 'linux/arm64'],+ dockerHub: {+ 'linux/amd64': AMD64_DIGEST,+ 'linux/arm64': ARM64_DIGEST,+ },+ ghcr: {+ 'linux/amd64': AMD64_DIGEST,+ 'linux/arm64': ARM64_DIGEST,+ },+ sbom: 'SPDX-2.x',+ provenance: 'SLSA BuildKit',+ })+ })++ it('accepts current SLSA provenance and verifies the GitHub builder', () => {+ const current = artifact({ provenance: currentProvenance() })+ expect(+ verify({+ builderIdPrefix: 'https://github.com/docker/buildx/actions/runs/',+ dockerHub: current,+ ghcr: current,+ }).provenance+ ).toBe('SLSA BuildKit')+ })++ it.each([+ [+ 'builder identity',+ currentProvenance({ builderId: 'https://example.invalid/build/1' }),+ /builder identity conflicts/,+ ],+ [+ 'source revision',+ currentProvenance({ revision: '0'.repeat(40) }),+ /provenance revision conflicts/,+ ],+ ])('rejects a conflicting current SLSA %s', (_, document, error) => {+ expect(() =>+ verify({+ builderIdPrefix: 'https://github.com/docker/buildx/actions/runs/',+ dockerHub: artifact({ provenance: document }),+ ghcr: artifact({ provenance: document }),+ })+ ).toThrow(error)+ })++ it.each([+ [+ 'missing attestation',+ artifact({ index: index({ omitArmAttestation: true }) }),+ /exactly one attestation/,+ ],+ [+ 'empty SBOM',+ artifact({ sbom: sbom({ emptyArmPackages: true }) }),+ /package list is empty/,+ ],+ [+ 'incomplete provenance',+ artifact({+ provenance: provenance({ incompleteArmMaterials: true }),+ }),+ /incomplete at materials/,+ ],+ ])('rejects %s', (_, dockerHub, error) => {+ expect(() => verify({ dockerHub })).toThrow(error)+ })++ it('rejects a registry digest divergence before attestation checks', () => {+ const ghcrInspect = inspect()+ ghcrInspect.manifest.digest = `sha256:${'0'.repeat(64)}`+ expect(() => verify({ ghcr: artifact({ inspect: ghcrInspect }) })).toThrow(+ /Immutable container tags disagree/+ )+ })++ it('keeps the expected public registry coordinates in the verified labels', () => {+ expect(CONTAINER_REPOSITORIES).toEqual({+ dockerHub: 'docker.io/motrixapp/motrix-server',+ ghcr: 'ghcr.io/agalwood/motrix-server',+ })+ })+})diff --git a/tests/scripts/workflow-release-matrix.test.ts b/tests/scripts/workflow-release-matrix.test.tsindex f215fe58..154ee5dd 100644--- a/tests/scripts/workflow-release-matrix.test.ts+++ b/tests/scripts/workflow-release-matrix.test.ts@@ -92,6 +92,41 @@ const EXPECTED_ACTION_PINS = new Map([comment: 'v6.7',},],+ [+ 'docker/setup-qemu-action',+ {+ sha: '96fe6ef7f33517b61c61be40b68a1882f3264fb8',+ comment: 'v4.2.0',+ },+ ],+ [+ 'docker/setup-buildx-action',+ {+ sha: 'bb05f3f5519dd87d3ba754cc423b652a5edd6d2c',+ comment: 'v4.2.0',+ },+ ],+ [+ 'docker/login-action',+ {+ sha: 'dbcb813823bdd20940b903addbd779551569679f',+ comment: 'v4.6.0',+ },+ ],+ [+ 'docker/build-push-action',+ {+ sha: '53b7df96c91f9c12dcc8a07bcb9ccacbed38856a',+ comment: 'v7.3.0',+ },+ ],+ [+ 'sigstore/cosign-installer',+ {+ sha: '6f9f17788090df1f26f669e9d70d6ae9567deba6',+ comment: 'v4.1.2',+ },+ ],])const EXPECTED_TARGETS: ExpectedTarget[] = [@@ -511,6 +546,9 @@ describe('release workflow publication contract', () => {)const preflightSteps = jobSteps(preflightJob)const metadataStep = preflightSteps.find((step) => step.id === 'metadata')+ const containerMetadataStep = preflightSteps.find(+ (step) => step.id === 'container'+ )const ancestryStep = preflightSteps.find((step) =>stringField(step, 'run', '').includes('git merge-base --is-ancestor'))@@ -535,6 +573,23 @@ describe('release workflow publication contract', () => {expect(stringField(preflightOutputs, 'channel')).toContain('steps.metadata.outputs.channel')+ expect(containerMetadataStep).toBeDefined()+ expect(stringField(containerMetadataStep as LooseRecord, 'run')).toContain(+ 'scripts/container-release-metadata.mjs'+ )+ for (const output of [+ 'container_version',+ 'container_prerelease',+ 'container_dockerhub_repository',+ 'container_ghcr_repository',+ 'container_immutable_tags',+ 'container_floating_tags',+ 'container_labels',+ ]) {+ expect(stringField(preflightOutputs, output)).toContain(+ `steps.container.outputs.${output}`+ )+ }expect(ancestryStep).toBeDefined()expect(stringField(ancestryStep as LooseRecord, 'if')).toContain("github.event_name == 'push'"@@ -583,6 +638,109 @@ describe('release workflow publication contract', () => {)})+ it('publishes resumable signed multi-architecture containers only from release tags', () => {+ const jobs = workflowJobs(releaseWorkflow)+ const containerJob = asRecord(+ jobs['publish-container'],+ 'publish-container job'+ )+ expect(jobNeeds(containerJob)).toEqual(+ expect.arrayContaining(['preflight', 'publish'])+ )+ const condition = stringField(containerJob, 'if')+ expect(condition).toContain("github.event_name == 'push'")+ expect(condition).toContain("startsWith(github.ref, 'refs/tags/v')")+ expect(stringField(containerJob, 'environment')).toBe('container-release')+ expect(asRecord(containerJob.permissions, 'container permissions')).toEqual(+ {+ contents: 'read',+ 'id-token': 'write',+ packages: 'write',+ }+ )++ const steps = jobSteps(containerJob)+ const stepIndex = (name: string) =>+ steps.findIndex((step) => step.name === name)+ const build =+ steps[stepIndex('Build and stage immutable multi-architecture image')]+ expect(build).toBeDefined()+ const buildInputs = asRecord(build?.with, 'container build inputs')+ expect(stringField(buildInputs, 'platforms')).toBe(+ 'linux/amd64,linux/arm64'+ )+ expect(buildInputs.push).toBe(true)+ expect(buildInputs.sbom).toBe(true)+ expect(stringField(buildInputs, 'provenance')).toBe('mode=max')+ expect(stringField(buildInputs, 'cache-from')).toContain('type=gha')+ expect(stringField(buildInputs, 'cache-to')).toContain('mode=max')++ const qemu = steps.find((step) => step.name === 'Set up pinned QEMU')+ expect(stringField(asRecord(qemu?.with, 'QEMU inputs'), 'image')).toMatch(+ /^tonistiigi\/binfmt@sha256:[0-9a-f]{64}$/+ )+ expect(stringField(asRecord(qemu?.with, 'QEMU inputs'), 'platforms')).toBe(+ 'arm64'+ )++ const inspectCommand = stringField(+ steps[stepIndex('Inspect existing immutable tags')] as LooseRecord,+ 'run'+ )+ expect(inspectCommand).not.toContain('pull access denied')+ expect(stepIndex('Resolve immutable publication state')).toBeLessThan(+ stepIndex('Build and stage immutable multi-architecture image')+ )+ expect(stepIndex('Verify immutable publication state')).toBeLessThan(+ stepIndex('Sign immutable digests with GitHub OIDC')+ )+ expect(stepIndex('Sign immutable digests with GitHub OIDC')).toBeLessThan(+ stepIndex('Prepare anonymous registry client')+ )+ expect(stepIndex('Verify immutable signatures')).toBeLessThan(+ stepIndex('Verify anonymous multi-architecture artifacts')+ )+ expect(+ stepIndex('Verify anonymous multi-architecture artifacts')+ ).toBeLessThan(stepIndex('Smoke anonymous published architectures'))+ expect(stepIndex('Smoke anonymous published architectures')).toBeLessThan(+ stepIndex('Promote stable container aliases')+ )+ expect(stepIndex('Promote stable container aliases')).toBeLessThan(+ stepIndex('Update Docker Hub description')+ )++ const publicVerification = steps[+ stepIndex('Verify anonymous multi-architecture artifacts')+ ] as LooseRecord+ expect(+ stringField(+ asRecord(publicVerification.env, 'anonymous env'),+ 'DOCKER_CONFIG'+ )+ ).toContain('anonymous-docker')+ const publicCommand = stringField(publicVerification, 'run')+ expect(publicCommand).toContain("--format '{{json .SBOM}}'")+ expect(publicCommand).toContain("--format '{{json .Provenance}}'")+ expect(publicCommand).toContain('verify-container-publication.mjs')+ const smokeCommand = stringField(+ steps[+ stepIndex('Smoke anonymous published architectures')+ ] as LooseRecord,+ 'run'+ )+ expect(smokeCommand).toContain('--platform linux/amd64')+ expect(smokeCommand).toContain('--platform linux/arm64')+ expect(smokeCommand).toContain('--mode health')+ expect(smokeCommand).toContain('smoke-server-image.mjs')++ const allOtherJobs = Object.entries(jobs).filter(+ ([name]) => name !== 'publish-container'+ )+ expect(JSON.stringify(allOtherJobs)).not.toContain('DOCKERHUB_TOKEN')+ expect(JSON.stringify(allOtherJobs)).not.toContain('packages":"write')+ })+it('assembles all target artifacts before publication', () => {const jobs = workflowJobs(releaseWorkflow)const assembleJob = asRecord(jobs.assemble, 'assemble job')