A full-featured download manager.
fix(security): harden supply-chain trust boundaries (#1846)
Dr_rOot630c03622958
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 4faf962b..f7dc1148 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -92,14 +92,7 @@ jobs:runs-on: ${{ matrix.os }}timeout-minutes: 90environment:- name: >-- ${{- github.event_name == 'push' && matrix.platform == 'darwin'- && 'macos-release-signing'- || github.event_name == 'push' && matrix.platform == 'win32'- && 'windows-release-signing'- || 'release-build'- }}+ name: release-builddeployment: falsestrategy:fail-fast: false@@ -204,58 +197,6 @@ jobs:- name: Third-party notice contractrun: pnpm run check:third-party-notices- - name: Validate macOS release credentials- if: >-- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- matrix.platform == 'darwin'- shell: bash- env:- MAC_CERTS: ${{ secrets.MAC_CERTS }}- MAC_CERTS_PASSWORD: ${{ secrets.MAC_CERTS_PASSWORD }}- API_KEY: ${{ secrets.API_KEY }}- API_KEY_ID: ${{ secrets.API_KEY_ID }}- API_KEY_ISSUER_ID: ${{ secrets.API_KEY_ISSUER_ID }}- run: |- set -euo pipefail- missing=()- for name in \- MAC_CERTS \- MAC_CERTS_PASSWORD \- API_KEY \- API_KEY_ID \- API_KEY_ISSUER_ID- do- if [[ -z "${!name:-}" ]]; then- missing+=("$name")- fi- done- if (( ${#missing[@]} > 0 )); then- echo "Missing required macOS release secrets: ${missing[*]}" >&2- exit 1- fi-- - name: Validate Windows release credentials- if: >-- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- matrix.platform == 'win32'- shell: pwsh- env:- WIN_CSC_LINK: ${{ secrets.WIN_CSC_LINK }}- WIN_CSC_KEY_PASSWORD: ${{ secrets.WIN_CSC_KEY_PASSWORD }}- run: |- $missing = @()- if ([string]::IsNullOrWhiteSpace($env:WIN_CSC_LINK)) {- $missing += 'WIN_CSC_LINK'- }- if ([string]::IsNullOrWhiteSpace($env:WIN_CSC_KEY_PASSWORD)) {- $missing += 'WIN_CSC_KEY_PASSWORD'- }- if ($missing.Count -gt 0) {- throw "Missing required Windows release secrets: $($missing -join ', ')"- }-# Build each target on a runner with the same native CPU architecture.# This also ensures better-sqlite3 is rebuilt for the packaged Electron.- name: Build@@ -265,38 +206,12 @@ jobs:pnpm run build:electronpnpm run stage:electron -- --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}- # Materialize the private key only after all project-controlled build- # scripts have completed. The path is passed through a step output so the- # notarization variables exist only in the macOS electron-builder process.- - name: Prepare Apple API Key- id: apple-api-key- if: >-- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- matrix.platform == 'darwin'- shell: bash- env:- APPLE_API_KEY_CONTENT: ${{ secrets.API_KEY }}- APPLE_API_KEY_ID_VALUE: ${{ secrets.API_KEY_ID }}- run: |- set -euo pipefail- key_path="${RUNNER_TEMP}/AuthKey_${APPLE_API_KEY_ID_VALUE}.p8"- printf '%s\n' "$APPLE_API_KEY_CONTENT" > "$key_path"- chmod 600 "$key_path"- echo "path=${key_path}" >> "$GITHUB_OUTPUT"-- # Keep signing credentials scoped to their platform. electron-builder- # 26 checks Apple ID before API Key, so the production path injects only- # the API Key variables prepared above.+ # Tagged macOS and Windows outputs are deliberately unsigned here. A+ # fresh, no-checkout job signs only the verified data artifact below.- name: Electron Builder (macOS)if: matrix.platform == 'darwin'env:- CSC_LINK: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && secrets.MAC_CERTS || '' }}- CSC_KEY_PASSWORD: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && secrets.MAC_CERTS_PASSWORD || '' }}- CSC_IDENTITY_AUTO_DISCOVERY: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && 'true' || 'false' }}- APPLE_API_KEY: ${{ steps.apple-api-key.outputs.path }}- APPLE_API_KEY_ID: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && secrets.API_KEY_ID || '' }}- APPLE_API_ISSUER: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && secrets.API_KEY_ISSUER_ID || '' }}+ CSC_IDENTITY_AUTO_DISCOVERY: 'false'run: >-pnpm exec electron-builder${{ matrix.electron_builder_args }}@@ -314,8 +229,6 @@ jobs:- name: Electron Builder (Windows)if: matrix.platform == 'win32'env:- CSC_LINK: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && secrets.WIN_CSC_LINK || '' }}- CSC_KEY_PASSWORD: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && secrets.WIN_CSC_KEY_PASSWORD || '' }}CSC_IDENTITY_AUTO_DISCOVERY: 'false'run: >-pnpm exec electron-builder@@ -338,20 +251,6 @@ jobs:-Binary"${{ matrix.resources_dir }}/bin/motrix-native-host.exe"- - name: Remove Apple API Key- if: >-- always() &&- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- matrix.platform == 'darwin'- shell: bash- env:- APPLE_API_KEY_PATH: ${{ steps.apple-api-key.outputs.path }}- run: |- if [[ -n "${APPLE_API_KEY_PATH:-}" ]]; then- rm -f "$APPLE_API_KEY_PATH"- fi-- name: Verify packaged resourcesshell: node {0}env:@@ -398,6 +297,32 @@ jobs:}}+ - name: Create isolated signing input+ if: >-+ github.event_name == 'push' &&+ startsWith(github.ref, 'refs/tags/v') &&+ (matrix.platform == 'darwin' || matrix.platform == 'win32')+ run: >-+ node scripts/release-signing-input.mjs+ --mode create+ --directory "release/signing-input-${{ matrix.target }}"+ --platform ${{ matrix.platform }}+ --arch ${{ matrix.arch }}+ --commit "$GITHUB_SHA"+ --archive "release/signing-input-${{ matrix.target }}.tar"++ - name: Upload isolated signing input+ if: >-+ github.event_name == 'push' &&+ startsWith(github.ref, 'refs/tags/v') &&+ (matrix.platform == 'darwin' || matrix.platform == 'win32')+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: signing-input-${{ matrix.target }}+ path: release/signing-input-${{ matrix.target }}.tar+ if-no-files-found: error+ retention-days: 2+- name: Verify Linux package formatsif: matrix.platform == 'linux'shell: bash@@ -473,12 +398,511 @@ jobs:exit 1fi- - name: Verify macOS signatures+ - name: Upload target release inputif: >-- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- matrix.platform == 'darwin'+ matrix.platform == 'linux' ||+ github.event_name == 'workflow_dispatch'+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: release-input-${{ matrix.target }}+ path: |+ release/*.blockmap+ release/beta*.yml+ release/*.deb+ release/*.dmg+ release/*.exe+ release/*.rpm+ release/*.tar.gz+ release/latest*.yml+ release/size-reports/${{ matrix.target }}.json+ release/*.zip+ if-no-files-found: error+ retention-days: 7++ - name: Upload build diagnostics+ if: failure()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: build-diagnostics-${{ matrix.target }}+ path: |+ release/+ dist/+ .vite/+ if-no-files-found: ignore+ retention-days: 7++ sign:+ name: Sign / ${{ matrix.target }}+ needs: [preflight, build]+ if: >-+ github.event_name == 'push' &&+ startsWith(github.ref, 'refs/tags/v')+ runs-on: ${{ matrix.os }}+ timeout-minutes: 60+ environment:+ name: ${{ matrix.signing_environment }}+ deployment: false+ strategy:+ fail-fast: false+ matrix:+ include:+ - target: darwin-arm64+ os: macos-26+ platform: darwin+ arch: arm64+ signing_environment: macos-release-signing+ electron_builder_args: --mac --arm64+ resources_dir: release/mac-arm64/Motrix.app/Contents/Resources+ app_path: release/mac-arm64/Motrix.app+ electron_sha256: ee939d1564d83d61032b3b3cb23af4e46005a4900c91f0695f7ed793f0ce6e83+ - target: darwin-x64+ os: macos-26-intel+ platform: darwin+ arch: x64+ signing_environment: macos-release-signing+ electron_builder_args: --mac --x64+ resources_dir: release/mac/Motrix.app/Contents/Resources+ app_path: release/mac/Motrix.app+ electron_sha256: 7347bbd5fb529eea64f9c2d148bb1c19222d98946ff234ffe27953a1bbcb9dae+ - target: win32-x64+ os: windows-2025+ platform: win32+ arch: x64+ signing_environment: windows-release-signing+ electron_builder_args: --win --x64+ resources_dir: release/win-unpacked/resources+ app_path: release/win-unpacked+ electron_sha256: 18528bedc6a9b04bdc5efb7b803cbc3cb0e5ea6415d54046e23d464d89a00da9+ env:+ CUSTOM_DMGBUILD_PATH: ''+ ELECTRON_BUILDER_7ZIP_PATH: ''+ ELECTRON_BUILDER_BINARIES_ALLOW_HTTP: ''+ ELECTRON_BUILDER_BINARIES_CUSTOM_DIR: ''+ ELECTRON_BUILDER_BINARIES_DOWNLOAD_OVERRIDE_URL: ''+ ELECTRON_BUILDER_BINARIES_MIRROR: ''+ ELECTRON_BUILDER_NSIS_DIR: ''+ ELECTRON_BUILDER_NSIS_RESOURCES_DIR: ''+ ELECTRON_BUILDER_OSSL_SIGNCODE_PATH: ''+ ELECTRON_BUILDER_RCEDIT_PATH: ''+ ELECTRON_BUILDER_WINDOWS_KITS_PATH: ''+ MACOSX_DEPLOYMENT_TARGET: ${{ matrix.platform == 'darwin' && '12.0' || '' }}+ NPM_CONFIG_ELECTRON_BUILDER_BINARIES_CUSTOM_DIR: ''+ NPM_CONFIG_ELECTRON_BUILDER_BINARIES_MIRROR: ''+ SIGNTOOL_PATH: ''+ USE_SYSTEM_OSSLSIGNCODE: ''+ USE_SYSTEM_SIGNCODE: ''++ # Deliberately no checkout and no project package-manager install. Only the+ # workflow-pinned verifier and digest-complete data artifact enter this job.+ steps:+ - name: Download isolated signing input+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1+ with:+ name: signing-input-${{ matrix.target }}+ path: signing-transport++ - name: Safely extract bounded signing input+ shell: node {0}+ env:+ EXPECTED_ARCH: ${{ matrix.arch }}+ EXPECTED_PLATFORM: ${{ matrix.platform }}+ run: |+ const fs = require('node:fs')+ const path = require('node:path')+ const decoder = new TextDecoder('utf-8', { fatal: true })+ const limits = {+ archiveBytes: 1024 * 1024 * 1024,+ inputBytes: 768 * 1024 * 1024,+ fileBytes: 512 * 1024 * 1024,+ files: 50_000,+ pathBytes: 4096,+ }+ const archive = path.resolve(+ 'signing-transport',+ `signing-input-${process.env.EXPECTED_PLATFORM}-${process.env.EXPECTED_ARCH}.tar`+ )+ const archiveInfo = fs.lstatSync(archive)+ if (+ !archiveInfo.isFile() ||+ archiveInfo.size < 1024 ||+ archiveInfo.size > limits.archiveBytes ||+ archiveInfo.size % 512 !== 0+ ) {+ throw new Error('signing input tar violates archive size limits')+ }+ const root = path.resolve('signing-input')+ fs.mkdirSync(root, { recursive: false, mode: 0o700 })+ const handle = fs.openSync(archive, 'r')+ const readExactly = (offset, length) => {+ const output = Buffer.alloc(length)+ let read = 0+ while (read < length) {+ const count = fs.readSync(+ handle,+ output,+ read,+ length - read,+ offset + read+ )+ if (count === 0) throw new Error('truncated signing input tar')+ read += count+ }+ return output+ }+ const textField = (header, offset, length) => {+ const field = header.subarray(offset, offset + length)+ const nul = field.indexOf(0)+ const end = nul < 0 ? field.length : nul+ if (+ nul >= 0 &&+ field.subarray(nul).some((value) => value !== 0)+ ) {+ throw new Error('non-canonical tar text field')+ }+ return decoder.decode(field.subarray(0, end))+ }+ const octalField = (header, offset, length) => {+ const value = decoder.decode(+ header.subarray(offset, offset + length)+ )+ const match = /^([0-7]+)(?:\0[ \0]*| +)$/.exec(value)+ if (!match) {+ throw new Error('invalid tar numeric field')+ }+ const parsed = Number.parseInt(match[1], 8)+ if (!Number.isSafeInteger(parsed)) {+ throw new Error('tar numeric field exceeds safe integer range')+ }+ return parsed+ }+ const validatePath = (value) => {+ const segments = value.split('/')+ if (+ !value ||+ value.includes('\\') ||+ /[\u0000-\u001f\u007f:]/u.test(value) ||+ Buffer.byteLength(value) > limits.pathBytes ||+ path.posix.normalize(value) !== value ||+ path.posix.isAbsolute(value) ||+ value === '..' ||+ value.startsWith('../') ||+ segments.some(+ (segment) =>+ !segment ||+ /[ .]$/u.test(segment) ||+ /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu.test(+ segment+ )+ )+ ) {+ throw new Error(`unsafe tar path: ${value}`)+ }+ return value+ }+ const parsePaxPath = (bytes) => {+ const record = decoder.decode(bytes)+ const match = /^([0-9]+) path=([^\n]+)\n$/.exec(record)+ if (!match || Number(match[1]) !== bytes.length) {+ throw new Error('unsupported pax header')+ }+ return validatePath(match[2])+ }+ const allZero = (bytes) =>+ bytes.every((value) => value === 0)+ const seen = new Set()+ let fileCount = 0+ let inputBytes = 0+ let offset = 0+ let paxPath+ let ended = false+ try {+ while (offset < archiveInfo.size) {+ const header = readExactly(offset, 512)+ if (allZero(header)) {+ const second = readExactly(offset + 512, 512)+ if (!allZero(second)) {+ throw new Error('tar requires two zero end blocks')+ }+ offset += 1024+ if (offset !== archiveInfo.size) {+ throw new Error('tar contains trailing bytes')+ }+ ended = true+ break+ }+ const storedChecksum = octalField(header, 148, 8)+ const checksumHeader = Buffer.from(header)+ checksumHeader.fill(0x20, 148, 156)+ const actualChecksum = checksumHeader.reduce(+ (total, value) => total + value,+ 0+ )+ if (storedChecksum !== actualChecksum) {+ throw new Error('tar header checksum mismatch')+ }+ if (+ textField(header, 257, 6) !== 'ustar' ||+ textField(header, 263, 2) !== '00' ||+ textField(header, 345, 155) !== ''+ ) {+ throw new Error('unsupported tar header format')+ }+ const type = textField(header, 156, 1) || '0'+ const size = octalField(header, 124, 12)+ const mode = octalField(header, 100, 8) & 0o777+ if (size > limits.fileBytes) {+ throw new Error('tar entry exceeds per-file limit')+ }+ const dataStart = offset + 512+ const dataEnd = dataStart + size+ const next = dataStart + Math.ceil(size / 512) * 512+ if (next > archiveInfo.size) {+ throw new Error('truncated tar entry')+ }+ const padding = readExactly(dataEnd, next - dataEnd)+ if (!allZero(padding)) {+ throw new Error('tar entry has non-zero padding')+ }+ if (type === 'x') {+ if (+ paxPath !== undefined ||+ mode !== 0o644 ||+ size > limits.pathBytes + 32+ ) {+ throw new Error('invalid pax header')+ }+ paxPath = parsePaxPath(readExactly(dataStart, size))+ } else if (type === '0') {+ const headerPath = validatePath(textField(header, 0, 100))+ const relative = paxPath ?? headerPath+ paxPath = undefined+ if (seen.has(relative)) {+ throw new Error(`duplicate tar path: ${relative}`)+ }+ if (![0o644, 0o755].includes(mode)) {+ throw new Error(`unexpected tar mode: ${relative}`)+ }+ fileCount += 1+ inputBytes += size+ if (+ fileCount > limits.files ||+ inputBytes > limits.inputBytes+ ) {+ throw new Error('tar exceeds input limits')+ }+ const destination = path.resolve(root, relative)+ if (!destination.startsWith(`${root}${path.sep}`)) {+ throw new Error(`tar path escapes root: ${relative}`)+ }+ fs.mkdirSync(path.dirname(destination), {+ recursive: true,+ mode: 0o700,+ })+ const output = fs.openSync(destination, 'wx', mode)+ try {+ let copied = 0+ const buffer = Buffer.alloc(1024 * 1024)+ while (copied < size) {+ const length = Math.min(buffer.length, size - copied)+ const count = fs.readSync(+ handle,+ buffer,+ 0,+ length,+ dataStart + copied+ )+ if (count === 0) {+ throw new Error('truncated tar file contents')+ }+ fs.writeSync(output, buffer, 0, count)+ copied += count+ }+ fs.fchmodSync(output, mode)+ } finally {+ fs.closeSync(output)+ }+ seen.add(relative)+ } else {+ throw new Error(`unsupported tar entry type: ${type}`)+ }+ offset = next+ }+ } finally {+ fs.closeSync(handle)+ }+ if (+ !ended ||+ paxPath !== undefined ||+ fileCount === 0 ||+ !seen.has('signing-input-manifest.json') ||+ !seen.has('scripts/release-signing-input.mjs')+ ) {+ throw new Error('incomplete signing input tar')+ }++ - name: Verify signing input before secrets+ shell: node {0}+ env:+ EXPECTED_ARCH: ${{ matrix.arch }}+ EXPECTED_COMMIT: ${{ github.sha }}+ EXPECTED_PLATFORM: ${{ matrix.platform }}+ # Updated only after reviewing the verifier source itself.+ VERIFIER_SHA256: fa26b0c2cfde003c5f0605f0f5a123f372f8b1ac5a8dce3c0700c4a2039e7b6c+ run: |+ const crypto = require('node:crypto')+ const fs = require('node:fs')+ const { spawnSync } = require('node:child_process')+ const verifier = 'signing-input/scripts/release-signing-input.mjs'+ const actual = crypto+ .createHash('sha256')+ .update(fs.readFileSync(verifier))+ .digest('hex')+ if (actual !== process.env.VERIFIER_SHA256) {+ throw new Error('signing input verifier digest mismatch')+ }+ const result = spawnSync(+ process.execPath,+ [+ verifier,+ '--mode',+ 'verify',+ '--directory',+ 'signing-input',+ '--platform',+ process.env.EXPECTED_PLATFORM,+ '--arch',+ process.env.EXPECTED_ARCH,+ '--commit',+ process.env.EXPECTED_COMMIT,+ ],+ { stdio: 'inherit' }+ )+ if (result.status !== 0) {+ throw new Error('signing input verification failed')+ }++ - name: Install exact signing dependency closure+ shell: bash+ run: |+ set -euo pipefail+ cp signing-input/signing-tool/package.json signing-input/package.json+ cp signing-input/signing-tool/package-lock.json signing-input/package-lock.json+ npm ci \+ --prefix signing-input \+ --ignore-scripts \+ --no-audit \+ --no-fund \+ --registry https://registry.npmjs.org/+ node - <<'NODE'+ const pkg = require('./signing-input/node_modules/electron-builder/package.json')+ if (pkg.version !== '26.15.7') {+ throw new Error('unexpected electron-builder version')+ }+ NODE++ - name: Download digest-pinned Electron distribution+ shell: bash+ env:+ ELECTRON_SHA256: ${{ matrix.electron_sha256 }}+ run: |+ set -euo pipefail+ mkdir -p signing-input/trusted+ cp \+ signing-input/signing-policy/installer.nsh \+ signing-input/trusted/installer.nsh+ url="https://github.com/electron/electron/releases/download/v43.3.0/electron-v43.3.0-${{ matrix.platform }}-${{ matrix.arch }}.zip"+ curl --fail --location --proto '=https' --tlsv1.2 \+ "$url" --output signing-input/trusted/electron.zip+ node - <<'NODE'+ const crypto = require('node:crypto')+ const fs = require('node:fs')+ const actual = crypto+ .createHash('sha256')+ .update(fs.readFileSync('signing-input/trusted/electron.zip'))+ .digest('hex')+ if (actual !== process.env.ELECTRON_SHA256) {+ throw new Error('Electron distribution digest mismatch')+ }+ NODE++ - name: Validate macOS release credentials+ if: matrix.platform == 'darwin'+ shell: bash+ env:+ MAC_CERTS: ${{ secrets.MAC_CERTS }}+ MAC_CERTS_PASSWORD: ${{ secrets.MAC_CERTS_PASSWORD }}+ API_KEY: ${{ secrets.API_KEY }}+ API_KEY_ID: ${{ secrets.API_KEY_ID }}+ API_KEY_ISSUER_ID: ${{ secrets.API_KEY_ISSUER_ID }}+ run: |+ set -euo pipefail+ for name in MAC_CERTS MAC_CERTS_PASSWORD API_KEY API_KEY_ID API_KEY_ISSUER_ID; do+ [[ -n "${!name:-}" ]] || { echo "Missing $name" >&2; exit 1; }+ done++ - name: Validate Windows release credentials+ if: matrix.platform == 'win32'+ shell: pwsh+ env:+ WIN_CSC_LINK: ${{ secrets.WIN_CSC_LINK }}+ WIN_CSC_KEY_PASSWORD: ${{ secrets.WIN_CSC_KEY_PASSWORD }}+ run: |+ if ([string]::IsNullOrWhiteSpace($env:WIN_CSC_LINK) -or+ [string]::IsNullOrWhiteSpace($env:WIN_CSC_KEY_PASSWORD)) {+ throw 'Missing Windows signing credentials'+ }++ - name: Prepare Apple API Key+ id: apple-api-key+ if: matrix.platform == 'darwin'shell: bash+ env:+ APPLE_API_KEY_CONTENT: ${{ secrets.API_KEY }}+ APPLE_API_KEY_ID_VALUE: ${{ secrets.API_KEY_ID }}+ run: |+ set -euo pipefail+ key_path="${RUNNER_TEMP}/AuthKey_${APPLE_API_KEY_ID_VALUE}.p8"+ printf '%s\n' "$APPLE_API_KEY_CONTENT" > "$key_path"+ chmod 600 "$key_path"+ echo "path=${key_path}" >> "$GITHUB_OUTPUT"++ - name: Electron Builder (macOS signing boundary)+ if: matrix.platform == 'darwin'+ working-directory: signing-input+ env:+ ELECTRON_BUILDER_CACHE: ${{ runner.temp }}/motrix-signing-cache+ ELECTRON_DOWNLOAD_CACHE_MODE: '1'+ CSC_LINK: ${{ secrets.MAC_CERTS }}+ CSC_KEY_PASSWORD: ${{ secrets.MAC_CERTS_PASSWORD }}+ CSC_IDENTITY_AUTO_DISCOVERY: 'true'+ APPLE_API_KEY: ${{ steps.apple-api-key.outputs.path }}+ APPLE_API_KEY_ID: ${{ secrets.API_KEY_ID }}+ APPLE_API_ISSUER: ${{ secrets.API_KEY_ISSUER_ID }}+ run: >-+ node node_modules/electron-builder/out/cli/cli.js+ --config electron-builder.signing.json+ ${{ matrix.electron_builder_args }}+ --publish never++ - name: Electron Builder (Windows signing boundary)+ if: matrix.platform == 'win32'+ working-directory: signing-input+ env:+ ELECTRON_BUILDER_CACHE: ${{ runner.temp }}/motrix-signing-cache+ ELECTRON_DOWNLOAD_CACHE_MODE: '1'+ CSC_LINK: ${{ secrets.WIN_CSC_LINK }}+ CSC_KEY_PASSWORD: ${{ secrets.WIN_CSC_KEY_PASSWORD }}+ CSC_IDENTITY_AUTO_DISCOVERY: 'false'+ run: >-+ node node_modules/electron-builder/out/cli/cli.js+ --config electron-builder.signing.json+ ${{ matrix.electron_builder_args }}+ --publish never++ - name: Verify macOS signatures+ if: matrix.platform == 'darwin'+ shell: bash+ working-directory: signing-inputrun: |set -euo pipefailcodesign --verify --deep --strict --verbose=2 "${{ matrix.app_path }}"@@ -487,11 +911,9 @@ jobs:xcrun stapler validate "${{ matrix.app_path }}"- name: Verify Windows signatures- if: >-- github.event_name == 'push' &&- startsWith(github.ref, 'refs/tags/v') &&- matrix.platform == 'win32'+ if: matrix.platform == 'win32'shell: pwsh+ working-directory: signing-inputrun: |$files = @('release/win-unpacked/Motrix.exe',@@ -511,39 +933,51 @@ jobs:}}- - name: Upload target release input+ - name: Verify signed Electron package+ working-directory: signing-input+ run: >-+ node scripts/verify-electron-package.mjs+ --app-dir "${{ matrix.app_path }}"+ --platform ${{ matrix.platform }}+ --arch ${{ matrix.arch }}+ --report "release/size-reports/${{ matrix.target }}.json"++ - name: Remove Apple API Key+ if: always() && matrix.platform == 'darwin'+ shell: bash+ env:+ APPLE_API_KEY_PATH: ${{ steps.apple-api-key.outputs.path }}+ run: |+ if [[ -n "${APPLE_API_KEY_PATH:-}" ]]; then+ rm -f "$APPLE_API_KEY_PATH"+ fi++ - name: Upload signed release inputuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: release-input-${{ matrix.target }}path: |- release/*.blockmap- release/beta*.yml- release/*.deb- release/*.dmg- release/*.exe- release/*.rpm- release/*.tar.gz- release/latest*.yml- release/size-reports/${{ matrix.target }}.json- release/*.zip+ signing-input/release/*.blockmap+ signing-input/release/beta*.yml+ signing-input/release/*.dmg+ signing-input/release/*.exe+ signing-input/release/latest*.yml+ signing-input/release/size-reports/${{ matrix.target }}.json+ signing-input/release/*.zipif-no-files-found: errorretention-days: 7- - name: Upload build diagnostics- if: failure()- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1- with:- name: build-diagnostics-${{ matrix.target }}- path: |- release/- dist/- .vite/- if-no-files-found: ignore- retention-days: 7-assemble:name: Assemble and validate release- needs: [preflight, build]+ needs: [preflight, build, sign]+ if: >-+ always() &&+ needs.preflight.result == 'success' &&+ needs.build.result == 'success' &&+ (+ (github.event_name == 'push' && needs.sign.result == 'success') ||+ (github.event_name == 'workflow_dispatch' && needs.sign.result == 'skipped')+ )runs-on: ubuntu-22.04timeout-minutes: 15env:diff --git a/Dockerfile b/Dockerfileindex 71eccc60..48620378 100644--- a/Dockerfile+++ b/Dockerfile@@ -55,6 +55,8 @@ RUN apk add --no-cache aria2 ca-certificates \/opt/yarn-v1.22.22 \&& rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \/usr/local/bin/pnpm /usr/local/bin/yarn /usr/local/bin/yarnpkg \+ && printf '%s\n' '#!/bin/sh' 'exec node /app/dist/server/motrix-admin.mjs "$@"' > /usr/local/bin/motrix-admin \+ && chmod 0755 /usr/local/bin/motrix-admin \&& mkdir -p /data/home /data/tmp /downloads \&& chown -R node:node /data /downloadsWORKDIR /app@@ -101,6 +103,8 @@ RUN apk add --no-cache aria2 ca-certificates \/opt/yarn-v1.22.22 \&& rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack \/usr/local/bin/pnpm /usr/local/bin/yarn /usr/local/bin/yarnpkg \+ && printf '%s\n' '#!/bin/sh' 'exec node /app/dist/server/motrix-admin.mjs "$@"' > /usr/local/bin/motrix-admin \+ && chmod 0755 /usr/local/bin/motrix-admin \&& mkdir -p /data/home /data/tmp /downloads \&& chown -R node:node /data /downloadsWORKDIR /appdiff --git a/README.md b/README.mdindex 8b68dd86..851a20cf 100644--- a/README.md+++ b/README.md@@ -32,7 +32,7 @@ The same core powers two ways to run Motrix:- 🧩 QuickJS-based plugin sandboxing, fine-grained permissions, and an in-app marketplace- 🌐 Chrome and Firefox extensions that hand browser downloads off to Motrix in one click- ⌨️ Official `@motrix/cli` client for everyday shell use and AI agents-- 🐳 Docker-ready headless server with secure device-code pairing for remote clients+- 🐳 Docker-ready headless server with secure device-code pairing for remote CLI and agent clients- 🎬 Extensible URL Resolver plugins for extracting media from supported sites- 🤖 System tray integration and launch at startup- 🌍 Simplified Chinese and English UI, with more languages planned@@ -108,8 +108,24 @@ docker compose up -d --waitThe runtime is non-root, supports a read-only root filesystem, validates mountpermissions before accepting work, and preserves downloads, sessions, and-installed plugins across container replacement. Remote clients such as the CLI-and browser extensions pair through a device-code flow. See the+installed plugins across container replacement. The standard direct-LAN setup+publishes the Web service on port 8080 and MDXP on port 16801. Set+`MOTRIX_PUBLIC_URL` to the Web approval URL that remote clients can actually+reach; the Compose files do not substitute a misleading localhost URL.++If the Web approval URL is temporarily unavailable, an SSH operator can list+and approve the exact client code without exposing another port:++```bash+docker compose exec server motrix-admin pairing pending+docker compose exec server motrix-admin pairing approve ABCD-EFGH+```++Remote CLI and agent clients pair through the device-code flow. Browser+extensions pair with the desktop app through native messaging; first-time+extension pairing is not provided by the headless server. Direct HTTP is+appropriate only on a trusted LAN. Internet or untrusted-LAN access requires a+TLS reverse proxy and firewall rules around the origin ports. See the[Docker Server deployment guide](./docs/docker-server.md) for ownership setup,Docker Hub/GHCR image and tag selection, DSM 7 and fnOS installation, ports,diagnostics, and backup/upgrade instructions.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 49b9a233..89f5e1de 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -32,7 +32,7 @@ Motrix 是一款界面简洁、功能丰富的桌面下载管理器,可处理- 🧩 插件采用 QuickJS 沙箱隔离和细粒度能力授权,并可直接从应用内插件市场安装- 🌐 Chrome 和 Firefox 扩展可一键将浏览器下载任务交给 Motrix- ⌨️ 官方命令行客户端 `@motrix/cli` 既适合日常操作,也可供 AI agent 调用-- 🐳 Headless server 可通过 Docker 部署,远程设备可使用 device-code 安全配对+- 🐳 Headless server 可通过 Docker 部署,远程 CLI 和 agent 可使用 device-code 安全配对- 🎬 URL Resolver 插件可解析站点媒体页面,并可扩展对更多站点的支持- 🤖 可驻留系统托盘,并支持开机自启动- 🌍 界面支持简体中文和英语,后续将加入更多语言@@ -107,8 +107,23 @@ docker compose up -d --wait```runtime 以非 root 用户运行,支持只读根文件系统,在接受任务前检查挂载权限,-并在替换容器后保留下载、session 和已安装插件。CLI、浏览器扩展等远程客户端-可通过 device-code 与服务器配对。Docker Hub/GHCR 镜像与 tag 选择、群晖+并在替换容器后保留下载、session 和已安装插件。标准的直连 LAN 部署会把 Web+服务发布到 8080 端口,把 MDXP 发布到 16801 端口。请将+`MOTRIX_PUBLIC_URL` 设为远程客户端实际可访问的 Web 审批 URL;Compose 文件不会+为它填入会误导远程客户端的 localhost URL。++如果 Web 审批 URL 暂时不可用,SSH operator 无需开放额外端口即可列出请求,+并批准客户端显示的指定验证码:++```bash+docker compose exec server motrix-admin pairing pending+docker compose exec server motrix-admin pairing approve ABCD-EFGH+```++远程 CLI 和 agent 客户端通过 device-code flow 配对。浏览器扩展通过 native messaging+与桌面应用配对;headless server 不提供浏览器扩展的首次配对。只应在可信 LAN 上+直接使用 HTTP;通过公网或不可信 LAN 访问时,必须配置 TLS 反向代理,并用防火墙保护+源端口。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.yamlindex 909c8f97..25356509 100644--- a/compose.named-volumes.yaml+++ b/compose.named-volumes.yaml@@ -20,10 +20,10 @@ services:MOTRIX_ALLOWED_SAVE_DIRS: /downloadsMOTRIX_MDXP_HOST: 0.0.0.0MOTRIX_MDXP_PORT: 16801- MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-http://localhost:8080}"+ MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-}"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"+ - "${MOTRIX_WEB_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_HTTP_PORT:-8080}:8080"+ - "${MOTRIX_MDXP_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_MDXP_PUBLIC_PORT:-16801}:16801"volumes:- motrix-data:/data- motrix-downloads:/downloadsdiff --git a/compose.reverse-proxy.env b/compose.reverse-proxy.envnew file mode 100644index 00000000..ce444373--- /dev/null+++ b/compose.reverse-proxy.env@@ -0,0 +1,6 @@+# Bind both published services to the Docker host loopback for a host proxy.+MOTRIX_WEB_BIND_IP=127.0.0.1+MOTRIX_MDXP_BIND_IP=127.0.0.1++# Set this separately to the externally reachable HTTPS Web URL, for example:+# MOTRIX_PUBLIC_URL=https://motrix.example.comdiff --git a/compose.yaml b/compose.yamlindex 3f896a01..21d4a839 100644--- a/compose.yaml+++ b/compose.yaml@@ -20,10 +20,10 @@ services:MOTRIX_ALLOWED_SAVE_DIRS: /downloadsMOTRIX_MDXP_HOST: 0.0.0.0MOTRIX_MDXP_PORT: 16801- MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-http://localhost:8080}"+ MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-}"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"+ - "${MOTRIX_WEB_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_HTTP_PORT:-8080}:8080"+ - "${MOTRIX_MDXP_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_MDXP_PUBLIC_PORT:-16801}:16801"volumes:- ./motrix-data:/data- ./downloads:/downloadsdiff --git a/docs/docker-server.md b/docs/docker-server.mdindex 192c990b..8568b7a3 100644--- a/docs/docker-server.md+++ b/docs/docker-server.md@@ -119,6 +119,66 @@ Do not add `--volumes` to `docker compose down`: that option deletes the namedvolumes. Bind mounts are usually easier when downloads must also appear in aNAS shared folder.+## Network publication modes++The listeners inside the container and the ports published on the Docker host+are separate boundaries. The Web/API process listens on `0.0.0.0:8080` inside+the container, and the Compose files set the internal MDXP listener to+`MOTRIX_MDXP_HOST=0.0.0.0` on port 16801. Those container-wide listeners let+Docker forward traffic; they do not by themselves make either service public.+The host addresses in Compose `ports` decide which host interfaces can reach+them.++The standard direct-LAN configuration keeps the existing defaults: both host+ports bind to `0.0.0.0`, so trusted LAN devices can reach the Web service on+8080 and MDXP on 16801. The publication controls are independent:++| Compose variable | Controls | Default and fallback |+| --- | --- | --- |+| `MOTRIX_WEB_BIND_IP` | Host address publishing container port 8080 | `MOTRIX_BIND_IP`, then `0.0.0.0` |+| `MOTRIX_MDXP_BIND_IP` | Host address publishing container port 16801 | `MOTRIX_BIND_IP`, then `0.0.0.0` |+| `MOTRIX_BIND_IP` | Compatibility fallback for both services | `0.0.0.0` |++Existing deployments that set only `MOTRIX_BIND_IP` keep the same behavior.+New deployments can bind the services differently, for example publishing the+Web UI on a LAN address while keeping MDXP on host loopback. Do not change the+container's `MOTRIX_MDXP_HOST` to `127.0.0.1`: that loopback belongs to the+container, so Docker port forwarding and other containers cannot reach it.++### Reverse proxy on the Docker host++The included [`compose.reverse-proxy.env`](../compose.reverse-proxy.env) binds+both published origin ports to the Docker host's loopback. It is intended for a+reverse proxy running on that host:++```bash+export MOTRIX_PUBLIC_URL='https://motrix.example.com'+docker compose --env-file compose.reverse-proxy.env -f compose.yaml pull server+docker compose --env-file compose.reverse-proxy.env -f compose.yaml up -d --wait+```++For named volumes, replace `-f compose.yaml` with+`-f compose.named-volumes.yaml`. Configure the host proxy with separate+upstreams for `127.0.0.1:8080` (Web UI/API) and `127.0.0.1:16801` (MDXP HTTP and+SSE), and preserve cookies, authorization headers, and streaming responses.+The environment file only restricts host publication: it does not enable TLS,+disable either service, or disable pairing. TLS certificates and proxy routing+remain operator configuration.++### Reverse proxy in another container++When the proxy is a container on the same user-defined Docker network, the+safer design is to omit `ports` from the Motrix service entirely. Route the+proxy to `server:8080` and `server:16801` over that private network, and publish+only the proxy's TLS entry point. Merely binding Motrix to host loopback still+publishes origin ports and is unnecessary for this topology.++The repository does not include a runnable container-proxy Compose example,+because certificate mounts, proxy image, hostnames, and whether MDXP uses a+separate origin are deployment-specific. Start from the base service contract,+remove its two `ports` entries in your deployment Compose, and keep both+internal listeners on `0.0.0.0` so the proxy container can reach them.+## Synology DSM 7 Container ManagerDSM labels can vary slightly between Container Manager updates, but the@@ -145,10 +205,11 @@ deployment model is the same:`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.+whole NAS filesystem. If DSM's reverse proxy runs in the host network context,+use `compose.reverse-proxy.env` so both origins bind to host loopback. If the+proxy cannot reach host loopback, bind each required origin to a selected NAS+address with `MOTRIX_WEB_BIND_IP` and `MOTRIX_MDXP_BIND_IP`, then restrict both+ports with the DSM firewall.## fnOS Docker/Compose@@ -203,7 +264,9 @@ docker run -d \```The image already defines its health check, non-root user, data paths, and-graceful `SIGTERM` behavior.+graceful `SIGTERM` behavior. In this command,+`MOTRIX_MDXP_HOST=0.0.0.0` controls the listener inside the container, while+the two `-p` options publish those container ports on the Docker host.## Web, MDXP, token, and HTTPS boundaries@@ -212,11 +275,16 @@ The default addresses are different services:| Address | Purpose || --- | --- || `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 |+| `http://NAS_HOST:16801` | MDXP client base; unary `POST /mdxp`, event stream `GET /mdxp/events`, and CLI/agent 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:+device-code clients. It has no localhost default: set it explicitly whenever a+remote client must pair, and do not advertise `localhost`, `127.0.0.1`, or+`0.0.0.0` to a client on another machine. Use the Web port or its reverse-proxy+URL, not the MDXP port. Leaving it unset does not disable pairing, but the+client cannot receive a useful approval URL from the server. On first start,+Motrix generates `/data/operator-token` at mode `0600`. With bind mounts, read+it with:```bashcat motrix-data/operator-token@@ -226,12 +294,38 @@ The same token is reused across restart and image replacement. You may set`MOTRIX_OPERATOR_TOKEN` instead, but environment variables are visible incontainer metadata; the generated file is the safer single-host default.-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+If the Web approval URL is unavailable, an operator connected over SSH can+approve the exact device code from inside the running container. The command+uses the existing operator credential over container loopback; it never prints+that credential or the client token:++```bash+docker compose exec server motrix-admin pairing pending+docker compose exec server motrix-admin pairing approve ABCD-EFGH+```++To reject a request instead:++```bash+docker compose exec server motrix-admin pairing deny ABCD-EFGH+```++Start pairing on the client first, then enter the code shown by that client.+The command intentionally has no approve-latest, approve-all, remote endpoint,+or token argument. Web approval remains available and is the normal path; this+is an optional local operator path for headless or recovery deployments.++Plain HTTP can be appropriate for a trusted LAN; Motrix does not force HTTPS.+For Internet or untrusted-LAN access, TLS termination at a trusted reverse+proxy **and** firewall protection for the origin ports are required. Proxy port+8080 as the Web origin and preserve cookies, authorization headers, and+streaming responses. MDXP is a separate HTTP/SSE service: remote clients need a+TLS-enabled proxy/upstream to port 16801 as well. Forwarding only port 8080 doesnot publish MDXP, and forwarding only 16801 does not serve the approval UI.+These protections must not be implemented by disabling pairing; remote+CLI/agent pairing remains an operator-approved workflow. First-time browser+extension pairing is a desktop/native-messaging flow and is not offered by the+headless server.## Download paths and plugins@@ -366,9 +460,12 @@ detection.| `MOTRIX_ALLOW_UNMANAGED_PLUGINS` | `false` | Allow plugin directories without install provenance || `MOTRIX_OPERATOR_TOKEN` | generated file | Operator control-plane credential || `MOTRIX_SECRETS_SEED` | generated lockbox | 64-hex-character plugin secret key |-| `MOTRIX_MDXP_HOST` | `127.0.0.1` (Compose: `0.0.0.0`) | MDXP bind address |+| `MOTRIX_WEB_BIND_IP` | Compose: `0.0.0.0` | Host address publishing Web port 8080; falls back through `MOTRIX_BIND_IP` |+| `MOTRIX_MDXP_BIND_IP` | Compose: `0.0.0.0` | Host address publishing MDXP port 16801; falls back through `MOTRIX_BIND_IP` |+| `MOTRIX_BIND_IP` | Compose: `0.0.0.0` | Backward-compatible shared host-publish fallback |+| `MOTRIX_MDXP_HOST` | runtime: `127.0.0.1`; Compose: `0.0.0.0` | MDXP listener inside the container, not the host publish address || `MOTRIX_MDXP_PORT` | `16801` | MDXP listen port; `0` disables a stable published port |-| `MOTRIX_PUBLIC_URL` | unset | Externally reachable Web approval URL, not the MDXP URL |+| `MOTRIX_PUBLIC_URL` | unset | Explicit externally reachable Web approval URL, not the MDXP URL; never defaults to localhost || `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 3bed9ccf..4268b5a8 100644--- a/docs/docker-server.zh-CN.md+++ b/docs/docker-server.zh-CN.md@@ -111,6 +111,57 @@ docker compose -f compose.named-volumes.yaml up -d --wait执行 `docker compose down` 时不要添加 `--volumes`,该参数会删除 namedvolumes。需要让下载文件同时出现在 NAS 共享文件夹时,bind mount 通常更合适。+## 网络发布模式++容器内的 listener 与 Docker 宿主上发布的端口是两层独立边界。Web/API 进程在+容器内监听 `0.0.0.0:8080`,Compose 文件则把容器内 MDXP listener 设为+`MOTRIX_MDXP_HOST=0.0.0.0`,端口为 16801。这些面向整个容器的 listener 使+Docker 能够转发流量,但不会单独把服务变成公网服务。最终哪些宿主接口可以访问+它们,由 Compose `ports` 中的宿主地址决定。++标准直连 LAN 配置保持现有默认值:两个宿主端口都绑定到 `0.0.0.0`,可信 LAN+设备可通过 8080 访问 Web 服务,通过 16801 访问 MDXP。两项发布可以独立控制:++| Compose 变量 | 控制对象 | 默认值与 fallback |+| --- | --- | --- |+| `MOTRIX_WEB_BIND_IP` | 把容器 8080 端口发布到的宿主地址 | `MOTRIX_BIND_IP`,然后是 `0.0.0.0` |+| `MOTRIX_MDXP_BIND_IP` | 把容器 16801 端口发布到的宿主地址 | `MOTRIX_BIND_IP`,然后是 `0.0.0.0` |+| `MOTRIX_BIND_IP` | 两项服务的兼容 fallback | `0.0.0.0` |++原有部署只设置 `MOTRIX_BIND_IP` 时,行为保持不变。新部署可以分别绑定两项服务,+例如把 Web 界面发布到 LAN 地址,但让 MDXP 仅绑定到宿主 loopback。不要把容器内的+`MOTRIX_MDXP_HOST` 改为 `127.0.0.1`:该 loopback 属于容器,Docker 端口转发和其他容器+都无法访问它。++### 运行在 Docker 宿主上的反向代理++仓库提供的 [`compose.reverse-proxy.env`](../compose.reverse-proxy.env) 会把两个已发布的+origin 端口都绑定到 Docker 宿主 loopback,适用于运行在同一宿主上的反向代理:++```bash+export MOTRIX_PUBLIC_URL='https://motrix.example.com'+docker compose --env-file compose.reverse-proxy.env -f compose.yaml pull server+docker compose --env-file compose.reverse-proxy.env -f compose.yaml up -d --wait+```++如果使用 named volume,请把 `-f compose.yaml` 替换为+`-f compose.named-volumes.yaml`。宿主反向代理需要配置两个独立 upstream:+`127.0.0.1:8080`(Web 界面/API)和 `127.0.0.1:16801`(MDXP HTTP 与 SSE),并保留 cookie、+Authorization header 和流式响应。该 environment 文件只限制宿主发布范围;它不会启用+TLS、禁用任一服务或禁用配对。TLS 证书与代理路由仍需要 operator 自行配置。++### 运行在其他容器中的反向代理++如果反向代理容器与 Motrix 位于同一个用户定义 Docker network,更安全的设计是完全省略+Motrix service 的 `ports`。让代理通过该私有 network 访问 `server:8080` 和+`server:16801`,并且只发布代理的 TLS 入口。在这种拓扑中,把 Motrix 绑定到宿主+loopback 仍会发布 origin 端口,因此没有必要。++仓库没有提供可直接运行的容器反向代理 Compose 示例,因为证书挂载、代理镜像、域名以及 MDXP+是否使用独立 origin 都与具体部署有关。请以基础 service contract 为起点,在自己的部署+Compose 中删除两条 `ports`,并让两个容器内 listener 继续使用 `0.0.0.0`,确保代理容器+可以访问它们。+## 群晖 DSM 7 Container Manager不同版本的 Container Manager 界面名称可能略有区别,但部署模型相同:@@ -133,8 +184,9 @@ volumes。需要让下载文件同时出现在 NAS 共享文件夹时,bind mou`motrix-data/operator-token` 解锁。不要启用“高权限”、挂载 Docker socket 或授权访问整个 NAS 文件系统。若 DSM-反向代理是 Web 的唯一入口,仅当代理的网络环境可访问主机 loopback 时才设置-`MOTRIX_BIND_IP=127.0.0.1`;否则监听 NAS 地址,并通过 DSM 防火墙限制端口。+反向代理运行在宿主网络环境时,可使用 `compose.reverse-proxy.env` 让两个 origin 都绑定到宿主+loopback。如果代理无法访问宿主 loopback,请用 `MOTRIX_WEB_BIND_IP` 和+`MOTRIX_MDXP_BIND_IP` 把各自需要的 origin 绑定到选定的 NAS 地址,再用 DSM 防火墙限制这两个端口。## 飞牛 fnOS Docker/Compose@@ -183,7 +235,9 @@ docker run -d \motrixapp/motrix-server:latest```-镜像已经定义 healthcheck、非 root 用户、数据路径和优雅 `SIGTERM` 行为。+镜像已经定义 healthcheck、非 root 用户、数据路径和优雅 `SIGTERM` 行为。在这条命令中,+`MOTRIX_MDXP_HOST=0.0.0.0` 控制容器内 listener,两个 `-p` 选项则把容器端口发布到+Docker 宿主。## Web、MDXP、token 与 HTTPS 边界@@ -192,11 +246,13 @@ docker run -d \| 地址 | 用途 || --- | --- || `http://NAS_HOST:8080` | Web 界面、operator RPC/API 与 `GET /healthz` |-| `http://NAS_HOST:16801` | MDXP 客户端基址;单次调用 `POST /mdxp`、事件流 `GET /mdxp/events` 与 device-code 配对 |+| `http://NAS_HOST:16801` | MDXP 客户端基址;单次调用 `POST /mdxp`、事件流 `GET /mdxp/events` 与 CLI/agent device-code 配对 |`MOTRIX_PUBLIC_URL` 是 device-code 客户端收到的、外部可访问的 **Web 审批-URL**,不要把它设置为 MDXP 端口。首次启动时,Motrix 会以 `0600` 权限生成-`/data/operator-token`。使用 bind mount 时可这样读取:+URL**。它没有 localhost 默认值:远程客户端需要配对时必须显式设置,不要向另一台机器上的+客户端发布 `localhost`、`127.0.0.1` 或 `0.0.0.0`。应使用 Web 端口或它的反向代理 URL,+而不是 MDXP 端口。留空不会禁用配对,但客户端无法从服务器获得有效的审批 URL。+首次启动时,Motrix 会以 `0600` 权限生成 `/data/operator-token`。使用 bind mount 时可这样读取:```bashcat motrix-data/operator-token@@ -205,11 +261,32 @@ cat motrix-data/operator-token重启或替换镜像时会继续使用同一 token。也可以设置 `MOTRIX_OPERATOR_TOKEN`,但环境变量能从容器元数据中看到;单机部署默认使用生成文件更安全。-不要把明文 HTTP 直接暴露到公网。应在可信反向代理终止 HTTPS,并用防火墙-限制源端口。把 8080 作为 Web upstream,并保留 cookie、Authorization header-和流式响应。MDXP 是独立的 HTTP/SSE 服务:远程 MDXP 客户端需要另一个启用-TLS、指向 16801 的代理/upstream。只转发 8080 不会发布 MDXP,只转发 16801-也不会提供审批界面。+当 Web 审批 URL 暂时不可用时,通过 SSH 连接的 operator 可以在运行中的容器+里批准指定的 device code。该命令只通过容器 loopback 使用现有 operator+credential,不会输出该 credential 或客户端 token:++```bash+docker compose exec server motrix-admin pairing pending+docker compose exec server motrix-admin pairing approve ABCD-EFGH+```++如果需要拒绝请求:++```bash+docker compose exec server motrix-admin pairing deny ABCD-EFGH+```++先在客户端发起 pairing,再输入该客户端显示的验证码。该命令刻意不提供+approve-latest、approve-all、远程 endpoint 或 token 参数。Web 审批仍是正常+路径;这个入口只用于 headless 或恢复场景下的本机 operator 操作。++在可信 LAN 中可以使用明文 HTTP,Motrix 不会强制 HTTPS。通过公网或不可信 LAN 访问时,+必须同时使用可信反向代理终止 TLS,并用防火墙保护 origin 端口。把 8080 作为 Web+origin,并保留 cookie、Authorization header 和流式响应。MDXP 是独立的 HTTP/SSE 服务:+远程客户端还需要一个启用 TLS、指向 16801 的代理/upstream。只转发 8080 不会发布+MDXP,只转发 16801 也不会提供审批界面。不应通过禁用配对来实现这些保护;远程+CLI/agent 配对仍然是一项需要 operator 审批的正常流程。浏览器扩展的首次配对是桌面应用/+native messaging flow,headless server 不提供该流程。## 下载路径与插件@@ -334,9 +411,12 @@ secret-store 状态和 FFmpeg 探测结果。| `MOTRIX_ALLOW_UNMANAGED_PLUGINS` | `false` | 允许没有安装来源记录的插件目录 || `MOTRIX_OPERATOR_TOKEN` | 自动生成文件 | operator 控制面凭据 || `MOTRIX_SECRETS_SEED` | 自动生成 lockbox | 64 位十六进制插件 secret 密钥 |-| `MOTRIX_MDXP_HOST` | `127.0.0.1`(Compose 为 `0.0.0.0`) | MDXP 监听地址 |+| `MOTRIX_WEB_BIND_IP` | Compose:`0.0.0.0` | 发布 Web 8080 端口的宿主地址;通过 `MOTRIX_BIND_IP` fallback |+| `MOTRIX_MDXP_BIND_IP` | Compose:`0.0.0.0` | 发布 MDXP 16801 端口的宿主地址;通过 `MOTRIX_BIND_IP` fallback |+| `MOTRIX_BIND_IP` | Compose:`0.0.0.0` | 向后兼容的共享宿主发布 fallback |+| `MOTRIX_MDXP_HOST` | runtime:`127.0.0.1`;Compose:`0.0.0.0` | 容器内 MDXP listener,不是宿主发布地址 || `MOTRIX_MDXP_PORT` | `16801` | MDXP 监听端口;`0` 表示不使用固定发布端口 |-| `MOTRIX_PUBLIC_URL` | 未设置 | 外部可访问的 Web 审批 URL,不是 MDXP URL |+| `MOTRIX_PUBLIC_URL` | 未设置 | 显式设置的外部可访问 Web 审批 URL,不是 MDXP URL;不会默认为 localhost || `MOTRIX_FFMPEG_PATH` | 自动探测 | 可选的 FFmpeg 绝对路径 || `MOTRIX_HOST_LANGUAGE` | 系统设置 | Server/插件语言覆盖值 || `LOG_LEVEL` | `info` | 输出到容器 stdout 的 Pino 日志级别 |diff --git a/electron-builder.signing.json b/electron-builder.signing.jsonnew file mode 100644index 00000000..e6240a7a--- /dev/null+++ b/electron-builder.signing.json@@ -0,0 +1,177 @@+{+ "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json",+ "appId": "app.motrix.native",+ "productName": "Motrix",+ "copyright": "Copyright © 2026 Dr_rOot",+ "extends": null,+ "asar": true,+ "asarUnpack": [+ "**/node_modules/{better-sqlite3,bindings,file-uri-to-path}/**",+ "dist/renderer/**"+ ],+ "directories": {+ "app": "dist/electron-app",+ "output": "release",+ "buildResources": "signing-build-resources"+ },+ "files": [+ ".motrix-package-stage.json",+ "dist/core/plugin/host/**",+ "dist/main/**",+ "dist/preload/**",+ "dist/renderer/**",+ "package.json",+ {+ "from": "node_modules",+ "to": "node_modules",+ "filter": [+ "**/*",+ "!**/*.map",+ "!**/*.ts",+ "!**/*.tsx",+ "!**/tsconfig*.json",+ "!**/biome.json",+ "!**/vite*.config.*"+ ]+ },+ "!**/*.map",+ "!**/*.ts",+ "!**/*.tsx",+ "!**/tsconfig*.json",+ "!**/biome.json",+ "!**/vite*.config.*"+ ],+ "extraResources": [+ {+ "from": "./THIRD_PARTY_NOTICES.md",+ "to": "./THIRD_PARTY_NOTICES.md"+ },+ {+ "from": "./THIRD_PARTY_NOTICES.zh-CN.md",+ "to": "./THIRD_PARTY_NOTICES.zh-CN.md"+ },+ {+ "from": "./THIRD_PARTY_LICENSES",+ "to": "./THIRD_PARTY_LICENSES"+ },+ {+ "from": "./build/legal",+ "to": "./legal",+ "filter": [+ "THIRD_PARTY_DEPENDENCIES.md",+ "THIRD_PARTY_LICENSES.txt",+ "sbom.spdx.json"+ ]+ }+ ],+ "electronFuses": {+ "runAsNode": false,+ "enableCookieEncryption": false,+ "enableNodeOptionsEnvironmentVariable": false,+ "enableNodeCliInspectArguments": false,+ "enableEmbeddedAsarIntegrityValidation": false,+ "onlyLoadAppFromAsar": true,+ "loadBrowserProcessSpecificV8Snapshot": false,+ "grantFileProtocolExtraPrivileges": true+ },+ "protocols": [+ {+ "name": "Motrix Protocol",+ "schemes": ["motrix", "mo"]+ },+ {+ "name": "Magnet Protocol",+ "schemes": ["magnet"]+ }+ ],+ "fileAssociations": [+ {+ "ext": "torrent",+ "mimeType": "application/x-bittorrent",+ "name": "Torrent",+ "role": "Viewer"+ }+ ],+ "mac": {+ "category": "public.app-category.utilities",+ "type": "distribution",+ "artifactName": "${productName}-${version}-${arch}.${ext}",+ "minimumSystemVersion": "12.0",+ "hardenedRuntime": true,+ "gatekeeperAssess": false,+ "entitlements": "signing-build-resources/entitlements.mac.plist",+ "entitlementsInherit": "signing-build-resources/entitlements.mac.plist",+ "darkModeSupport": true,+ "extendInfo": {+ "NSLocalNetworkUsageDescription": "Motrix uses the local network for UPnP port mapping and discovering download peers."+ },+ "target": ["dmg", "zip"],+ "extraResources": [+ { "from": "./extra/aria2.conf", "to": "./extra/aria2.conf" },+ { "from": "./dist/builtin-plugins", "to": "./builtin-plugins" },+ { "from": "./extra/darwin/${arch}/", "to": "./extra/darwin/${arch}/" },+ {+ "from": "./packages/native-host/dist/darwin-${arch}/motrix-native-host",+ "to": "bin/motrix-native-host"+ },+ {+ "from": "./extra/tray/",+ "to": "./extra/tray/",+ "filter": [+ "[email protected]",+ "[email protected]",+ "tray.svg",+ "resvg.wasm",+ "SFNS-Regular.ttf"+ ]+ }+ ]+ },+ "dmg": {+ "window": { "width": 540, "height": 380 },+ "contents": [+ { "x": 410, "y": 230, "type": "link", "path": "/Applications" },+ { "x": 130, "y": 230, "type": "file" }+ ]+ },+ "win": {+ "target": [+ { "target": "nsis", "arch": ["x64"] },+ { "target": "zip", "arch": ["x64"] }+ ],+ "extraResources": [+ { "from": "./extra/aria2.conf", "to": "./extra/aria2.conf" },+ { "from": "./dist/builtin-plugins", "to": "./builtin-plugins" },+ { "from": "./extra/win32/${arch}/", "to": "./extra/win32/${arch}/" },+ {+ "from": "./packages/native-host/dist/win32-${arch}/motrix-native-host.exe",+ "to": "bin/motrix-native-host.exe"+ },+ {+ "from": "./extra/tray/",+ "to": "./extra/tray/",+ "filter": ["mo-tray-colorful-*.ico"]+ }+ ]+ },+ "nsis": {+ "include": "trusted/installer.nsh",+ "script": null,+ "customNsisBinary": null,+ "customNsisResources": null,+ "artifactName": "${productName}-Setup-${version}.${ext}",+ "oneClick": false,+ "allowToChangeInstallationDirectory": true,+ "deleteAppDataOnUninstall": false,+ "perMachine": false+ },+ "electronDist": "trusted/electron.zip",+ "electronVersion": "43.3.0",+ "npmRebuild": false,+ "detectUpdateChannel": true,+ "generateUpdatesFilesForAllChannels": true,+ "publish": {+ "provider": "generic",+ "url": "https://dl.motrix.app/releases/"+ }+}diff --git a/scripts/audit-server-runtime.mjs b/scripts/audit-server-runtime.mjsindex c0a45064..55538115 100644--- a/scripts/audit-server-runtime.mjs+++ b/scripts/audit-server-runtime.mjs@@ -82,17 +82,35 @@ async function auditInputs(repoRoot, inputs, collectExternals) {throw new Error(`missing ${input.type} input: ${input.source}`)}if (collectExternals) {- const entry =- input.type === 'file' ? source : path.join(source, input.entry)- if (input.type === 'directory') {- if (!(await stat(entry).catch(() => null))?.isFile()) {- throw new Error(`missing build entry: ${input.source}/${input.entry}`)+ const entries =+ input.type === 'file'+ ? [source]+ : (Array.isArray(input.entry) ? input.entry : [input.entry]).map(+ (entry) => path.join(source, entry)+ )+ for (const [index, entry] of entries.entries()) {+ if (+ input.type === 'directory' &&+ !(await stat(entry).catch(() => null))?.isFile()+ ) {+ const relativeEntry = Array.isArray(input.entry)+ ? input.entry[index]+ : input.entry+ throw new Error(+ `missing build entry: ${input.source}/${relativeEntry}`+ )}}if (input.scanExternals) {- const sourceText = await readFile(entry, 'utf8')- for (const specifier of scanStaticModuleSpecifiers(sourceText)) {- specifiers.add(specifier)+ const modules =+ input.type === 'directory'+ ? await listJavaScriptFiles(source)+ : entries+ for (const modulePath of modules) {+ const sourceText = await readFile(modulePath, 'utf8')+ for (const specifier of scanStaticModuleSpecifiers(sourceText)) {+ specifiers.add(specifier)+ }}}}@@ -110,6 +128,23 @@ async function auditInputs(repoRoot, inputs, collectExternals) {return { records, specifiers: [...specifiers].sort() }}+async function listJavaScriptFiles(directory) {+ const files = []+ async function walk(current) {+ const entries = await readdir(current, { withFileTypes: true })+ entries.sort((left, right) => left.name.localeCompare(right.name))+ for (const entry of entries) {+ const entryPath = path.join(current, entry.name)+ if (entry.isDirectory()) await walk(entryPath)+ else if (entry.isFile() && /\.(?:c|m)?js$/.test(entry.name)) {+ files.push(entryPath)+ }+ }+ }+ await walk(directory)+ return files+}+async function resolvePackageRoot(repoRoot, name) {const require = createRequire(path.join(repoRoot, 'package.json'))const candidates = [path.join(repoRoot, 'node_modules', name, 'package.json')]diff --git a/scripts/release-signing-input.mjs b/scripts/release-signing-input.mjsnew file mode 100644index 00000000..e3ab2c46--- /dev/null+++ b/scripts/release-signing-input.mjs@@ -0,0 +1,791 @@+import { createHash } from 'node:crypto'+import { createReadStream } from 'node:fs'+import {+ cp,+ lstat,+ mkdir,+ open,+ readdir,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const REPOSITORY_ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..'+)+const SCHEMA_VERSION = 2+const ELECTRON_BUILDER_VERSION = '26.15.7'+const ELECTRON_VERSION = '43.3.0'+const PLATFORMS = new Set(['darwin', 'win32'])+const ARCHES = new Set(['arm64', 'x64'])++export const SIGNING_ARCHIVE_LIMITS = Object.freeze({+ archiveBytes: 1024 * 1024 * 1024,+ inputBytes: 768 * 1024 * 1024,+ fileBytes: 512 * 1024 * 1024,+ files: 50_000,+ manifestBytes: 16 * 1024 * 1024,+ pathBytes: 4096,+})++const TRUSTED_INPUT_SHA256 = Object.freeze({+ 'electron-builder.signing.json':+ '9bae9c7366f9666e2c7fae705a99fc3e160ba20582d665e9074e3133e684a3c8',+ 'signing-build-resources/256x256.png':+ '044d3b64a14aa512ca41469372d1ad630557daaeb2cb4e709d34f2d3c57d4c3b',+ 'signing-build-resources/background.tiff':+ 'f15290fe1a059a6b262466445fd24a63eabf0e2a4f734f9812dfe8ac0b9609c1',+ 'signing-build-resources/entitlements.mac.plist':+ '38e56782c6c54555ff3c19b344ce8887e0689d935770a45208883e37f6aec500',+ 'signing-build-resources/icon.icns':+ 'f9ff86f32c2110b21d71a49a346f4186c4ef2cf1aed3884eca9704cb77fb4ed7',+ 'signing-build-resources/icon.ico':+ 'a71d20d0ca732e27b445e3f09a0cd22cb356620929416e790d005dfff9c4e5a7',+ 'signing-build-resources/torrent.icns':+ '1c8e042a7d4391fa241b4411badbe4a7393a8ad8429679838bf43b25ab29425f',+ 'signing-build-resources/torrent.ico':+ '7743ad382011e30236e91322164f0ebd20c283e634db44c36f314aa2abf2f5a8',+ 'signing-policy/installer.nsh':+ '961d33dafec6c6deab622b473217896a6fc64abbcd0cb30dadc5308d026eeeb4',+ 'signing-tool/package.json':+ 'b8ddd0e1bb90198d99628eb8b5b8c3c2b8cbda4a3aee48f118a36244467fac51',+ 'signing-tool/package-lock.json':+ 'd19faa86a197df62719776877d600b2345670a81d58b1939949681aee8b225bf',+ 'scripts/electron-package-size-budgets.json':+ 'f37ffcdb32967077cf66711526de91201d1bb976f3e48687cbc89fba89b94696',+ 'scripts/electron-package-utils.mjs':+ '9d408f9edc91182be5d5aed39f2c5a5d20f5523e08d9c08e630c23c66302daa8',+ 'scripts/native-binary-target.mjs':+ '6f0a42eecf729eb6de2df28b5d7449993590e494deb4e309b99c367094045797',+ 'scripts/verify-electron-package.mjs':+ 'fc8a3eb35684e2b21c46b6677a2568aeffbd4a7a6befae09fc57c9068b05c680',+})++const SOURCE_MAPPINGS = [+ ['THIRD_PARTY_LICENSES', 'THIRD_PARTY_LICENSES'],+ ['THIRD_PARTY_NOTICES.md', 'THIRD_PARTY_NOTICES.md'],+ ['THIRD_PARTY_NOTICES.zh-CN.md', 'THIRD_PARTY_NOTICES.zh-CN.md'],+ ['build/legal', 'build/legal'],+ ['build/256x256.png', 'signing-build-resources/256x256.png'],+ ['build/background.tiff', 'signing-build-resources/background.tiff'],+ [+ 'build/entitlements.mac.plist',+ 'signing-build-resources/entitlements.mac.plist',+ ],+ ['build/icon.icns', 'signing-build-resources/icon.icns'],+ ['build/icon.ico', 'signing-build-resources/icon.ico'],+ ['build/torrent.icns', 'signing-build-resources/torrent.icns'],+ ['build/torrent.ico', 'signing-build-resources/torrent.ico'],+ ['build/installer.nsh', 'signing-policy/installer.nsh'],+ ['dist/builtin-plugins', 'dist/builtin-plugins'],+ ['dist/electron-app', 'dist/electron-app'],+ ['electron-builder.signing.json', 'electron-builder.signing.json'],+ ['extra/aria2.conf', 'extra/aria2.conf'],+ ['extra/tray', 'extra/tray'],+ ['scripts/release-signing-tool/package.json', 'signing-tool/package.json'],+ [+ 'scripts/release-signing-tool/package-lock.json',+ 'signing-tool/package-lock.json',+ ],+ [+ 'scripts/electron-package-size-budgets.json',+ 'scripts/electron-package-size-budgets.json',+ ],+ ['scripts/electron-package-utils.mjs', 'scripts/electron-package-utils.mjs'],+ ['scripts/native-binary-target.mjs', 'scripts/native-binary-target.mjs'],+ [+ 'scripts/verify-electron-package.mjs',+ 'scripts/verify-electron-package.mjs',+ ],+ ['scripts/release-signing-input.mjs', 'scripts/release-signing-input.mjs'],+]++async function sha256File(absolutePath, expectedBytes) {+ const hash = createHash('sha256')+ let observedBytes = 0+ for await (const chunk of createReadStream(absolutePath)) {+ observedBytes += chunk.length+ if (observedBytes > SIGNING_ARCHIVE_LIMITS.fileBytes) {+ throw new Error(`signing input file exceeds size limit: ${absolutePath}`)+ }+ hash.update(chunk)+ }+ if (expectedBytes !== undefined && observedBytes !== expectedBytes) {+ throw new Error(`signing input file changed while reading: ${absolutePath}`)+ }+ return hash.digest('hex')+}++function portable(relativePath) {+ return relativePath.split(path.sep).join('/')+}++function compareNames(left, right) {+ if (left.name < right.name) return -1+ if (left.name > right.name) return 1+ return 0+}++function isAllowedSigningDataPath(relativePath) {+ return (+ [+ 'THIRD_PARTY_NOTICES.md',+ 'THIRD_PARTY_NOTICES.zh-CN.md',+ 'electron-builder.signing.json',+ 'signing-policy/installer.nsh',+ 'signing-tool/package.json',+ 'signing-tool/package-lock.json',+ 'scripts/electron-package-size-budgets.json',+ 'scripts/electron-package-utils.mjs',+ 'scripts/native-binary-target.mjs',+ 'scripts/release-signing-input.mjs',+ 'scripts/verify-electron-package.mjs',+ ].includes(relativePath) ||+ [+ 'THIRD_PARTY_LICENSES/',+ 'build/legal/',+ 'dist/builtin-plugins/',+ 'dist/electron-app/',+ 'extra/',+ 'packages/native-host/dist/',+ 'signing-build-resources/',+ 'size-reports/',+ ].some((prefix) => relativePath.startsWith(prefix))+ )+}++function isForbiddenControlPath(relativePath) {+ if (+ relativePath === 'signing-tool/package.json' ||+ relativePath === 'signing-tool/package-lock.json'+ ) {+ return false+ }+ const lowercasePath = relativePath.toLowerCase()+ const basename = path.posix.basename(lowercasePath)+ return (+ basename === 'electron-builder.env' ||+ basename === 'yarn.lock' ||+ basename === 'pnpm-lock.yaml' ||+ basename === 'package-lock.json' ||+ basename === 'npm-shrinkwrap.json' ||+ basename === 'pnpm-workspace.yaml' ||+ basename === '.npmrc' ||+ basename === '.pnpmfile.cjs' ||+ basename.startsWith('bun.lock') ||+ basename.startsWith('.yarnrc') ||+ basename.startsWith('.pnp.') ||+ basename === '.yarn' ||+ lowercasePath.startsWith('.yarn/') ||+ lowercasePath.includes('/.yarn/')+ )+}++function isAllowedSigningDirectory(relativePath) {+ const recursiveRoots = [+ 'THIRD_PARTY_LICENSES',+ 'build/legal',+ 'dist/builtin-plugins',+ 'dist/electron-app',+ 'extra',+ 'packages/native-host/dist',+ ]+ const flatRoots = [+ 'signing-build-resources',+ 'signing-policy',+ 'signing-tool',+ 'scripts',+ 'size-reports',+ ]+ return (+ recursiveRoots.some(+ (root) =>+ relativePath === root ||+ relativePath.startsWith(`${root}/`) ||+ root.startsWith(`${relativePath}/`)+ ) ||+ flatRoots.some(+ (root) => relativePath === root || root.startsWith(`${relativePath}/`)+ )+ )+}++function isAllowedSigningBuildResource(relativePath) {+ return new Set([+ 'signing-build-resources/256x256.png',+ 'signing-build-resources/background.tiff',+ 'signing-build-resources/entitlements.mac.plist',+ 'signing-build-resources/icon.icns',+ 'signing-build-resources/icon.ico',+ 'signing-build-resources/torrent.icns',+ 'signing-build-resources/torrent.ico',+ ]).has(relativePath)+}++function parseOptions(argv) {+ const options = {}+ for (let index = 0; index < argv.length; index += 1) {+ const argument = argv[index]+ if (!argument.startsWith('--')) {+ throw new Error(`unknown argument: ${argument}`)+ }+ const key = argument.slice(2)+ if (+ !['arch', 'archive', 'commit', 'directory', 'mode', 'platform'].includes(+ key+ )+ ) {+ throw new Error(`unknown option: ${argument}`)+ }+ const value = argv[index + 1]+ if (!value || value.startsWith('--')) {+ throw new Error(`missing value for ${argument}`)+ }+ options[key] = value+ index += 1+ }+ if (!['create', 'verify'].includes(options.mode)) {+ throw new Error('--mode must be create or verify')+ }+ if (!PLATFORMS.has(options.platform)) {+ throw new Error('--platform must be darwin or win32')+ }+ if (!ARCHES.has(options.arch)) {+ throw new Error('--arch must be arm64 or x64')+ }+ if (+ typeof options.commit !== 'string' ||+ !/^[0-9a-f]{40}$/u.test(options.commit)+ ) {+ throw new Error('--commit must be a lowercase 40-character Git SHA')+ }+ if (!options.directory) throw new Error('--directory is required')+ if (options.mode === 'create' && !options.archive) {+ throw new Error('--archive is required in create mode')+ }+ if (options.platform === 'win32' && options.arch !== 'x64') {+ throw new Error('Windows signing input only supports x64')+ }+ return options+}++async function assertSafeTree(root) {+ const canonicalRoot = await realpath(root)+ async function visit(current, relative = '') {+ for (const entry of await readdir(current, { withFileTypes: true })) {+ const entryPath = path.join(current, entry.name)+ const relativePath = portable(+ relative ? path.join(relative, entry.name) : entry.name+ )+ if (entry.isSymbolicLink()) {+ throw new Error(`signing input must not contain symlinks: ${entryPath}`)+ }+ if (entry.isDirectory()) {+ if (+ relativePath === 'trusted' ||+ relativePath.startsWith('trusted/') ||+ relativePath === 'release' ||+ relativePath.startsWith('release/') ||+ isForbiddenControlPath(relativePath) ||+ !isAllowedSigningDirectory(relativePath)+ ) {+ throw new Error(+ `signing input contains a reserved directory: ${relativePath}`+ )+ }+ await visit(entryPath, relativePath)+ } else if (+ entry.isFile() &&+ relativePath !== 'signing-input-manifest.json' &&+ (isForbiddenControlPath(relativePath) ||+ !isAllowedSigningDataPath(relativePath))+ ) {+ throw new Error(+ `signing input contains a reserved file: ${relativePath}`+ )+ } else if (!entry.isFile()) {+ throw new Error(`signing input must contain only files: ${entryPath}`)+ }+ }+ }+ await visit(canonicalRoot)+}++function targetResource(platform, arch) {+ const executable = platform === 'win32' ? 'aria2c.exe' : 'aria2c'+ return `extra/${platform}/${arch}/${executable}`+}++function nativeHostResource(platform, arch) {+ const executable =+ platform === 'win32' ? 'motrix-native-host.exe' : 'motrix-native-host'+ return `packages/native-host/dist/${platform}-${arch}/${executable}`+}++function normalizedMode(relativePath, info, options) {+ if (+ relativePath === targetResource(options.platform, options.arch) ||+ relativePath === nativeHostResource(options.platform, options.arch)+ ) {+ return 0o755+ }+ return (info.mode & 0o111) === 0 ? 0o644 : 0o755+}++async function inventory(root, options = {}) {+ const files = []+ let totalBytes = 0+ async function visit(current, relative) {+ const entries = await readdir(current, { withFileTypes: true })+ entries.sort(compareNames)+ for (const entry of entries) {+ const absolute = path.join(current, entry.name)+ const relativePath = relative+ ? path.join(relative, entry.name)+ : entry.name+ if (entry.isSymbolicLink()) {+ throw new Error(+ `signing input must not contain symlinks: ${relativePath}`+ )+ }+ if (entry.isDirectory()) {+ await visit(absolute, relativePath)+ } else if (entry.isFile()) {+ const normalized = portable(relativePath)+ if (normalized === options.exclude) continue+ if (Buffer.byteLength(normalized) > SIGNING_ARCHIVE_LIMITS.pathBytes) {+ throw new Error(`signing input path exceeds limit: ${normalized}`)+ }+ const info = await lstat(absolute)+ if (!info.isFile() || info.size > SIGNING_ARCHIVE_LIMITS.fileBytes) {+ throw new Error(`signing input file exceeds limit: ${normalized}`)+ }+ totalBytes += info.size+ if (+ files.length + 1 > SIGNING_ARCHIVE_LIMITS.files ||+ totalBytes > SIGNING_ARCHIVE_LIMITS.inputBytes+ ) {+ throw new Error('signing input exceeds archive limits')+ }+ files.push({+ path: normalized,+ bytes: info.size,+ mode: normalizedMode(normalized, info, options),+ sha256: await sha256File(absolute, info.size),+ })+ } else {+ throw new Error(+ `signing input must contain only files: ${relativePath}`+ )+ }+ }+ }+ await visit(root, '')+ return files+}++function tarString(buffer, offset, length, value) {+ const bytes = Buffer.from(value)+ if (bytes.length > length) throw new Error(`tar field is too long: ${value}`)+ bytes.copy(buffer, offset)+}++function tarOctal(buffer, offset, length, value) {+ const encoded = value.toString(8).padStart(length - 1, '0')+ if (encoded.length >= length) {+ throw new Error(`tar value is too large: ${value}`)+ }+ tarString(buffer, offset, length, `${encoded}\0`)+}++function tarHeader(name, size, mode, type) {+ const header = Buffer.alloc(512)+ tarString(header, 0, 100, name)+ tarOctal(header, 100, 8, mode)+ tarOctal(header, 108, 8, 0)+ tarOctal(header, 116, 8, 0)+ tarOctal(header, 124, 12, size)+ tarOctal(header, 136, 12, 0)+ header.fill(0x20, 148, 156)+ tarString(header, 156, 1, type)+ tarString(header, 257, 6, 'ustar')+ tarString(header, 263, 2, '00')+ tarString(header, 265, 32, 'root')+ tarString(header, 297, 32, 'root')+ const checksum = header.reduce((sum, byte) => sum + byte, 0)+ tarString(header, 148, 8, `${checksum.toString(8).padStart(6, '0')}\0 `)+ return header+}++function paxPathRecord(relativePath) {+ const body = `path=${relativePath}\n`+ let length = Buffer.byteLength(body) + 3+ while (true) {+ const record = `${length} ${body}`+ const actual = Buffer.byteLength(record)+ if (actual === length) return Buffer.from(record)+ length = actual+ }+}++function tarEntryBytes(relativePath, size) {+ const paxBytes =+ Buffer.byteLength(relativePath) > 100+ ? 512 + Math.ceil(paxPathRecord(relativePath).length / 512) * 512+ : 0+ return paxBytes + 512 + Math.ceil(size / 512) * 512+}++async function writeAll(handle, bytes) {+ let offset = 0+ while (offset < bytes.length) {+ const result = await handle.write(bytes, offset, bytes.length - offset)+ offset += result.bytesWritten+ }+}++async function writeFileContents(handle, absolutePath, expectedBytes) {+ let observedBytes = 0+ for await (const chunk of createReadStream(absolutePath)) {+ observedBytes += chunk.length+ if (observedBytes > expectedBytes) {+ throw new Error(`signing input file changed: ${absolutePath}`)+ }+ await writeAll(handle, chunk)+ }+ if (observedBytes !== expectedBytes) {+ throw new Error(`signing input file changed: ${absolutePath}`)+ }+}++async function writeTarEntry(handle, root, entry, index) {+ let tarName = entry.path+ if (Buffer.byteLength(entry.path) > 100) {+ const pax = paxPathRecord(entry.path)+ await writeAll(+ handle,+ tarHeader(+ `PaxHeaders/${String(index).padStart(8, '0')}`,+ pax.length,+ 0o644,+ 'x'+ )+ )+ await writeAll(handle, pax)+ await writeAll(handle, Buffer.alloc((512 - (pax.length % 512)) % 512))+ tarName = `PaxFiles/${String(index).padStart(8, '0')}`+ }+ await writeAll(handle, tarHeader(tarName, entry.bytes, entry.mode, '0'))+ await writeFileContents(handle, path.join(root, entry.path), entry.bytes)+ await writeAll(handle, Buffer.alloc((512 - (entry.bytes % 512)) % 512))+}++export async function createSigningArchive(directory, archive, options) {+ const root = path.resolve(directory)+ const archivePath = path.resolve(archive)+ const entries = await inventory(root, options)+ const archiveBytes =+ entries.reduce(+ (total, entry) => total + tarEntryBytes(entry.path, entry.bytes),+ 0+ ) + 1024+ if (archiveBytes > SIGNING_ARCHIVE_LIMITS.archiveBytes) {+ throw new Error('signing input tar exceeds archive size limit')+ }+ await mkdir(path.dirname(archivePath), { recursive: true })+ const handle = await open(archivePath, 'w', 0o644)+ try {+ for (const [index, entry] of entries.entries()) {+ await writeTarEntry(handle, root, entry, index)+ }+ await writeAll(handle, Buffer.alloc(1024))+ } finally {+ await handle.close()+ }+}++async function copySource(sourcePath, destinationPath, output) {+ const source = path.join(REPOSITORY_ROOT, sourcePath)+ const info = await lstat(source).catch(() => null)+ if (!info) throw new Error(`missing signing input source: ${sourcePath}`)+ if (info.isSymbolicLink()) {+ throw new Error(`signing input source must not be a symlink: ${sourcePath}`)+ }+ const target = path.join(output, destinationPath)+ await mkdir(path.dirname(target), { recursive: true })+ await cp(source, target, { recursive: true, dereference: false })+}++async function verifyTrustedInputDigests(root) {+ for (const [relativePath, expected] of Object.entries(TRUSTED_INPUT_SHA256)) {+ const absolute = path.join(root, relativePath)+ const info = await lstat(absolute).catch(() => null)+ if (+ !info?.isFile() ||+ info.size > SIGNING_ARCHIVE_LIMITS.fileBytes ||+ (await sha256File(absolute, info.size)) !== expected+ ) {+ throw new Error(`trusted signing input digest mismatch: ${relativePath}`)+ }+ }+}++export async function createSigningInput(options) {+ const output = path.resolve(options.directory)+ await rm(output, { recursive: true, force: true })+ await mkdir(output, { recursive: true })++ const targetKey = `${options.platform}-${options.arch}`+ for (const [sourcePath, destinationPath] of [+ ...SOURCE_MAPPINGS,+ [+ targetResource(options.platform, options.arch),+ targetResource(options.platform, options.arch),+ ],+ [+ nativeHostResource(options.platform, options.arch),+ nativeHostResource(options.platform, options.arch),+ ],+ [+ `release/size-reports/${targetKey}.json`,+ `size-reports/${targetKey}.json`,+ ],+ ]) {+ await copySource(sourcePath, destinationPath, output)+ }+ await assertSafeTree(output)+ await verifyTrustedInputDigests(output)++ const manifest = {+ schemaVersion: SCHEMA_VERSION,+ commit: options.commit,+ target: {+ key: targetKey,+ platform: options.platform,+ arch: options.arch,+ },+ tools: {+ electronBuilder: ELECTRON_BUILDER_VERSION,+ electron: ELECTRON_VERSION,+ },+ limits: SIGNING_ARCHIVE_LIMITS,+ files: await inventory(output, options),+ }+ await writeFile(+ path.join(output, 'signing-input-manifest.json'),+ `${JSON.stringify(manifest, null, 2)}\n`,+ { flag: 'wx', mode: 0o644 }+ )+ if (options.archive) {+ await createSigningArchive(output, options.archive, options)+ }+ return manifest+}++function exactKeys(value, expected, label) {+ const actual = Object.keys(value).sort()+ if (JSON.stringify(actual) !== JSON.stringify([...expected].sort())) {+ throw new Error(`${label} has unexpected keys`)+ }+}++function verifyManifestEntry(entry) {+ exactKeys(entry, ['bytes', 'mode', 'path', 'sha256'], 'file inventory entry')+ if (+ typeof entry.path !== 'string' ||+ entry.path.length === 0 ||+ entry.path.includes('\\') ||+ entry.path.includes('\0') ||+ Buffer.byteLength(entry.path) > SIGNING_ARCHIVE_LIMITS.pathBytes ||+ path.posix.normalize(entry.path) !== entry.path ||+ path.posix.isAbsolute(entry.path) ||+ entry.path === '..' ||+ entry.path.startsWith('../') ||+ entry.path === 'trusted' ||+ entry.path.startsWith('trusted/') ||+ entry.path === 'release' ||+ entry.path.startsWith('release/') ||+ entry.path === 'package.json' ||+ (/(?:^|\/)installer\.ns[hi]$/iu.test(entry.path) &&+ entry.path !== 'signing-policy/installer.nsh') ||+ entry.path.startsWith('signing-build-resources/x86-unicode/') ||+ entry.path.startsWith('signing-build-resources/x86-ansi/') ||+ !isAllowedSigningDataPath(entry.path) ||+ (entry.path.startsWith('signing-build-resources/') &&+ !isAllowedSigningBuildResource(entry.path)) ||+ isForbiddenControlPath(entry.path) ||+ !Number.isSafeInteger(entry.bytes) ||+ entry.bytes < 0 ||+ entry.bytes > SIGNING_ARCHIVE_LIMITS.fileBytes ||+ ![0o644, 0o755].includes(entry.mode) ||+ typeof entry.sha256 !== 'string' ||+ !/^[0-9a-f]{64}$/u.test(entry.sha256)+ ) {+ throw new Error('signing input manifest contains an invalid file entry')+ }+}++async function verifyRestrictedConfig(input) {+ const config = JSON.parse(+ await readFile(path.join(input, 'electron-builder.signing.json'), 'utf8')+ )+ for (const hook of [+ 'afterAllArtifactBuild',+ 'afterExtract',+ 'afterPack',+ 'afterSign',+ 'appxManifestCreated',+ 'artifactBuildCompleted',+ 'artifactBuildStarted',+ 'beforeBuild',+ 'beforePack',+ 'msiProjectCreated',+ 'onNodeModuleFile',+ ]) {+ if (Object.hasOwn(config, hook)) {+ throw new Error(`restricted signing config must not define ${hook}`)+ }+ }+ if (+ config.electronDist !== 'trusted/electron.zip' ||+ config.electronVersion !== ELECTRON_VERSION ||+ config.extends !== null ||+ config.npmRebuild !== false ||+ config.directories?.buildResources !== 'signing-build-resources' ||+ config.nsis?.include !== 'trusted/installer.nsh' ||+ config.nsis?.script !== null ||+ config.nsis?.customNsisBinary !== null ||+ config.nsis?.customNsisResources !== null ||+ config.toolsets?.nsis !== undefined ||+ config.mac?.sign !== undefined ||+ config.win?.signtoolOptions?.sign !== undefined+ ) {+ throw new Error('restricted signing config is not self-contained')+ }+}++async function verifySigningTool(input) {+ const toolPackage = JSON.parse(+ await readFile(path.join(input, 'signing-tool/package.json'), 'utf8')+ )+ const toolLock = JSON.parse(+ await readFile(path.join(input, 'signing-tool/package-lock.json'), 'utf8')+ )+ if (+ toolPackage.private !== true ||+ toolPackage.scripts !== undefined ||+ toolPackage.dependencies?.['electron-builder'] !==+ ELECTRON_BUILDER_VERSION ||+ toolLock.lockfileVersion !== 3 ||+ toolLock.packages?.['']?.dependencies?.['electron-builder'] !==+ ELECTRON_BUILDER_VERSION ||+ toolLock.packages?.['node_modules/electron-builder']?.version !==+ ELECTRON_BUILDER_VERSION+ ) {+ throw new Error('signing tool dependency closure is not pinned')+ }+ for (const [packagePath, metadata] of Object.entries(toolLock.packages)) {+ if (packagePath === '') continue+ if (+ typeof metadata.version !== 'string' ||+ typeof metadata.resolved !== 'string' ||+ !metadata.resolved.startsWith('https://registry.npmjs.org/') ||+ typeof metadata.integrity !== 'string' ||+ !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(metadata.integrity)+ ) {+ throw new Error(+ `signing tool lock contains an unpinned package: ${packagePath}`+ )+ }+ }+}++export async function verifySigningInput(options) {+ const input = path.resolve(options.directory)+ const manifestPath = path.join(input, 'signing-input-manifest.json')+ const manifestInfo = await lstat(manifestPath)+ if (+ !manifestInfo.isFile() ||+ manifestInfo.size > SIGNING_ARCHIVE_LIMITS.manifestBytes+ ) {+ throw new Error('signing input manifest exceeds size limit')+ }+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))+ exactKeys(+ manifest,+ ['commit', 'files', 'limits', 'schemaVersion', 'target', 'tools'],+ 'signing input manifest'+ )+ exactKeys(manifest.target, ['arch', 'key', 'platform'], 'target')+ exactKeys(manifest.tools, ['electron', 'electronBuilder'], 'tools')+ if (+ manifest.schemaVersion !== SCHEMA_VERSION ||+ manifest.commit !== options.commit ||+ manifest.target.platform !== options.platform ||+ manifest.target.arch !== options.arch ||+ manifest.target.key !== `${options.platform}-${options.arch}` ||+ manifest.tools.electronBuilder !== ELECTRON_BUILDER_VERSION ||+ manifest.tools.electron !== ELECTRON_VERSION ||+ JSON.stringify(manifest.limits) !==+ JSON.stringify(SIGNING_ARCHIVE_LIMITS) ||+ !Array.isArray(manifest.files)+ ) {+ throw new Error('signing input manifest metadata does not match the job')+ }+ if (+ manifest.files.length === 0 ||+ manifest.files.length > SIGNING_ARCHIVE_LIMITS.files+ ) {+ throw new Error('signing input file inventory exceeds limit')+ }+ for (const entry of manifest.files) verifyManifestEntry(entry)+ const expectedPaths = manifest.files.map((entry) => entry.path)+ if (+ JSON.stringify(expectedPaths) !==+ JSON.stringify([...new Set(expectedPaths)].sort())+ ) {+ throw new Error('signing input file inventory must be sorted and unique')+ }+ const totalBytes = manifest.files.reduce(+ (total, entry) => total + entry.bytes,+ 0+ )+ if (+ !Number.isSafeInteger(totalBytes) ||+ totalBytes > SIGNING_ARCHIVE_LIMITS.inputBytes+ ) {+ throw new Error('signing input file inventory exceeds size limit')+ }++ await assertSafeTree(input)+ const actual = await inventory(input, {+ exclude: 'signing-input-manifest.json',+ platform: options.platform,+ arch: options.arch,+ })+ if (JSON.stringify(actual) !== JSON.stringify(manifest.files)) {+ throw new Error('signing input file inventory or digest does not match')+ }+ await verifyTrustedInputDigests(input)+ await verifyRestrictedConfig(input)+ await verifySigningTool(input)+ return manifest+}++async function main() {+ const options = parseOptions(process.argv.slice(2))+ if (options.mode === 'create') await createSigningInput(options)+ else await verifySigningInput(options)+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ await main().catch((error) => {+ console.error(error instanceof Error ? error.message : String(error))+ process.exitCode = 1+ })+}diff --git a/scripts/release-signing-tool/package-lock.json b/scripts/release-signing-tool/package-lock.jsonnew file mode 100644index 00000000..e9b54a04--- /dev/null+++ b/scripts/release-signing-tool/package-lock.json@@ -0,0 +1,3219 @@+{+ "name": "motrix-release-signing-tool",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "motrix-release-signing-tool",+ "version": "1.0.0",+ "dependencies": {+ "electron-builder": "26.15.7"+ }+ },+ "node_modules/@electron/asar": {+ "version": "3.4.1",+ "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz",+ "integrity": "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==",+ "license": "MIT",+ "dependencies": {+ "commander": "^5.0.0",+ "glob": "^7.1.6",+ "minimatch": "^3.0.4"+ },+ "bin": {+ "asar": "bin/asar.js"+ },+ "engines": {+ "node": ">=10.12.0"+ }+ },+ "node_modules/@electron/asar/node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "license": "MIT"+ },+ "node_modules/@electron/asar/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/@electron/asar/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/@electron/fuses": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-1.8.0.tgz",+ "integrity": "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==",+ "license": "MIT",+ "dependencies": {+ "chalk": "^4.1.1",+ "fs-extra": "^9.0.1",+ "minimist": "^1.2.5"+ },+ "bin": {+ "electron-fuses": "dist/bin.js"+ }+ },+ "node_modules/@electron/fuses/node_modules/fs-extra": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",+ "license": "MIT",+ "dependencies": {+ "at-least-node": "^1.0.0",+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@electron/get": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz",+ "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "env-paths": "^2.2.0",+ "fs-extra": "^8.1.0",+ "got": "^11.8.5",+ "progress": "^2.0.3",+ "semver": "^6.2.0",+ "sumchecker": "^3.0.1"+ },+ "engines": {+ "node": ">=14"+ },+ "optionalDependencies": {+ "global-agent": "^3.0.0"+ }+ },+ "node_modules/@electron/get/node_modules/fs-extra": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",+ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^4.0.0",+ "universalify": "^0.1.0"+ },+ "engines": {+ "node": ">=6 <7 || >=8"+ }+ },+ "node_modules/@electron/get/node_modules/jsonfile": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",+ "license": "MIT",+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/@electron/get/node_modules/semver": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ }+ },+ "node_modules/@electron/get/node_modules/universalify": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",+ "license": "MIT",+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/@electron/notarize": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.5.0.tgz",+ "integrity": "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "fs-extra": "^9.0.1",+ "promise-retry": "^2.0.1"+ },+ "engines": {+ "node": ">= 10.0.0"+ }+ },+ "node_modules/@electron/notarize/node_modules/fs-extra": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",+ "license": "MIT",+ "dependencies": {+ "at-least-node": "^1.0.0",+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@electron/osx-sign": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.3.3.tgz",+ "integrity": "sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "compare-version": "^0.1.2",+ "debug": "^4.3.4",+ "fs-extra": "^10.0.0",+ "isbinaryfile": "^4.0.8",+ "minimist": "^1.2.6",+ "plist": "^3.0.5"+ },+ "bin": {+ "electron-osx-flat": "bin/electron-osx-flat.js",+ "electron-osx-sign": "bin/electron-osx-sign.js"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/@electron/osx-sign/node_modules/isbinaryfile": {+ "version": "4.0.10",+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",+ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",+ "license": "MIT",+ "engines": {+ "node": ">= 8.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/gjtorikian/"+ }+ },+ "node_modules/@electron/rebuild": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.0.tgz",+ "integrity": "sha512-RKL/O+jGoXJMxrx/5771y1n0xTKmFuOYGO3gMmwypBM6rsH0kou0mswwdXA2JrhIkE4xyC7v9vGk0n6NPzgOxQ==",+ "license": "MIT",+ "dependencies": {+ "@malept/cross-spawn-promise": "^2.0.0",+ "debug": "^4.1.1",+ "node-abi": "^4.2.0",+ "node-api-version": "^0.2.1",+ "node-gyp": "^12.2.0",+ "read-binary-file-arch": "^1.0.6"+ },+ "bin": {+ "electron-rebuild": "lib/cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/@electron/universal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz",+ "integrity": "sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==",+ "license": "MIT",+ "dependencies": {+ "@electron/asar": "^3.3.1",+ "@malept/cross-spawn-promise": "^2.0.0",+ "debug": "^4.3.1",+ "dir-compare": "^4.2.0",+ "fs-extra": "^11.1.1",+ "minimatch": "^9.0.3",+ "plist": "^3.1.0"+ },+ "engines": {+ "node": ">=16.4"+ }+ },+ "node_modules/@electron/universal/node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "license": "MIT"+ },+ "node_modules/@electron/universal/node_modules/brace-expansion": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",+ "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0"+ }+ },+ "node_modules/@electron/universal/node_modules/fs-extra": {+ "version": "11.4.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/@electron/universal/node_modules/minimatch": {+ "version": "9.0.9",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^2.0.2"+ },+ "engines": {+ "node": ">=16 || 14 >=14.17"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/@electron/windows-sign": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz",+ "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==",+ "license": "BSD-2-Clause",+ "optional": true,+ "peer": true,+ "dependencies": {+ "cross-dirname": "^0.1.0",+ "debug": "^4.3.4",+ "fs-extra": "^11.1.1",+ "minimist": "^1.2.8",+ "postject": "^1.0.0-alpha.6"+ },+ "bin": {+ "electron-windows-sign": "bin/electron-windows-sign.js"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/@electron/windows-sign/node_modules/fs-extra": {+ "version": "11.4.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.0.tgz",+ "integrity": "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/@isaacs/fs-minipass": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",+ "license": "ISC",+ "dependencies": {+ "minipass": "^7.0.4"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@malept/cross-spawn-promise": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",+ "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/malept"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"+ }+ ],+ "license": "Apache-2.0",+ "dependencies": {+ "cross-spawn": "^7.0.1"+ },+ "engines": {+ "node": ">= 12.13.0"+ }+ },+ "node_modules/@malept/flatpak-bundler": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/@malept/flatpak-bundler/-/flatpak-bundler-0.4.0.tgz",+ "integrity": "sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "fs-extra": "^9.0.0",+ "lodash": "^4.17.15",+ "tmp-promise": "^3.0.2"+ },+ "engines": {+ "node": ">= 10.0.0"+ }+ },+ "node_modules/@malept/flatpak-bundler/node_modules/fs-extra": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",+ "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",+ "license": "MIT",+ "dependencies": {+ "at-least-node": "^1.0.0",+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@noble/hashes": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",+ "integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@peculiar/asn1-schema": {+ "version": "2.8.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.8.0.tgz",+ "integrity": "sha512-7YT0U/ze0tF2QOBbE15gKZwy5tvgGyLRiRHLzhlbOpf7BT032oBSd0haZqXn5W6l26WLlu3dyxzjM+2638/z2Q==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/utils": "^2.0.2",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/json-schema": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz",+ "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.0.0"+ },+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@peculiar/utils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",+ "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/webcrypto": {+ "version": "1.7.1",+ "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.1.tgz",+ "integrity": "sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.7.0",+ "@peculiar/json-schema": "^1.1.12",+ "@peculiar/utils": "^2.0.2",+ "tslib": "^2.8.1",+ "webcrypto-core": "^1.9.2"+ },+ "engines": {+ "node": ">=14.18.0"+ }+ },+ "node_modules/@sindresorhus/is": {+ "version": "4.6.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",+ "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@szmarczak/http-timer": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",+ "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",+ "license": "MIT",+ "dependencies": {+ "defer-to-connect": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@types/cacheable-request": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",+ "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",+ "license": "MIT",+ "dependencies": {+ "@types/http-cache-semantics": "*",+ "@types/keyv": "^3.1.4",+ "@types/node": "*",+ "@types/responselike": "^1.0.0"+ }+ },+ "node_modules/@types/debug": {+ "version": "4.1.13",+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },+ "node_modules/@types/fs-extra": {+ "version": "9.0.13",+ "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz",+ "integrity": "sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==",+ "license": "MIT"+ },+ "node_modules/@types/keyv": {+ "version": "3.1.4",+ "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",+ "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "26.2.0",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",+ "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",+ "license": "MIT",+ "dependencies": {+ "undici-types": "~8.3.0"+ }+ },+ "node_modules/@types/responselike": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz",+ "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@xmldom/xmldom": {+ "version": "0.8.14",+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.14.tgz",+ "integrity": "sha512-T4EDRUBVZYRldYApjEJiU0e1stYWaRAX7CuSnKzrpwdZKo53zGV8/pqfzV6FfwNl9YThD2OumQYvqtvjvgG7aQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ }+ },+ "node_modules/abbrev": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz",+ "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==",+ "license": "ISC",+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/agent-base": {+ "version": "7.1.4",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/app-builder-lib": {+ "version": "26.15.7",+ "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.15.7.tgz",+ "integrity": "sha512-C7APoYISPExUmrEntNhDpz9Tccb4uWuEDfLaC0WPPc7/pwzz0WZGznCz/ycPfkkzw6tKOalceD8g6TgHmVz1QA==",+ "license": "MIT",+ "dependencies": {+ "@electron/asar": "3.4.1",+ "@electron/fuses": "^1.8.0",+ "@electron/get": "^3.0.0",+ "@electron/notarize": "2.5.0",+ "@electron/osx-sign": "1.3.3",+ "@electron/rebuild": "^4.0.4",+ "@electron/universal": "2.0.3",+ "@malept/flatpak-bundler": "^0.4.0",+ "@noble/hashes": "^2.2.0",+ "@peculiar/webcrypto": "^1.7.1",+ "@types/fs-extra": "9.0.13",+ "ajv": "^8.18.0",+ "asn1js": "^3.0.10",+ "async-exit-hook": "^2.0.1",+ "builder-util": "26.15.3",+ "builder-util-runtime": "9.7.0",+ "chromium-pickle-js": "^0.2.0",+ "ci-info": "4.3.1",+ "debug": "^4.3.4",+ "dotenv": "^16.4.5",+ "dotenv-expand": "^11.0.6",+ "ejs": "^3.1.8",+ "electron-publish": "26.15.3",+ "fs-extra": "^10.1.0",+ "hosted-git-info": "^4.1.0",+ "isbinaryfile": "^5.0.0",+ "jiti": "^2.4.2",+ "js-yaml": "^4.1.0",+ "json5": "^2.2.3",+ "lazy-val": "^1.0.5",+ "minimatch": "^10.2.5",+ "pkijs": "^3.4.0",+ "plist": "3.1.0",+ "proper-lockfile": "^4.1.2",+ "resedit": "^1.7.0",+ "semver": "~7.7.3",+ "tar": "^7.5.7",+ "temp-file": "^3.4.0",+ "tiny-async-pool": "1.3.0",+ "unzipper": "^0.12.3",+ "which": "^5.0.0"+ },+ "engines": {+ "node": ">=14.0.0"+ },+ "peerDependencies": {+ "dmg-builder": "26.15.7",+ "electron-builder-squirrel-windows": "26.15.7"+ }+ },+ "node_modules/app-builder-lib/node_modules/ci-info": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz",+ "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/sibiraj-s"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "license": "Python-2.0"+ },+ "node_modules/asn1js": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",+ "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "pvtsutils": "^1.3.6",+ "pvutils": "^1.1.5",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/async": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",+ "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",+ "license": "MIT"+ },+ "node_modules/async-exit-hook": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/async-exit-hook/-/async-exit-hook-2.0.1.tgz",+ "integrity": "sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.12.0"+ }+ },+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",+ "license": "MIT"+ },+ "node_modules/at-least-node": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz",+ "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==",+ "license": "ISC",+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/aws4": {+ "version": "1.13.2",+ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",+ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==",+ "license": "MIT"+ },+ "node_modules/balanced-match": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/bluebird": {+ "version": "3.7.2",+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",+ "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",+ "license": "MIT"+ },+ "node_modules/boolean": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",+ "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",+ "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",+ "license": "MIT",+ "optional": true+ },+ "node_modules/brace-expansion": {+ "version": "5.0.9",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",+ "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/buffer-from": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",+ "license": "MIT"+ },+ "node_modules/builder-util": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",+ "integrity": "sha512-q2hn7Mbo2nFNkVekPiHFx6Nfo3hURmES3tfBn+k5Pqxl2RkmP3QGqZUhH/q9Pch/4G05NRhPjDlVj1O8q4Txvw==",+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.1.6",+ "builder-util-runtime": "9.7.0",+ "chalk": "^4.1.2",+ "cross-spawn": "^7.0.6",+ "debug": "^4.3.4",+ "fs-extra": "^10.1.0",+ "http-proxy-agent": "^7.0.0",+ "https-proxy-agent": "^7.0.0",+ "js-yaml": "^4.1.0",+ "sanitize-filename": "^1.6.3",+ "source-map-support": "^0.5.19",+ "stat-mode": "^1.0.0",+ "temp-file": "^3.4.0",+ "tiny-async-pool": "1.3.0"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/builder-util-runtime": {+ "version": "9.7.0",+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",+ "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.3.4",+ "sax": "^1.2.4"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/bytestreamjs": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz",+ "integrity": "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/cacheable-lookup": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",+ "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",+ "license": "MIT",+ "engines": {+ "node": ">=10.6.0"+ }+ },+ "node_modules/cacheable-request": {+ "version": "7.0.4",+ "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",+ "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",+ "license": "MIT",+ "dependencies": {+ "clone-response": "^1.0.2",+ "get-stream": "^5.1.0",+ "http-cache-semantics": "^4.0.0",+ "keyv": "^4.0.0",+ "lowercase-keys": "^2.0.0",+ "normalize-url": "^6.0.1",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/chalk": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.1.0",+ "supports-color": "^7.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/chownr": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/chromium-pickle-js": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz",+ "integrity": "sha512-1R5Fho+jBq0DDydt+/vHWj5KJNJCKdARKOCwZUen84I5BreWoLqRLANH1U87eJy1tiASPtMnGqJJq0ZsLoRPOw==",+ "license": "MIT"+ },+ "node_modules/ci-info": {+ "version": "4.4.0",+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz",+ "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/sibiraj-s"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/cliui": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.1",+ "wrap-ansi": "^7.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/clone-response": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",+ "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "license": "MIT",+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "license": "MIT"+ },+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "license": "MIT",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/commander": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",+ "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/compare-version": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/compare-version/-/compare-version-0.1.2.tgz",+ "integrity": "sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/concat-map": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",+ "license": "MIT"+ },+ "node_modules/core-util-is": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",+ "license": "MIT"+ },+ "node_modules/cross-dirname": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",+ "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==",+ "license": "MIT",+ "optional": true,+ "peer": true+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/cross-spawn/node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/cross-spawn/node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/decompress-response": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",+ "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",+ "license": "MIT",+ "dependencies": {+ "mimic-response": "^3.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/decompress-response/node_modules/mimic-response": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",+ "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/defer-to-connect": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",+ "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/define-data-property": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0",+ "es-errors": "^1.3.0",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/define-properties": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-data-property": "^1.0.1",+ "has-property-descriptors": "^1.0.0",+ "object-keys": "^1.1.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/detect-node": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",+ "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/dir-compare": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",+ "integrity": "sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==",+ "license": "MIT",+ "dependencies": {+ "minimatch": "^3.0.5",+ "p-limit": "^3.1.0 "+ }+ },+ "node_modules/dir-compare/node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "license": "MIT"+ },+ "node_modules/dir-compare/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/dir-compare/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/dmg-builder": {+ "version": "26.15.7",+ "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.15.7.tgz",+ "integrity": "sha512-rfo1YyAWO0L3cZLKCqKQiLYbW6ZXebRUfK0kWp4oXxO7dDFLrf7alRkWImNuXvZVQhs6Idzy++cwOk8I+xPDhw==",+ "license": "MIT",+ "dependencies": {+ "app-builder-lib": "26.15.7",+ "builder-util": "26.15.3",+ "fs-extra": "^10.1.0",+ "js-yaml": "^4.1.0"+ }+ },+ "node_modules/dotenv": {+ "version": "16.6.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",+ "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/dotenv-expand": {+ "version": "11.0.7",+ "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-11.0.7.tgz",+ "integrity": "sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "dotenv": "^16.4.5"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/duplexer2": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz",+ "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "readable-stream": "^2.0.2"+ }+ },+ "node_modules/ejs": {+ "version": "3.1.10",+ "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz",+ "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==",+ "license": "Apache-2.0",+ "dependencies": {+ "jake": "^10.8.5"+ },+ "bin": {+ "ejs": "bin/cli.js"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/electron-builder": {+ "version": "26.15.7",+ "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.15.7.tgz",+ "integrity": "sha512-DBpaNzxsPs1BvEblzFoNriSbzsBqDCy/gseIngeEhYzQG1IxfB7Hvc2tBBVmpWE2BTQGP9J1RrAvDT+Vc/uAxg==",+ "license": "MIT",+ "dependencies": {+ "app-builder-lib": "26.15.7",+ "builder-util": "26.15.3",+ "builder-util-runtime": "9.7.0",+ "chalk": "^4.1.2",+ "ci-info": "^4.2.0",+ "dmg-builder": "26.15.7",+ "fs-extra": "^10.1.0",+ "lazy-val": "^1.0.5",+ "simple-update-notifier": "2.0.0",+ "yargs": "^17.6.2"+ },+ "bin": {+ "electron-builder": "cli.js",+ "install-app-deps": "install-app-deps.js"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/electron-builder-squirrel-windows": {+ "version": "26.15.7",+ "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.15.7.tgz",+ "integrity": "sha512-B4uvn2NzFSuf084udWqugludFull6CRJiWe2dLzMnZLl6G5hdAGk0fsBMGlBSpKjvQCJn8IPc+S7OnJ+GXqwLA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "app-builder-lib": "26.15.7",+ "builder-util": "26.15.3",+ "electron-winstaller": "5.4.0"+ }+ },+ "node_modules/electron-publish": {+ "version": "26.15.3",+ "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.15.3.tgz",+ "integrity": "sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==",+ "license": "MIT",+ "dependencies": {+ "@types/fs-extra": "^9.0.11",+ "aws4": "^1.13.2",+ "builder-util": "26.15.3",+ "builder-util-runtime": "9.7.0",+ "chalk": "^4.1.2",+ "form-data": "^4.0.5",+ "fs-extra": "^10.1.0",+ "lazy-val": "^1.0.5",+ "mime": "^2.5.2"+ }+ },+ "node_modules/electron-winstaller": {+ "version": "5.4.0",+ "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz",+ "integrity": "sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==",+ "hasInstallScript": true,+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@electron/asar": "^3.2.1",+ "debug": "^4.1.1",+ "fs-extra": "^7.0.1",+ "lodash": "^4.17.21",+ "temp": "^0.9.0"+ },+ "engines": {+ "node": ">=8.0.0"+ },+ "optionalDependencies": {+ "@electron/windows-sign": "^1.1.2"+ }+ },+ "node_modules/electron-winstaller/node_modules/fs-extra": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",+ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "graceful-fs": "^4.1.2",+ "jsonfile": "^4.0.0",+ "universalify": "^0.1.0"+ },+ "engines": {+ "node": ">=6 <7 || >=8"+ }+ },+ "node_modules/electron-winstaller/node_modules/jsonfile": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",+ "license": "MIT",+ "peer": true,+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/electron-winstaller/node_modules/universalify": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">= 4.0.0"+ }+ },+ "node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "license": "MIT"+ },+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },+ "node_modules/env-paths": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/err-code": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",+ "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",+ "license": "MIT"+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es6-error": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",+ "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escape-string-regexp": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/exponential-backoff": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",+ "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==",+ "license": "Apache-2.0"+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",+ "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/filelist": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",+ "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==",+ "license": "Apache-2.0",+ "dependencies": {+ "minimatch": "^5.0.1"+ }+ },+ "node_modules/filelist/node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "license": "MIT"+ },+ "node_modules/filelist/node_modules/brace-expansion": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",+ "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0"+ }+ },+ "node_modules/filelist/node_modules/minimatch": {+ "version": "5.1.9",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",+ "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^2.0.1"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/form-data": {+ "version": "4.0.6",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",+ "license": "MIT",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.4",+ "mime-types": "^2.1.35"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/fs-extra": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",+ "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/fs.realpath": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",+ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",+ "license": "ISC"+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-stream": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",+ "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",+ "license": "MIT",+ "dependencies": {+ "pump": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/glob": {+ "version": "7.2.3",+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",+ "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",+ "license": "ISC",+ "dependencies": {+ "fs.realpath": "^1.0.0",+ "inflight": "^1.0.4",+ "inherits": "2",+ "minimatch": "^3.1.1",+ "once": "^1.3.0",+ "path-is-absolute": "^1.0.0"+ },+ "engines": {+ "node": "*"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/glob/node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "license": "MIT"+ },+ "node_modules/glob/node_modules/brace-expansion": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0",+ "concat-map": "0.0.1"+ }+ },+ "node_modules/glob/node_modules/minimatch": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^1.1.7"+ },+ "engines": {+ "node": "*"+ }+ },+ "node_modules/global-agent": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",+ "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "es6-error": "^4.1.1",+ "matcher": "^3.0.0",+ "roarr": "^2.15.3",+ "semver": "^7.3.2",+ "serialize-error": "^7.0.1"+ },+ "engines": {+ "node": ">=10.0"+ }+ },+ "node_modules/globalthis": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "define-properties": "^1.2.1",+ "gopd": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/got": {+ "version": "11.8.6",+ "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",+ "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",+ "license": "MIT",+ "dependencies": {+ "@sindresorhus/is": "^4.0.0",+ "@szmarczak/http-timer": "^4.0.5",+ "@types/cacheable-request": "^6.0.1",+ "@types/responselike": "^1.0.0",+ "cacheable-lookup": "^5.0.3",+ "cacheable-request": "^7.0.2",+ "decompress-response": "^6.0.0",+ "http2-wrapper": "^1.0.0-beta.5.2",+ "lowercase-keys": "^2.0.0",+ "p-cancelable": "^2.0.0",+ "responselike": "^2.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/got?sponsor=1"+ }+ },+ "node_modules/graceful-fs": {+ "version": "4.2.11",+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",+ "license": "ISC"+ },+ "node_modules/has-flag": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/has-property-descriptors": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "es-define-property": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "license": "MIT",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hosted-git-info": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz",+ "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==",+ "license": "ISC",+ "dependencies": {+ "lru-cache": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/http-cache-semantics": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",+ "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",+ "license": "BSD-2-Clause"+ },+ "node_modules/http-proxy-agent": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.0",+ "debug": "^4.3.4"+ },+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/http2-wrapper": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",+ "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",+ "license": "MIT",+ "dependencies": {+ "quick-lru": "^5.1.1",+ "resolve-alpn": "^1.0.0"+ },+ "engines": {+ "node": ">=10.19.0"+ }+ },+ "node_modules/https-proxy-agent": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.2",+ "debug": "4"+ },+ "engines": {+ "node": ">= 14"+ }+ },+ "node_modules/inflight": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",+ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",+ "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",+ "license": "ISC",+ "dependencies": {+ "once": "^1.3.0",+ "wrappy": "1"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/isarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",+ "license": "MIT"+ },+ "node_modules/isbinaryfile": {+ "version": "5.0.7",+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-5.0.7.tgz",+ "integrity": "sha512-gnWD14Jh3FzS3CPhF0AxNOJ8CxqeblPTADzI38r0wt8ZyQl5edpy75myt08EG2oKvpyiqSqsx+Wkz9vtkbTqYQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/gjtorikian/"+ }+ },+ "node_modules/isexe": {+ "version": "3.1.5",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",+ "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/jake": {+ "version": "10.9.4",+ "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",+ "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==",+ "license": "Apache-2.0",+ "dependencies": {+ "async": "^3.2.6",+ "filelist": "^1.0.4",+ "picocolors": "^1.1.1"+ },+ "bin": {+ "jake": "bin/cli.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/jiti": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",+ "license": "MIT",+ "bin": {+ "jiti": "lib/jiti-cli.mjs"+ }+ },+ "node_modules/js-yaml": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",+ "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },+ "node_modules/json-buffer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",+ "license": "MIT"+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json-stringify-safe": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",+ "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",+ "license": "ISC",+ "optional": true+ },+ "node_modules/json5": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",+ "license": "MIT",+ "bin": {+ "json5": "lib/cli.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/jsonfile": {+ "version": "6.2.1",+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",+ "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",+ "license": "MIT",+ "dependencies": {+ "universalify": "^2.0.0"+ },+ "optionalDependencies": {+ "graceful-fs": "^4.1.6"+ }+ },+ "node_modules/keyv": {+ "version": "4.5.4",+ "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",+ "license": "MIT",+ "dependencies": {+ "json-buffer": "3.0.1"+ }+ },+ "node_modules/lazy-val": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",+ "integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",+ "license": "MIT"+ },+ "node_modules/lodash": {+ "version": "4.18.1",+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",+ "license": "MIT"+ },+ "node_modules/lowercase-keys": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",+ "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/lru-cache": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",+ "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",+ "license": "ISC",+ "dependencies": {+ "yallist": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/matcher": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",+ "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "escape-string-regexp": "^4.0.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/mime": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz",+ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==",+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mimic-response": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",+ "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/minimatch": {+ "version": "10.2.6",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "brace-expansion": "^5.0.8"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/minipass": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=16 || 14 >=14.17"+ }+ },+ "node_modules/minizlib": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",+ "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",+ "license": "MIT",+ "dependencies": {+ "minipass": "^7.1.2"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/mkdirp": {+ "version": "0.5.6",+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "minimist": "^1.2.6"+ },+ "bin": {+ "mkdirp": "bin/cmd.js"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/node-abi": {+ "version": "4.33.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.33.0.tgz",+ "integrity": "sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.6.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/node-api-version": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/node-api-version/-/node-api-version-0.2.1.tgz",+ "integrity": "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.3.5"+ }+ },+ "node_modules/node-gyp": {+ "version": "12.4.0",+ "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz",+ "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==",+ "license": "MIT",+ "dependencies": {+ "env-paths": "^2.2.0",+ "exponential-backoff": "^3.1.1",+ "graceful-fs": "^4.2.6",+ "nopt": "^9.0.0",+ "proc-log": "^6.0.0",+ "semver": "^7.3.5",+ "tar": "^7.5.4",+ "tinyglobby": "^0.2.12",+ "undici": "^6.25.0",+ "which": "^6.0.0"+ },+ "bin": {+ "node-gyp": "bin/node-gyp.js"+ },+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/node-gyp/node_modules/isexe": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz",+ "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/node-gyp/node_modules/which": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz",+ "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^4.0.0"+ },+ "bin": {+ "node-which": "bin/which.js"+ },+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/node-int64": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz",+ "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==",+ "license": "MIT"+ },+ "node_modules/nopt": {+ "version": "9.0.0",+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz",+ "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==",+ "license": "ISC",+ "dependencies": {+ "abbrev": "^4.0.0"+ },+ "bin": {+ "nopt": "bin/nopt.js"+ },+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/normalize-url": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",+ "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/object-keys": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/p-cancelable": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",+ "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "license": "MIT",+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/path-is-absolute": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",+ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/pe-library": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz",+ "integrity": "sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==",+ "license": "MIT",+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/jet2jet"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/pkijs": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz",+ "integrity": "sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@noble/hashes": "1.4.0",+ "asn1js": "^3.0.6",+ "bytestreamjs": "^2.0.1",+ "pvtsutils": "^1.3.6",+ "pvutils": "^1.1.3",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/pkijs/node_modules/@noble/hashes": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",+ "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==",+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/plist": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",+ "integrity": "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==",+ "license": "MIT",+ "dependencies": {+ "@xmldom/xmldom": "^0.8.8",+ "base64-js": "^1.5.1",+ "xmlbuilder": "^15.1.1"+ },+ "engines": {+ "node": ">=10.4.0"+ }+ },+ "node_modules/postject": {+ "version": "1.0.0-alpha.6",+ "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",+ "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "commander": "^9.4.0"+ },+ "bin": {+ "postject": "dist/cli.js"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/postject/node_modules/commander": {+ "version": "9.5.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",+ "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "engines": {+ "node": "^12.20.0 || >=14"+ }+ },+ "node_modules/proc-log": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz",+ "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==",+ "license": "ISC",+ "engines": {+ "node": "^20.17.0 || >=22.9.0"+ }+ },+ "node_modules/process-nextick-args": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",+ "license": "MIT"+ },+ "node_modules/progress": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/promise-retry": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",+ "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",+ "license": "MIT",+ "dependencies": {+ "err-code": "^2.0.2",+ "retry": "^0.12.0"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/proper-lockfile": {+ "version": "4.1.2",+ "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",+ "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.4",+ "retry": "^0.12.0",+ "signal-exit": "^3.0.2"+ }+ },+ "node_modules/pump": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.1.0",+ "once": "^1.3.1"+ }+ },+ "node_modules/pvtsutils": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",+ "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/pvutils": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",+ "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",+ "license": "MIT",+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/quick-lru": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",+ "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/read-binary-file-arch": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",+ "integrity": "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.3.4"+ },+ "bin": {+ "read-binary-file-arch": "cli.js"+ }+ },+ "node_modules/readable-stream": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",+ "license": "MIT",+ "dependencies": {+ "core-util-is": "~1.0.0",+ "inherits": "~2.0.3",+ "isarray": "~1.0.0",+ "process-nextick-args": "~2.0.0",+ "safe-buffer": "~5.1.1",+ "string_decoder": "~1.1.1",+ "util-deprecate": "~1.0.1"+ }+ },+ "node_modules/require-directory": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/resedit": {+ "version": "1.7.2",+ "resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz",+ "integrity": "sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==",+ "license": "MIT",+ "dependencies": {+ "pe-library": "^0.4.1"+ },+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/jet2jet"+ }+ },+ "node_modules/resolve-alpn": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",+ "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==",+ "license": "MIT"+ },+ "node_modules/responselike": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",+ "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",+ "license": "MIT",+ "dependencies": {+ "lowercase-keys": "^2.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/retry": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",+ "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/rimraf": {+ "version": "2.6.3",+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",+ "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==",+ "deprecated": "Rimraf versions prior to v4 are no longer supported",+ "license": "ISC",+ "peer": true,+ "dependencies": {+ "glob": "^7.1.3"+ },+ "bin": {+ "rimraf": "bin.js"+ }+ },+ "node_modules/roarr": {+ "version": "2.15.4",+ "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",+ "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",+ "license": "BSD-3-Clause",+ "optional": true,+ "dependencies": {+ "boolean": "^3.0.1",+ "detect-node": "^2.0.4",+ "globalthis": "^1.0.1",+ "json-stringify-safe": "^5.0.1",+ "semver-compare": "^1.0.0",+ "sprintf-js": "^1.1.2"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/safe-buffer": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",+ "license": "MIT"+ },+ "node_modules/sanitize-filename": {+ "version": "1.6.4",+ "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz",+ "integrity": "sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==",+ "license": "WTFPL OR ISC",+ "dependencies": {+ "truncate-utf8-bytes": "^1.0.0"+ }+ },+ "node_modules/sax": {+ "version": "1.6.1",+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",+ "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=11.0.0"+ }+ },+ "node_modules/semver": {+ "version": "7.7.4",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/semver-compare": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",+ "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/serialize-error": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",+ "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "type-fest": "^0.13.1"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/signal-exit": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "license": "ISC"+ },+ "node_modules/simple-update-notifier": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",+ "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.5.3"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/source-map-support": {+ "version": "0.5.21",+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",+ "license": "MIT",+ "dependencies": {+ "buffer-from": "^1.0.0",+ "source-map": "^0.6.0"+ }+ },+ "node_modules/sprintf-js": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",+ "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",+ "license": "BSD-3-Clause",+ "optional": true+ },+ "node_modules/stat-mode": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-1.0.0.tgz",+ "integrity": "sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/string_decoder": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.1.0"+ }+ },+ "node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/sumchecker": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",+ "license": "Apache-2.0",+ "dependencies": {+ "debug": "^4.1.0"+ },+ "engines": {+ "node": ">= 8.0"+ }+ },+ "node_modules/supports-color": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",+ "license": "MIT",+ "dependencies": {+ "has-flag": "^4.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/tar": {+ "version": "7.5.22",+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",+ "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "@isaacs/fs-minipass": "^4.0.0",+ "chownr": "^3.0.0",+ "minipass": "^7.1.2",+ "minizlib": "^3.1.0",+ "yallist": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tar/node_modules/yallist": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/temp": {+ "version": "0.9.4",+ "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz",+ "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "mkdirp": "^0.5.1",+ "rimraf": "~2.6.2"+ },+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/temp-file": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/temp-file/-/temp-file-3.4.0.tgz",+ "integrity": "sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==",+ "license": "MIT",+ "dependencies": {+ "async-exit-hook": "^2.0.1",+ "fs-extra": "^10.0.0"+ }+ },+ "node_modules/tiny-async-pool": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz",+ "integrity": "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==",+ "license": "MIT",+ "dependencies": {+ "semver": "^5.5.0"+ }+ },+ "node_modules/tiny-async-pool/node_modules/semver": {+ "version": "5.7.2",+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",+ "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/tmp": {+ "version": "0.2.7",+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",+ "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",+ "license": "MIT",+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/tmp-promise": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/tmp-promise/-/tmp-promise-3.0.3.tgz",+ "integrity": "sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==",+ "license": "MIT",+ "dependencies": {+ "tmp": "^0.2.0"+ }+ },+ "node_modules/truncate-utf8-bytes": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz",+ "integrity": "sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==",+ "license": "WTFPL",+ "dependencies": {+ "utf8-byte-length": "^1.0.1"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/type-fest": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",+ "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",+ "license": "(MIT OR CC0-1.0)",+ "optional": true,+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/undici": {+ "version": "6.28.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz",+ "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.17"+ }+ },+ "node_modules/undici-types": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",+ "license": "MIT"+ },+ "node_modules/universalify": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",+ "license": "MIT",+ "engines": {+ "node": ">= 10.0.0"+ }+ },+ "node_modules/unzipper": {+ "version": "0.12.5",+ "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz",+ "integrity": "sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==",+ "license": "MIT",+ "dependencies": {+ "bluebird": "~3.7.2",+ "duplexer2": "~0.1.4",+ "fs-extra": "11.3.1",+ "graceful-fs": "^4.2.2",+ "node-int64": "^0.4.0"+ }+ },+ "node_modules/unzipper/node_modules/fs-extra": {+ "version": "11.3.1",+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz",+ "integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==",+ "license": "MIT",+ "dependencies": {+ "graceful-fs": "^4.2.0",+ "jsonfile": "^6.0.1",+ "universalify": "^2.0.0"+ },+ "engines": {+ "node": ">=14.14"+ }+ },+ "node_modules/utf8-byte-length": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/utf8-byte-length/-/utf8-byte-length-1.0.5.tgz",+ "integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",+ "license": "(WTFPL OR MIT)"+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/webcrypto-core": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz",+ "integrity": "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.7.0",+ "@peculiar/json-schema": "^1.1.12",+ "@peculiar/utils": "^2.0.2",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/which": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",+ "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^3.1.1"+ },+ "bin": {+ "node-which": "bin/which.js"+ },+ "engines": {+ "node": "^18.17.0 || >=20.5.0"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/xmlbuilder": {+ "version": "15.1.1",+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",+ "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",+ "license": "MIT",+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yallist": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",+ "license": "ISC"+ },+ "node_modules/yargs": {+ "version": "17.7.3",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",+ "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^8.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "require-directory": "^2.1.1",+ "string-width": "^4.2.3",+ "y18n": "^5.0.5",+ "yargs-parser": "^21.1.1"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yargs-parser": {+ "version": "21.1.1",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ }+ }+}diff --git a/scripts/release-signing-tool/package.json b/scripts/release-signing-tool/package.jsonnew file mode 100644index 00000000..fbe590e1--- /dev/null+++ b/scripts/release-signing-tool/package.json@@ -0,0 +1,9 @@+{+ "name": "motrix-release-signing-tool",+ "version": "1.0.0",+ "private": true,+ "description": "Pinned electron-builder dependency closure for isolated release signing",+ "dependencies": {+ "electron-builder": "26.15.7"+ }+}diff --git a/scripts/server-package-utils.mjs b/scripts/server-package-utils.mjsindex 771f2ab9..4a21734f 100644--- a/scripts/server-package-utils.mjs+++ b/scripts/server-package-utils.mjs@@ -127,10 +127,24 @@ function validateInputList(value, keys, label, withEntry) {sources.push(input.source)if (withEntry) {if (input.type === 'directory') {- input.entry = normalizeRelativePath(- input.entry,- `${label}[${index}].entry`- )+ const entries = Array.isArray(input.entry)+ ? input.entry.map((entry, entryIndex) =>+ normalizeRelativePath(+ entry,+ `${label}[${index}].entry[${entryIndex}]`+ )+ )+ : [normalizeRelativePath(input.entry, `${label}[${index}].entry`)]+ if (+ entries.length === 0 ||+ !isDeepStrictEqual(entries, [...new Set(entries)].sort())+ ) {+ throw new Error(+ `${label}[${index}].entry must contain unique paths in sorted order`+ )+ }+ if (Array.isArray(input.entry)) input.entry = entries+ else input.entry = entries[0]} else if (input.entry !== null) {throw new Error(`${label}[${index}].entry must be null for a file`)}diff --git a/scripts/server-runtime-dependencies.json b/scripts/server-runtime-dependencies.jsonindex d5f449db..0bc8d8b5 100644--- a/scripts/server-runtime-dependencies.json+++ b/scripts/server-runtime-dependencies.json@@ -19,6 +19,7 @@"bittorrent-peerid","chokidar","fastify",+ "i18next","libsodium-wrappers","parse-torrent","pino",@@ -50,7 +51,7 @@"source": "dist/server","destination": "dist/server","type": "directory",- "entry": "index.mjs",+ "entry": ["index.mjs", "motrix-admin.mjs"],"scanExternals": true}],diff --git a/scripts/smoke-server-image.mjs b/scripts/smoke-server-image.mjsindex 2f2eeb36..ab36e2f3 100644--- a/scripts/smoke-server-image.mjs+++ b/scripts/smoke-server-image.mjs@@ -445,6 +445,18 @@ async function startServerContainer(options) {async function assertRuntimeContract(name, url, token, identity, timeoutMs) {await assertOperatorAuth(url, token)+ const operatorCliOutput = await docker([+ 'exec',+ name,+ 'motrix-admin',+ 'pairing',+ 'pending',+ '--json',+ ])+ const operatorCli = JSON.parse(operatorCliOutput)+ if (operatorCli.ok !== true || !Array.isArray(operatorCli.requests)) {+ throw new Error(`unexpected motrix-admin response: ${operatorCliOutput}`)+ }const diagnostics = await requestJson(`${url}/api/diagnostics`, {headers: { authorization: `Bearer ${token}` },})diff --git a/scripts/smoke-server-package.mjs b/scripts/smoke-server-package.mjsindex 30b83fac..b8b23912 100644--- a/scripts/smoke-server-package.mjs+++ b/scripts/smoke-server-package.mjs@@ -89,6 +89,41 @@ async function assertDirectRootsResolve(stageRoot, dependencies) {)}+async function assertOperatorCli(stageRoot, timeoutMs) {+ const executable = path.join(stageRoot, 'dist/server/motrix-admin.mjs')+ await withTimeout(+ new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [executable, '--help'], {+ cwd: stageRoot,+ env: { ...process.env, NODE_PATH: undefined },+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ let stdout = ''+ let stderr = ''+ child.stdout.on('data', (chunk) => {+ stdout = `${stdout}${chunk}`.slice(-MAX_LOG_BYTES)+ })+ child.stderr.on('data', (chunk) => {+ stderr = `${stderr}${chunk}`.slice(-MAX_LOG_BYTES)+ })+ child.once('error', reject)+ child.once('exit', (code) => {+ if (code === 0 && stdout.includes('motrix-admin pairing pending')) {+ resolve()+ return+ }+ reject(+ new Error(+ `operator CLI help failed: code=${code} stderr=${stderr.trim()}`+ )+ )+ })+ }),+ timeoutMs,+ 'operator CLI help'+ )+}+function assertSqlite(stageRoot, scratchRoot) {const require = createRequire(path.join(stageRoot, 'package.json'))const Database = require('better-sqlite3')@@ -318,6 +353,7 @@ export async function smokeServerPackage(options) {await assertDirectRootsResolve(stageRoot, dependencies)assertSqlite(stageRoot, scratchRoot)await assertQuickJsWorker(stageRoot, timeoutMs)+ await assertOperatorCli(stageRoot, timeoutMs)const port = await availablePort()const systemRoot = path.join(scratchRoot, 'system')@@ -383,6 +419,7 @@ export async function smokeServerPackage(options) {quickJsWorker: true,health: true,operatorAuth: true,+ operatorCli: true,databaseBytes: database.size,shutdown: 'SIGTERM',durationMs: Date.now() - startedAt,diff --git a/scripts/verify-server-package.mjs b/scripts/verify-server-package.mjsindex 7df1412d..b804b717 100644--- a/scripts/verify-server-package.mjs+++ b/scripts/verify-server-package.mjs@@ -287,6 +287,15 @@ export async function verifyServerPackage(options) {}return `${actualRoots.length} runtime roots match the contract`})+ await check('operator-cli', async () => {+ const bundle = await lstat(+ path.join(stageRoot, 'dist/server/motrix-admin.mjs')+ )+ if (!bundle.isFile()) {+ throw new Error('dist/server/motrix-admin.mjs is not a regular file')+ }+ return 'operator CLI bundle is present'+ })await check('artifact-tree', async () => {tree = await walkStage(stageRoot)if (tree.symlinks.length > 0) {diff --git a/src/core/plugin/host/plugin-host.test.ts b/src/core/plugin/host/plugin-host.test.tsindex e22b47af..f8840953 100644--- a/src/core/plugin/host/plugin-host.test.ts+++ b/src/core/plugin/host/plugin-host.test.ts@@ -86,6 +86,22 @@ parentPort.on('message', (msg) => {return file}+function writeStubWorkerNeverReady(dir: string): string {+ const file = path.join(dir, 'StubWorkerNeverReady.cjs')+ writeFileSync(+ file,+ `+const { parentPort } = require('worker_threads')+parentPort.on('message', (msg) => {+ if (msg.type === 'event' && msg.event === 'deactivate') {+ parentPort.postMessage({ type: 'event', event: 'deactivateComplete', ok: true })+ }+})+`+ )+ return file+}+function plantPlugin(parent: string,id: string,@@ -185,6 +201,27 @@ describe('PluginHost', () => {await host.shutdown()})+ it('uses an injected bundle reader for a community plugin', async () => {+ const readBundleSource = vi.fn(async () => 'export default {}')+ const host = new PluginHost({+ registry,+ stateStore,+ capabilityHost: capHost,+ workerScriptPath: workerPath,+ appVersion: '2.5.0',+ runtime: 'server',+ hostLanguage: 'en-US',+ readBundleSource,+ })++ await host.activate('alice.demo')++ expect(readBundleSource).toHaveBeenCalledWith(+ path.join(root, 'plugins', 'alice.demo', 'dist', 'plugin.js')+ )+ await host.shutdown()+ })+it('throws PluginActivationCapExceeded when over soft cap', async () => {const host = new PluginHost({registry,@@ -280,6 +317,88 @@ describe('PluginHost', () => {await host.shutdown()})+ it('cancels activation blocked on bundle read without a late worker', async () => {+ let markReadStarted!: () => void+ const readStarted = new Promise<void>((resolve) => {+ markReadStarted = resolve+ })+ let releaseRead!: (source: string) => void+ const blockedRead = new Promise<string>((resolve) => {+ releaseRead = resolve+ })+ const host = new PluginHost({+ registry,+ stateStore,+ capabilityHost: capHost,+ workerScriptPath: workerPath,+ appVersion: '2.5.0',+ runtime: 'server',+ hostLanguage: 'en-US',+ readBundleSource: () => {+ markReadStarted()+ return blockedRead+ },+ })++ const activation = host.activate('alice.demo')+ const activationRejected = expect(activation).rejects.toThrow(+ /plugin\.activation\.superseded/+ )+ await readStarted+ await host.deactivate('alice.demo')+ await activationRejected++ expect(host.isQuiescent('alice.demo')).toBe(true)+ expect(host.bridgeFor('alice.demo')).toBeUndefined()+ expect(host.workerFor('alice.demo')).toBeUndefined()++ // Completing the underlying filesystem operation after deactivate() has+ // returned must not resume the superseded activation continuation.+ releaseRead('export default {}')+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(host.isQuiescent('alice.demo')).toBe(true)+ expect(host.workerFor('alice.demo')).toBeUndefined()+ await host.shutdown()+ })++ it('deactivate terminates a not-ready worker and rejects replacement activation', async () => {+ const neverReadyWorker = writeStubWorkerNeverReady(root)+ const host = new PluginHost({+ registry,+ stateStore,+ capabilityHost: capHost,+ workerScriptPath: neverReadyWorker,+ activationTimeoutMs: 10_000,+ deactivateBudgetMs: 200,+ appVersion: '2.5.0',+ runtime: 'server',+ hostLanguage: 'en-US',+ })++ const activation = host.activate('alice.demo')+ const activationRejected = expect(activation).rejects.toThrow(+ /plugin\.activation\.superseded/+ )+ await vi.waitFor(() => expect(host.workerFor('alice.demo')).toBeDefined())+ const oldWorker = host.workerFor('alice.demo')!+ const terminate = vi.spyOn(oldWorker, 'terminate')++ const deactivation = host.deactivate('alice.demo')+ await expect(host.activate('alice.demo')).rejects.toThrow(+ /plugin\.activation\.superseded/+ )+ await deactivation+ await activationRejected++ expect(terminate).toHaveBeenCalledOnce()+ expect(host.isQuiescent('alice.demo')).toBe(true)+ expect(host.isActive('alice.demo')).toBe(false)+ expect(host.allActive()).toEqual([])+ expect(host.bridgeFor('alice.demo')).toBeUndefined()+ expect(host.workerFor('alice.demo')).toBeUndefined()+ await host.shutdown()+ })+it('invokeCommand rejects with not_available when plugin is inactive', async () => {const host = new PluginHost({registry,@@ -456,6 +575,70 @@ describe('PluginHost.deactivate — lifecycle wiring', () => {expect(host.isActive('alice.demo')).toBe(false)})+ it('falls back to direct worker termination when bridge disposal fails', async () => {+ const workerPath = writeStubWorker(root)+ const host = new PluginHost({+ registry,+ stateStore,+ capabilityHost: capHost,+ workerScriptPath: workerPath,+ appVersion: '2.5.0',+ runtime: 'server',+ hostLanguage: 'en-US',+ })+ await host.activate('alice.demo')+ const bridge = host.bridgeFor('alice.demo')!+ const worker = bridge.getWorker()+ const realTerminate = worker.terminate.bind(worker)+ const dispose = vi.spyOn(bridge, 'dispose')+ const terminate = vi+ .spyOn(worker, 'terminate')+ .mockRejectedValueOnce(new Error('dispose terminate failed'))+ .mockImplementation(realTerminate)++ await host.deactivate('alice.demo')++ expect(dispose).toHaveBeenCalledOnce()+ expect(terminate).toHaveBeenCalledTimes(2)+ expect(host.isQuiescent('alice.demo')).toBe(true)+ expect(stateStore.get('alice.demo')?.status).toBe('inactive')+ })++ it('does not cache a rejected teardown and retries the terminate backstop', async () => {+ const workerPath = writeStubWorker(root)+ const host = new PluginHost({+ registry,+ stateStore,+ capabilityHost: capHost,+ workerScriptPath: workerPath,+ appVersion: '2.5.0',+ runtime: 'server',+ hostLanguage: 'en-US',+ })+ await host.activate('alice.demo')+ const bridge = host.bridgeFor('alice.demo')!+ const worker = bridge.getWorker()+ const realTerminate = worker.terminate.bind(worker)+ const dispose = vi.spyOn(bridge, 'dispose')+ const terminate = vi+ .spyOn(worker, 'terminate')+ .mockRejectedValueOnce(new Error('dispose terminate failed'))+ .mockRejectedValueOnce(new Error('terminate failed'))+ .mockImplementation(realTerminate)++ await expect(host.deactivate('alice.demo')).rejects.toThrow(+ 'terminate failed'+ )+ expect(host.isQuiescent('alice.demo')).toBe(false)++ await host.deactivate('alice.demo')++ expect(dispose).toHaveBeenCalledOnce()+ expect(terminate).toHaveBeenCalledTimes(3)+ expect(host.isQuiescent('alice.demo')).toBe(true)+ expect(stateStore.get('alice.demo')?.status).toBe('inactive')+ })+it('deactivate completes (with logged warning) when worker reports error', async () => {const workerPath = writeStubWorkerDeactivateError(root)const warnMessages: string[] = []diff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.tsindex b6910566..e159aa6a 100644--- a/src/core/plugin/host/plugin-host.ts+++ b/src/core/plugin/host/plugin-host.ts@@ -73,6 +73,8 @@ export interface PluginHostOptions {* Absent → no ffmpeg gate (all plugins pass regardless of manifest range).*/ffmpegDetect?: () => Promise<FfmpegDetection>+ /** Injectable bundle-source reader; defaults to `readFile(path, 'utf8')`. */+ readBundleSource?: (bundlePath: string) => Promise<string>/*** Injectable for tests; defaults to the pinned build-time keys. Mirrors* `PluginRegistryOptions.signingPubkeys` — the host re-verifies@@ -87,6 +89,10 @@ interface Active {manifest: PluginManifestlastActivityAt: numberregistrations: Array<{ kind: 'hook' | 'command'; key: string }>+ /** Shared teardown promise so fatal/deactivate races cannot dispose twice. */+ teardown?: Promise<void>+ /** A failed dispose() must retry the worker termination backstop directly. */+ disposeNeedsBackstop?: boolean/*** Snapshot taken at activation time. `true` when the plugin does not* declare ffmpeg at all (vacuously satisfied), or when detection met the@@ -97,6 +103,14 @@ interface Active {ffmpegAdvertised: boolean}+interface ActivationAttempt {+ epoch: number+ cancelled: boolean+ cancellation: Promise<never>+ cancel(): void+ promise: Promise<void>+}+/*** Default soft cap on concurrently-active plugins, shared by PluginHost and* ActivationDispatcher so their independent defaults can't silently diverge.@@ -105,15 +119,21 @@ export const DEFAULT_MAX_ACTIVE_PLUGINS = 32export class PluginHost {private readonly active = new Map<string, Active>()- // In-flight activations keyed by pluginId, so concurrent activate() calls- // for the same plugin share one promise instead of each spawning a worker.- private readonly activating = new Map<string, Promise<void>>()+ // Per-plugin activation/deactivation state. The epoch invalidates every+ // await continuation from an older activation, while `quiescing` is a+ // synchronous tombstone that prevents a replacement worker from starting+ // until teardown has fully completed.+ private readonly activating = new Map<string, ActivationAttempt>()+ private readonly deactivating = new Map<string, Promise<void>>()+ private readonly activationEpochs = new Map<string, number>()+ private readonly quiescing = new Set<string>()private readonly maxActivePlugins: numberprivate readonly idleDisposeMs: numberprivate readonly activationTimeoutMs: numberprivate readonly deactivateBudgetMs: numberprivate idleTimer?: NodeJS.Timeoutprivate unsubscribeLocale: () => void = () => {}+ private shuttingDown = falseconstructor(private readonly opts: PluginHostOptions) {this.maxActivePlugins = opts.maxActivePlugins ?? DEFAULT_MAX_ACTIVE_PLUGINS@@ -131,6 +151,7 @@ export class PluginHost {private broadcastLocaleChange(_lang: string): void {for (const [pluginId, active] of this.active) {+ if (this.quiescing.has(pluginId)) continuetry {const snap = this.opts.capabilityHost.i18nSnapshot(pluginId)active.bridge.postLocaleChange(@@ -155,7 +176,21 @@ export class PluginHost {}isActive(pluginId: string): boolean {- return this.active.has(pluginId)+ return this.active.has(pluginId) && !this.quiescing.has(pluginId)+ }++ /**+ * True only when no worker, bridge, activation continuation, or teardown+ * remains for the plugin. Installer commit/uninstall use this stronger+ * postcondition instead of treating an early `active.delete()` as stopped.+ */+ isQuiescent(pluginId: string): boolean {+ return (+ !this.active.has(pluginId) &&+ !this.activating.has(pluginId) &&+ !this.deactivating.has(pluginId) &&+ !this.quiescing.has(pluginId)+ )}/**@@ -164,11 +199,11 @@ export class PluginHost {* is not active.*/getFfmpegAdvertised(pluginId: string): boolean | undefined {- return this.active.get(pluginId)?.ffmpegAdvertised+ return this.activeForUse(pluginId)?.ffmpegAdvertised}activeIds(): string[] {- return [...this.active.keys()]+ return [...this.active.keys()].filter((id) => !this.quiescing.has(id))}/**@@ -185,7 +220,7 @@ export class PluginHost {commandId: string,args: unknown): Promise<unknown> {- const a = this.active.get(pluginId)+ const a = this.activeForUse(pluginId)if (!a) {return Promise.reject(new AppError(@@ -199,6 +234,20 @@ export class PluginHost {}async activate(pluginId: string): Promise<void> {+ if (this.shuttingDown) {+ throw new AppError(+ ErrorCode.PluginRuntimeFault,+ 'plugin.activation.host_shutting_down'+ )+ }+ // Check the tombstone before `active`: the old worker remains owned by+ // `active` until dispose() completes, but must not be considered a valid+ // idempotent activation while teardown is underway.+ if (this.quiescing.has(pluginId)) {+ throw this.activationSupersededError(pluginId)+ }+ const inFlight = this.activating.get(pluginId)+ if (inFlight) return inFlight.promiseconst existing = this.active.get(pluginId)if (existing) {existing.lastActivityAt = Date.now()@@ -209,16 +258,46 @@ export class PluginHost {// resolution), so two overlapping calls would otherwise both pass the// guard above, both spawn a worker, and the second active.set() would// orphan the first bridge. Share one in-flight promise keyed by pluginId.- const inFlight = this.activating.get(pluginId)- if (inFlight) return inFlight- const promise = this.doActivate(pluginId).finally(() => {- this.activating.delete(pluginId)+ const epoch = (this.activationEpochs.get(pluginId) ?? 0) + 1+ this.activationEpochs.set(pluginId, epoch)+ let rejectCancellation!: (error: Error) => void+ const cancellation = new Promise<never>((_resolve, reject) => {+ rejectCancellation = reject})- this.activating.set(pluginId, promise)+ // The cancellation promise is raced at every async boundary. Keep a+ // handler attached even between those boundaries to avoid an unhandled+ // rejection when deactivate() wins immediately.+ void cancellation.catch(() => undefined)+ const attempt: ActivationAttempt = {+ epoch,+ cancelled: false,+ cancellation,+ cancel: () => {+ if (attempt.cancelled) return+ attempt.cancelled = true+ rejectCancellation(this.activationSupersededError(pluginId))+ },+ promise: Promise.resolve(),+ }+ // Start in a microtask so the attempt and its real promise are both+ // published before registry/capability test doubles can re-enter us.+ const promise = Promise.resolve()+ .then(() => this.doActivate(pluginId, attempt))+ .finally(() => {+ if (this.activating.get(pluginId) === attempt) {+ this.activating.delete(pluginId)+ }+ })+ attempt.promise = promise+ this.activating.set(pluginId, attempt)return promise}- private async doActivate(pluginId: string): Promise<void> {+ private async doActivate(+ pluginId: string,+ attempt: ActivationAttempt+ ): Promise<void> {+ this.assertActivationCurrent(pluginId, attempt)const indexed = this.opts.registry.get(pluginId)if (!indexed) {throw new AppError(@@ -245,7 +324,11 @@ export class PluginHost {let ffmpegDetection: FfmpegDetection = { available: false }if (needsFfmpeg && this.opts.ffmpegDetect) {- ffmpegDetection = await this.opts.ffmpegDetect()+ ffmpegDetection = await this.awaitActivation(+ pluginId,+ attempt,+ this.opts.ffmpegDetect()+ )}const ffmpegSatisfied =@@ -294,8 +377,10 @@ export class PluginHost {// the tree would otherwise get unverified code run with builtin// privilege. Re-verify on every activation; nothing here is cached// across the signature check performed at scan time.- const moextBytes = await readFile(- path.join(indexed.rootDir, 'bundle.moext')+ const moextBytes = await this.awaitActivation(+ pluginId,+ attempt,+ readFile(path.join(indexed.rootDir, 'bundle.moext')))if (!verifyBuiltinSignature(@@ -314,7 +399,11 @@ export class PluginHost {'plugin.update.builtin_bad_signature')}- const entryBytes = await readMoextEntry(moextBytes, indexed.manifest.main)+ const entryBytes = await this.awaitActivation(+ pluginId,+ attempt,+ readMoextEntry(moextBytes, indexed.manifest.main)+ )if (!entryBytes) {this.opts.stateStore.recordError(pluginId,@@ -328,7 +417,13 @@ export class PluginHost {}bundleSource = entryBytes.toString('utf8')} else {- bundleSource = await readFile(bundlePath, 'utf8')+ const readBundleSource =+ this.opts.readBundleSource ?? ((file) => readFile(file, 'utf8'))+ bundleSource = await this.awaitActivation(+ pluginId,+ attempt,+ readBundleSource(bundlePath)+ )}let resolveReady: () => void@@ -339,10 +434,16 @@ export class PluginHost {})const effectivePermissions = this.opts.pluginGrants- ? await this.opts.pluginGrants.effectivePermissionsFor(pluginId)+ ? await this.awaitActivation(+ pluginId,+ attempt,+ this.opts.pluginGrants.effectivePermissionsFor(pluginId)+ ): undefined- const bridge = new CapabilityBridge(+ this.assertActivationCurrent(pluginId, attempt)+ let bridge: CapabilityBridge | undefined+ bridge = new CapabilityBridge({pluginId,manifest: indexed.manifest,@@ -357,21 +458,43 @@ export class PluginHost {},{onReady: () => {+ if (+ !bridge ||+ !this.isActivationCurrent(pluginId, attempt) ||+ this.active.get(pluginId)?.bridge !== bridge+ ) {+ return+ }this.opts.stateStore.markActivated(pluginId, Date.now())this.opts.registry.refreshState(pluginId)resolveReady()},onRegister: (kind, key) => {- this.active.get(pluginId)?.registrations.push({ kind, key })+ const current = this.active.get(pluginId)+ if (+ bridge &&+ current?.bridge === bridge &&+ !this.quiescing.has(pluginId)+ ) {+ current.registrations.push({ kind, key })+ }},onFatal: (code, message) => {+ if (+ !bridge ||+ this.active.get(pluginId)?.bridge !== bridge ||+ this.quiescing.has(pluginId)+ ) {+ return+ }this.opts.stateStore.recordError(pluginId, `${code}: ${message}`)this.opts.registry.refreshState(pluginId)- void this.deactivate(pluginId)rejectReady(new AppError(ErrorCode.PluginRuntimeFault, message))+ void this.deactivate(pluginId).catch(() => undefined)},})+ this.assertActivationCurrent(pluginId, attempt)this.active.set(pluginId, {bridge,manifest: indexed.manifest,@@ -395,9 +518,18 @@ export class PluginHost {})try {- await Promise.race([ready, timeoutP])+ await this.awaitActivation(+ pluginId,+ attempt,+ Promise.race([ready, timeoutP])+ )} catch (e) {- void this.deactivate(pluginId)+ const current = this.active.get(pluginId)+ if (bridge && current?.bridge === bridge) {+ await this.teardownActive(pluginId, current)+ } else if (bridge) {+ await bridge.dispose()+ }throw e} finally {if (timeoutHandle) clearTimeout(timeoutHandle)@@ -405,13 +537,63 @@ export class PluginHost {}async deactivate(pluginId: string): Promise<void> {- const a = this.active.get(pluginId)- if (!a) return- this.active.delete(pluginId)+ const existing = this.deactivating.get(pluginId)+ if (existing) return existing++ // Establish the tombstone and supersede the activation synchronously,+ // before yielding to any continuation that could publish a bridge.+ this.quiescing.add(pluginId)+ this.activationEpochs.set(+ pluginId,+ (this.activationEpochs.get(pluginId) ?? 0) + 1+ )+ const attempt = this.activating.get(pluginId)+ attempt?.cancel()++ const promise = Promise.resolve()+ .then(() => this.doDeactivate(pluginId, attempt))+ .finally(() => {+ if (this.deactivating.get(pluginId) === promise) {+ this.deactivating.delete(pluginId)+ this.quiescing.delete(pluginId)+ }+ })+ this.deactivating.set(pluginId, promise)+ return promise+ }++ private async doDeactivate(+ pluginId: string,+ attempt: ActivationAttempt | undefined+ ): Promise<void> {+ // The attempt rejects when cancellation wins. Its catch path owns cleanup+ // for any bridge it managed to create, so wait for that path before+ // checking the stable active entry below.+ await attempt?.promise.catch(() => undefined)+ const active = this.active.get(pluginId)+ if (active) await this.teardownActive(pluginId, active)+ }+ private teardownActive(pluginId: string, active: Active): Promise<void> {+ if (active.teardown) return active.teardown+ let teardown!: Promise<void>+ teardown = this.performTeardown(pluginId, active).catch((error) => {+ // A rejected teardown must not be cached forever. Keep the active entry+ // owned by the host and let a later deactivate/upgrade retry termination.+ if (active.teardown === teardown) active.teardown = undefined+ throw error+ })+ active.teardown = teardown+ return teardown+ }++ private async performTeardown(+ pluginId: string,+ active: Active+ ): Promise<void> {// 1. Run worker-side deactivate handlers (budget enforced by bridge).try {- await a.bridge.runDeactivate(this.deactivateBudgetMs)+ await active.bridge.runDeactivate(this.deactivateBudgetMs)} catch (e) {this.opts.capabilityHost.createLog(pluginId)@@ -436,12 +618,91 @@ export class PluginHost {}}- // 3. Tear down bridge and mark inactive.- await a.bridge.dispose()+ // 3. Tear down bridge and mark inactive. CapabilityBridge marks itself+ // disposed before awaiting Worker.terminate(), so a rejected dispose()+ // cannot itself be retried; terminate the worker directly as a backstop.+ await this.disposeActiveBridge(pluginId, active)+ if (this.active.get(pluginId) === active) {+ this.active.delete(pluginId)+ }this.opts.stateStore.setStatus(pluginId, 'inactive')this.opts.registry.refreshState(pluginId)}+ private async disposeActiveBridge(+ pluginId: string,+ active: Active+ ): Promise<void> {+ if (!active.disposeNeedsBackstop) {+ try {+ await active.bridge.dispose()+ return+ } catch (error) {+ active.disposeNeedsBackstop = true+ this.opts.capabilityHost+ .createLog(pluginId)+ .warn('worker bridge dispose failed; terminating worker directly', {+ error: (error as Error).message,+ code: (error as Error & { code?: string }).code,+ })+ }+ }++ try {+ await active.bridge.getWorker().terminate()+ active.disposeNeedsBackstop = false+ } catch (error) {+ this.opts.capabilityHost+ .createLog(pluginId)+ .warn('worker terminate backstop failed', {+ error: (error as Error).message,+ code: (error as Error & { code?: string }).code,+ })+ throw error+ }+ }++ private async awaitActivation<T>(+ pluginId: string,+ attempt: ActivationAttempt,+ operation: PromiseLike<T>+ ): Promise<T> {+ const value = await Promise.race([+ Promise.resolve(operation),+ attempt.cancellation,+ ])+ this.assertActivationCurrent(pluginId, attempt)+ return value+ }++ private isActivationCurrent(+ pluginId: string,+ attempt: ActivationAttempt+ ): boolean {+ return (+ !attempt.cancelled &&+ !this.quiescing.has(pluginId) &&+ this.activationEpochs.get(pluginId) === attempt.epoch &&+ this.activating.get(pluginId) === attempt+ )+ }++ private assertActivationCurrent(+ pluginId: string,+ attempt: ActivationAttempt+ ): void {+ if (!this.isActivationCurrent(pluginId, attempt)) {+ throw this.activationSupersededError(pluginId)+ }+ }++ private activationSupersededError(pluginId: string): AppError {+ return new AppError(+ ErrorCode.PluginRuntimeFault,+ `plugin.activation.superseded: ${pluginId}`+ )+ }+/*** Plan C — list every currently active plugin with the descriptors the* HookOrchestrator needs (manifest for eligibility/role, bridge for hook@@ -450,6 +711,7 @@ export class PluginHost {allActive(): ActivePluginInfo[] {const out: ActivePluginInfo[] = []for (const [id, a] of this.active.entries()) {+ if (this.quiescing.has(id)) continueout.push({id,manifest: a.manifest,@@ -467,22 +729,24 @@ export class PluginHost {*/activeMeta(): ActiveMeta[] {const now = Date.now()- return [...this.active.entries()].map(([id, a]) => ({- id,- lastActivityAt: a.lastActivityAt,- idleMs: now - a.lastActivityAt,- evictionTier: deriveEvictionTier(a.manifest),- }))+ return [...this.active.entries()]+ .filter(([id]) => !this.quiescing.has(id))+ .map(([id, a]) => ({+ id,+ lastActivityAt: a.lastActivityAt,+ idleMs: now - a.lastActivityAt,+ evictionTier: deriveEvictionTier(a.manifest),+ }))}/** Plan C — bridge accessor used by HookOrchestrator and tests. */bridgeFor(pluginId: string): CapabilityBridge | undefined {- return this.active.get(pluginId)?.bridge+ return this.activeForUse(pluginId)?.bridge}/** Plan C — worker accessor used by `newHookAbort` for the terminate path. */workerFor(pluginId: string): Worker | undefined {- return this.active.get(pluginId)?.bridge.getWorker()+ return this.activeForUse(pluginId)?.bridge.getWorker()}/**@@ -505,7 +769,7 @@ export class PluginHost {metadataSnapshot?: Record<string, unknown>}): Promise<void> {- const a = this.active.get(pluginId)+ const a = this.activeForUse(pluginId)if (!a) {throw new AppError(ErrorCode.PluginRuntimeFault,@@ -532,7 +796,7 @@ export class PluginHost {async disable(pluginId: string, reason: string): Promise<void> {this.opts.stateStore.setEnabled(pluginId, false)this.opts.stateStore.recordError(pluginId, reason)- if (this.active.has(pluginId)) {+ if (!this.isQuiescent(pluginId)) {await this.deactivate(pluginId)}this.opts.stateStore.setStatus(pluginId, 'disabled')@@ -540,14 +804,21 @@ export class PluginHost {}async shutdown(): Promise<void> {+ this.shuttingDown = truethis.unsubscribeLocale()if (this.idleTimer) clearInterval(this.idleTimer)- await Promise.all([...this.active.keys()].map((id) => this.deactivate(id)))+ const pluginIds = new Set([+ ...this.active.keys(),+ ...this.activating.keys(),+ ...this.deactivating.keys(),+ ])+ await Promise.all([...pluginIds].map((id) => this.deactivate(id)))}private sweepIdle(): void {const now = Date.now()for (const [id, a] of this.active.entries()) {+ if (this.quiescing.has(id)) continueif (now - a.lastActivityAt >= this.idleDisposeMs) {void this.deactivate(id)}@@ -566,6 +837,11 @@ export class PluginHost {get idleDisposeMsForTest(): number {return this.idleDisposeMs}++ private activeForUse(pluginId: string): Active | undefined {+ if (this.quiescing.has(pluginId)) return undefined+ return this.active.get(pluginId)+ }}export function parsePluginIdleDisposeMs(diff --git a/src/core/plugin/install/e2e-install.test.ts b/src/core/plugin/install/e2e-install.test.tsindex 89473521..f6f8cd85 100644--- a/src/core/plugin/install/e2e-install.test.ts+++ b/src/core/plugin/install/e2e-install.test.ts@@ -11,12 +11,13 @@ import {readdir,readFile,rm,+ stat,writeFile,} from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'import type { RegistryPluginDTO } from '@shared/schemas/registry'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { CapabilityHost } from '../capabilities/interface'import { PluginHost } from '../host/plugin-host'import { PluginRegistry } from '../plugin-registry'@@ -25,6 +26,7 @@ import { PluginStateStore } from '../state/plugin-state-store'import {PluginInstaller,type PluginInstallerOptions,+ type PluginRuntimeHostLike,} from './plugin-installer'import { buildRegistryExpectation } from './registry-expectation'@@ -364,17 +366,13 @@ describe('PluginInstaller e2e', () => {})})- it('upgrade fail rolls back: backup restored when staging rename fails', async () => {+ it('keeps only the protected archive pending and re-reads it at commit', async () => {const v1 = await writeMoext(path.join(inputDir, 'v1.moext'), manifestJSON())const { stagingId: id1 } = await installer.stage(v1, {type: 'github',spec: 'example/test',})await installer.commit(id1, {})- const v1Bytes = await readFile(- path.join(pluginsDir, 'example.test', 'dist/plugin.js'),- 'utf8'- )const v2 = await writeMoext(path.join(inputDir, 'v2.moext'),@@ -387,14 +385,159 @@ describe('PluginInstaller e2e', () => {})const stagingPath = path.join(pluginsDir, '_staging', id2)- await rm(stagingPath, { recursive: true, force: true })+ const archivePath = path.join(stagingPath, 'archive.moext')+ expect((await readFile(archivePath)).equals(await readFile(v2))).toBe(true)+ expect(existsSync(path.join(stagingPath, 'tree'))).toBe(false)+ if (process.platform !== 'win32') {+ expect((await stat(archivePath)).mode & 0o777).toBe(0o600)+ }- await expect(installer.commit(id2, {})).rejects.toThrow()- const restored = await readFile(+ await installer.commit(id2, {})+ const committed = await readFile(path.join(pluginsDir, 'example.test', 'dist/plugin.js'),'utf8')- expect(restored).toBe(v1Bytes)+ expect(committed).toBe('console.log(2);')+ expect(existsSync(stagingPath)).toBe(false)+ })++ it('rejects a staged archive changed after consent and lets cancel clean it', async () => {+ const moext = await writeMoext(+ path.join(inputDir, 'tampered-archive.moext'),+ manifestJSON()+ )+ const staged = await installer.stage(moext, {+ type: 'github',+ spec: 'example/test',+ })+ const stagingPath = path.join(pluginsDir, '_staging', staged.stagingId)+ const archivePath = path.join(stagingPath, 'archive.moext')+ await writeFile(+ archivePath,+ Buffer.concat([await readFile(archivePath), Buffer.from([0])])+ )++ await expect(installer.commit(staged.stagingId, {})).rejects.toMatchObject({+ message: 'plugin.install.sha256_mismatch',+ })+ expect(existsSync(path.join(pluginsDir, 'example.test'))).toBe(false)++ await installer.cancel(staged.stagingId)+ expect(existsSync(stagingPath)).toBe(false)+ })++ it('rejects a stale consent when the install changes before commit', async () => {+ const v1 = await writeMoext(path.join(inputDir, 'v1.moext'), manifestJSON())+ const first = await installer.stage(v1, {+ type: 'github',+ spec: 'example/test',+ })+ await installer.commit(first.stagingId, {})++ const v2 = await writeMoext(+ path.join(inputDir, 'v2.moext'),+ manifestJSON({ permissions: ['http'], version: '1.1.0' }),+ Buffer.from('console.log(2);', 'utf8')+ )+ const staged = await installer.stage(v2, {+ type: 'github',+ spec: 'example/test',+ })+ const recordPath = path.join(pluginsDir, 'example.test', '_install.json')+ const record = JSON.parse(await readFile(recordPath, 'utf8'))+ record.grants = { storage: 'granted' }+ await writeFile(recordPath, `${JSON.stringify(record, null, 2)}\n`)++ await expect(installer.commit(staged.stagingId, {})).rejects.toMatchObject({+ message: 'plugin.install.changed_since_staging',+ })+ expect(+ await readFile(+ path.join(pluginsDir, 'example.test', 'dist/plugin.js'),+ 'utf8'+ )+ ).toBe('console.log(1);')+ })++ it('serializes concurrent commits and rejects the stale transaction', async () => {+ const v1 = await writeMoext(path.join(inputDir, 'v1.moext'), manifestJSON())+ const first = await installer.stage(v1, {+ type: 'github',+ spec: 'example/test',+ })+ await installer.commit(first.stagingId, {})++ const v2 = await writeMoext(+ path.join(inputDir, 'v2.moext'),+ manifestJSON({ permissions: ['http'], version: '1.1.0' }),+ Buffer.from('console.log(2);', 'utf8')+ )+ const v3 = await writeMoext(+ path.join(inputDir, 'v3.moext'),+ manifestJSON({ permissions: ['storage'], version: '1.2.0' }),+ Buffer.from('console.log(3);', 'utf8')+ )+ const staged2 = await installer.stage(v2, {+ type: 'github',+ spec: 'example/test',+ })+ const staged3 = await installer.stage(v3, {+ type: 'github',+ spec: 'example/test',+ })++ const results = await Promise.allSettled([+ installer.commit(staged2.stagingId, {}),+ installer.commit(staged3.stagingId, {}),+ ])++ expect(results[0]).toMatchObject({ status: 'fulfilled' })+ expect(results[1]).toMatchObject({+ status: 'rejected',+ reason: { message: 'plugin.install.changed_since_staging' },+ })+ expect(+ await readFile(+ path.join(pluginsDir, 'example.test', 'dist/plugin.js'),+ 'utf8'+ )+ ).toBe('console.log(2);')+ })++ it('aborts an upgrade until the runtime is quiescent', async () => {+ const v1 = await writeMoext(path.join(inputDir, 'v1.moext'), manifestJSON())+ const first = await installer.stage(v1, {+ type: 'github',+ spec: 'example/test',+ })+ await installer.commit(first.stagingId, {})++ const v2 = await writeMoext(+ path.join(inputDir, 'v2.moext'),+ manifestJSON({ permissions: ['http'], version: '1.1.0' }),+ Buffer.from('console.log(2);', 'utf8')+ )+ const update = await installer.stage(v2, {+ type: 'github',+ spec: 'example/test',+ })+ const incompleteRuntime: PluginRuntimeHostLike = {+ isQuiescent: () => false,+ deactivate: vi.fn(async () => undefined),+ }++ await expect(+ installer.commit(update.stagingId, {}, incompleteRuntime)+ ).rejects.toMatchObject({+ message: 'plugin.install.runtime_still_active',+ })+ expect(incompleteRuntime.deactivate).toHaveBeenCalledWith('example.test')+ expect(+ await readFile(+ path.join(pluginsDir, 'example.test', 'dist/plugin.js'),+ 'utf8'+ )+ ).toBe('console.log(1);')})it('uninstall purges state + storage + metadata + cookie jar + dir', async () => {@@ -419,6 +562,30 @@ describe('PluginInstaller e2e', () => {expect(existsSync(path.join(pluginsDir, 'example.test'))).toBe(false)})+ it('uninstall rejects traversal before touching state or files', async () => {+ const sentinel = path.join(tmp, 'keep.txt')+ await writeFile(sentinel, 'keep')++ await expect(installer.uninstall('..')).rejects.toMatchObject({+ message: 'plugin.install.invalid_plugin_id',+ })++ expect(existsSync(sentinel)).toBe(true)+ expect(calls.deactivated).toEqual([])+ expect(calls.storageDeleteAll).toEqual([])+ })++ it('keeps uninstall compatible with a valid unmanaged plugin directory', async () => {+ const unmanagedDir = path.join(pluginsDir, 'example.unmanaged')+ await mkdir(unmanagedDir, { recursive: true })+ await writeFile(path.join(unmanagedDir, 'marker'), 'present')++ await installer.uninstall('example.unmanaged')++ expect(existsSync(unmanagedDir)).toBe(false)+ expect(calls.deactivated).toContain('example.unmanaged')+ })+it('zip-slip moext rejected at stage', async () => {const bad = makeZip([{@@ -433,7 +600,7 @@ describe('PluginInstaller e2e', () => {installer.stage(moext, {type: 'local',absPath: moext,- fileHash: 'f'.repeat(64),+ fileHash: createHash('sha256').update(bad).digest('hex'),})).rejects.toMatchObject({ message: 'plugin.install.zip_slip' })expect(existsSync(path.join(pluginsDir, 'example.test'))).toBe(false)@@ -694,15 +861,11 @@ describe('registry source install', () => {}const fakeFetchOf = (bytes: Buffer): typeof fetch =>- (async () => ({- ok: true,- status: 200,- arrayBuffer: async () =>- bytes.buffer.slice(- bytes.byteOffset,- bytes.byteOffset + bytes.byteLength- ),- })) as unknown as typeof fetch+ (async () =>+ new Response(Uint8Array.from(bytes), {+ status: 200,+ headers: { 'content-length': String(bytes.byteLength) },+ })) as unknown as typeof fetchit('installs, records registry source, and silently upgrades', async () => {// v1 — download through the verified fetcher, stage with expectation@@ -761,6 +924,30 @@ describe('registry source install', () => {expect(installedBundle).toBe('exports.x=2')})+ it('rejects a registry package replaced after verified download', async () => {+ const verified = makeZip([+ { name: 'motrix-plugin.json', data: Buffer.from(manifestJSON()) },+ { name: 'dist/plugin.js', data: Buffer.from('exports.x=1') },+ ])+ const replaced = makeZip([+ { name: 'motrix-plugin.json', data: Buffer.from(manifestJSON()) },+ { name: 'dist/plugin.js', data: Buffer.from('exports.x=2') },+ ])+ const entry = registryEntry(verified, '1.0.0')+ const downloaded = path.join(downloadsDir, 'replaced.moext')+ await downloadRegistryMoext(entry, downloaded, fakeFetchOf(verified))+ await writeFile(downloaded, replaced)++ await expect(+ installer.stage(+ downloaded,+ { type: 'registry', pluginId: 'example.test' },+ { expect: buildRegistryExpectation(entry) }+ )+ ).rejects.toMatchObject({ message: 'plugin.install.sha256_mismatch' })+ expect(registry.get('example.test')).toBeUndefined()+ })+it('rejects a package whose manifest disagrees with the registry entry', async () => {const v3 = makeZip([{diff --git a/src/core/plugin/install/github-fetcher.test.ts b/src/core/plugin/install/github-fetcher.test.tsindex 8619d92b..3e29b45c 100644--- a/src/core/plugin/install/github-fetcher.test.ts+++ b/src/core/plugin/install/github-fetcher.test.ts@@ -4,19 +4,10 @@ import path from 'node:path'import { Readable } from 'node:stream'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-// Stub undici.request before importing the SUT. downloadGithubMoext also-// composes a redirect-following dispatcher (undici v8 moved maxRedirections-// out of request() options); the mocked request ignores the dispatcher, so a-// structural stub for Agent/interceptors is enough.+// Stub undici.request before importing the SUT.const mockRequest = vi.fn()vi.mock('undici', () => ({request: (...a: unknown[]) => mockRequest(...a),- Agent: class {- compose() {- return {}- }- },- interceptors: { redirect: () => ({}) },}))const { downloadGithubMoext, parseGithubSpec } = await import(@@ -41,8 +32,12 @@ function jsonResponse(payload: unknown, statusCode = 200) {}}-function streamResponse(bytes: Buffer, statusCode = 200) {- return { statusCode, body: Readable.from(bytes) }+function streamResponse(+ bytes: Buffer,+ statusCode = 200,+ headers: Record<string, string> = {}+) {+ return { statusCode, body: Readable.from(bytes), headers }}describe('parseGithubSpec', () => {@@ -127,6 +122,30 @@ describe('downloadGithubMoext', () => {)})+ it('URL-encodes a tag before putting it in the GitHub API path', async () => {+ mockRequest+ .mockResolvedValueOnce(+ jsonResponse({+ tag_name: 'release/1',+ assets: [+ {+ name: 'widget.moext',+ browser_download_url: 'https://gh/assets/widget.moext',+ },+ ],+ })+ )+ .mockResolvedValueOnce(streamResponse(Buffer.from('bytes')))++ await downloadGithubMoext(+ { owner: 'acme', repo: 'widget', tag: 'release/1' },+ path.join(tmp, 'tagged-slash.moext')+ )+ expect(mockRequest.mock.calls[0]?.[0]).toBe(+ 'https://api.github.com/repos/acme/widget/releases/tags/release%2F1'+ )+ })+it('rejects when GitHub returns non-200', async () => {mockRequest.mockResolvedValueOnce(jsonResponse({ message: 'not found' }, 404)@@ -184,4 +203,89 @@ describe('downloadGithubMoext', () => {message: 'plugin.install.gh_asset_download_failed: 500',})})++ it('rejects an insecure GitHub asset URL before downloading it', async () => {+ mockRequest.mockResolvedValueOnce(+ jsonResponse({+ tag_name: 'v1.0.0',+ assets: [+ {+ name: 'x.moext',+ browser_download_url: 'http://assets.example/x.moext',+ },+ ],+ })+ )++ await expect(+ downloadGithubMoext(+ { owner: 'acme', repo: 'widget', tag: 'v1.0.0' },+ path.join(tmp, 'x.moext')+ )+ ).rejects.toMatchObject({+ message: 'plugin.install.gh_asset_insecure_url',+ })+ expect(mockRequest).toHaveBeenCalledOnce()+ })++ it('rejects a GitHub asset redirect that downgrades HTTPS', async () => {+ mockRequest+ .mockResolvedValueOnce(+ jsonResponse({+ tag_name: 'v1.0.0',+ assets: [+ {+ name: 'x.moext',+ browser_download_url: 'https://assets.example/x.moext',+ },+ ],+ })+ )+ .mockResolvedValueOnce(+ streamResponse(Buffer.alloc(0), 302, {+ location: 'http://cdn.example/x.moext',+ })+ )++ await expect(+ downloadGithubMoext(+ { owner: 'acme', repo: 'widget', tag: 'v1.0.0' },+ path.join(tmp, 'x.moext')+ )+ ).rejects.toMatchObject({+ message: 'plugin.install.redirect_protocol_downgrade',+ })+ expect(mockRequest).toHaveBeenCalledTimes(2)+ })++ it('rejects a GitHub asset after five redirects', async () => {+ mockRequest.mockResolvedValueOnce(+ jsonResponse({+ tag_name: 'v1.0.0',+ assets: [+ {+ name: 'x.moext',+ browser_download_url: 'https://assets.example/x.moext',+ },+ ],+ })+ )+ for (let hop = 0; hop < 6; hop += 1) {+ mockRequest.mockResolvedValueOnce(+ streamResponse(Buffer.alloc(0), 302, {+ location: `https://cdn.example/hop-${hop}.moext`,+ })+ )+ }++ await expect(+ downloadGithubMoext(+ { owner: 'acme', repo: 'widget', tag: 'v1.0.0' },+ path.join(tmp, 'x.moext')+ )+ ).rejects.toMatchObject({+ message: 'plugin.install.too_many_redirects',+ })+ expect(mockRequest).toHaveBeenCalledTimes(7)+ })})diff --git a/src/core/plugin/install/github-fetcher.ts b/src/core/plugin/install/github-fetcher.tsindex 31cfb4d0..3e0d5608 100644--- a/src/core/plugin/install/github-fetcher.ts+++ b/src/core/plugin/install/github-fetcher.ts@@ -7,7 +7,7 @@import { mkdir, rm, writeFile } from 'node:fs/promises'import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'-import { Agent, interceptors, request } from 'undici'+import { request } from 'undici'export interface GhReleaseSpec {owner: string@@ -39,13 +39,67 @@ export interface DownloadResult {const USER_AGENT = 'motrix-plugin-installer'const MAX_MOEXT_BYTES = 5 * 1024 * 1024+const MAX_REDIRECTS = 5+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])++function requireHttpsUrl(rawUrl: string, errorKey: string): URL {+ let url: URL+ try {+ url = new URL(rawUrl)+ } catch {+ throw new AppError(ErrorCode.PluginManifestInvalid, errorKey)+ }+ if (url.protocol !== 'https:') {+ throw new AppError(ErrorCode.PluginManifestInvalid, errorKey)+ }+ return url+}++function responseHeader(+ headers: Record<string, string | string[] | undefined>,+ name: string+): string | undefined {+ const value = headers[name]+ return Array.isArray(value) ? value[0] : value+}++async function cancelBody(body: unknown): Promise<void> {+ const stream = body as {+ destroy?: (error?: Error) => unknown+ cancel?: (reason?: unknown) => Promise<void>+ }+ if (typeof stream.destroy === 'function') {+ stream.destroy()+ } else if (typeof stream.cancel === 'function') {+ await stream.cancel().catch(() => undefined)+ }+}++function resolveHttpsRedirect(location: string, current: URL): URL {+ let next: URL+ try {+ next = new URL(location, current)+ } catch {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.invalid_redirect'+ )+ }+ if (next.protocol !== 'https:') {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.redirect_protocol_downgrade'+ )+ }+ return next+}export async function downloadGithubMoext(spec: GhReleaseSpec,destFile: string): Promise<DownloadResult> {const apiUrl = spec.tag- ? `https://api.github.com/repos/${spec.owner}/${spec.repo}/releases/tags/${spec.tag}`+ ? `https://api.github.com/repos/${spec.owner}/${spec.repo}/releases/tags/${encodeURIComponent(spec.tag)}`: `https://api.github.com/repos/${spec.owner}/${spec.repo}/releases/latest`const meta = await request(apiUrl, {@@ -70,17 +124,39 @@ export async function downloadGithubMoext(}await mkdir(path.dirname(destFile), { recursive: true })- // undici v8 removed the `maxRedirections` request option; redirect handling- // now lives in a composed dispatcher. A GitHub asset's browser_download_url- // 302-redirects to a CDN, so this download MUST follow redirects or it- // returns the redirect status instead of the bytes.- const dispatcher = new Agent().compose(- interceptors.redirect({ maxRedirections: 5 })+ // GitHub release assets redirect to a CDN. Follow manually so an HTTPS+ // download cannot silently downgrade on a later hop.+ let assetUrl = requireHttpsUrl(+ asset.browser_download_url,+ 'plugin.install.gh_asset_insecure_url')- const dl = await request(asset.browser_download_url, {- headers: { 'user-agent': USER_AGENT },- dispatcher,- })+ let dl: Awaited<ReturnType<typeof request>> | undefined+ for (let redirects = 0; ; redirects += 1) {+ const response = await request(assetUrl.href, {+ headers: { 'user-agent': USER_AGENT },+ })+ if (!REDIRECT_STATUSES.has(response.statusCode)) {+ dl = response+ break+ }+ if (redirects >= MAX_REDIRECTS) {+ await cancelBody(response.body)+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.too_many_redirects'+ )+ }+ const location = responseHeader(response.headers, 'location')+ if (!location) {+ await cancelBody(response.body)+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.invalid_redirect'+ )+ }+ await cancelBody(response.body)+ assetUrl = resolveHttpsRedirect(location, assetUrl)+ }if (dl.statusCode !== 200) {throw new AppError(ErrorCode.PluginManifestInvalid,diff --git a/src/core/plugin/install/moext-reader.test.ts b/src/core/plugin/install/moext-reader.test.tsindex a20b5ea9..8669ca37 100644--- a/src/core/plugin/install/moext-reader.test.ts+++ b/src/core/plugin/install/moext-reader.test.ts@@ -1,10 +1,16 @@import { Buffer } from 'node:buffer'import { createHash } from 'node:crypto'-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { existsSync } from 'node:fs'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { extractMoext, readMoextEntry } from './moext-reader'+import {+ extractLoadedMoext,+ extractMoext,+ loadMoext,+ readMoextEntry,+} from './moext-reader'// Minimal zip writer for fixtures. yauzl reads what we write here, so we keep// it on the central directory + local file header format with no compression.@@ -40,7 +46,7 @@ function makeZip(entries: FakeEntry[]): Buffer {const lfh = Buffer.alloc(30)lfh.writeUInt32LE(0x04034b50, 0)lfh.writeUInt16LE(20, 4) // version needed- lfh.writeUInt16LE(0, 6) // flags+ lfh.writeUInt16LE(0x800, 6) // UTF-8 nameslfh.writeUInt16LE(0, 8) // compression: storedlfh.writeUInt16LE(0, 10) // mod timelfh.writeUInt16LE(0, 12) // mod date@@ -58,7 +64,7 @@ function makeZip(entries: FakeEntry[]): Buffer {cdh.writeUInt32LE(0x02014b50, 0)cdh.writeUInt16LE(20, 4) // version made bycdh.writeUInt16LE(20, 6) // version needed- cdh.writeUInt16LE(0, 8)+ cdh.writeUInt16LE(0x800, 8) // UTF-8 namescdh.writeUInt16LE(0, 10)cdh.writeUInt16LE(0, 12)cdh.writeUInt16LE(0, 14)@@ -104,10 +110,6 @@ const VALID_MANIFEST = JSON.stringify({contributes: {},})const TINY_BUNDLE = Buffer.from('export default function(){};', 'utf8')-const EXPECTED_BUNDLE_SHA = createHash('sha256')- .update(TINY_BUNDLE)- .digest('hex')-let tmp: stringbeforeEach(async () => {@@ -124,8 +126,20 @@ async function writeFixture(name: string, buf: Buffer): Promise<string> {return p}+async function expectPathCollision(+ fixtureName: string,+ entries: FakeEntry[]+): Promise<void> {+ const dest = path.join(tmp, `${fixtureName}-dest`)+ const moext = await writeFixture(`${fixtureName}.moext`, makeZip(entries))+ await expect(extractMoext(moext, dest)).rejects.toMatchObject({+ message: 'plugin.install.path_collision',+ })+ expect(existsSync(dest)).toBe(false)+}+describe('moext-reader', () => {- it('valid bundle extracts; manifest readable; bundle sha256 correct', async () => {+ it('valid bundle extracts and preserves bundle digest semantics', async () => {const moextBuf = makeZip([{ name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },{ name: 'dist/plugin.js', data: TINY_BUNDLE },@@ -133,12 +147,161 @@ describe('moext-reader', () => {const moext = await writeFixture('valid.moext', moextBuf)const dest = path.join(tmp, 'unpacked')const result = await extractMoext(moext, dest)- expect(result.bundleSha256).toBe(EXPECTED_BUNDLE_SHA)+ expect(result.bundleSha256).toBe(+ createHash('sha256').update(TINY_BUNDLE).digest('hex')+ )expect(JSON.parse(result.manifestRaw).id).toBe('com.example.test')const onDisk = await readFile(path.join(dest, 'dist/plugin.js'))expect(onDisk.equals(TINY_BUNDLE)).toBe(true)})+ it('retains a complete-archive digest independently of the bundle digest', async () => {+ const baseEntries = [+ { name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ ]+ const first = makeZip([+ ...baseEntries,+ { name: 'dist/alternate.js', data: Buffer.from('first') },+ ])+ const second = makeZip([+ ...baseEntries,+ { name: 'dist/alternate.js', data: Buffer.from('second') },+ ])++ const firstLoaded = await loadMoext(+ await writeFixture('first.moext', first)+ )+ const secondLoaded = await loadMoext(+ await writeFixture('second.moext', second)+ )+ const firstResult = await extractLoadedMoext(+ firstLoaded,+ path.join(tmp, 'first')+ )+ const secondResult = await extractLoadedMoext(+ secondLoaded,+ path.join(tmp, 'second')+ )++ expect(firstLoaded.archiveSha256).not.toBe(secondLoaded.archiveSha256)+ expect(firstResult.bundleSha256).toBe(secondResult.bundleSha256)+ })++ it('rejects retained package bytes that no longer match their digest', async () => {+ const moextBuf = makeZip([+ { name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ ])+ const loaded = await loadMoext(+ await writeFixture('mutated.moext', moextBuf)+ )+ loaded.bytes[0] ^= 0xff++ await expect(+ extractLoadedMoext(loaded, path.join(tmp, 'mutated'))+ ).rejects.toMatchObject({ message: 'plugin.install.sha256_mismatch' })+ })++ it('keeps Linux-valid case, Unicode, colon, trailing-dot, and reserved names usable', async () => {+ if (process.platform !== 'linux') return+ const entries: FakeEntry[] = [+ { name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ { name: 'assets/Name.txt', data: Buffer.from('upper', 'utf8') },+ { name: 'assets/name.txt', data: Buffer.from('lower', 'utf8') },+ { name: 'assets/café.json', data: Buffer.from('nfc', 'utf8') },+ { name: 'assets/cafe\u0301.json', data: Buffer.from('nfd', 'utf8') },+ { name: 'assets/name:part', data: Buffer.from('colon', 'utf8') },+ { name: 'assets/trailing.', data: Buffer.from('dot', 'utf8') },+ { name: 'assets/CON', data: Buffer.from('reserved', 'utf8') },+ ]+ const dest = path.join(tmp, 'linux-valid-dest')+ const moext = await writeFixture('linux-valid.moext', makeZip(entries))++ await extractMoext(moext, dest)++ expect(await readFile(path.join(dest, 'assets/Name.txt'), 'utf8')).toBe(+ 'upper'+ )+ expect(await readFile(path.join(dest, 'assets/name.txt'), 'utf8')).toBe(+ 'lower'+ )+ expect(await readFile(path.join(dest, 'assets/name:part'), 'utf8')).toBe(+ 'colon'+ )+ })++ it('allows ordinary path components containing two dots', async () => {+ const dest = path.join(tmp, 'two-dots-dest')+ const moext = await writeFixture(+ 'two-dots.moext',+ makeZip([+ {+ name: 'motrix-plugin.json',+ data: Buffer.from(VALID_MANIFEST, 'utf8'),+ },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ { name: 'assets/name..part', data: Buffer.from('dots', 'utf8') },+ ])+ )++ await extractMoext(moext, dest)++ expect(await readFile(path.join(dest, 'assets/name..part'), 'utf8')).toBe(+ 'dots'+ )+ })++ it('rejects exact duplicate paths', async () => {+ await expectPathCollision('exact-collision', [+ { name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ { name: 'assets/data.json', data: Buffer.from('{}', 'utf8') },+ { name: 'assets/data.json', data: Buffer.from('{"x":1}', 'utf8') },+ ])+ })++ it('maps an exclusive-create EEXIST to path_collision', async () => {+ const dest = path.join(tmp, 'preexisting-dest')+ await mkdir(dest, { recursive: true })+ await writeFile(path.join(dest, 'motrix-plugin.json'), 'keep')+ const moext = await writeFixture(+ 'preexisting.moext',+ makeZip([+ {+ name: 'motrix-plugin.json',+ data: Buffer.from(VALID_MANIFEST, 'utf8'),+ },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ ])+ )++ await expect(extractMoext(moext, dest)).rejects.toMatchObject({+ message: 'plugin.install.path_collision',+ })+ expect(await readFile(path.join(dest, 'motrix-plugin.json'), 'utf8')).toBe(+ 'keep'+ )+ })++ it('rejects file-directory prefix conflicts in either entry order', async () => {+ const requiredEntries: FakeEntry[] = [+ { name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },+ { name: 'dist/plugin.js', data: TINY_BUNDLE },+ ]+ await expectPathCollision('file-before-child', [+ ...requiredEntries,+ { name: 'assets', data: Buffer.from('file', 'utf8') },+ { name: 'assets/payload.js', data: Buffer.from('child', 'utf8') },+ ])+ await expectPathCollision('child-before-file', [+ ...requiredEntries,+ { name: 'assets/payload.js', data: Buffer.from('child', 'utf8') },+ { name: 'assets', data: Buffer.from('file', 'utf8') },+ ])+ })+it('zip-slip "../escape.txt" rejected', async () => {const moextBuf = makeZip([{ name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },@@ -161,21 +324,21 @@ describe('moext-reader', () => {).rejects.toMatchObject({ message: 'plugin.install.zip_slip' })})- it('backslash entry is normalized by yauzl to forward slashes (no escape)', async () => {+ it('backslash entry is normalized by yauzl but missing bundle writes nothing', async () => {// yauzl 3.x rewrites '\' to '/' before handing the entry to us. The// resulting name 'a/b/c' is a valid nested path inside destDir, so the- // extraction succeeds (path-traversal defenses already cover '..' / '/').- // The bundle is still missing in this fixture, which the reader flags.+ // path validation accepts that contained name, but the full preflight sees+ // the required bundle is missing before creating the destination tree.const moextBuf = makeZip([{ name: 'motrix-plugin.json', data: Buffer.from(VALID_MANIFEST, 'utf8') },{ name: 'a\\b\\c', data: Buffer.from('x', 'utf8') },])const moext = await writeFixture('back.moext', moextBuf)- await expect(- extractMoext(moext, path.join(tmp, 'unpacked'))- ).rejects.toMatchObject({ message: 'plugin.install.bundle_missing' })- const onDisk = await readFile(path.join(tmp, 'unpacked', 'a/b/c'), 'utf8')- expect(onDisk).toBe('x')+ const dest = path.join(tmp, 'unpacked')+ await expect(extractMoext(moext, dest)).rejects.toMatchObject({+ message: 'plugin.install.bundle_missing',+ })+ expect(existsSync(dest)).toBe(false)})it('symlink entry rejected via external-attr mode', async () => {diff --git a/src/core/plugin/install/moext-reader.ts b/src/core/plugin/install/moext-reader.tsindex 77111a0f..da06939b 100644--- a/src/core/plugin/install/moext-reader.ts+++ b/src/core/plugin/install/moext-reader.ts@@ -4,20 +4,24 @@// - zip-slip: absolute paths, '..' segments, backslashes// - symlinks: external-file-attribute mode bits indicate a link// - oversized: per-bundle and total caps+// - collisions: exact duplicate paths and file/directory conflicts//-// Hashing: SHA-256 of `dist/plugin.js` (informational in Phase 1A —-// Phase 2 layers detached signing on top).+// Integrity: the archive is read once, hashed, and that exact in-memory byte+// sequence is used for extraction so a path replacement cannot make+// verification and unpacking observe different packages. ExtractResult keeps+// the existing SHA-256-of-dist/plugin.js install-record semantics.import { createHash } from 'node:crypto'import { createWriteStream } from 'node:fs'-import { mkdir, stat } from 'node:fs/promises'+import { mkdir, open } from 'node:fs/promises'import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'import yauzl from 'yauzl'const BUNDLE_SIZE_MAX = 1 << 20 // 1 MB — limit on dist/plugin.jsconst MOEXT_TOTAL_MAX = 5 << 20 // 5 MB — total uncompressed cap-const HASHED_ENTRY = 'dist/plugin.js'+const FILE_READ_CHUNK = 64 << 10+const DEFAULT_BUNDLE_ENTRY = 'dist/plugin.js'const MANIFEST_ENTRY = 'motrix-plugin.json'const SYMLINK_MODE = 0o120000@@ -27,6 +31,25 @@ export interface ExtractResult {totalUncompressed: number}+export interface LoadedMoext {+ /** Exact package bytes from one bounded file-descriptor read. */+ readonly bytes: Buffer+ /** SHA-256 of the complete .moext archive. */+ readonly archiveSha256: string+}++interface MoextScanResult {+ totalUncompressed: number+ hasManifest: boolean+ hasDefaultBundle: boolean+}++interface PathIndex {+ explicitPaths: Set<string>+ filePaths: Set<string>+ requiredDirectoryPaths: Set<string>+}+function fail(code: string): never {throw new AppError(ErrorCode.PluginManifestInvalid, code)}@@ -36,7 +59,7 @@ function fail(code: string): never {// (extractMoext) or reading a single entry into memory (readMoextEntry).function assertSafeEntryName(entryName: string): void {if (- entryName.includes('..') ||+ entryName.split('/').includes('..') ||entryName.startsWith('/') ||entryName.includes('\\')) {@@ -72,18 +95,172 @@ function entryIsSymlink(entry: yauzl.Entry): boolean {return mode === SYMLINK_MODE}-export async function extractMoext(- moextPath: string,+function pathCollision(): never {+ fail('plugin.install.path_collision')+}++/** Register exact duplicate and file-vs-directory conflicts before writing. */+function registerPath(+ entryName: string,+ isDirectory: boolean,+ index: PathIndex+): void {+ const withoutTrailingSlash = isDirectory ? entryName.slice(0, -1) : entryName+ if (withoutTrailingSlash.length === 0) pathCollision()++ const parts = withoutTrailingSlash.split('/')+ for (let i = 0; i < parts.length - 1; i += 1) {+ const prefix = parts.slice(0, i + 1).join('/')+ if (index.filePaths.has(prefix)) pathCollision()+ index.requiredDirectoryPaths.add(prefix)+ }++ if (index.explicitPaths.has(withoutTrailingSlash)) pathCollision()+ if (!isDirectory && index.requiredDirectoryPaths.has(withoutTrailingSlash)) {+ pathCollision()+ }+ index.explicitPaths.add(withoutTrailingSlash)+ if (!isDirectory) index.filePaths.add(withoutTrailingSlash)+}++function translateZipError(error: Error): Error {+ if (isZipSlipYauzlError(error.message)) {+ return new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.zip_slip'+ )+ }+ return error+}++/** Preflight every central-directory entry without creating destDir. */+function scanMoextEntries(bytes: Buffer): Promise<MoextScanResult> {+ return new Promise<MoextScanResult>((resolve, reject) => {+ yauzl.fromBuffer(bytes, { lazyEntries: true }, (openErr, zip) => {+ if (openErr || !zip) {+ reject(+ openErr ??+ new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.zip_invalid'+ )+ )+ return+ }++ const index: PathIndex = {+ explicitPaths: new Set(),+ filePaths: new Set(),+ requiredDirectoryPaths: new Set(),+ }+ let totalUncompressed = 0+ let hasManifest = false+ let hasDefaultBundle = false+ let settled = false++ const finish = (error?: unknown) => {+ if (settled) return+ settled = true+ zip.close()+ if (error) {+ reject(error)+ } else {+ resolve({+ totalUncompressed,+ hasManifest,+ hasDefaultBundle,+ })+ }+ }++ zip.on('entry', (entry: yauzl.Entry) => {+ try {+ assertSafeEntryName(entry.fileName)+ const isDirectory = entry.fileName.endsWith('/')+ registerPath(entry.fileName, isDirectory, index)+ if (entryIsSymlink(entry)) fail('plugin.install.zip_symlink')++ totalUncompressed += entry.uncompressedSize+ if (totalUncompressed > MOEXT_TOTAL_MAX) {+ fail('plugin.manifest.bundle_too_large')+ }+ if (+ entry.fileName === DEFAULT_BUNDLE_ENTRY &&+ entry.uncompressedSize > BUNDLE_SIZE_MAX+ ) {+ fail('plugin.manifest.bundle_too_large')+ }+ if (entry.fileName === MANIFEST_ENTRY && !isDirectory) {+ hasManifest = true+ }+ if (entry.fileName === DEFAULT_BUNDLE_ENTRY && !isDirectory) {+ hasDefaultBundle = true+ }+ zip.readEntry()+ } catch (error) {+ finish(error)+ }+ })+ zip.on('end', () => finish())+ zip.on('error', (error: Error) => finish(translateZipError(error)))+ zip.readEntry()+ })+ })+}++export async function loadMoext(moextPath: string): Promise<LoadedMoext> {+ // Read through one open file descriptor and stop at the compressed-size+ // limit. A pathname swap after open cannot change which file is verified,+ // and an oversized file is never buffered in full before rejection.+ const handle = await open(moextPath, 'r')+ const chunks: Buffer[] = []+ let total = 0+ try {+ for (;;) {+ const remaining = MOEXT_TOTAL_MAX + 1 - total+ const chunk = Buffer.allocUnsafe(Math.min(FILE_READ_CHUNK, remaining))+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null)+ if (bytesRead === 0) break+ total += bytesRead+ if (total > MOEXT_TOTAL_MAX) {+ fail('plugin.manifest.bundle_too_large')+ }+ chunks.push(chunk.subarray(0, bytesRead))+ }+ } finally {+ await handle.close()+ }+ const bytes = Buffer.concat(chunks, total)+ return {+ bytes,+ archiveSha256: createHash('sha256').update(bytes).digest('hex'),+ }+}++export async function extractLoadedMoext(+ loaded: LoadedMoext,destDir: string): Promise<ExtractResult> {- const fileStat = await stat(moextPath)- if (fileStat.size > MOEXT_TOTAL_MAX) {+ if (loaded.bytes.byteLength > MOEXT_TOTAL_MAX) {fail('plugin.manifest.bundle_too_large')}+ if (+ createHash('sha256').update(loaded.bytes).digest('hex') !==+ loaded.archiveSha256+ ) {+ fail('plugin.install.sha256_mismatch')+ }+ const scan = await scanMoextEntries(loaded.bytes)+ if (!scan.hasManifest) {+ fail('plugin.install.manifest_not_at_root')+ }+ if (!scan.hasDefaultBundle) {+ fail('plugin.install.bundle_missing')+ }await mkdir(destDir, { recursive: true })return new Promise<ExtractResult>((resolve, reject) => {- yauzl.open(moextPath, { lazyEntries: true }, (openErr, zip) => {+ yauzl.fromBuffer(loaded.bytes, { lazyEntries: true }, (openErr, zip) => {if (openErr || !zip) {reject(openErr ??@@ -95,7 +272,8 @@ export async function extractMoext(return}let manifestRaw: string | null = null- let bundleHash: string | null = null+ let hasDefaultBundle = false+ let defaultBundleSha256: string | null = nulllet totalUncompressed = 0// Actual decompressed bytes streamed across ALL entries. totalUncompressed// above trusts the zip header's uncompressedSize (forgeable); this caps@@ -141,7 +319,7 @@ export async function extractMoext(.catch((e) => finish(e))return}- const isBundle = entry.fileName === HASHED_ENTRY+ const isBundle = entry.fileName === DEFAULT_BUNDLE_ENTRYif (isBundle && entry.uncompressedSize > BUNDLE_SIZE_MAX) {finish(new AppError(@@ -166,11 +344,27 @@ export async function extractMoext(.then(() =>new Promise<void>((res, rej) => {- const ws = createWriteStream(target)+ // Never overwrite an earlier entry or a pre-existing path.+ // The host filesystem itself decides whether distinct ZIP+ // spellings (case, Unicode, Win32 aliases) name one file.+ const ws = createWriteStream(target, { flags: 'wx' })const hash = isBundle ? createHash('sha256') : nullconst manifestChunks: Buffer[] | null =entry.fileName === MANIFEST_ENTRY ? [] : nulllet written = 0+ const rejectWrite = (error: NodeJS.ErrnoException) => {+ stream.destroy()+ if (error.code === 'EEXIST') {+ rej(+ new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.path_collision'+ )+ )+ return+ }+ rej(error)+ }stream.on('data', (chunk: Buffer) => {written += chunk.lengthtotalActualBytes += chunk.length@@ -188,13 +382,18 @@ export async function extractMoext()return}- if (hash) hash.update(chunk)if (manifestChunks) manifestChunks.push(chunk)+ hash?.update(chunk)ws.write(chunk)})stream.on('end', () => {- ws.end(() => {- if (hash) bundleHash = hash.digest('hex')+ ws.end((error?: Error | null) => {+ if (error) {+ rejectWrite(error)+ return+ }+ if (isBundle) hasDefaultBundle = true+ if (hash) defaultBundleSha256 = hash.digest('hex')if (manifestChunks) {manifestRaw =Buffer.concat(manifestChunks).toString('utf8')@@ -203,7 +402,7 @@ export async function extractMoext(})})stream.on('error', rej)- ws.on('error', rej)+ ws.on('error', rejectWrite)})).then(() => zip.readEntry())@@ -224,7 +423,7 @@ export async function extractMoext()return}- if (!bundleHash) {+ if (!hasDefaultBundle || !defaultBundleSha256) {finish(new AppError(ErrorCode.PluginManifestInvalid,@@ -234,9 +433,9 @@ export async function extractMoext(return}finish(null, {- bundleSha256: bundleHash,+ bundleSha256: defaultBundleSha256,manifestRaw,- totalUncompressed,+ totalUncompressed: scan.totalUncompressed,})})@@ -257,6 +456,13 @@ export async function extractMoext(})}+export async function extractMoext(+ moextPath: string,+ destDir: string+): Promise<ExtractResult> {+ return extractLoadedMoext(await loadMoext(moextPath), destDir)+}+/*** In-memory single-entry reader for an already-loaded .moext buffer. Used by* the Firefox-packed-XPI read path (2026-07-18 design §4): once the bundle'sdiff --git a/src/core/plugin/install/plugin-installer.ts b/src/core/plugin/install/plugin-installer.tsindex 84cd6759..09fdfca1 100644--- a/src/core/plugin/install/plugin-installer.ts+++ b/src/core/plugin/install/plugin-installer.ts@@ -14,11 +14,12 @@// row → purge plugin_storage + plugin_task_metadata + plugin_cookie_jar →// remove the install directory → refresh registry.-import { createHash } from 'node:crypto'-import { mkdir, readFile, rename, rm } from 'node:fs/promises'+import { randomUUID } from 'node:crypto'+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'import path from 'node:path'import { FALLBACK_LOCALE } from '@shared/constants/locales'import { AppError, ErrorCode } from '@shared/errors'+import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'import type { PluginManifest } from '@shared/types/plugin'import type {ConsentPayload,@@ -45,7 +46,7 @@ import {requiresConsent,writeInstallRecord,} from './install-record'-import { extractMoext } from './moext-reader'+import { extractLoadedMoext, loadMoext } from './moext-reader'import { computePublicCommandHashes } from './public-command-hash'import {assertMatchesRegistryExpectation,@@ -72,6 +73,15 @@ export interface CommandSchemaCacheLike {uninstall(pluginId: string): void}+/**+ * Runtime teardown seam shared by the Electron and server plugin hosts.+ * `deactivate()` does not resolve until the worker bridge has been disposed.+ */+export interface PluginRuntimeHostLike {+ isQuiescent(pluginId: string): boolean+ deactivate(pluginId: string): Promise<void>+}+export interface PluginInstallerOptions {pluginsDir: stringregistry: PluginRegistry@@ -106,6 +116,10 @@ interface StagedInstall {source: InstallRecordSourcestagingDir: stringconsent: ConsentPayload+ archivePath: string+ archiveSha256: string+ previousRecord: InstallRecord | null+ runtimeHost?: PluginRuntimeHostLike}export interface StageResult {@@ -120,6 +134,10 @@ export interface StageResult {export interface StageOptions {/** §6.3 registry↔manifest consistency gate; checked before any commit. */expect?: RegistryExpectation+ /** Digest pinned by a non-registry source such as server bootstrap. */+ expectedSha256?: string+ /** Runtime teardown seam supplied by the shell command boundary. */+ runtimeHost?: PluginRuntimeHostLike}async function loadManifestLocale(@@ -155,8 +173,42 @@ async function resolveManifestForInstall(})}+function resolvePluginInstallDir(pluginsDir: string, pluginId: string): string {+ if (!REGISTRY_PLUGIN_ID_RE.test(pluginId)) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.invalid_plugin_id'+ )+ }++ const root = path.resolve(pluginsDir)+ const candidate = path.resolve(root, pluginId)+ const relative = path.relative(root, candidate)+ if (+ relative === '' ||+ relative === '..' ||+ relative.startsWith(`..${path.sep}`) ||+ path.isAbsolute(relative)+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.invalid_plugin_id'+ )+ }+ return candidate+}++function sameInstallRecord(+ left: InstallRecord | null,+ right: InstallRecord | null+): boolean {+ if (left === null || right === null) return left === right+ return JSON.stringify(left) === JSON.stringify(right)+}+export class PluginInstaller {private readonly pending = new Map<string, StagedInstall>()+ private readonly mutationTails = new Map<string, Promise<void>>()constructor(private readonly opts: PluginInstallerOptions) {}@@ -170,27 +222,39 @@ export class PluginInstaller {'_staging',`s_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`)- const { bundleSha256, manifestRaw } = await extractMoext(- moextPath,- stagingDir- )- const localFileHash =+ const extractedDir = path.join(stagingDir, 'tree')+ const archivePath = path.join(stagingDir, 'archive.moext')+ const loadedMoext = await loadMoext(moextPath)+ const pinnedSha256 =sourceInput.type === 'local'- ? createHash('sha256')- .update(await readFile(moextPath))- .digest('hex')- : null- if (- sourceInput.type === 'local' &&- sourceInput.fileHash !== localFileHash- ) {- await rm(stagingDir, { recursive: true, force: true })+ ? sourceInput.fileHash+ : (options?.expectedSha256 ?? options?.expect?.packageSha256)+ if (pinnedSha256 && loadedMoext.archiveSha256 !== pinnedSha256) {throw new AppError(ErrorCode.PluginManifestInvalid,- 'plugin.install.local_file_hash_mismatch'+ sourceInput.type === 'local'+ ? 'plugin.install.local_file_hash_mismatch'+ : 'plugin.install.sha256_mismatch')}+ let manifestRaw: string+ let bundleSha256: string+ try {+ const extracted = await extractLoadedMoext(loadedMoext, extractedDir)+ manifestRaw = extracted.manifestRaw+ bundleSha256 = extracted.bundleSha256+ // Consent can remain open indefinitely. Keep the exact package on disk+ // instead of retaining up to 5 MiB in the installer's pending Map.+ await writeFile(archivePath, loadedMoext.bytes, {+ flag: 'wx',+ mode: 0o600,+ })+ } catch (error) {+ await rm(stagingDir, { recursive: true, force: true })+ throw error+ }+let parsedManifest: PluginManifesttry {const result = parseManifest(manifestRaw, {@@ -198,7 +262,7 @@ export class PluginInstaller {})parsedManifest = await resolveManifestForInstall(result.manifest as PluginManifest,- stagingDir+ extractedDir)} catch (e) {await rm(stagingDir, { recursive: true, force: true })@@ -221,7 +285,10 @@ export class PluginInstaller {bundleSha256,recordedAt: Date.now(),}- const finalDir = path.join(this.opts.pluginsDir, parsedManifest.id)+ const finalDir = resolvePluginInstallDir(+ this.opts.pluginsDir,+ parsedManifest.id+ )const prev = await readInstallRecord(finalDir)if (this.opts.serverAck) {@@ -315,6 +382,11 @@ export class PluginInstaller {{ ffmpegDetection })+ // Locale/manifest resolution is complete. A pending consent transaction+ // only needs the protected archive, so do not retain a second extracted+ // copy indefinitely alongside it.+ await rm(extractedDir, { recursive: true, force: true })+const stagingId = path.basename(stagingDir)const staged: StagedInstall = {pluginId: parsedManifest.id,@@ -322,11 +394,19 @@ export class PluginInstaller {source,stagingDir,consent,+ archivePath,+ archiveSha256: loadedMoext.archiveSha256,+ previousRecord: prev,+ runtimeHost: options?.runtimeHost,}this.pending.set(stagingId, staged)if (!needConsent) {- const committed = await this.commit(stagingId, prev?.grants ?? {})+ const committed = await this.commit(+ stagingId,+ prev?.grants ?? {},+ options?.runtimeHost+ )return {stagingId,consent,@@ -339,7 +419,8 @@ export class PluginInstaller {async commit(stagingId: string,- grants: GrantsMap+ grants: GrantsMap,+ runtimeHost?: PluginRuntimeHostLike): Promise<{ pluginId: string }> {const staged = this.pending.get(stagingId)if (!staged) {@@ -348,81 +429,223 @@ export class PluginInstaller {'plugin.install.staging_not_found')}- const finalDir = path.join(this.opts.pluginsDir, staged.pluginId)- const prev = await readInstallRecord(finalDir)- if (prev) {- // Upgrade: deactivate first, then atomic dir swap with rollback.- await this.opts.capabilityHost.lifecycle.runDeactivate(staged.pluginId)- const backup = `${finalDir}.bak-${Date.now()}`- await rename(finalDir, backup)- try {- await rename(staged.stagingDir, finalDir)- } catch (e) {- await rename(backup, finalDir).catch(() => {})- throw e+ return this.withPluginMutation(staged.pluginId, async () => {+ // A second commit may have consumed this staging entry while this call+ // waited for the per-plugin mutation lock.+ if (this.pending.get(stagingId) !== staged) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.staging_not_found'+ )}- await rm(backup, { recursive: true, force: true })- } else {- await mkdir(this.opts.pluginsDir, { recursive: true })- await rename(staged.stagingDir, finalDir)- }- const record: InstallRecord = {- version: 1,- pluginId: staged.pluginId,- source: staged.source,- grants,- consentSnapshot: {- permissions: staged.newManifest.permissions,- optionalPermissions: staged.newManifest.optionalPermissions ?? [],- invokesCommands: staged.newManifest.invokesCommands ?? [],- publicCommands: computePublicCommandHashes(staged.newManifest),- requestedHeapMB: staged.newManifest.requestedHeapMB ?? 32,- enginesMotrix: staged.newManifest.engines.motrix,- hostPermissions: staged.newManifest.hostPermissions ?? [],- },- }- await writeInstallRecord(finalDir, record)-- if (this.opts.schemaCache) {- this.opts.schemaCache.installCommandSchemas(- staged.pluginId,- (staged.newManifest.contributes.commands ?? []) as ReadonlyArray<{- id: string- argsSchema?: unknown- resultSchema?: unknown- public?: boolean- }>+ const finalDir = resolvePluginInstallDir(+ this.opts.pluginsDir,+ staged.pluginId)- }+ const prev = await readInstallRecord(finalDir)+ if (!sameInstallRecord(prev, staged.previousRecord)) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.changed_since_staging'+ )+ }- await this.opts.registry.discover()- this.pending.delete(stagingId)- return { pluginId: staged.pluginId }+ const record: InstallRecord = {+ version: 1,+ pluginId: staged.pluginId,+ source: staged.source,+ grants,+ consentSnapshot: {+ permissions: staged.newManifest.permissions,+ optionalPermissions: staged.newManifest.optionalPermissions ?? [],+ invokesCommands: staged.newManifest.invokesCommands ?? [],+ publicCommands: computePublicCommandHashes(staged.newManifest),+ requestedHeapMB: staged.newManifest.requestedHeapMB ?? 32,+ enginesMotrix: staged.newManifest.engines.motrix,+ hostPermissions: staged.newManifest.hostPermissions ?? [],+ },+ }+ const commitDir = path.join(+ this.opts.pluginsDir,+ '_staging',+ `c_${randomUUID()}`+ )+ let backupDir: string | null = null+ let swapped = false++ try {+ // Never commit the long-lived staging tree: it was visible while the+ // consent dialog was open. Re-read through one file descriptor, verify+ // the staged archive digest, then extract those exact bytes into the+ // one-shot swap directory.+ const loadedMoext = await loadMoext(staged.archivePath)+ if (loadedMoext.archiveSha256 !== staged.archiveSha256) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.sha256_mismatch'+ )+ }+ await extractLoadedMoext(loadedMoext, commitDir)+ await writeInstallRecord(commitDir, record)+ await mkdir(this.opts.pluginsDir, { recursive: true })++ if (prev) {+ // PluginHost.deactivate waits for the worker-side handler, tears+ // down the bridge, and terminates the worker before disk changes.+ await this.stopRuntime(+ staged.pluginId,+ runtimeHost ?? staged.runtimeHost+ )+ backupDir = `${finalDir}.bak-${randomUUID()}`+ await rename(finalDir, backupDir)+ }+ await rename(commitDir, finalDir)+ swapped = true++ this.installCommandSchemas(staged.pluginId, staged.newManifest)+ await this.opts.registry.discover()++ this.pending.delete(stagingId)+ await rm(staged.stagingDir, { recursive: true, force: true }).catch(+ () => undefined+ )+ if (backupDir) {+ await rm(backupDir, { recursive: true, force: true }).catch(+ () => undefined+ )+ }+ return { pluginId: staged.pluginId }+ } catch (error) {+ if (backupDir) {+ if (swapped) {+ await rm(finalDir, { recursive: true, force: true }).catch(+ () => undefined+ )+ }+ await rename(backupDir, finalDir).catch(() => undefined)+ } else if (swapped) {+ await rm(finalDir, { recursive: true, force: true }).catch(+ () => undefined+ )+ }+ if (backupDir || swapped) {+ await this.opts.registry+ .discover()+ .then(() => {+ const restored = this.opts.registry.get(staged.pluginId)+ if (restored) {+ this.installCommandSchemas(staged.pluginId, restored.manifest)+ } else if (this.opts.schemaCache) {+ this.opts.schemaCache.uninstall(staged.pluginId)+ }+ })+ .catch(() => undefined)+ }+ throw error+ } finally {+ await rm(commitDir, { recursive: true, force: true }).catch(+ () => undefined+ )+ }+ })}async cancel(stagingId: string): Promise<void> {const staged = this.pending.get(stagingId)if (!staged) return- await rm(staged.stagingDir, { recursive: true, force: true })- this.pending.delete(stagingId)+ await this.withPluginMutation(staged.pluginId, async () => {+ if (this.pending.get(stagingId) !== staged) return+ this.pending.delete(stagingId)+ await rm(staged.stagingDir, { recursive: true, force: true })+ })+ }++ async uninstall(+ pluginId: string,+ runtimeHost?: PluginRuntimeHostLike+ ): Promise<void> {+ const finalDir = resolvePluginInstallDir(this.opts.pluginsDir, pluginId)+ await this.withPluginMutation(pluginId, async () => {+ // A worker retaining old code must not survive removal of its durable+ // files. Unlike handler failures (which PluginHost handles internally),+ // a bridge-disposal failure aborts the uninstall.+ if (runtimeHost) {+ await this.stopRuntime(pluginId, runtimeHost)+ } else {+ // Preserve the legacy direct-installer behavior for embedders that do+ // not yet supply a PluginHost. Production IPC always passes it.+ await this.opts.capabilityHost.lifecycle+ .runDeactivate(pluginId)+ .catch(() => undefined)+ }+ this.opts.stateStore.remove(pluginId)+ await this.opts.capabilityHost.storage.deleteAll(pluginId)+ await this.opts.capabilityHost.metadata.deleteAllForPlugin(pluginId)+ this.opts.capabilityHost.cookieJarFor(pluginId).clear()+ await rm(finalDir, { recursive: true, force: true })+ if (this.opts.schemaCache) this.opts.schemaCache.uninstall(pluginId)+ await this.opts.registry.discover()+ })+ }++ private installCommandSchemas(+ pluginId: string,+ manifest: PluginManifest+ ): void {+ if (!this.opts.schemaCache) return+ this.opts.schemaCache.installCommandSchemas(+ pluginId,+ (manifest.contributes.commands ?? []) as ReadonlyArray<{+ id: string+ argsSchema?: unknown+ resultSchema?: unknown+ public?: boolean+ }>+ )+ }++ private async stopRuntime(+ pluginId: string,+ runtimeHost?: PluginRuntimeHostLike+ ): Promise<void> {+ if (!runtimeHost) {+ await this.opts.capabilityHost.lifecycle.runDeactivate(pluginId)+ return+ }+ await runtimeHost.deactivate(pluginId)+ if (!runtimeHost.isQuiescent(pluginId)) {+ throw new AppError(+ ErrorCode.PluginRuntimeFault,+ 'plugin.install.runtime_still_active'+ )+ }}- async uninstall(pluginId: string): Promise<void> {- const finalDir = path.join(this.opts.pluginsDir, pluginId)- // Best-effort deactivate — uninstalling something that failed to- // activate shouldn't block teardown.- await this.opts.capabilityHost.lifecycle- .runDeactivate(pluginId)- .catch(() => {})- this.opts.stateStore.remove(pluginId)- await this.opts.capabilityHost.storage.deleteAll(pluginId)- await this.opts.capabilityHost.metadata.deleteAllForPlugin(pluginId)- this.opts.capabilityHost.cookieJarFor(pluginId).clear()- await rm(finalDir, { recursive: true, force: true })- if (this.opts.schemaCache) this.opts.schemaCache.uninstall(pluginId)- await this.opts.registry.discover()+ private async withPluginMutation<T>(+ pluginId: string,+ operation: () => Promise<T>+ ): Promise<T> {+ const previous = this.mutationTails.get(pluginId) ?? Promise.resolve()+ let release!: () => void+ const current = new Promise<void>((resolve) => {+ release = resolve+ })+ const tail = previous.then(+ () => current,+ () => current+ )+ this.mutationTails.set(pluginId, tail)+ await previous.catch(() => undefined)+ try {+ return await operation()+ } finally {+ release()+ if (this.mutationTails.get(pluginId) === tail) {+ this.mutationTails.delete(pluginId)+ }+ }}private collectCalleeTitles(diff --git a/src/core/plugin/install/registry-expectation.ts b/src/core/plugin/install/registry-expectation.tsindex 13a8ec6e..4457ddee 100644--- a/src/core/plugin/install/registry-expectation.ts+++ b/src/core/plugin/install/registry-expectation.ts@@ -14,12 +14,14 @@ export interface RegistryExpectation {permissions: ReadonlyArray<string>optionalPermissions: ReadonlyArray<string>hostPermissions: ReadonlyArray<string>+ /** Complete .moext digest verified by the registry download boundary. */+ packageSha256?: string}export function buildRegistryExpectation(entry: RegistryPlugin): RegistryExpectation {- return {+ const expectation: RegistryExpectation = {id: entry.id,version: entry.version,enginesMotrix: entry.engines.motrix,@@ -27,6 +29,8 @@ export function buildRegistryExpectation(optionalPermissions: entry.optionalPermissions,hostPermissions: entry.hostPermissions,}+ if (entry.package?.sha256) expectation.packageSha256 = entry.package.sha256+ return expectation}function isSubset(diff --git a/src/core/plugin/registry/registry-fetcher.test.ts b/src/core/plugin/registry/registry-fetcher.test.tsindex 2d4ef486..7b7dd19e 100644--- a/src/core/plugin/registry/registry-fetcher.test.ts+++ b/src/core/plugin/registry/registry-fetcher.test.ts@@ -4,11 +4,12 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'import type { RegistryPluginDTO } from '@shared/schemas/registry'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {assertAllowlistedPackageUrl,downloadRegistryMoext,fetchVerifiedPackageBytes,+ MAX_REGISTRY_PACKAGE_BYTES,} from './registry-fetcher'const BYTES = Buffer.from('fake-moext-bytes')@@ -46,13 +47,16 @@ function entry(}}-function fakeFetch(body: Buffer, status = 200): typeof fetch {- return (async () => ({- ok: status === 200,- status,- arrayBuffer: async () =>- body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),- })) as unknown as typeof fetch+function responseFetch(response: Response): typeof fetch {+ return vi.fn(async () => response) as unknown as typeof fetch+}++function fakeFetch(+ body: Buffer,+ status = 200,+ headers?: HeadersInit+): typeof fetch {+ return responseFetch(new Response(Uint8Array.from(body), { status, headers }))}describe('assertAllowlistedPackageUrl', () => {@@ -132,8 +136,130 @@ describe('downloadRegistryMoext', () => {})describe('fetchVerifiedPackageBytes', () => {- it('fetchVerifiedPackageBytes returns the verified bytes without touching disk', async () => {+ it('returns verified bytes when Content-Length is absent', async () => {const bytes = await fetchVerifiedPackageBytes(entry(), fakeFetch(BYTES))expect(bytes).toEqual(BYTES)})++ it('verifies size and sha256 across streamed chunks', async () => {+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(BYTES.subarray(0, 4))+ controller.enqueue(BYTES.subarray(4))+ controller.close()+ },+ })++ await expect(+ fetchVerifiedPackageBytes(+ entry(),+ responseFetch(+ new Response(stream, {+ headers: { 'content-length': String(BYTES.byteLength) },+ })+ )+ )+ ).resolves.toEqual(BYTES)+ })++ it('cancels immediately when the stream exceeds the declared size', async () => {+ const cancel = vi.fn()+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(Buffer.concat([BYTES, Buffer.from('!')]))+ },+ cancel,+ })++ await expect(+ fetchVerifiedPackageBytes(entry(), responseFetch(new Response(stream)))+ ).rejects.toThrowError(/registry_size_mismatch/)+ expect(cancel).toHaveBeenCalledOnce()+ })++ it('cancels immediately when the stream exceeds the absolute cap', async () => {+ const cancel = vi.fn()+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array(MAX_REGISTRY_PACKAGE_BYTES + 1))+ },+ cancel,+ })++ await expect(+ fetchVerifiedPackageBytes(+ entry({ size: MAX_REGISTRY_PACKAGE_BYTES }),+ responseFetch(new Response(stream))+ )+ ).rejects.toThrowError(/package_too_large/)+ expect(cancel).toHaveBeenCalledOnce()+ })++ it('does not trust a mismatched Content-Length over verified body bytes', async () => {+ await expect(+ fetchVerifiedPackageBytes(+ entry(),+ responseFetch(+ new Response(Uint8Array.from(BYTES), {+ headers: { 'content-length': String(BYTES.byteLength - 1) },+ })+ )+ )+ ).resolves.toEqual(BYTES)+ })++ it('cancels a Content-Length above the absolute cap', async () => {+ const cancel = vi.fn()+ const stream = new ReadableStream<Uint8Array>({ cancel })++ await expect(+ fetchVerifiedPackageBytes(+ entry(),+ responseFetch(+ new Response(stream, {+ headers: {+ 'content-length': String(MAX_REGISTRY_PACKAGE_BYTES + 1),+ },+ })+ )+ )+ ).rejects.toThrowError(/package_too_large/)+ expect(cancel).toHaveBeenCalledOnce()+ })++ it('rejects an invalid declared package size before fetching', async () => {+ const fetchImpl = vi.fn()+ await expect(+ fetchVerifiedPackageBytes(+ entry({ size: MAX_REGISTRY_PACKAGE_BYTES + 1 }),+ fetchImpl+ )+ ).rejects.toThrowError(/package_too_large/)+ expect(fetchImpl).not.toHaveBeenCalled()+ })++ it('rejects an absent response body', async () => {+ await expect(+ fetchVerifiedPackageBytes(+ entry(),+ responseFetch(new Response(null, { status: 200 }))+ )+ ).rejects.toThrowError(/registry_download_failed: empty body/)+ })++ it('wraps response stream errors', async () => {+ const cause = new Error('stream failed')+ const stream = new ReadableStream<Uint8Array>({+ pull(controller) {+ controller.error(cause)+ },+ })++ await expect(+ fetchVerifiedPackageBytes(entry(), responseFetch(new Response(stream)))+ ).rejects.toMatchObject({+ message: 'plugin.install.registry_download_failed: stream error',+ cause,+ })+ })})diff --git a/src/core/plugin/registry/registry-fetcher.ts b/src/core/plugin/registry/registry-fetcher.tsindex e13126d6..472a2d9b 100644--- a/src/core/plugin/registry/registry-fetcher.ts+++ b/src/core/plugin/registry/registry-fetcher.ts@@ -1,7 +1,7 @@// §6.3 download boundary for registry packages: https + host allowlist on// the INITIAL url (GitHub assets 302 to a CDN — integrity past the redirect-// is anchored by sha256, not hostname), then size + sha256 verified fully-// in memory BEFORE anything is written to disk.+// is anchored by sha256, not hostname), then size + sha256 verified through+// a bounded stream BEFORE anything is written to disk.import { createHash } from 'node:crypto'import { mkdir, writeFile } from 'node:fs/promises'@@ -14,6 +14,19 @@ export const REGISTRY_PACKAGE_HOSTS: ReadonlySet<string> = new Set(['dl.motrix.app',])+export const MAX_REGISTRY_PACKAGE_BYTES = 5 * 1024 * 1024++function packageError(message: string, cause?: unknown): AppError {+ return new AppError(ErrorCode.PluginManifestInvalid, message, cause)+}++async function cancelBody(+ body: ReadableStream<Uint8Array> | null,+ reason: unknown+): Promise<void> {+ await body?.cancel(reason).catch(() => undefined)+}+export function assertAllowlistedPackageUrl(rawUrl: string): URL {let u: URLtry {@@ -44,29 +57,91 @@ export async function fetchVerifiedPackageBytes('plugin.install.registry_no_package')}+ if (!Number.isSafeInteger(pkg.size) || pkg.size <= 0) {+ throw packageError('plugin.install.registry_size_mismatch')+ }+ if (pkg.size > MAX_REGISTRY_PACKAGE_BYTES) {+ throw packageError('plugin.install.package_too_large')+ }const url = assertAllowlistedPackageUrl(pkg.url)const res = await fetchImpl(url)if (!res.ok) {- throw new AppError(+ const error = new AppError(ErrorCode.PluginManifestInvalid,`plugin.install.registry_download_failed: ${res.status}`)+ await cancelBody(res.body, error)+ throw error}- const bytes = Buffer.from(await res.arrayBuffer())- if (bytes.byteLength !== pkg.size) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.registry_size_mismatch'++ const contentLength = res.headers.get('content-length')?.trim()+ // Content-Length is only an early resource-limit hint. Proxies and+ // transparent encoding can omit or rewrite it, so integrity relies on the+ // bounded stream, final byte count, and SHA-256 below.+ if (contentLength && /^\d+$/.test(contentLength)) {+ const declaredLength = BigInt(contentLength)+ if (declaredLength > BigInt(MAX_REGISTRY_PACKAGE_BYTES)) {+ const error = packageError('plugin.install.package_too_large')+ await cancelBody(res.body, error)+ throw error+ }+ }++ if (!res.body) {+ throw packageError('plugin.install.registry_download_failed: empty body')+ }++ let reader: ReadableStreamDefaultReader<Uint8Array>+ try {+ reader = res.body.getReader()+ } catch (cause) {+ throw packageError(+ 'plugin.install.registry_download_failed: stream error',+ cause)}- const digest = createHash('sha256').update(bytes).digest('hex')- if (digest !== pkg.sha256) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.registry_sha256_mismatch'+ const chunks: Buffer[] = []+ const hash = createHash('sha256')+ let total = 0+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break++ total += value.byteLength+ if (total > MAX_REGISTRY_PACKAGE_BYTES || total > pkg.size) {+ const error = packageError(+ total > MAX_REGISTRY_PACKAGE_BYTES+ ? 'plugin.install.package_too_large'+ : 'plugin.install.registry_size_mismatch'+ )+ await reader.cancel(error).catch(() => undefined)+ throw error+ }++ const chunk = Buffer.from(value)+ hash.update(chunk)+ chunks.push(chunk)+ }+ } catch (cause) {+ await reader.cancel(cause).catch(() => undefined)+ if (cause instanceof AppError) throw cause+ throw packageError(+ 'plugin.install.registry_download_failed: stream error',+ cause)+ } finally {+ reader.releaseLock()+ }++ if (total !== pkg.size) {+ throw packageError('plugin.install.registry_size_mismatch')+ }+ const digest = hash.digest('hex')+ if (digest !== pkg.sha256) {+ throw packageError('plugin.install.registry_sha256_mismatch')}- return bytes+ return Buffer.concat(chunks, total)}export async function downloadRegistryMoext(diff --git a/src/core/plugin/update/builtin-updater.test.ts b/src/core/plugin/update/builtin-updater.test.tsindex ee77ead5..c9fabe0d 100644--- a/src/core/plugin/update/builtin-updater.test.ts+++ b/src/core/plugin/update/builtin-updater.test.ts@@ -41,12 +41,11 @@ afterEach(async () => {})function fetchImplOf(bytes: Buffer): typeof fetch {- return (async () => ({- ok: true,- status: 200,- arrayBuffer: async () =>- bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),- })) as unknown as typeof fetch+ return async () =>+ new Response(Uint8Array.from(bytes), {+ status: 200,+ headers: { 'content-length': String(bytes.byteLength) },+ })}function makeUpdater(diff --git a/src/core/plugin/update/e2e-builtin-update.test.ts b/src/core/plugin/update/e2e-builtin-update.test.tsindex 92e91c6d..b86e99af 100644--- a/src/core/plugin/update/e2e-builtin-update.test.ts+++ b/src/core/plugin/update/e2e-builtin-update.test.ts@@ -34,12 +34,11 @@ function plantSeed(builtinDir: string, version: string): void {}function fetchImplOf(bytes: Buffer): typeof fetch {- return (async () => ({- ok: true,- status: 200,- arrayBuffer: async () =>- bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),- })) as unknown as typeof fetch+ return async () =>+ new Response(Uint8Array.from(bytes), {+ status: 200,+ headers: { 'content-length': String(bytes.byteLength) },+ })}// ---------------------------------------------------------------------------diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.tsindex 88f13784..b46af885 100644--- a/src/main/bridge/bootstrap-lifecycle.test.ts+++ b/src/main/bridge/bootstrap-lifecycle.test.ts@@ -51,6 +51,13 @@ vi.mock('electron', () => ({},}))+vi.mock('../ipc/trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ listener: (...args: unknown[]) => unknown+ ) => electron.handle(channel, listener),+}))+import { bootstrapBridge } from './index'function args(): Parameters<typeof bootstrapBridge>[0] {diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex e245ab0e..518af9e0 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -45,6 +45,7 @@ import type { PluginManifest } from '@shared/types/plugin'import type { TaskActivityRecorder } from '@shared/types/task-activity'import { app, ipcMain } from 'electron'import { CancellationTokenSource } from 'vscode-jsonrpc'+import { registerTrustedIpcHandler } from '../ipc/trusted-ipc'import { i18n } from '../lib/i18n'import { isPackagedLinuxFlatpak } from './flatpak-environment'import { resolveNativeHostBinaryPath } from './native-host-path'@@ -680,7 +681,7 @@ export async function bootstrapBridge(args: {channel: string,listener: Parameters<typeof ipcMain.handle>[1]): void => {- ipcMain.handle(channel, (...listenerArgs) =>+ registerTrustedIpcHandler(channel, (...listenerArgs) =>args.trackAsyncWork(async () => listener(...listenerArgs)))installedIpcChannels.push(channel)diff --git a/src/main/index.ts b/src/main/index.tsindex 6e05e374..64ea0b49 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -158,6 +158,7 @@ import {LiquidGlassController,shouldEnableLiquidGlassByDefault,} from './window/liquid-glass'+import { initializeRendererUrlPolicy } from './window/renderer-url-policy'import { WindowManager } from './window/window-manager'// ─── Platform Early Setup ───────────────────────────────@@ -184,6 +185,11 @@ if (process.platform === 'linux') {}const platform = createElectronPlatformServices()+const rendererUrlPolicy = initializeRendererUrlPolicy({+ isPackaged: app.isPackaged,+ appPath: app.getAppPath(),+ devServerUrl: app.isPackaged ? null : process.env.VITE_DEV_SERVER_URL,+})// ─── Logger ─────────────────────────────────────────────@@ -481,13 +487,7 @@ function loadWindowUrl(win: BrowserWindow, route: string) {const params = new URLSearchParams(query)params.set('locale', resolvedApplicationLocale)const localizedRoute = `${pathname}?${params.toString()}`- const devServerUrl = process.env.VITE_DEV_SERVER_URL- if (devServerUrl) {- win.loadURL(`${devServerUrl}${localizedRoute}`)- } else {- const search = `?${params.toString()}`- win.loadFile(path.join(__dirname, '../renderer/index.html'), { search })- }+ rendererUrlPolicy.loadWindow(win, localizedRoute)}// Send an IPC event to the add-task window without racing the renderer@@ -1334,6 +1334,7 @@ async function initializeMainProcess(): Promise<void> {preloadPath: path.join(__dirname, '../preload/preload.cjs'),loadUrl: loadWindowUrl,liquidGlass,+ rendererUrlPolicy,resolveOpenTarget: (requested) =>!gate.isAccepted() && requested !== 'onboarding'? 'onboarding'@@ -2316,7 +2317,7 @@ const requestForcedQuit = (reason: string) => {}registerTerminationSignalHandlers(requestForcedQuit)-if (process.env.VITE_DEV_SERVER_URL) {+if (rendererUrlPolicy.isDevelopmentServer) {registerDevShutdownHandler(() => requestForcedQuit('dev-runner'))}diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.tsindex 2a8585c3..f4d55c38 100644--- a/src/main/ipc/commands.test.ts+++ b/src/main/ipc/commands.test.ts@@ -40,6 +40,15 @@ vi.mock('electron', () => ({},}))+// Sender trust is covered by trusted-ipc.test.ts. Keep these handler tests+// focused on command dispatch while preserving the same registration seam.+vi.mock('./trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ listener: (...args: unknown[]) => unknown+ ) => ipcHandleMock(channel, listener),+}))+function fakeCtx() {// Build the rpc spies first, then wrap them in a real Aria2Adapter so the// create path (handleCreateTask → adapter.createDownload/addTorrent)@@ -180,6 +189,14 @@ function fakeCtx() {},pluginHost: {allActive: vi.fn(() => []),+ deactivate: vi.fn().mockResolvedValue(undefined),+ isQuiescent: vi.fn(() => true),+ },+ pluginInstaller: {+ stage: vi.fn(),+ commit: vi.fn().mockResolvedValue({ pluginId: 'test.plugin' }),+ cancel: vi.fn().mockResolvedValue(undefined),+ uninstall: vi.fn().mockResolvedValue(undefined),},userDataDir: '/tmp/userdata',pluginsDir: '/tmp/userdata/plugins',@@ -245,6 +262,31 @@ describe('buildCommandHandlers', () => {})+ it('passes PluginHost through commit and uninstall lifecycle commands', async () => {+ const ctx = fakeCtx()+ const handlers = buildCommandHandlers(ctx as unknown as CommandContext)++ await expect(+ handlers[Commands.ConfirmPluginInstall]?.({+ stagingId: 's1',+ grants: { notify: 'denied' },+ })+ ).resolves.toEqual({ ok: true, pluginId: 'test.plugin' })+ await expect(+ handlers[Commands.UninstallPlugin]?.({ pluginId: 'test.plugin' })+ ).resolves.toEqual({ ok: true })++ expect(ctx.pluginInstaller.commit).toHaveBeenCalledWith(+ 's1',+ { notify: 'denied' },+ ctx.pluginHost+ )+ expect(ctx.pluginInstaller.uninstall).toHaveBeenCalledWith(+ 'test.plugin',+ ctx.pluginHost+ )+ })+it('returns a map keyed by Commands channels', () => {// @ts-expect-error — fake ctx is partial; handler map keys are what we care aboutconst handlers = buildCommandHandlers(fakeCtx())diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.tsindex 83ee0858..5400b13b 100644--- a/src/main/ipc/commands.ts+++ b/src/main/ipc/commands.ts@@ -97,6 +97,7 @@ import { createSetSelectedFilesHandler } from './commands/set-selected-files'import { createUpdateGeoIPDatabaseHandler } from './commands/update-geo-ip-database'import { NatCommandHandlers } from './nat-commands'import { applyNatPrivacyGate } from './nat-settings-gate'+import { registerTrustedIpcHandler } from './trusted-ipc'const execFileAsync = promisify(execFile)@@ -1046,7 +1047,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {}},- [Commands.RevealInFolder]: createRevealInFolderHandler({ shell }),+ [Commands.RevealInFolder]: createRevealInFolderHandler({+ shell,+ getTask: (taskId) => taskManager.getById(taskId),+ }),[Commands.EnableNat]: async () => natHandlers.enable(),[Commands.DisableNat]: async () => natHandlers.disable(),@@ -1254,7 +1258,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {const result = await pluginInstaller.stage(moextPath,toSourceInput(parsed),- { expect }+ { expect, runtimeHost: pluginHost })if (result.committed && result.pluginId) {eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })@@ -1341,7 +1345,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {const parsed = confirmPluginInstallPayloadSchema.parse(payload)const { pluginId } = await pluginInstaller.commit(parsed.stagingId,- parsed.grants+ parsed.grants,+ pluginHost)eventBus.emit(Events.PluginInstalled, { pluginId })return { ok: true, pluginId }@@ -1370,7 +1375,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {[Commands.UninstallPlugin]: async (payload: unknown) => {const parsed = z.object({ pluginId: z.string().min(1) }).parse(payload)- await pluginInstaller.uninstall(parsed.pluginId)+ await pluginInstaller.uninstall(parsed.pluginId, pluginHost)await settingsManager.removePluginConfig(parsed.pluginId)eventBus.emit(Events.PluginUninstalled, { pluginId: parsed.pluginId })return { ok: true }@@ -1406,14 +1411,14 @@ export function registerCommandHandlers(ctx: CommandContext): () => void {channel === Commands.CloseCurrentWindow ||channel === Commands.ResizeWindow) {- ipcMain.handle(channel, (event, ...args) =>+ registerTrustedIpcHandler(channel, (event, ...args) =>invoke(() =>// biome-ignore lint/suspicious/noExplicitAny: sender forwarded explicitly(handler as any)(event.sender, ...args)))} else {- ipcMain.handle(channel, async (_event, ...args) =>+ registerTrustedIpcHandler(channel, async (_event, ...args) =>invoke(() => handler(...args)))}diff --git a/src/main/ipc/commands/reveal-in-folder.test.ts b/src/main/ipc/commands/reveal-in-folder.test.tsindex 19fc9eea..c6f8d60e 100644--- a/src/main/ipc/commands/reveal-in-folder.test.ts+++ b/src/main/ipc/commands/reveal-in-folder.test.ts@@ -2,19 +2,77 @@ import { describe, expect, it, vi } from 'vitest'import { createRevealInFolderHandler } from './reveal-in-folder'describe('revealInFolder', () => {- it('calls electron shell.showItemInFolder with the provided path', async () => {+ it('reveals the current path owned by the requested task', async () => {const shell = { showItemInFolder: vi.fn() }- const handler = createRevealInFolderHandler({ shell })- await handler({ path: '/Users/me/Downloads/file.iso' })+ const handler = createRevealInFolderHandler({+ shell,+ getTask: (taskId) =>+ taskId === 'task-1'+ ? { diskPath: '/Users/me/Downloads/file.iso' }+ : undefined,+ })++ await handler({ taskId: 'task-1' })+expect(shell.showItemInFolder).toHaveBeenCalledWith('/Users/me/Downloads/file.iso')})- it('throws AppError when path is empty', async () => {+ it('rejects an unknown task instead of accepting a renderer path', async () => {+ const shell = { showItemInFolder: vi.fn() }+ const handler = createRevealInFolderHandler({+ shell,+ getTask: () => undefined,+ })++ await expect(handler({ taskId: 'missing' })).rejects.toThrow(/not found/i)+ expect(shell.showItemInFolder).not.toHaveBeenCalled()+ })++ it.each([+ '\\\\server\\share\\downloads\\file.iso',+ '//server/share/downloads/file.iso',+ ])('allows a task-owned UNC path: %s', async (diskPath) => {+ const shell = { showItemInFolder: vi.fn() }+ const handler = createRevealInFolderHandler({+ shell,+ getTask: () => ({ diskPath }),+ })++ await handler({ taskId: 'task-unc' })++ expect(shell.showItemInFolder).toHaveBeenCalledWith(diskPath)+ })++ it.each([+ '\\\\?\\C:\\downloads\\file.iso',+ '\\\\.\\PhysicalDrive0',+ '\\??\\C:\\downloads\\file.iso',+ '//?/C:/downloads/file.iso',+ ])('rejects a Windows device namespace: %s', async (diskPath) => {+ const shell = { showItemInFolder: vi.fn() }+ const handler = createRevealInFolderHandler({+ shell,+ getTask: () => ({ diskPath }),+ })++ await expect(handler({ taskId: 'task-device' })).rejects.toThrow(+ /invalid path/i+ )+ expect(shell.showItemInFolder).not.toHaveBeenCalled()+ })++ it('rejects a relative task path', async () => {const shell = { showItemInFolder: vi.fn() }- const handler = createRevealInFolderHandler({ shell })- await expect(handler({ path: '' })).rejects.toThrow(/invalid/i)+ const handler = createRevealInFolderHandler({+ shell,+ getTask: () => ({ diskPath: '../downloads/file.iso' }),+ })++ await expect(handler({ taskId: 'task-relative' })).rejects.toThrow(+ /invalid path/i+ )expect(shell.showItemInFolder).not.toHaveBeenCalled()})})diff --git a/src/main/ipc/commands/reveal-in-folder.ts b/src/main/ipc/commands/reveal-in-folder.tsindex 5fc0165d..8036c500 100644--- a/src/main/ipc/commands/reveal-in-folder.ts+++ b/src/main/ipc/commands/reveal-in-folder.ts@@ -1,21 +1,55 @@+import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'+import type { DownloadTask } from '@shared/types/task'export interface RevealInFolderDeps {shell: { showItemInFolder: (path: string) => void }+ getTask: (taskId: string) => Pick<DownloadTask, 'diskPath'> | undefined}export interface RevealInFolderPayload {- path: string+ taskId: string+}++function isWindowsDeviceNamespace(value: string): boolean {+ const normalized = value.replaceAll('\\', '/')+ return (+ normalized.startsWith('//?/') ||+ normalized.startsWith('//./') ||+ normalized.startsWith('/??/') ||+ normalized.startsWith('//??/')+ )}export function createRevealInFolderHandler(deps: RevealInFolderDeps) {- return async ({ path }: RevealInFolderPayload): Promise<void> => {- if (!path) {+ return async (payload: RevealInFolderPayload): Promise<void> => {+ const taskId = payload?.taskId+ if (typeof taskId !== 'string' || taskId.trim() === '') {+ throw new AppError(+ ErrorCode.IpcInvalidPayload,+ 'revealInFolder: invalid task id'+ )+ }++ const task = deps.getTask(taskId)+ if (!task) {+ throw new AppError(ErrorCode.TaskNotFound, `Task not found: ${taskId}`)+ }++ const taskPath = task.diskPath+ if (+ typeof taskPath !== 'string' ||+ taskPath.trim() === '' ||+ taskPath.includes('\0') ||+ (!path.isAbsolute(taskPath) && !path.win32.isAbsolute(taskPath)) ||+ isWindowsDeviceNamespace(taskPath)+ ) {throw new AppError(ErrorCode.IpcInvalidPayload,- 'revealInFolder: invalid empty path'+ 'revealInFolder: task has an invalid path')}- deps.shell.showItemInFolder(path)++ deps.shell.showItemInFolder(taskPath)}}diff --git a/src/main/ipc/disclaimer.test.ts b/src/main/ipc/disclaimer.test.tsindex 50fb02ea..3959f9fb 100644--- a/src/main/ipc/disclaimer.test.ts+++ b/src/main/ipc/disclaimer.test.ts@@ -12,6 +12,13 @@ vi.mock('electron', () => ({ipcMain: { handle, removeHandler },}))+vi.mock('./trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ listener: (...args: unknown[]) => unknown+ ) => handle(channel, listener),+}))+import { buildDisclaimerHandlers, registerDisclaimerIpc } from './disclaimer'function createDeps() {diff --git a/src/main/ipc/disclaimer.ts b/src/main/ipc/disclaimer.tsindex 2039e0ca..dd6546fd 100644--- a/src/main/ipc/disclaimer.ts+++ b/src/main/ipc/disclaimer.ts@@ -6,6 +6,7 @@ import type { AppSettings } from '@shared/types/settings'import { ipcMain } from 'electron'import type { DisclaimerGate } from '../onboarding/disclaimer-gate'import type { WindowManager } from '../window/window-manager'+import { registerTrustedIpcHandler } from './trusted-ipc'export interface DisclaimerIpcDeps {gate: Pick<DisclaimerGate, 'accept'>@@ -53,7 +54,9 @@ export function registerDisclaimerIpc(deps: DisclaimerIpcDeps): () => void {const channels = Object.keys(handlers)for (const [channel, handler] of Object.entries(handlers)) {- ipcMain.handle(channel, async (_event, ...args) => handler(...args))+ registerTrustedIpcHandler(channel, async (_event, ...args) =>+ handler(...args)+ )}return () => {diff --git a/src/main/ipc/notifications.test.ts b/src/main/ipc/notifications.test.tsindex b374e2a4..8ee54309 100644--- a/src/main/ipc/notifications.test.ts+++ b/src/main/ipc/notifications.test.ts@@ -13,6 +13,13 @@ vi.mock('electron', () => ({ipcMain: { handle, removeHandler },}))+vi.mock('./trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ listener: (...args: unknown[]) => unknown+ ) => handle(channel, listener),+}))+import {buildNotificationHandlers,registerNotificationIpc,diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.tsindex 5ba601d0..681502d8 100644--- a/src/main/ipc/notifications.ts+++ b/src/main/ipc/notifications.ts@@ -3,6 +3,7 @@ import { Commands } from '@shared/protocol/commands'import type { Handler } from '@shared/protocol/handler-types'import { Queries } from '@shared/protocol/queries'import { ipcMain } from 'electron'+import { registerTrustedIpcHandler } from './trusted-ipc'export interface NotificationIpcDeps {notificationCenter: Pick<@@ -36,7 +37,7 @@ export function registerNotificationIpc(deps: NotificationIpcDeps): () => void {const channels = Object.keys(handlers)for (const [channel, handler] of Object.entries(handlers)) {- ipcMain.handle(channel, async (_event, ...args) =>+ registerTrustedIpcHandler(channel, async (_event, ...args) =>deps.trackAsyncWork? deps.trackAsyncWork(async () => handler(...args)): handler(...args)diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.tsindex 9a92dc92..706c089e 100644--- a/src/main/ipc/queries.test.ts+++ b/src/main/ipc/queries.test.ts@@ -20,8 +20,23 @@ import { makeElectronFfmpegDetect } from '../plugin/ffmpeg-detect-electron'import type { QueryContext } from './queries'import { buildQueryHandlers, registerQueryHandlers } from './queries'+const ipcMocks = vi.hoisted(() => ({+ handle: vi.fn(),+ removeHandler: vi.fn(),+}))+vi.mock('electron', () => ({- ipcMain: { handle: vi.fn(), removeHandler: vi.fn() },+ ipcMain: {+ handle: ipcMocks.handle,+ removeHandler: ipcMocks.removeHandler,+ },+}))++vi.mock('./trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ listener: (...args: unknown[]) => unknown+ ) => ipcMocks.handle(channel, listener),}))vi.mock('../plugin/ffmpeg-detect-electron', () => ({diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.tsindex a1d18cbe..35ef569c 100644--- a/src/main/ipc/queries.ts+++ b/src/main/ipc/queries.ts@@ -51,6 +51,7 @@ import { createGetTaskBtTrackerHandler } from './queries/get-task-bt-tracker'import { createGetTaskFilesHandler } from './queries/get-task-files'import { createGetTaskPeersHandler } from './queries/get-task-peers'import { createGetTaskPiecesHandler } from './queries/get-task-pieces'+import { registerTrustedIpcHandler } from './trusted-ipc'export interface QueryContext {cliToolService: Pick<CliToolService, 'getStatus'>@@ -296,7 +297,7 @@ export function registerQueryHandlers(ctx: QueryContext): () => void {const channels = Object.keys(handlers)for (const [channel, handler] of Object.entries(handlers)) {- ipcMain.handle(channel, async (_event, ...args) => {+ registerTrustedIpcHandler(channel, async (_event, ...args) => {const invoke = () =>ctx.trackAsyncWork? ctx.trackAsyncWork(async () => handler(...args))diff --git a/src/main/ipc/trusted-ipc.test.ts b/src/main/ipc/trusted-ipc.test.tsnew file mode 100644index 00000000..6c7b9495--- /dev/null+++ b/src/main/ipc/trusted-ipc.test.ts@@ -0,0 +1,94 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ fromWebContents: vi.fn(),+ handle: vi.fn(),+}))++vi.mock('electron', () => ({+ BrowserWindow: {+ fromWebContents: (...args: unknown[]) => mocks.fromWebContents(...args),+ },+ ipcMain: { handle: mocks.handle },+}))++import { initializeRendererUrlPolicy } from '../window/renderer-url-policy'+import {+ assertTrustedIpcSender,+ isTrustedRendererUrl,+ registerTrustedIpcHandler,+} from './trusted-ipc'++const rendererUrl =+ 'file:///opt/Motrix/resources/app.asar/dist/renderer/index.html?w=main'++initializeRendererUrlPolicy({+ isPackaged: true,+ appPath: '/opt/Motrix/resources/app.asar',+})++function trustedEvent(url = rendererUrl) {+ const frame = { url }+ const sender = {+ mainFrame: frame,+ getURL: vi.fn(() => url),+ isDestroyed: vi.fn(() => false),+ }+ mocks.fromWebContents.mockReturnValue({+ webContents: sender,+ isDestroyed: vi.fn(() => false),+ })+ return {+ sender,+ senderFrame: frame,+ } as unknown as Electron.IpcMainInvokeEvent+}++describe('trusted IPC sender validation', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('accepts only the packaged renderer entry point', () => {+ expect(isTrustedRendererUrl(rendererUrl)).toBe(true)+ expect(+ isTrustedRendererUrl(+ 'file:///opt/Motrix/resources/app.asar/dist/renderer/other.html'+ )+ ).toBe(false)+ expect(isTrustedRendererUrl('https://motrix.app/')).toBe(false)+ })++ it('accepts the current main frame of an owned BrowserWindow', () => {+ expect(() => assertTrustedIpcSender(trustedEvent())).not.toThrow()+ })++ it('rejects subframes, detached windows, and navigated senders', () => {+ const subframe = trustedEvent()+ Object.assign(subframe, { senderFrame: { url: rendererUrl } })+ expect(() => assertTrustedIpcSender(subframe)).toThrow('untrusted renderer')++ const detached = trustedEvent()+ mocks.fromWebContents.mockReturnValue(null)+ expect(() => assertTrustedIpcSender(detached)).toThrow('untrusted renderer')++ expect(() =>+ assertTrustedIpcSender(trustedEvent('https://attacker.example/'))+ ).toThrow('untrusted renderer')+ })++ it('validates before dispatching a registered handler', async () => {+ const listener = vi.fn().mockResolvedValue('ok')+ registerTrustedIpcHandler('query:test', listener)+ const wrapper = mocks.handle.mock.calls[0]?.[1]+ const event = trustedEvent()++ await expect(wrapper(event, 'value')).resolves.toBe('ok')+ expect(listener).toHaveBeenCalledWith(event, 'value')++ await expect(+ wrapper(trustedEvent('https://attacker.example/'))+ ).rejects.toThrow('untrusted renderer')+ expect(listener).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/main/ipc/trusted-ipc.ts b/src/main/ipc/trusted-ipc.tsnew file mode 100644index 00000000..984273cf--- /dev/null+++ b/src/main/ipc/trusted-ipc.ts@@ -0,0 +1,46 @@+import { BrowserWindow, ipcMain } from 'electron'+import {+ getRendererUrlPolicy,+ type RendererUrlPolicy,+} from '../window/renderer-url-policy'++export function isTrustedRendererUrl(+ rawUrl: string,+ policy: RendererUrlPolicy = getRendererUrlPolicy()+): boolean {+ return policy.isTrustedUrl(rawUrl)+}++export function assertTrustedIpcSender(+ event: Electron.IpcMainInvokeEvent+): void {+ const sender = event.sender+ const senderFrame = event.senderFrame+ if (!sender || !senderFrame || sender.isDestroyed()) {+ throw new Error('Blocked IPC call from an untrusted renderer')+ }++ const mainFrame = sender.mainFrame+ const owner = BrowserWindow.fromWebContents(sender)+ if (+ !owner ||+ owner.isDestroyed() ||+ owner.webContents !== sender ||+ !mainFrame ||+ senderFrame !== mainFrame ||+ sender.getURL() !== senderFrame.url ||+ !isTrustedRendererUrl(senderFrame.url)+ ) {+ throw new Error('Blocked IPC call from an untrusted renderer')+ }+}++export function registerTrustedIpcHandler(+ channel: string,+ listener: Parameters<typeof ipcMain.handle>[1]+): void {+ ipcMain.handle(channel, async (event, ...args) => {+ assertTrustedIpcSender(event)+ return listener(event, ...args)+ })+}diff --git a/src/main/window/renderer-url-policy.test.ts b/src/main/window/renderer-url-policy.test.tsnew file mode 100644index 00000000..2217d5c9--- /dev/null+++ b/src/main/window/renderer-url-policy.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it, vi } from 'vitest'++import { createRendererUrlPolicy } from './renderer-url-policy'++function createWindowLoader() {+ return {+ loadFile: vi.fn().mockResolvedValue(undefined),+ loadURL: vi.fn().mockResolvedValue(undefined),+ }+}++describe('renderer URL policy', () => {+ it('ignores a hostile dev-server environment in packaged builds', () => {+ const policy = createRendererUrlPolicy({+ isPackaged: true,+ appPath: '/opt/Motrix/resources/app.asar',+ devServerUrl: 'https://attacker.example/',+ })+ const win = createWindowLoader()++ policy.loadWindow(win as never, '?w=main&locale=en-US')++ expect(Object.isFrozen(policy)).toBe(true)+ expect(policy.isDevelopmentServer).toBe(false)+ expect(policy.devServerOrigin).toBeNull()+ expect(win.loadURL).not.toHaveBeenCalled()+ expect(win.loadFile).toHaveBeenCalledWith(+ '/opt/Motrix/resources/app.asar/dist/renderer/index.html',+ { search: '?w=main&locale=en-US' }+ )+ expect(+ policy.isTrustedUrl(+ 'file:///opt/Motrix/resources/app.asar/dist/renderer/index.html?w=main'+ )+ ).toBe(true)+ expect(policy.isTrustedUrl('https://attacker.example/')).toBe(false)+ })++ it.each([+ 'http://0.0.0.0:5173/',+ 'http://192.168.1.20:5173/',+ 'https://attacker.example/',+ ])('rejects a non-loopback development origin: %s', (devServerUrl) => {+ expect(() =>+ createRendererUrlPolicy({+ isPackaged: false,+ appPath: '/app',+ devServerUrl,+ })+ ).toThrow('loopback hostname')+ })++ it.each([+ 'http://localhost:5173/',+ 'http://127.0.0.1:5173/',+ 'https://[::1]:5173/',+ ])('trusts only the resolved loopback origin: %s', (devServerUrl) => {+ const policy = createRendererUrlPolicy({+ isPackaged: false,+ appPath: '/app',+ devServerUrl,+ })+ const win = createWindowLoader()++ policy.loadWindow(win as never, '?w=add-task&locale=zh-CN')++ expect(policy.devServerOrigin).toBe(new URL(devServerUrl).origin)+ expect(win.loadFile).not.toHaveBeenCalled()+ expect(win.loadURL).toHaveBeenCalledWith(+ `${new URL(devServerUrl).origin}/?w=add-task&locale=zh-CN`+ )+ expect(policy.isTrustedUrl(`${new URL(devServerUrl).origin}/?w=main`)).toBe(+ true+ )+ expect(policy.isTrustedUrl('http://localhost:6553/')).toBe(false)+ })++ it.each([+ 'file:///tmp/dev.html',+ 'ftp://localhost:5173/',+ 'http://localhost:5173/path',+ 'http://localhost:5173/?token=unsafe',+ ])('rejects a malformed development origin: %s', (devServerUrl) => {+ expect(() =>+ createRendererUrlPolicy({+ isPackaged: false,+ appPath: '/app',+ devServerUrl,+ })+ ).toThrow(/VITE_DEV_SERVER_URL/)+ })++ it('rejects renderer routes that are not query-only', () => {+ const policy = createRendererUrlPolicy({+ isPackaged: true,+ appPath: '/app',+ })+ const win = createWindowLoader()++ expect(() => policy.loadWindow(win as never, '/other.html')).toThrow(+ 'query string'+ )+ expect(() => policy.loadWindow(win as never, '?w=main#fragment')).toThrow(+ 'query string'+ )+ })+})diff --git a/src/main/window/renderer-url-policy.ts b/src/main/window/renderer-url-policy.tsnew file mode 100644index 00000000..cc514dbe--- /dev/null+++ b/src/main/window/renderer-url-policy.ts@@ -0,0 +1,128 @@+import path from 'node:path'+import { pathToFileURL } from 'node:url'+import type { BrowserWindow } from 'electron'++const RENDERER_ROUTE_BASE = new URL('https://renderer.invalid/')+const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]'])++export interface RendererUrlPolicyOptions {+ isPackaged: boolean+ appPath: string+ devServerUrl?: string | null+}++export interface RendererUrlPolicy {+ readonly rendererFilePath: string+ readonly devServerOrigin: string | null+ readonly isDevelopmentServer: boolean+ isTrustedUrl(rawUrl: string): boolean+ loadWindow(win: BrowserWindow, route: string): void+}++function parseDevServerOrigin(rawUrl: string): URL {+ let url: URL+ try {+ url = new URL(rawUrl)+ } catch {+ throw new Error('VITE_DEV_SERVER_URL must be a valid loopback origin')+ }++ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ throw new Error('VITE_DEV_SERVER_URL must use HTTP or HTTPS')+ }+ if (!LOOPBACK_HOSTNAMES.has(url.hostname)) {+ throw new Error('VITE_DEV_SERVER_URL must use a loopback hostname')+ }+ if (+ url.username ||+ url.password ||+ url.pathname !== '/' ||+ url.search ||+ url.hash+ ) {+ throw new Error('VITE_DEV_SERVER_URL must contain only an origin')+ }++ return url+}++function parseRendererRoute(route: string): string {+ const parsed = new URL(route, RENDERER_ROUTE_BASE)+ if (+ parsed.origin !== RENDERER_ROUTE_BASE.origin ||+ parsed.pathname !== '/' ||+ parsed.hash+ ) {+ throw new Error('Renderer routes must contain only a query string')+ }+ return parsed.search+}++export function createRendererUrlPolicy(+ options: RendererUrlPolicyOptions+): RendererUrlPolicy {+ const rendererFilePath = path.join(+ options.appPath,+ 'dist/renderer/index.html'+ )+ const rendererFileUrl = new URL(pathToFileURL(rendererFilePath).href)++ // Packaged applications must never turn an inherited development variable+ // into executable renderer content. Unpackaged builds keep the existing Vite+ // flow, restricted to the exact configured loopback origin.+ const devServer =+ !options.isPackaged && options.devServerUrl+ ? parseDevServerOrigin(options.devServerUrl)+ : null+ const devServerOrigin = devServer?.origin ?? null++ return Object.freeze<RendererUrlPolicy>({+ rendererFilePath,+ devServerOrigin,+ isDevelopmentServer: devServer !== null,+ isTrustedUrl(rawUrl) {+ let actual: URL+ try {+ actual = new URL(rawUrl)+ } catch {+ return false+ }++ if (actual.username || actual.password) return false+ if (devServerOrigin) return actual.origin === devServerOrigin++ return (+ actual.protocol === 'file:' &&+ actual.host === rendererFileUrl.host &&+ actual.pathname === rendererFileUrl.pathname+ )+ },+ loadWindow(win, route) {+ const search = parseRendererRoute(route)+ if (devServerOrigin) {+ void win.loadURL(`${devServerOrigin}/${search}`)+ return+ }+ void win.loadFile(rendererFilePath, { search })+ },+ })+}++let runtimeRendererUrlPolicy: RendererUrlPolicy | null = null++export function initializeRendererUrlPolicy(+ options: RendererUrlPolicyOptions+): RendererUrlPolicy {+ if (runtimeRendererUrlPolicy) {+ throw new Error('Renderer URL policy is already initialized')+ }+ runtimeRendererUrlPolicy = createRendererUrlPolicy(options)+ return runtimeRendererUrlPolicy+}++export function getRendererUrlPolicy(): RendererUrlPolicy {+ if (!runtimeRendererUrlPolicy) {+ throw new Error('Renderer URL policy is not initialized')+ }+ return runtimeRendererUrlPolicy+}diff --git a/src/main/window/window-manager.test.ts b/src/main/window/window-manager.test.tsindex 465d8f61..55730284 100644--- a/src/main/window/window-manager.test.ts+++ b/src/main/window/window-manager.test.ts@@ -97,9 +97,15 @@ vi.mock('electron', () => {import type { SettingsManager } from '@core/settings/settings-manager'import { BrowserWindow } from 'electron'import type { LiquidGlassController } from './liquid-glass'+import { initializeRendererUrlPolicy } from './renderer-url-policy'import { WINDOW_CONFIGS } from './window-configs'import { WindowManager } from './window-manager'+initializeRendererUrlPolicy({+ isPackaged: true,+ appPath: '/app',+})+function createMockSettingsManager(windowState: Record<string, unknown> = {}): SettingsManager {@@ -129,6 +135,52 @@ describe('WindowManager', () => {expect(wm.get('main')).toBe(win)})+ it('uses the explicit secure Electron renderer defaults', () => {+ const wm = new WindowManager({+ settingsManager: createMockSettingsManager(),+ preloadPath: '/fake/preload.cjs',+ loadUrl: vi.fn(),+ })++ const win = wm.open('main')+ const options = (win as unknown as { options: Record<string, unknown> })+ .options++ expect(options.webPreferences).toEqual({+ preload: '/fake/preload.cjs',+ nodeIntegration: false,+ contextIsolation: true,+ sandbox: true,+ })+ })++ it('blocks navigation and redirects outside the trusted renderer URL', () => {+ const wm = new WindowManager({+ settingsManager: createMockSettingsManager(),+ preloadPath: '/fake/preload.cjs',+ loadUrl: vi.fn(),+ })+ const win = wm.open('main')+ const on = win.webContents.on as ReturnType<typeof vi.fn>+ const navigate = on.mock.calls.find(+ ([event]) => event === 'will-navigate'+ )?.[1]+ const redirect = on.mock.calls.find(+ ([event]) => event === 'will-redirect'+ )?.[1]+ const trustedEvent = { preventDefault: vi.fn() }+ const externalEvent = { preventDefault: vi.fn() }+ const redirectEvent = { preventDefault: vi.fn() }++ navigate?.(trustedEvent, 'file:///app/dist/renderer/index.html?w=add-task')+ navigate?.(externalEvent, 'https://attacker.example/')+ redirect?.(redirectEvent, 'file:///tmp/attacker.html')++ expect(trustedEvent.preventDefault).not.toHaveBeenCalled()+ expect(externalEvent.preventDefault).toHaveBeenCalledOnce()+ expect(redirectEvent.preventDefault).toHaveBeenCalledOnce()+ })+it('creates the main window with Liquid Glass chrome when enabled', () => {const sm = createMockSettingsManager()const liquidGlass = {diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.tsindex fe9439fa..6a338a03 100644--- a/src/main/window/window-manager.ts+++ b/src/main/window/window-manager.ts@@ -6,6 +6,10 @@ import type { WindowBounds } from '@shared/types/settings'import { BrowserWindow, screen, shell } from 'electron'import type { LiquidGlassController } from './liquid-glass'import { buildPlatformOptions } from './platform-options'+import {+ getRendererUrlPolicy,+ type RendererUrlPolicy,+} from './renderer-url-policy'import type { WindowId } from './window-configs'import { WINDOW_CONFIGS } from './window-configs'@@ -25,6 +29,8 @@ export interface WindowManagerDeps {resolveOpenTarget?: (requested: WindowId) => WindowId/** Invoked when the OS signals session end (Windows window 'session-end'). */onSessionEnd?: () => void+ /** Frozen renderer trust policy shared with IPC sender validation. */+ rendererUrlPolicy?: RendererUrlPolicy}export class WindowManager {@@ -32,6 +38,7 @@ export class WindowManager {private deps: WindowManagerDepsprivate willQuit = falseprivate boundsTimers = new Map<WindowId, ReturnType<typeof setTimeout>>()+ private rendererUrlPolicy: RendererUrlPolicy// The window the user most recently asked to be brought to the// foreground. Read by each window's `ready-to-show` handler: a window// that finishes loading after this changes (e.g. main rendering after@@ -41,6 +48,7 @@ export class WindowManager {constructor(deps: WindowManagerDeps) {this.deps = deps+ this.rendererUrlPolicy = deps.rendererUrlPolicy ?? getRendererUrlPolicy()}open(id: WindowId, options: { show?: boolean } = {}): BrowserWindow {@@ -308,6 +316,9 @@ export class WindowManager {...platformOpts,webPreferences: {preload: this.deps.preloadPath,+ nodeIntegration: false,+ contextIsolation: true,+ sandbox: true,},})@@ -325,6 +336,17 @@ export class WindowManager {return { action: 'deny' }})+ const preventUntrustedNavigation = (+ event: Electron.Event,+ url: string+ ): void => {+ if (this.rendererUrlPolicy.isTrustedUrl(url)) return+ event.preventDefault()+ log.warn({ url }, 'blocked renderer navigation outside trusted entry')+ }+ win.webContents.on('will-navigate', preventUntrustedNavigation)+ win.webContents.on('will-redirect', preventUntrustedNavigation)+if (show) {win.once('ready-to-show', () => {if (win.isDestroyed()) returndiff --git a/src/preload/api.ts b/src/preload/api.tsindex 04b9ede9..495bb412 100644--- a/src/preload/api.ts+++ b/src/preload/api.ts@@ -1,14 +1,33 @@+import type {+ BridgeCommand,+ BridgeEvent,+ BridgeQuery,+} from '../shared/protocol/bridge'import type { CommandChannel } from '../shared/protocol/commands'-import type { EventChannel } from '../shared/protocol/events'+import type { EventChannel, Events } from '../shared/protocol/events'import type { QueryChannel } from '../shared/protocol/queries'+export type PluginLogEventChannel = `${typeof Events.PluginLog}:${string}`+export type RendererInvokeChannel =+ | CommandChannel+ | QueryChannel+ | BridgeCommand+ | BridgeQuery+export type RendererEventChannel =+ | EventChannel+ | BridgeEvent+ | PluginLogEventChannel+export interface MotrixAPI {- invoke(- channel: CommandChannel | QueryChannel,- ...args: unknown[]- ): Promise<unknown>- on(channel: EventChannel, callback: (...args: unknown[]) => void): void- off(channel: EventChannel, callback: (...args: unknown[]) => void): void+ invoke(channel: RendererInvokeChannel, ...args: unknown[]): Promise<unknown>+ on(+ channel: RendererEventChannel,+ callback: (...args: unknown[]) => void+ ): void+ off(+ channel: RendererEventChannel,+ callback: (...args: unknown[]) => void+ ): voidplatform: NodeJS.Platform// Electron 32+ removed File.path; webUtils.getPathForFile resolves the// absolute path of a File obtained from <input type="file"> or drag-drop.diff --git a/src/preload/preload.test.ts b/src/preload/preload.test.tsindex 45b6256c..faa6833e 100644--- a/src/preload/preload.test.ts+++ b/src/preload/preload.test.ts@@ -1,10 +1,18 @@+import {+ BridgeCommands,+ BridgeEvents,+ BridgeQueries,+} from '@shared/protocol/bridge'+import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'import { beforeEach, describe, expect, it, vi } from 'vitest'type IpcListener = (event: unknown, ...args: unknown[]) => voidconst mocks = vi.hoisted(() => ({exposed: undefined as Window['motrix'] | undefined,+ invoke: vi.fn(),listeners: new Map<string, Set<IpcListener>>(),on: vi.fn((channel: string, listener: IpcListener) => {let channelListeners = mocks.listeners.get(channel)@@ -26,7 +34,7 @@ vi.mock('electron', () => ({}),},ipcRenderer: {- invoke: vi.fn(),+ invoke: mocks.invoke,on: mocks.on,removeListener: mocks.removeListener,},@@ -126,3 +134,68 @@ describe('preload wrapperMap (F10: same callback on two channels)', () => {expect(mocks.listeners.get(channelB)?.size).toBe(0)})})++describe('preload IPC channel allowlist', () => {+ beforeEach(async () => {+ vi.resetModules()+ vi.clearAllMocks()+ mocks.exposed = undefined+ mocks.listeners.clear()+ await import('./preload')+ })++ it('forwards every declared command and query, including CLI install', () => {+ const channels = [+ ...Object.values(Commands),+ ...Object.values(Queries),+ ...Object.values(BridgeCommands),+ ...Object.values(BridgeQueries),+ ]++ for (const channel of channels) {+ mocks.exposed?.invoke(channel, 'argument')+ }++ expect(mocks.invoke).toHaveBeenCalledTimes(channels.length)+ expect(mocks.invoke).toHaveBeenCalledWith(+ Commands.InstallCliTool,+ 'argument'+ )+ })++ it('blocks undeclared invoke channels before Electron sees them', () => {+ expect(() => mocks.exposed?.invoke('command:notDeclared' as never)).toThrow(+ 'undeclared IPC invoke channel'+ )+ expect(mocks.invoke).not.toHaveBeenCalled()+ })++ it('registers every declared app and bridge event', () => {+ const callback = vi.fn()+ const channels = [...Object.values(Events), ...Object.values(BridgeEvents)]++ for (const channel of channels) {+ mocks.exposed?.on(channel, callback)+ }++ for (const channel of channels) {+ expect(mocks.listeners.get(channel)?.size).toBeGreaterThan(0)+ }+ })++ it('allows valid plugin log channels and rejects malformed events', () => {+ const callback = vi.fn()++ mocks.exposed?.on(`${Events.PluginLog}:example.contract`, callback)+ expect(+ mocks.listeners.get(`${Events.PluginLog}:example.contract`)?.size+ ).toBe(1)++ expect(() =>+ mocks.exposed?.on('event:notDeclared' as never, callback)+ ).toThrow('undeclared IPC event channel')+ expect(() =>+ mocks.exposed?.on(`${Events.PluginLog}:not-namespaced` as never, callback)+ ).toThrow('undeclared IPC event channel')+ })+})diff --git a/src/preload/preload.ts b/src/preload/preload.tsindex 87ba967f..a4a79a1f 100644--- a/src/preload/preload.ts+++ b/src/preload/preload.ts@@ -1,5 +1,11 @@+import {+ BridgeCommands,+ BridgeEvents,+ BridgeQueries,+} from '@shared/protocol/bridge'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'import { contextBridge, ipcRenderer, webUtils } from 'electron'import type { MotrixAPI } from './api'@@ -24,6 +30,32 @@ interface CallbackSubscription {// in the map — leaking BOTH real ipcRenderer listeners.const wrapperMap = new WeakMap<Callback, Map<string, CallbackSubscription>>()+const INVOKE_CHANNELS = new Set<string>([+ ...Object.values(Commands),+ ...Object.values(Queries),+ ...Object.values(BridgeCommands),+ ...Object.values(BridgeQueries),+])+const EVENT_CHANNELS = new Set<string>([+ ...Object.values(Events),+ ...Object.values(BridgeEvents),+])+const PLUGIN_LOG_CHANNEL_RE = new RegExp(+ `^${Events.PluginLog}:[a-z0-9-]+(?:\\.[a-z0-9-]+)+$`+)++function assertInvokeChannel(channel: string): void {+ if (!INVOKE_CHANNELS.has(channel)) {+ throw new Error(`Blocked undeclared IPC invoke channel: ${channel}`)+ }+}++function assertEventChannel(channel: string): void {+ if (!EVENT_CHANNELS.has(channel) && !PLUGIN_LOG_CHANNEL_RE.test(channel)) {+ throw new Error(`Blocked undeclared IPC event channel: ${channel}`)+ }+}+// Eager replay buffer for cold-start protocol/file events.//// Problem: the add-task window's renderer is code-split via React.lazy,@@ -72,8 +104,12 @@ for (const channel of BUFFERED_CHANNELS) {}const api: MotrixAPI = {- invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args),+ invoke: (channel, ...args) => {+ assertInvokeChannel(channel)+ return ipcRenderer.invoke(channel, ...args)+ },on: (channel, callback) => {+ assertEventChannel(channel)let active = truelet receivedLiveEvent = falseconst wrapper = (_event: Electron.IpcRendererEvent, ...args: unknown[]) => {@@ -115,6 +151,7 @@ const api: MotrixAPI = {}},off: (channel, callback) => {+ assertEventChannel(channel)const channelMap = wrapperMap.get(callback)const subscription = channelMap?.get(channel)if (subscription) {diff --git a/src/renderer/platform/web-services.test.ts b/src/renderer/platform/web-services.test.tsindex 19bcb531..58fef2e8 100644--- a/src/renderer/platform/web-services.test.ts+++ b/src/renderer/platform/web-services.test.ts@@ -1,11 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { sha256File } from './plugin-install-file'import { __webPathPickerBus, createWebServices } from './web-services'-vi.mock('./plugin-install-file', () => ({- sha256File: vi.fn(async () => 'b'.repeat(64)),-}))-describe('createWebServices', () => {let services: ReturnType<typeof createWebServices>@@ -54,7 +49,7 @@ describe('createWebServices', () => {) as unknown as typeof fetchservices = createWebServices({fetchImpl,- baseUrl: 'https://motrix.example',+ baseUrl: 'http://motrix.lan:8080',})const file = new File(['plugin'], '插件.moext')@@ -63,17 +58,16 @@ describe('createWebServices', () => {uploadId: '123e4567-e89b-42d3-a456-426614174000',fileHash: 'b'.repeat(64),})- expect(sha256File).toHaveBeenCalledWith(file)expect(fetchImpl).toHaveBeenCalledWith(- 'https://motrix.example/api/plugins/uploads',+ 'http://motrix.lan:8080/api/plugins/uploads',expect.objectContaining({method: 'POST',credentials: 'same-origin',body: file,- headers: expect.objectContaining({+ headers: {+ 'content-type': 'application/vnd.motrix.moext','x-motrix-file-name': encodeURIComponent('插件.moext'),- 'x-motrix-file-sha256': 'b'.repeat(64),- }),+ },}))})diff --git a/src/renderer/platform/web-services.ts b/src/renderer/platform/web-services.tsindex c688610f..83b034a1 100644--- a/src/renderer/platform/web-services.ts+++ b/src/renderer/platform/web-services.ts@@ -1,8 +1,9 @@import { toast } from '@renderer/components/ui/toast'import { i18n } from '@renderer/lib/i18n'-import { sha256File } from './plugin-install-file'import type { PlatformServices } from './services'+const SHA256_RE = /^[0-9a-f]{64}$/+type PickRequest = { defaultPath?: string }type PickListener = (req: PickRequest) => void@@ -61,14 +62,12 @@ export function createWebServices(pluginInstallFile: {mode: 'upload',async prepare(file) {- const fileHash = await sha256File(file)const response = await fetchImpl(`${baseUrl}/api/plugins/uploads`, {method: 'POST',credentials: 'same-origin',headers: {'content-type': 'application/vnd.motrix.moext','x-motrix-file-name': encodeURIComponent(file.name),- 'x-motrix-file-sha256': fileHash,},body: file,})@@ -84,14 +83,15 @@ export function createWebServices(}if (typeof reference.uploadId !== 'string' ||- reference.fileHash !== fileHash+ typeof reference.fileHash !== 'string' ||+ !SHA256_RE.test(reference.fileHash)) {throw new Error('Plugin upload returned an invalid reference')}return {sourceType: 'upload',uploadId: reference.uploadId,- fileHash,+ fileHash: reference.fileHash,}},},diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsxindex 9e21d34d..a38c7a3d 100644--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx@@ -132,7 +132,7 @@ function FinalizingActionBar({size="xs"variant="outline"onClick={() =>- transport.invoke(Commands.RevealInFolder, { path: task.diskPath })+ transport.invoke(Commands.RevealInFolder, { taskId: task.id })}><FolderOpen />@@ -295,7 +295,7 @@ export function TaskInspectorActionBar({variant="outline"onClick={() =>transport.invoke(Commands.RevealInFolder, {- path: single.diskPath,+ taskId: single.id,})}>diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex ab331034..7f1b6786 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -142,7 +142,7 @@ export function TaskInspectorDrawer({dir="ltr"onClick={() =>transport.invoke(Commands.RevealInFolder, {- path: single.diskPath,+ taskId: single.id,})}>diff --git a/src/server/bridge/public-url-diagnostic.test.ts b/src/server/bridge/public-url-diagnostic.test.tsnew file mode 100644index 00000000..83d44dbe--- /dev/null+++ b/src/server/bridge/public-url-diagnostic.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest'+import {+ diagnoseMdxpPublicUrl,+ MdxpPublicUrlWarningReason,+} from './public-url-diagnostic'++describe('diagnoseMdxpPublicUrl', () => {+ it.each(['localhost', 'dev.localhost', '127.0.0.1', '127.42.0.9', '::1'])(+ 'skips diagnostics for loopback MDXP host %s',+ (mdxpHost) => {+ expect(+ diagnoseMdxpPublicUrl({ mdxpHost, publicUrl: 'not a URL' })+ ).toBeUndefined()+ }+ )++ it.each([+ [undefined, MdxpPublicUrlWarningReason.NotSet],+ ['', MdxpPublicUrlWarningReason.Empty],+ [' ', MdxpPublicUrlWarningReason.Empty],+ ['not a URL', MdxpPublicUrlWarningReason.Invalid],+ ['ftp://nas.example.test', MdxpPublicUrlWarningReason.UnsupportedProtocol],+ ])('reports unusable public URL %j', (publicUrl, reason) => {+ expect(diagnoseMdxpPublicUrl({ mdxpHost: '0.0.0.0', publicUrl })).toEqual({+ reason,+ })+ })++ it.each([+ ['http://localhost:8080/approve?token=secret', 'http://localhost:8080'],+ ['http://127.0.0.1:8080/approve', 'http://127.0.0.1:8080'],+ ['http://127.42.0.9:8080/approve', 'http://127.42.0.9:8080'],+ ['http://admin.localhost:8080/approve', 'http://admin.localhost:8080'],+ ['http://[::1]:8080/approve', 'http://[::1]:8080'],+ ])(+ 'reports loopback public URL %s with only its origin',+ (publicUrl, origin) => {+ expect(diagnoseMdxpPublicUrl({ mdxpHost: '0.0.0.0', publicUrl })).toEqual(+ {+ reason: MdxpPublicUrlWarningReason.LoopbackHost,+ origin,+ }+ )+ }+ )++ it.each([+ ['http://0.0.0.0:8080/approve', 'http://0.0.0.0:8080'],+ ['http://[::]:8080/approve', 'http://[::]:8080'],+ ])('reports unspecified public URL %s', (publicUrl, origin) => {+ expect(diagnoseMdxpPublicUrl({ mdxpHost: '0.0.0.0', publicUrl })).toEqual({+ reason: MdxpPublicUrlWarningReason.UnspecifiedHost,+ origin,+ })+ })++ it('never includes credentials, path, or query in a reported origin', () => {+ expect(+ diagnoseMdxpPublicUrl({+ mdxpHost: '0.0.0.0',+ publicUrl:+ 'http://operator:password@localhost:8080/approve?token=secret',+ })+ ).toEqual({+ reason: MdxpPublicUrlWarningReason.LoopbackHost,+ origin: 'http://localhost:8080',+ })+ })++ it.each([+ 'http://192.168.1.20:8080',+ 'http://nas.local:8080/approve',+ 'https://downloads.example.test/approve?flow=device',+ ])('accepts remotely reachable HTTP(S) URL %s', (publicUrl) => {+ expect(+ diagnoseMdxpPublicUrl({ mdxpHost: '0.0.0.0', publicUrl })+ ).toBeUndefined()+ })+})diff --git a/src/server/bridge/public-url-diagnostic.ts b/src/server/bridge/public-url-diagnostic.tsnew file mode 100644index 00000000..352a47ee--- /dev/null+++ b/src/server/bridge/public-url-diagnostic.ts@@ -0,0 +1,90 @@+export enum MdxpPublicUrlWarningReason {+ NotSet = 'not-set',+ Empty = 'empty',+ Invalid = 'invalid',+ UnsupportedProtocol = 'unsupported-protocol',+ LoopbackHost = 'loopback-host',+ UnspecifiedHost = 'unspecified-host',+}++export interface MdxpPublicUrlWarning {+ reason: MdxpPublicUrlWarningReason+ /** Safe to log: URL.origin omits credentials, path, query, and fragment. */+ origin?: string+}++export interface MdxpPublicUrlDiagnosticInput {+ mdxpHost: string+ publicUrl: string | undefined+}++function normalizeHostname(hostname: string): string {+ const normalized = hostname.toLowerCase()+ if (normalized.startsWith('[') && normalized.endsWith(']')) {+ return normalized.slice(1, -1)+ }+ return normalized+}++function isLoopbackHost(hostname: string): boolean {+ const normalized = normalizeHostname(hostname)+ return (+ normalized === 'localhost' ||+ normalized.endsWith('.localhost') ||+ normalized === '::1' ||+ /^127(?:\.\d{1,3}){3}$/.test(normalized)+ )+}++function isUnspecifiedHost(hostname: string): boolean {+ const normalized = normalizeHostname(hostname)+ return normalized === '0.0.0.0' || normalized === '::'+}++/**+ * Diagnose a public-URL configuration only when MDXP is exposed beyond the+ * local machine. The result is informational: callers must not reject or+ * rewrite the configured URL based on it.+ */+export function diagnoseMdxpPublicUrl({+ mdxpHost,+ publicUrl,+}: MdxpPublicUrlDiagnosticInput): MdxpPublicUrlWarning | undefined {+ if (isLoopbackHost(mdxpHost)) return undefined++ if (publicUrl === undefined) {+ return { reason: MdxpPublicUrlWarningReason.NotSet }+ }++ const candidate = publicUrl.trim()+ if (candidate === '') {+ return { reason: MdxpPublicUrlWarningReason.Empty }+ }++ let parsed: URL+ try {+ parsed = new URL(candidate)+ } catch {+ return { reason: MdxpPublicUrlWarningReason.Invalid }+ }++ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ return { reason: MdxpPublicUrlWarningReason.UnsupportedProtocol }+ }++ if (isLoopbackHost(parsed.hostname)) {+ return {+ reason: MdxpPublicUrlWarningReason.LoopbackHost,+ origin: parsed.origin,+ }+ }++ if (isUnspecifiedHost(parsed.hostname)) {+ return {+ reason: MdxpPublicUrlWarningReason.UnspecifiedHost,+ origin: parsed.origin,+ }+ }++ return undefined+}diff --git a/src/server/index.ts b/src/server/index.tsindex fa088dcf..e3f4cb97 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -104,6 +104,7 @@ import {bootstrapBridgeForServer,type ServerBridgeRuntime,} from './bridge/bootstrap'+import { diagnoseMdxpPublicUrl } from './bridge/public-url-diagnostic'import {createServerDownloadPathPolicy,resolveServerDefaultSaveDir,@@ -522,6 +523,8 @@ async function main() {const pluginUploadStore = new PluginUploadStore(path.join(pluginsDir, '_uploads'))+ await pluginUploadStore.cleanupExpired()+ shutdownActions.closeIngress = () => pluginUploadStore.dispose()const pluginInstallService = new ServerPluginInstallService({installer: pluginInstaller,registryClient,@@ -926,8 +929,12 @@ async function main() {engine: supervisor.getStatus(),}),})- shutdownActions.closeIngress = () => app.close()+ shutdownActions.closeIngress = async () => {+ pluginUploadStore.dispose()+ await app.close()+ }if (!shellAsyncWork.isAccepting()) {+ pluginUploadStore.dispose()await app.close()return}@@ -1388,9 +1395,23 @@ async function main() {16801,{ allowZero: true })+ const mdxpHost = process.env.MOTRIX_MDXP_HOST ?? '127.0.0.1'+ const publicUrlWarning = diagnoseMdxpPublicUrl({+ mdxpHost,+ publicUrl: process.env.MOTRIX_PUBLIC_URL,+ })+ if (publicUrlWarning) {+ log.warn(+ {+ reason: publicUrlWarning.reason,+ publicOrigin: publicUrlWarning.origin,+ },+ 'non-loopback MDXP bind has no usable MOTRIX_PUBLIC_URL; remote clients may not receive a usable approval URL'+ )+ }const candidateBridgeRuntime = await bootstrapBridgeForServer({userDataDir: platform.userDataDir,- host: process.env.MOTRIX_MDXP_HOST ?? '127.0.0.1',+ host: mdxpHost,port: mdxpPort,motrixVersion: process.env.MOTRIX_APP_VERSION ?? '2.0.0',eventBus,diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.tsindex a825c719..d2e024d4 100644--- a/src/server/ipc/commands.test.ts+++ b/src/server/ipc/commands.test.ts@@ -775,6 +775,13 @@ describe('server plugin lifecycle commands', () => {pluginId: 'test.plugin',})).resolves.toMatchObject({ stagingId: 's1', committed: false })+ expect(ctx.pluginInstallService.stage).toHaveBeenCalledWith(+ {+ sourceType: 'registry',+ pluginId: 'test.plugin',+ },+ ctx.pluginHost+ )expect(ctx.eventBus.emit).toHaveBeenCalledWith(Events.PluginInstallConsentRequested,expect.objectContaining({ stagingId: 's1' })@@ -796,9 +803,11 @@ describe('server plugin lifecycle commands', () => {grants: { notify: 'denied' },})).resolves.toEqual({ ok: true, pluginId: 'test.plugin' })- expect(ctx.pluginInstaller.commit).toHaveBeenCalledWith('s1', {- notify: 'denied',- })+ expect(ctx.pluginInstaller.commit).toHaveBeenCalledWith(+ 's1',+ { notify: 'denied' },+ ctx.pluginHost+ )expect(ctx.eventBus.emit).toHaveBeenCalledWith(Events.PluginInstalled, {pluginId: 'test.plugin',})@@ -823,7 +832,10 @@ describe('server plugin lifecycle commands', () => {await handlers[Commands.UninstallPlugin]?.({ pluginId: 'test.plugin' })expect(ctx.pluginInstaller.cancel).toHaveBeenCalledWith('s1')- expect(ctx.pluginInstaller.uninstall).toHaveBeenCalledWith('test.plugin')+ expect(ctx.pluginInstaller.uninstall).toHaveBeenCalledWith(+ 'test.plugin',+ ctx.pluginHost+ )expect(ctx.settingsManager.removePluginConfig).toHaveBeenCalledWith('test.plugin')diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex a0f7c392..57fb05a5 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -637,7 +637,7 @@ export function buildServerCommandHandlers(},[Commands.InstallPlugin]: async (payload: unknown) => {- const result = await pluginInstallService.stage(payload)+ const result = await pluginInstallService.stage(payload, pluginHost)if (result.committed && result.pluginId) {eventBus.emit(Events.PluginInstalled, { pluginId: result.pluginId })} else {@@ -658,7 +658,8 @@ export function buildServerCommandHandlers(.parse(payload)const { pluginId } = await pluginInstaller.commit(parsed.stagingId,- parsed.grants+ parsed.grants,+ pluginHost)eventBus.emit(Events.PluginInstalled, { pluginId })return { ok: true, pluginId }@@ -686,7 +687,7 @@ export function buildServerCommandHandlers([Commands.UninstallPlugin]: async (payload: unknown) => {const parsed = z.object({ pluginId: z.string().min(1) }).parse(payload)- await pluginInstaller.uninstall(parsed.pluginId)+ await pluginInstaller.uninstall(parsed.pluginId, pluginHost)await settingsManager.removePluginConfig(parsed.pluginId)eventBus.emit(Events.PluginUninstalled, { pluginId: parsed.pluginId })return { ok: true }diff --git a/src/server/operator-admin.integration.test.ts b/src/server/operator-admin.integration.test.tsnew file mode 100644index 00000000..27c5a443--- /dev/null+++ b/src/server/operator-admin.integration.test.ts@@ -0,0 +1,88 @@+import { DeviceCodeService } from '@core/bridge/device-code-service'+import type { PairedClient, PairingService } from '@core/bridge/pairing-service'+import { resolveCliPair } from '@core/bridge/resolve-cli-pair'+import { BridgeCommands, BridgeQueries } from '@shared/protocol/bridge'+import { describe, expect, it, vi } from 'vitest'+import { OperatorAdminExitCode, runOperatorAdmin } from './operator-admin'++const OPERATOR_TOKEN = 'o'.repeat(43)+const AGENT_TOKEN = 'agent-token-that-only-the-requesting-client-may-poll'++function response(value: unknown): Response {+ return new Response(JSON.stringify(value), {+ headers: { 'content-type': 'application/json' },+ })+}++describe('motrix-admin pairing integration', () => {+ it('approves a real pending device code without disclosing capabilities', async () => {+ const paired: PairedClient = {+ identity: { kind: 'cli', id: 'device-id-for-admin-integration' },+ name: 'Integration CLI',+ token: AGENT_TOKEN,+ pairedAt: 1,+ lastActiveAt: null,+ }+ const pairing = {+ issueToken: vi.fn().mockResolvedValue(paired),+ } as unknown as PairingService+ const deviceCodes = new DeviceCodeService(pairing)+ const pending = deviceCodes.request(+ 'Integration CLI',+ '0.4.0',+ 'device-id-for-admin-integration'+ )+ const stdout: string[] = []+ const stderr: string[] = []++ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {+ const url = String(input)+ if (+ url.endsWith(+ `/rpc/query/${encodeURIComponent(+ BridgeQueries.ListPendingPairRequests+ )}`+ )+ ) {+ return response(deviceCodes.listPending())+ }+ expect(url).toBe(+ `http://127.0.0.1:8080/rpc/command/${encodeURIComponent(+ BridgeCommands.ResolvePair+ )}`+ )+ const body = JSON.parse(String(init?.body)) as {+ args: Array<{+ kind: 'cli'+ requestId: string+ decision: 'allow' | 'deny'+ }>+ }+ return response(+ await resolveCliPair(deviceCodes, body.args[0]!, () => {})+ )+ })++ const exitCode = await runOperatorAdmin(+ ['pairing', 'approve', pending.userCode, '--json'],+ {+ env: { MOTRIX_OPERATOR_TOKEN: OPERATOR_TOKEN },+ fetch: fetchMock as typeof fetch,+ writeStdout: (line) => stdout.push(line),+ writeStderr: (line) => stderr.push(line),+ }+ )++ expect(exitCode).toBe(OperatorAdminExitCode.Success)+ expect(pairing.issueToken).toHaveBeenCalledOnce()+ expect(deviceCodes.poll(pending.requestId)).toEqual({+ status: 'approved',+ token: AGENT_TOKEN,+ })+ const output = [...stdout, ...stderr].join('\n')+ expect(output).not.toContain(pending.requestId)+ expect(output).not.toContain(OPERATOR_TOKEN)+ expect(output).not.toContain(AGENT_TOKEN)+ deviceCodes.dispose()+ })+})diff --git a/src/server/operator-admin.test.ts b/src/server/operator-admin.test.tsnew file mode 100644index 00000000..0db47d9b--- /dev/null+++ b/src/server/operator-admin.test.ts@@ -0,0 +1,511 @@+import { describe, expect, it, vi } from 'vitest'+import { OperatorAdminExitCode, runOperatorAdmin } from './operator-admin'++const TOKEN = 't'.repeat(43)+const REQUEST_ID = 'r'.repeat(43)+const NOW = 1_800_000_000_000++type AdminOptions = NonNullable<Parameters<typeof runOperatorAdmin>[1]>++interface Harness {+ stdout: string[]+ stderr: string[]+ options: AdminOptions+ advance(milliseconds: number): void+}++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ })+}++function request(+ overrides: Partial<{+ requestId: string+ userCode: string+ clientName: string+ clientVersion: string+ createdAt: number+ expiresAt: number+ }> = {}+) {+ return {+ kind: 'cli' as const,+ requestId: REQUEST_ID,+ userCode: 'ABCD-EFGH',+ clientName: 'Motrix CLI',+ clientVersion: '1.2.3',+ createdAt: NOW - 1_000,+ expiresAt: NOW + 299_000,+ ...overrides,+ }+}++function harness(+ fetchMock: ReturnType<typeof vi.fn>,+ overrides: AdminOptions = {}+): Harness {+ const stdout: string[] = []+ const stderr: string[] = []+ let now = NOW+ return {+ stdout,+ stderr,+ options: {+ env: {+ MOTRIX_OPERATOR_TOKEN: TOKEN,+ PORT: '8123',+ },+ fetch: fetchMock as unknown as typeof fetch,+ now: () => now,+ sleep: async (milliseconds) => {+ now += milliseconds+ },+ writeStdout: (message) => stdout.push(message),+ writeStderr: (message) => stderr.push(message),+ pendingRetryWindowMs: 0,+ ...overrides,+ },+ advance: (milliseconds) => {+ now += milliseconds+ },+ }+}++function rpcCall(fetchMock: ReturnType<typeof vi.fn>, index: number) {+ const call = fetchMock.mock.calls[index]+ if (!call) throw new Error(`missing fetch call ${index}`)+ const [url, init] = call as [string, RequestInit]+ return {+ url,+ init,+ headers: new Headers(init.headers),+ body: JSON.parse(init.body as string) as { args: unknown[] },+ }+}++describe('runOperatorAdmin', () => {+ it('shows help without reading credentials or contacting the server', async () => {+ const fetchMock = vi.fn()+ const lstatMock = vi.fn()+ const h = harness(fetchMock, {+ env: {},+ lstat: lstatMock as unknown as NonNullable<AdminOptions['lstat']>,+ })++ await expect(runOperatorAdmin(['--help'], h.options)).resolves.toBe(+ OperatorAdminExitCode.Success+ )+ expect(h.stdout.join('\n')).toContain('motrix-admin pairing pending')+ expect(h.stderr).toEqual([])+ expect(fetchMock).not.toHaveBeenCalled()+ expect(lstatMock).not.toHaveBeenCalled()+ })++ it('localizes help and usage errors from the configured host locale', async () => {+ const help = harness(vi.fn(), {+ env: {+ MOTRIX_HOST_LANGUAGE: 'zh-CN',+ LANG: 'en_US.UTF-8',+ },+ })++ await expect(runOperatorAdmin(['--help'], help.options)).resolves.toBe(+ OperatorAdminExitCode.Success+ )+ expect(help.stdout.join('\n')).toContain('用法:')+ expect(help.stdout.join('\n')).toContain('仅通过容器内的本机回环地址')++ const invalid = harness(vi.fn(), {+ env: {+ MOTRIX_HOST_LANGUAGE: 'zh-CN',+ LANG: 'en_US.UTF-8',+ },+ })+ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCI-0FGH'], invalid.options)+ ).resolves.toBe(OperatorAdminExitCode.Usage)+ expect(invalid.stderr.join('\n')).toContain(+ '配对码必须包含 8 个 ASCII 字符'+ )+ expect(invalid.stderr.join('\n')).toContain('查看用法')+ })++ it('rejects malformed and ambiguous human codes before network access', async () => {+ const fetchMock = vi.fn()+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCI-0FGH'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Usage)+ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCDEFGſ'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Usage)+ expect(fetchMock).not.toHaveBeenCalled()+ expect(h.stderr.join('\n')).toContain('cannot use I, O, 0, or 1')+ })++ it('uses the environment credential and fixed loopback URL', async () => {+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]))+ const lstatMock = vi.fn()+ const h = harness(fetchMock, {+ lstat: lstatMock as unknown as NonNullable<AdminOptions['lstat']>,+ })++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)++ const call = rpcCall(fetchMock, 0)+ expect(call.url).toBe(+ 'http://127.0.0.1:8123/rpc/query/bridge%3AlistPendingPairRequests'+ )+ expect(call.headers.get('authorization')).toBe(`Bearer ${TOKEN}`)+ expect(call.body).toEqual({ args: [] })+ expect(lstatMock).not.toHaveBeenCalled()+ })++ it('reads the existing data-dir credential without provisioning it', async () => {+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]))+ const lstatMock = vi.fn().mockResolvedValue({ isFile: () => true })+ const readFileMock = vi.fn().mockResolvedValue(TOKEN)+ const h = harness(fetchMock, {+ env: { MOTRIX_DATA_DIR: '/data' },+ lstat: lstatMock as unknown as NonNullable<AdminOptions['lstat']>,+ readFile: readFileMock as unknown as NonNullable<+ AdminOptions['readFile']+ >,+ })++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ expect(lstatMock).toHaveBeenCalledWith('/data/operator-token')+ expect(readFileMock).toHaveBeenCalledWith('/data/operator-token', 'utf8')+ expect(rpcCall(fetchMock, 0).headers.get('authorization')).toBe(+ `Bearer ${TOKEN}`+ )+ })++ it('fails with the credential exit code when no token can be read', async () => {+ const fetchMock = vi.fn()+ const h = harness(fetchMock, {+ env: {},+ lstat: vi+ .fn()+ .mockRejectedValue(new Error('missing')) as unknown as NonNullable<+ AdminOptions['lstat']+ >,+ })++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Credential)+ expect(fetchMock).not.toHaveBeenCalled()+ expect(h.stderr.join('\n')).not.toContain(TOKEN)+ })++ it('sanitizes and bounds untrusted client metadata in human output', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ jsonResponse([+ request({+ clientName: `bad\u001b[31m\n${'x'.repeat(180)}`,+ clientVersion: `2.0\u202e${'y'.repeat(55)}`,+ }),+ ])+ )+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ expect(h.stdout).toHaveLength(1)+ expect(h.stdout[0]).not.toContain('\u001b')+ expect(h.stdout[0]).not.toContain('\n')+ expect(h.stdout[0]).not.toContain('\u202e')+ expect(h.stdout[0]?.length).toBeLessThan(170)+ expect(h.stdout[0]).not.toContain(REQUEST_ID)+ expect(h.stdout[0]).not.toContain(TOKEN)+ })++ it('projects JSON output without request ids or credentials', async () => {+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([request()]))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'pending', '--json'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ const output = h.stdout.join('')+ expect(JSON.parse(output)).toEqual({+ ok: true,+ requests: [+ {+ userCode: 'ABCD-EFGH',+ clientName: 'Motrix CLI',+ clientVersion: '1.2.3',+ createdAt: NOW - 1_000,+ expiresAt: NOW + 299_000,+ },+ ],+ })+ expect(output).not.toContain(REQUEST_ID)+ expect(output).not.toContain(TOKEN)+ })++ it('sanitizes and bounds untrusted client metadata in JSON output', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ jsonResponse([+ request({+ clientName: `bad\u001b[31m\n\u2066${'x'.repeat(120)}`,+ clientVersion: `2.0\u202e\r${'y'.repeat(50)}`,+ }),+ ])+ )+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'pending', '--json'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ const output = h.stdout.join('')+ const parsed = JSON.parse(output) as {+ requests: Array<{ clientName: string; clientVersion: string }>+ }+ const projected = parsed.requests[0]+ expect(projected).toBeDefined()+ expect(projected?.clientName).not.toMatch(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u)+ expect(projected?.clientVersion).not.toMatch(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u)+ expect([...(projected?.clientName ?? '')]).toHaveLength(80)+ expect([...(projected?.clientVersion ?? '')]).toHaveLength(32)+ expect(output).not.toContain(REQUEST_ID)+ expect(output).not.toContain(TOKEN)+ })++ it('retries pending queries on connection failures and startup 404s', async () => {+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(new TypeError('connection refused'))+ .mockResolvedValueOnce(jsonResponse({ error: 'unknown channel' }, 404))+ .mockResolvedValueOnce(jsonResponse([]))+ const h = harness(fetchMock, { pendingRetryWindowMs: 1_000 })++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ expect(fetchMock).toHaveBeenCalledTimes(3)+ expect(h.stdout).toEqual(['No pending pairing requests.'])+ })++ it('does not retry a 404 that is not the exact unknown-channel response', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse({ error: 'not found' }, 404))+ .mockResolvedValueOnce(jsonResponse([]))+ const h = harness(fetchMock, { pendingRetryWindowMs: 1_000 })++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(h.stderr.join('\n')).toContain('HTTP 404')+ })++ it('uses the unavailable exit code when loopback readiness times out', async () => {+ const fetchMock = vi.fn().mockRejectedValue(new TypeError('refused'))+ const h = harness(fetchMock, { pendingRetryWindowMs: 0 })++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Unavailable)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it('normalizes a code and approves exactly its unique request', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse([request()]))+ .mockResolvedValueOnce(jsonResponse({ ok: true }))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(+ ['pairing', 'approve', ' abcd ', '-', 'efgh '],+ h.options+ )+ ).resolves.toBe(OperatorAdminExitCode.Success)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ const mutation = rpcCall(fetchMock, 1)+ expect(mutation.url).toBe(+ 'http://127.0.0.1:8123/rpc/command/bridge%3AresolvePair'+ )+ expect(mutation.body).toEqual({+ args: [+ {+ kind: 'cli',+ requestId: REQUEST_ID,+ decision: 'allow',+ },+ ],+ })+ expect(h.stdout).toEqual(['Approved ABCD-EFGH for Motrix CLI (1.2.3).'])+ })++ it('sends deny through the same authoritative decision RPC', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse([request()]))+ .mockResolvedValueOnce(jsonResponse({ ok: true }))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'deny', 'ABCDEFGH'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ expect(rpcCall(fetchMock, 1).body.args).toEqual([+ { kind: 'cli', requestId: REQUEST_ID, decision: 'deny' },+ ])+ expect(h.stdout[0]).toContain('Denied ABCD-EFGH')+ })++ it('fails closed when no request matches without sending a mutation', async () => {+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([request()]))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'JKLM-NPQR'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it('fails closed when a code is not unique without sending a mutation', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ jsonResponse([+ request(),+ request({ requestId: 's'.repeat(43), clientName: 'Other CLI' }),+ ])+ )+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCD-EFGH'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(h.stderr.join('\n')).toContain('no decision was applied')+ })++ it('does not retry a failed mutation', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse([request()]))+ .mockRejectedValueOnce(new TypeError('connection reset'))+ const h = harness(fetchMock, { pendingRetryWindowMs: 1_000 })++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCD-EFGH'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('bounds a mutation with one timeout and never retries it', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse([request()]))+ .mockImplementationOnce((_url, init: RequestInit) => {+ return new Promise<Response>((_resolve, reject) => {+ init.signal?.addEventListener(+ 'abort',+ () => reject(new TypeError('aborted')),+ { once: true }+ )+ })+ })+ const h = harness(fetchMock, { mutationTimeoutMs: 1 })++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCD-EFGH'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(h.stderr.join('\n')).toContain('outcome is unknown')+ })++ it('honors the authoritative unavailable decision result', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse([request()]))+ .mockResolvedValueOnce(jsonResponse({ ok: false, reason: 'unavailable' }))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCD-EFGH'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(h.stdout).toEqual([])+ })++ it('rejects malformed pending and mutation responses strictly', async () => {+ const invalidPending = vi+ .fn()+ .mockResolvedValue(jsonResponse([{ ...request(), token: 'leaked' }]))+ const pendingHarness = harness(invalidPending)++ await expect(+ runOperatorAdmin(['pairing', 'pending'], pendingHarness.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(pendingHarness.stdout).toEqual([])+ expect(pendingHarness.stderr.join('')).not.toContain('leaked')++ const invalidMutation = vi+ .fn()+ .mockResolvedValueOnce(jsonResponse([request()]))+ .mockResolvedValueOnce(jsonResponse({ ok: true, token: 'leaked' }))+ const mutationHarness = harness(invalidMutation)+ await expect(+ runOperatorAdmin(+ ['pairing', 'approve', 'ABCD-EFGH'],+ mutationHarness.options+ )+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(mutationHarness.stdout).toEqual([])+ expect(mutationHarness.stderr.join('')).not.toContain('leaked')+ })++ it('uses distinct credential and server failure exit codes', async () => {+ const unauthorizedFetch = vi+ .fn()+ .mockResolvedValue(jsonResponse({ error: 'unauthorized' }, 401))+ const unauthorized = harness(unauthorizedFetch)+ await expect(+ runOperatorAdmin(['pairing', 'pending'], unauthorized.options)+ ).resolves.toBe(OperatorAdminExitCode.Credential)++ const failedFetch = vi+ .fn()+ .mockResolvedValue(jsonResponse({ error: 'failure' }, 500))+ const failed = harness(failedFetch)+ await expect(+ runOperatorAdmin(['pairing', 'pending'], failed.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ })++ it('emits granular machine error codes with localized messages', async () => {+ const h = harness(vi.fn(), {+ env: {+ MOTRIX_OPERATOR_TOKEN: TOKEN,+ MOTRIX_HOST_LANGUAGE: 'zh-CN',+ },+ })++ await expect(+ runOperatorAdmin(['pairing', 'approve', 'ABCI-0FGH', '--json'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Usage)+ expect(JSON.parse(h.stderr.join(''))).toEqual({+ ok: false,+ error: {+ code: 'usage.pairingCodeInvalid',+ kind: 'usage',+ message: '配对码必须包含 8 个 ASCII 字符,且不能使用 I、O、0 或 1。',+ },+ })+ })+})diff --git a/src/server/operator-admin.ts b/src/server/operator-admin.tsnew file mode 100644index 00000000..92c86427--- /dev/null+++ b/src/server/operator-admin.ts@@ -0,0 +1,758 @@+import { lstat, readFile } from 'node:fs/promises'+import { isAbsolute, join } from 'node:path'+import {+ FALLBACK_LOCALE,+ resolveSupportedLocale,+ SUPPORTED_LOCALE_CODES,+} from '@shared/constants/locales'+import { I18N_RESOURCES } from '@shared/i18n-resources'+import {+ BridgeCommands,+ BridgeQueries,+ type PendingPairRequestInfo,+ type ResolvePairParams,+ type ResolvePairResult,+} from '@shared/protocol/bridge'+import { createInstance } from 'i18next'+import { z } from 'zod'+import { parseServerPort } from './environment'++const OPERATOR_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43,128}$/+const USER_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{8}$/+const WIRE_USER_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/+const DEFAULT_DATA_DIR = '/data'+const DEFAULT_PORT = 8080+const PENDING_RETRY_WINDOW_MS = 5_000+const PENDING_RETRY_DELAY_MS = 250+const MUTATION_TIMEOUT_MS = 5_000+const MAX_PENDING_ATTEMPTS = 32+const MAX_RESPONSE_BYTES = 1024 * 1024+const MAX_CLIENT_NAME_LENGTH = 80+const MAX_CLIENT_VERSION_LENGTH = 32++type PendingCliRequest = Extract<PendingPairRequestInfo, { kind: 'cli' }>+type Translate = (+ key: string,+ values?: Readonly<Record<string, string | number>>+) => string++const pendingCliRequestSchema: z.ZodType<PendingCliRequest> = z+ .object({+ kind: z.literal('cli'),+ requestId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),+ userCode: z.string().regex(WIRE_USER_CODE_PATTERN),+ clientName: z.string().min(1).max(200),+ clientVersion: z.string().max(64),+ createdAt: z.number().int().nonnegative(),+ expiresAt: z.number().int().nonnegative(),+ })+ .strict()++const pendingResponseSchema = z.array(pendingCliRequestSchema).max(1_000)++const resolvePairResultSchema: z.ZodType<ResolvePairResult> =+ z.discriminatedUnion('ok', [+ z.object({ ok: z.literal(true) }).strict(),+ z+ .object({ ok: z.literal(false), reason: z.literal('unavailable') })+ .strict(),+ ])++const unknownChannelResponseSchema = z+ .object({ error: z.literal('unknown channel') })+ .strict()++export enum OperatorAdminExitCode {+ Success = 0,+ Usage = 2,+ Unavailable = 3,+ Credential = 4,+ Server = 5,+}++enum OperatorAdminErrorKind {+ Usage = 'usage',+ Unavailable = 'unavailable',+ Credential = 'credential',+ Server = 'server',+}++enum OperatorAdminErrorCode {+ JsonRepeated = 'usage.jsonRepeated',+ UnknownOption = 'usage.unknownOption',+ PairingCommandRequired = 'usage.pairingCommandRequired',+ PairingOperationRequired = 'usage.pairingOperationRequired',+ PairingCodeInvalid = 'usage.pairingCodeInvalid',+ PortInvalid = 'usage.portInvalid',+ TokenHeaderInvalid = 'credential.tokenHeaderInvalid',+ DataDirNotAbsolute = 'credential.dataDirNotAbsolute',+ CredentialUnavailable = 'credential.unavailable',+ CredentialNotFile = 'credential.notFile',+ CredentialUnreadable = 'credential.unreadable',+ CredentialInvalid = 'credential.invalid',+ CredentialRejected = 'credential.rejected',+ ResponseUnreadable = 'server.responseUnreadable',+ ResponseOversized = 'server.responseOversized',+ ResponseInvalidJson = 'server.responseInvalidJson',+ RpcHttp = 'server.rpcHttp',+ ApprovalUnavailable = 'server.approvalUnavailable',+ PendingResponseInvalid = 'server.pendingResponseInvalid',+ DecisionOutcomeUnknown = 'server.decisionOutcomeUnknown',+ DecisionResponseInvalid = 'server.decisionResponseInvalid',+ RequestNoLongerPending = 'server.requestNoLongerPending',+ NoMatchingRequest = 'server.noMatchingRequest',+ AmbiguousRequest = 'server.ambiguousRequest',+ Unexpected = 'server.unexpected',+ LoopbackUnavailable = 'unavailable.loopback',+ ApprovalNotReady = 'unavailable.approvalNotReady',+}++interface ErrorInterpolation {+ [key: string]: string | number+}++class OperatorAdminError extends Error {+ constructor(+ readonly kind: OperatorAdminErrorKind,+ readonly code: OperatorAdminErrorCode,+ readonly values: ErrorInterpolation = {}+ ) {+ super(code)+ this.name = 'OperatorAdminError'+ }+}++interface OperatorAdminDependencies {+ env: NodeJS.ProcessEnv+ fetch: typeof globalThis.fetch+ lstat: typeof lstat+ readFile: typeof readFile+ now: () => number+ sleep: (milliseconds: number) => Promise<void>+ writeStdout: (message: string) => void+ writeStderr: (message: string) => void+ pendingRetryWindowMs: number+ mutationTimeoutMs: number+}++export interface OperatorAdminOptions+ extends Partial<OperatorAdminDependencies> {}++interface ParsedCommand {+ json: boolean+ operation: 'pending' | 'approve' | 'deny'+ userCode?: string+}++interface ProjectedPairRequest {+ userCode: string+ clientName: string+ clientVersion: string+ createdAt: number+ expiresAt: number+}++function defaultDependencies(+ options: OperatorAdminOptions+): OperatorAdminDependencies {+ return {+ env: options.env ?? process.env,+ fetch: options.fetch ?? fetch.bind(globalThis),+ lstat: options.lstat ?? lstat,+ readFile: options.readFile ?? readFile,+ now: options.now ?? Date.now,+ sleep:+ options.sleep ??+ ((milliseconds) =>+ new Promise((resolve) => setTimeout(resolve, milliseconds))),+ writeStdout:+ options.writeStdout ??+ ((message) => {+ process.stdout.write(`${message}\n`)+ }),+ writeStderr:+ options.writeStderr ??+ ((message) => {+ process.stderr.write(`${message}\n`)+ }),+ pendingRetryWindowMs:+ options.pendingRetryWindowMs ?? PENDING_RETRY_WINDOW_MS,+ mutationTimeoutMs: options.mutationTimeoutMs ?? MUTATION_TIMEOUT_MS,+ }+}++async function createTranslator(env: NodeJS.ProcessEnv): Promise<Translate> {+ const locale = resolveSupportedLocale(env.MOTRIX_HOST_LANGUAGE, env.LANG)+ const instance = createInstance()+ await instance.init({+ resources: I18N_RESOURCES,+ supportedLngs: SUPPORTED_LOCALE_CODES,+ lng: locale,+ fallbackLng: FALLBACK_LOCALE,+ interpolation: {+ escapeValue: false,+ },+ })+ const fixedT = instance.getFixedT(locale)+ return (key, values) => String(fixedT(key, values))+}++function exitCodeFor(error: OperatorAdminError): OperatorAdminExitCode {+ switch (error.kind) {+ case OperatorAdminErrorKind.Usage:+ return OperatorAdminExitCode.Usage+ case OperatorAdminErrorKind.Unavailable:+ return OperatorAdminExitCode.Unavailable+ case OperatorAdminErrorKind.Credential:+ return OperatorAdminExitCode.Credential+ case OperatorAdminErrorKind.Server:+ return OperatorAdminExitCode.Server+ }+}++function parseCommand(argv: readonly string[]): ParsedCommand | 'help' {+ const jsonCount = argv.filter((arg) => arg === '--json').length+ const json = jsonCount > 0+ if (jsonCount > 1) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.JsonRepeated+ )+ }++ if (+ argv.length === 0 ||+ argv.includes('--help') ||+ argv.includes('-h') ||+ (argv.length === 1 && argv[0] === 'help')+ ) {+ return 'help'+ }++ const args = argv.filter((arg) => arg !== '--json')+ if (args.some((arg) => arg.startsWith('--'))) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.UnknownOption+ )+ }+ if (args[0] !== 'pairing') {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.PairingCommandRequired+ )+ }++ const operation = args[1]+ if (operation === 'pending' && args.length === 2) {+ return { json, operation }+ }+ if ((operation === 'approve' || operation === 'deny') && args.length >= 3) {+ return {+ json,+ operation,+ userCode: normalizeUserCode(args.slice(2).join('')),+ }+ }+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.PairingOperationRequired+ )+}++export function normalizeUserCode(input: string): string {+ const stripped = input.replace(/[\t\n\v\f\r -]/g, '')+ if ([...stripped].some((character) => character.charCodeAt(0) > 0x7f)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.PairingCodeInvalid+ )+ }+ const normalized = stripped.toUpperCase()+ if (!USER_CODE_PATTERN.test(normalized)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.PairingCodeInvalid+ )+ }+ return `${normalized.slice(0, 4)}-${normalized.slice(4)}`+}++async function readOperatorToken(+ deps: OperatorAdminDependencies+): Promise<string> {+ const fromEnvironment = deps.env.MOTRIX_OPERATOR_TOKEN+ if (typeof fromEnvironment === 'string' && fromEnvironment.length > 0) {+ if (/[\r\n\0]/.test(fromEnvironment)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.TokenHeaderInvalid+ )+ }+ return fromEnvironment+ }++ const dataDir = deps.env.MOTRIX_DATA_DIR || DEFAULT_DATA_DIR+ if (!isAbsolute(dataDir)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.DataDirNotAbsolute+ )+ }+ const tokenPath = join(dataDir, 'operator-token')+ let metadata: Awaited<ReturnType<typeof lstat>>+ try {+ metadata = await deps.lstat(tokenPath)+ } catch {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.CredentialUnavailable+ )+ }+ if (!metadata.isFile()) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.CredentialNotFile+ )+ }++ let token: string+ try {+ token = await deps.readFile(tokenPath, 'utf8')+ } catch {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.CredentialUnreadable+ )+ }+ if (!OPERATOR_TOKEN_PATTERN.test(token)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.CredentialInvalid+ )+ }+ return token+}++function serverBaseUrl(env: NodeJS.ProcessEnv): string {+ let port: number+ try {+ port = parseServerPort(env.PORT, 'PORT', DEFAULT_PORT)+ } catch {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Usage,+ OperatorAdminErrorCode.PortInvalid+ )+ }+ return `http://127.0.0.1:${port}`+}++async function discardResponse(response: Response): Promise<void> {+ try {+ await response.body?.cancel()+ } catch {+ // The status is all the caller needs; a failed body cancellation is benign.+ }+}++async function readResponseText(response: Response): Promise<string> {+ let text: string+ try {+ text = await response.text()+ } catch {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.ResponseUnreadable+ )+ }+ if (Buffer.byteLength(text, 'utf8') > MAX_RESPONSE_BYTES) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.ResponseOversized+ )+ }+ return text+}++async function parseJsonResponse(response: Response): Promise<unknown> {+ const text = await readResponseText(response)+ try {+ return JSON.parse(text) as unknown+ } catch {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.ResponseInvalidJson+ )+ }+}++async function isUnknownChannelResponse(response: Response): Promise<boolean> {+ let text: string+ try {+ text = await response.text()+ } catch {+ return false+ }+ if (Buffer.byteLength(text, 'utf8') > MAX_RESPONSE_BYTES) return false+ try {+ return unknownChannelResponseSchema.safeParse(JSON.parse(text)).success+ } catch {+ return false+ }+}++function requestInit(token: string, args: unknown[]): RequestInit {+ return {+ method: 'POST',+ headers: {+ accept: 'application/json',+ authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify({ args }),+ cache: 'no-store',+ redirect: 'error',+ }+}++function classifyHttpStatus(status: number, mutation: boolean): never {+ if (status === 401 || status === 403) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Credential,+ OperatorAdminErrorCode.CredentialRejected+ )+ }+ if (status === 404 && mutation) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.ApprovalUnavailable+ )+ }+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.RpcHttp,+ { status }+ )+}++function retryWindowExpired(+ deps: OperatorAdminDependencies,+ startedAt: number,+ attempts: number+): boolean {+ return (+ deps.now() - startedAt >= deps.pendingRetryWindowMs ||+ attempts >= MAX_PENDING_ATTEMPTS+ )+}++async function waitBeforePendingRetry(+ deps: OperatorAdminDependencies,+ startedAt: number+): Promise<void> {+ await deps.sleep(+ Math.min(+ PENDING_RETRY_DELAY_MS,+ Math.max(0, deps.pendingRetryWindowMs - (deps.now() - startedAt))+ )+ )+}++async function listPendingRequests(+ deps: OperatorAdminDependencies,+ baseUrl: string,+ token: string+): Promise<PendingCliRequest[]> {+ const startedAt = deps.now()+ let attempts = 0+ while (attempts < MAX_PENDING_ATTEMPTS) {+ attempts += 1+ const elapsed = Math.max(0, deps.now() - startedAt)+ const remaining = Math.max(1, deps.pendingRetryWindowMs - elapsed)+ const controller = new AbortController()+ const timeout = setTimeout(() => controller.abort(), remaining)+ let response: Response+ try {+ response = await deps.fetch(+ `${baseUrl}/rpc/query/${encodeURIComponent(+ BridgeQueries.ListPendingPairRequests+ )}`,+ {+ ...requestInit(token, []),+ signal: controller.signal,+ }+ )+ } catch {+ if (retryWindowExpired(deps, startedAt, attempts)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Unavailable,+ OperatorAdminErrorCode.LoopbackUnavailable+ )+ }+ await waitBeforePendingRetry(deps, startedAt)+ continue+ } finally {+ clearTimeout(timeout)+ }++ if (response.status === 404) {+ const isStartupResponse = await isUnknownChannelResponse(response)+ if (!isStartupResponse) classifyHttpStatus(response.status, false)+ if (retryWindowExpired(deps, startedAt, attempts)) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Unavailable,+ OperatorAdminErrorCode.ApprovalNotReady+ )+ }+ await waitBeforePendingRetry(deps, startedAt)+ continue+ }+ if (!response.ok) {+ await discardResponse(response)+ classifyHttpStatus(response.status, false)+ }++ const parsed = pendingResponseSchema.safeParse(+ await parseJsonResponse(response)+ )+ if (!parsed.success) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.PendingResponseInvalid+ )+ }+ return parsed.data+ }++ throw new OperatorAdminError(+ OperatorAdminErrorKind.Unavailable,+ OperatorAdminErrorCode.ApprovalNotReady+ )+}++async function resolvePairRequest(+ deps: OperatorAdminDependencies,+ baseUrl: string,+ token: string,+ params: ResolvePairParams+): Promise<void> {+ const controller = new AbortController()+ const timeout = setTimeout(() => controller.abort(), deps.mutationTimeoutMs)+ try {+ const response = await deps.fetch(+ `${baseUrl}/rpc/command/${encodeURIComponent(+ BridgeCommands.ResolvePair+ )}`,+ {+ ...requestInit(token, [params]),+ signal: controller.signal,+ }+ )+ if (!response.ok) {+ await discardResponse(response)+ classifyHttpStatus(response.status, true)+ }+ const parsed = resolvePairResultSchema.safeParse(+ await parseJsonResponse(response)+ )+ if (!parsed.success) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.DecisionResponseInvalid+ )+ }+ if (!parsed.data.ok) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.RequestNoLongerPending+ )+ }+ } catch (error) {+ if (error instanceof OperatorAdminError) throw error+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.DecisionOutcomeUnknown+ )+ } finally {+ clearTimeout(timeout)+ }+}++function findUniqueRequest(+ requests: readonly PendingCliRequest[],+ userCode: string+): PendingCliRequest {+ const matches = requests.filter((request) => request.userCode === userCode)+ if (matches.length === 0) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.NoMatchingRequest,+ { userCode }+ )+ }+ if (matches.length !== 1) {+ throw new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.AmbiguousRequest,+ { userCode }+ )+ }+ return matches[0] as PendingCliRequest+}++function safeOutputText(value: string, maximum: number): string {+ const cleaned = value+ .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ')+ .replace(/\s+/gu, ' ')+ .trim()+ const limited = [...cleaned].slice(0, maximum).join('')+ return limited || '-'+}++function projectRequest(request: PendingCliRequest): ProjectedPairRequest {+ return {+ userCode: request.userCode,+ clientName: safeOutputText(request.clientName, MAX_CLIENT_NAME_LENGTH),+ clientVersion: safeOutputText(+ request.clientVersion,+ MAX_CLIENT_VERSION_LENGTH+ ),+ createdAt: request.createdAt,+ expiresAt: request.expiresAt,+ }+}++function formatTtl(t: Translate, expiresAt: number, now: number): string {+ const seconds = Math.max(0, Math.ceil((expiresAt - now) / 1_000))+ return t('operatorAdmin.pending.ttl', {+ minutes: Math.floor(seconds / 60),+ seconds: seconds % 60,+ })+}++function printPending(+ deps: OperatorAdminDependencies,+ t: Translate,+ requests: readonly PendingCliRequest[],+ json: boolean+): void {+ const sorted = [...requests].sort(+ (left, right) => left.createdAt - right.createdAt+ )+ const projected = sorted.map(projectRequest)+ if (json) {+ deps.writeStdout(JSON.stringify({ ok: true, requests: projected }))+ return+ }+ if (projected.length === 0) {+ deps.writeStdout(t('operatorAdmin.pending.none'))+ return+ }+ for (const request of projected) {+ deps.writeStdout(+ t('operatorAdmin.pending.row', {+ userCode: request.userCode,+ clientName: request.clientName,+ clientVersion: request.clientVersion,+ ttl: formatTtl(t, request.expiresAt, deps.now()),+ })+ )+ }+}++function printDecision(+ deps: OperatorAdminDependencies,+ t: Translate,+ request: PendingCliRequest,+ operation: 'approve' | 'deny',+ json: boolean+): void {+ const projected = projectRequest(request)+ if (json) {+ deps.writeStdout(+ JSON.stringify({+ ok: true,+ action: operation,+ request: projected,+ })+ )+ return+ }+ deps.writeStdout(+ t(`operatorAdmin.decision.${operation}`, {+ userCode: projected.userCode,+ clientName: projected.clientName,+ clientVersion: projected.clientVersion,+ })+ )+}++function printError(+ deps: OperatorAdminDependencies,+ t: Translate,+ error: OperatorAdminError,+ json: boolean+): void {+ const message = safeOutputText(+ t(`operatorAdmin.errors.${error.code}`, error.values),+ 240+ )+ if (json) {+ deps.writeStderr(+ JSON.stringify({+ ok: false,+ error: { code: error.code, kind: error.kind, message },+ })+ )+ return+ }+ deps.writeStderr(t('operatorAdmin.errorPrefix', { message }))+ if (error.kind === OperatorAdminErrorKind.Usage) {+ deps.writeStderr(t('operatorAdmin.usageHint'))+ }+}++export async function runOperatorAdmin(+ argv: readonly string[],+ options: OperatorAdminOptions = {}+): Promise<OperatorAdminExitCode> {+ const deps = defaultDependencies(options)+ const t = await createTranslator(deps.env)+ let json = argv.includes('--json')+ try {+ const command = parseCommand(argv)+ if (command === 'help') {+ deps.writeStdout(t('operatorAdmin.help'))+ return OperatorAdminExitCode.Success+ }+ json = command.json++ const token = await readOperatorToken(deps)+ const baseUrl = serverBaseUrl(deps.env)+ const pending = await listPendingRequests(deps, baseUrl, token)+ if (command.operation === 'pending') {+ printPending(deps, t, pending, command.json)+ return OperatorAdminExitCode.Success+ }++ const request = findUniqueRequest(pending, command.userCode as string)+ const params: ResolvePairParams = {+ kind: 'cli',+ requestId: request.requestId,+ decision: command.operation === 'approve' ? 'allow' : 'deny',+ }+ await resolvePairRequest(deps, baseUrl, token, params)+ printDecision(deps, t, request, command.operation, command.json)+ return OperatorAdminExitCode.Success+ } catch (error) {+ const normalized =+ error instanceof OperatorAdminError+ ? error+ : new OperatorAdminError(+ OperatorAdminErrorKind.Server,+ OperatorAdminErrorCode.Unexpected+ )+ printError(deps, t, normalized, json)+ return exitCodeFor(normalized)+ }+}diff --git a/src/server/operator-cli.ts b/src/server/operator-cli.tsnew file mode 100644index 00000000..258d654f--- /dev/null+++ b/src/server/operator-cli.ts@@ -0,0 +1,5 @@+#!/usr/bin/env node++import { runOperatorAdmin } from './operator-admin'++process.exitCode = await runOperatorAdmin(process.argv.slice(2))diff --git a/src/server/plugin/install-service.integration.test.ts b/src/server/plugin/install-service.integration.test.tsindex 7e6d62a3..2b32e8e9 100644--- a/src/server/plugin/install-service.integration.test.ts+++ b/src/server/plugin/install-service.integration.test.ts@@ -33,6 +33,11 @@ function capabilityHost(): CapabilityHost {} as unknown as CapabilityHost}+const runtimeHost = {+ deactivate: async () => undefined,+ isQuiescent: () => true,+}+describe('Server plugin install lifecycle integration', () => {it('installs, persists enablement across rediscovery, and uninstalls', async () => {const root = await mkdtemp(path.join(tmpdir(), 'motrix-server-plugin-e2e-'))@@ -72,13 +77,16 @@ describe('Server plugin install lifecycle integration', () => {.update(await readFile(fixture)).digest('hex')- const staged = await service.stage({- sourceType: 'local',- absPath: fixture,- fileHash,- })+ const staged = await service.stage(+ {+ sourceType: 'local',+ absPath: fixture,+ fileHash,+ },+ runtimeHost+ )expect(staged.committed).toBe(false)- await installer.commit(staged.stagingId, { notify: 'denied' })+ await installer.commit(staged.stagingId, { notify: 'denied' }, runtimeHost)expect(existsSync(path.join(pluginsDir, 'test.demo-config', '_install.json'))).toBe(true)@@ -102,7 +110,7 @@ describe('Server plugin install lifecycle integration', () => {capabilityHost: capabilityHost(),hostVersion: '2.0.0',})- await restartedInstaller.uninstall('test.demo-config')+ await restartedInstaller.uninstall('test.demo-config', runtimeHost)expect(restartedRegistry.get('test.demo-config')).toBeUndefined()expect(existsSync(path.join(pluginsDir, 'test.demo-config'))).toBe(false)database.close()diff --git a/src/server/plugin/install-service.ts b/src/server/plugin/install-service.tsindex a3440413..71533443 100644--- a/src/server/plugin/install-service.ts+++ b/src/server/plugin/install-service.ts@@ -7,6 +7,7 @@ import {} from '@core/plugin/install/github-fetcher'import type {PluginInstaller,+ PluginRuntimeHostLike,StageResult,} from '@core/plugin/install/plugin-installer'import {@@ -120,14 +121,17 @@ export class ServerPluginInstallService {this.fetchImpl = options.fetchImpl ?? fetch}- async stage(rawPayload: unknown): Promise<StageResult> {+ async stage(+ rawPayload: unknown,+ runtimeHost?: PluginRuntimeHostLike+ ): Promise<StageResult> {const payload = serverInstallPluginPayloadSchema.parse(rawPayload)const materialized = await this.materialize(payload)try {return await this.options.installer.stage(materialized.moextPath,materialized.source,- { expect: materialized.expect }+ { expect: materialized.expect, runtimeHost })} finally {if (materialized.temporary) {diff --git a/src/server/plugin/upload-store.test.ts b/src/server/plugin/upload-store.test.tsindex c72f7a41..23bb924e 100644--- a/src/server/plugin/upload-store.test.ts+++ b/src/server/plugin/upload-store.test.ts@@ -1,8 +1,8 @@import { createHash } from 'node:crypto'-import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { mkdtemp, readdir, readFile, rm, utimes } from 'node:fs/promises'import { tmpdir } from 'node:os'import path from 'node:path'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { PluginUploadStore } from './upload-store'let root: string@@ -14,6 +14,7 @@ beforeEach(async () => {})afterEach(async () => {+ store.dispose()await rm(root, { recursive: true, force: true })})@@ -31,6 +32,17 @@ describe('PluginUploadStore', () => {).rejects.toMatchObject({ message: 'plugin.install.upload_not_found' })})+ it('computes the authoritative hash when the browser omits a claim', async () => {+ const bytes = Buffer.from('plain HTTP plugin bytes')+ const expectedHash = createHash('sha256').update(bytes).digest('hex')++ await expect(+ store.put(bytes, undefined, 'lan.moext')+ ).resolves.toMatchObject({+ fileHash: expectedHash,+ })+ })+it('rejects a mismatched hash and a non-moext filename', async () => {const bytes = Buffer.from('plugin bytes')await expect(@@ -51,4 +63,117 @@ describe('PluginUploadStore', () => {message: 'plugin.install.upload_reference_invalid',})})++ it('enforces the retained-file count under concurrent puts', async () => {+ const countLimitedStore = new PluginUploadStore(root, {+ maxCount: 1,+ maxTotalBytes: 100,+ })+ const first = Buffer.from('first plugin')+ const second = Buffer.from('second plugin')+ const results = await Promise.allSettled([+ countLimitedStore.put(+ first,+ createHash('sha256').update(first).digest('hex'),+ 'first.moext'+ ),+ countLimitedStore.put(+ second,+ createHash('sha256').update(second).digest('hex'),+ 'second.moext'+ ),+ ])++ expect(+ results.filter((result) => result.status === 'fulfilled')+ ).toHaveLength(1)+ const rejection = results.find((result) => result.status === 'rejected')+ expect(rejection).toMatchObject({+ reason: { message: 'plugin.install.upload_quota_exceeded' },+ })+ expect(await readdir(root)).toHaveLength(1)+ countLimitedStore.dispose()+ })++ it('rejects before a put would exceed the retained byte quota', async () => {+ const byteLimitedStore = new PluginUploadStore(root, {+ maxCount: 10,+ maxTotalBytes: 12,+ })+ const first = Buffer.from('12345678')+ await byteLimitedStore.put(+ first,+ createHash('sha256').update(first).digest('hex'),+ 'first.moext'+ )+ const second = Buffer.from('abcdef')++ await expect(+ byteLimitedStore.put(+ second,+ createHash('sha256').update(second).digest('hex'),+ 'second.moext'+ )+ ).rejects.toMatchObject({+ message: 'plugin.install.upload_quota_exceeded',+ })+ expect(await readdir(root)).toHaveLength(1)+ byteLimitedStore.dispose()+ })++ it('removes TTL-expired uploads and makes quota available again', async () => {+ let clock = Date.now()+ const expiringStore = new PluginUploadStore(root, {+ maxCount: 1,+ maxTotalBytes: 100,+ ttlMs: 1_000,+ now: () => clock,+ })+ const first = Buffer.from('first plugin')+ const reference = await expiringStore.put(+ first,+ createHash('sha256').update(first).digest('hex'),+ 'first.moext'+ )+ const firstPath = path.join(root, `${reference.uploadId}.moext`)+ const expiredAt = new Date(clock - 1_001)+ await utimes(firstPath, expiredAt, expiredAt)++ expect(await expiringStore.cleanupExpired()).toBe(1)+ await expect(+ expiringStore.resolve(reference.uploadId, reference.fileHash)+ ).rejects.toMatchObject({ message: 'plugin.install.upload_not_found' })++ clock += 1+ const second = Buffer.from('second plugin')+ await expect(+ expiringStore.put(+ second,+ createHash('sha256').update(second).digest('hex'),+ 'second.moext'+ )+ ).resolves.toMatchObject({+ fileHash: createHash('sha256').update(second).digest('hex'),+ })+ expiringStore.dispose()+ })++ it('clears its scheduled cleanup timer on dispose', async () => {+ vi.useFakeTimers()+ try {+ vi.setSystemTime(Date.now())+ const disposableStore = new PluginUploadStore(root, { ttlMs: 1_000 })+ const bytes = Buffer.from('plugin bytes')+ await disposableStore.put(+ bytes,+ createHash('sha256').update(bytes).digest('hex'),+ 'plugin.moext'+ )+ expect(vi.getTimerCount()).toBe(1)+ disposableStore.dispose()+ expect(vi.getTimerCount()).toBe(0)+ } finally {+ vi.useRealTimers()+ }+ })})diff --git a/src/server/plugin/upload-store.ts b/src/server/plugin/upload-store.tsindex 2c70b8b2..9d755f9f 100644--- a/src/server/plugin/upload-store.ts+++ b/src/server/plugin/upload-store.ts@@ -1,28 +1,82 @@import { createHash, randomUUID } from 'node:crypto'-import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'+import type { Dirent } from 'node:fs'+import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'export const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024+export const DEFAULT_PLUGIN_UPLOAD_MAX_COUNT = 16+export const DEFAULT_PLUGIN_UPLOAD_TOTAL_BYTES = 32 * 1024 * 1024+export const DEFAULT_PLUGIN_UPLOAD_TTL_MS = 60 * 60 * 1000+const SHA256_RE = /^[0-9a-f]{64}$/-const UPLOAD_ID_RE =- /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/+const UPLOAD_ID_SOURCE =+ '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'+const UPLOAD_ID_RE = new RegExp(`^${UPLOAD_ID_SOURCE}$`)+const UPLOAD_FILE_RE = new RegExp(`^${UPLOAD_ID_SOURCE}\\.moext$`)function sha256(bytes: Uint8Array): string {return createHash('sha256').update(bytes).digest('hex')}+function isMissingFile(cause: unknown): boolean {+ return (+ cause instanceof Error &&+ 'code' in cause &&+ (cause as NodeJS.ErrnoException).code === 'ENOENT'+ )+}++function assertPositiveInteger(value: number, name: string): void {+ if (!Number.isSafeInteger(value) || value <= 0) {+ throw new TypeError(`${name} must be a positive integer`)+ }+}+export interface PluginUploadReference {uploadId: stringfileHash: string}+export interface PluginUploadStoreOptions {+ maxCount?: number+ maxTotalBytes?: number+ ttlMs?: number+ now?: () => number+}++interface UploadInventoryEntry {+ path: string+ size: number+ modifiedAt: number+}+export class PluginUploadStore {- constructor(private readonly uploadsDir: string) {}+ private readonly maxCount: number+ private readonly maxTotalBytes: number+ private readonly ttlMs: number+ private readonly now: () => number+ private operationQueue: Promise<void> = Promise.resolve()+ private cleanupTimer: ReturnType<typeof setTimeout> | undefined+ private disposed = false++ constructor(+ private readonly uploadsDir: string,+ options: PluginUploadStoreOptions = {}+ ) {+ this.maxCount = options.maxCount ?? DEFAULT_PLUGIN_UPLOAD_MAX_COUNT+ this.maxTotalBytes =+ options.maxTotalBytes ?? DEFAULT_PLUGIN_UPLOAD_TOTAL_BYTES+ this.ttlMs = options.ttlMs ?? DEFAULT_PLUGIN_UPLOAD_TTL_MS+ this.now = options.now ?? Date.now+ assertPositiveInteger(this.maxCount, 'maxCount')+ assertPositiveInteger(this.maxTotalBytes, 'maxTotalBytes')+ assertPositiveInteger(this.ttlMs, 'ttlMs')+ }async put(bytes: Buffer,- claimedHash: string,+ claimedHash: string | undefined,originalName: string): Promise<PluginUploadReference> {if (bytes.byteLength === 0 || bytes.byteLength > MAX_PLUGIN_UPLOAD_BYTES) {@@ -38,19 +92,38 @@ export class PluginUploadStore {)}const fileHash = sha256(bytes)- if (!SHA256_RE.test(claimedHash) || claimedHash !== fileHash) {+ if (+ claimedHash !== undefined &&+ (!SHA256_RE.test(claimedHash) || claimedHash !== fileHash)+ ) {throw new AppError(ErrorCode.PluginManifestInvalid,'plugin.install.local_file_hash_mismatch')}- await mkdir(this.uploadsDir, { recursive: true })- const uploadId = randomUUID()- await writeFile(this.pathFor(uploadId), bytes, {- flag: 'wx',- mode: 0o600,++ return this.exclusive(async () => {+ await mkdir(this.uploadsDir, { recursive: true })+ const inventory = await this.cleanupAndInventory()+ const totalBytes = inventory.reduce((sum, entry) => sum + entry.size, 0)+ if (+ inventory.length >= this.maxCount ||+ totalBytes + bytes.byteLength > this.maxTotalBytes+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_quota_exceeded'+ )+ }++ const uploadId = randomUUID()+ await writeFile(this.pathFor(uploadId), bytes, {+ flag: 'wx',+ mode: 0o600,+ })+ await this.cleanupAndInventory()+ return { uploadId, fileHash }})- return { uploadId, fileHash }}async resolve(uploadId: string, expectedHash: string): Promise<string> {@@ -60,31 +133,125 @@ export class PluginUploadStore {'plugin.install.upload_reference_invalid')}- let bytes: Buffer- try {- bytes = await readFile(this.pathFor(uploadId))- } catch (cause) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.upload_not_found',- cause- )- }- if (- bytes.byteLength > MAX_PLUGIN_UPLOAD_BYTES ||- sha256(bytes) !== expectedHash- ) {- throw new AppError(- ErrorCode.PluginManifestInvalid,- 'plugin.install.local_file_hash_mismatch'- )- }- return this.pathFor(uploadId)++ return this.exclusive(async () => {+ await this.cleanupAndInventory()+ const uploadPath = this.pathFor(uploadId)+ let bytes: Buffer+ try {+ bytes = await readFile(uploadPath)+ } catch (cause) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.upload_not_found',+ cause+ )+ }+ if (+ bytes.byteLength > MAX_PLUGIN_UPLOAD_BYTES ||+ sha256(bytes) !== expectedHash+ ) {+ throw new AppError(+ ErrorCode.PluginManifestInvalid,+ 'plugin.install.local_file_hash_mismatch'+ )+ }+ return uploadPath+ })}async remove(uploadId: string): Promise<void> {if (!UPLOAD_ID_RE.test(uploadId)) return- await rm(this.pathFor(uploadId), { force: true })+ await this.exclusive(async () => {+ await rm(this.pathFor(uploadId), { force: true })+ await this.cleanupAndInventory()+ })+ }++ /** Remove retained upload packages whose TTL elapsed. */+ async cleanupExpired(): Promise<number> {+ return this.exclusive(async () => {+ const before = await this.inventory()+ const after = await this.cleanupAndInventory(before)+ return before.length - after.length+ })+ }++ dispose(): void {+ this.disposed = true+ if (this.cleanupTimer) clearTimeout(this.cleanupTimer)+ this.cleanupTimer = undefined+ }++ private exclusive<T>(operation: () => Promise<T>): Promise<T> {+ const result = this.operationQueue.then(operation, operation)+ this.operationQueue = result.then(+ () => undefined,+ () => undefined+ )+ return result+ }++ private async cleanupAndInventory(+ current?: readonly UploadInventoryEntry[]+ ): Promise<UploadInventoryEntry[]> {+ const inventory = current ?? (await this.inventory())+ const cutoff = this.now() - this.ttlMs+ const retained: UploadInventoryEntry[] = []+ for (const entry of inventory) {+ if (entry.modifiedAt <= cutoff) {+ await rm(entry.path, { force: true })+ } else {+ retained.push(entry)+ }+ }+ this.scheduleCleanup(retained)+ return retained+ }++ private scheduleCleanup(inventory: readonly UploadInventoryEntry[]): void {+ if (this.cleanupTimer) clearTimeout(this.cleanupTimer)+ this.cleanupTimer = undefined+ if (this.disposed) return+ const nextExpiry = Math.min(+ ...inventory.map((entry) => entry.modifiedAt + this.ttlMs)+ )+ if (!Number.isFinite(nextExpiry)) return+ const delay = Math.max(1, Math.min(2_147_483_647, nextExpiry - this.now()))+ this.cleanupTimer = setTimeout(() => {+ this.cleanupTimer = undefined+ void this.cleanupExpired().catch(() => undefined)+ }, delay)+ this.cleanupTimer.unref()+ }++ private async inventory(): Promise<UploadInventoryEntry[]> {+ let directoryEntries: Dirent[]+ try {+ directoryEntries = await readdir(this.uploadsDir, {+ withFileTypes: true,+ })+ } catch (cause) {+ if (isMissingFile(cause)) return []+ throw cause+ }++ const inventory: UploadInventoryEntry[] = []+ for (const entry of directoryEntries) {+ if (!entry.isFile() || !UPLOAD_FILE_RE.test(entry.name)) continue+ const uploadPath = path.join(this.uploadsDir, entry.name)+ try {+ const metadata = await stat(uploadPath)+ inventory.push({+ path: uploadPath,+ size: metadata.size,+ modifiedAt: metadata.mtimeMs,+ })+ } catch (cause) {+ if (!isMissingFile(cause)) throw cause+ }+ }+ return inventory}private pathFor(uploadId: string): string {diff --git a/src/server/routes/plugin-uploads.test.ts b/src/server/routes/plugin-uploads.test.tsindex a7af7d17..6ef21f6d 100644--- a/src/server/routes/plugin-uploads.test.ts+++ b/src/server/routes/plugin-uploads.test.ts@@ -22,7 +22,7 @@ afterEach(async () => {})describe('plugin upload route', () => {- it('returns an opaque upload reference for a verified package', async () => {+ it('returns a server-hashed opaque reference without a client digest', async () => {const app = Fastify()registerPluginUploadRoute(app, new PluginUploadStore(root))const bytes = Buffer.from('plugin bytes')@@ -34,7 +34,6 @@ describe('plugin upload route', () => {headers: {'content-type': PLUGIN_UPLOAD_CONTENT_TYPE,'x-motrix-file-name': encodeURIComponent('test.moext'),- 'x-motrix-file-sha256': fileHash,},payload: bytes,})diff --git a/src/server/routes/plugin-uploads.ts b/src/server/routes/plugin-uploads.tsindex fbd0ad56..d5d4e875 100644--- a/src/server/routes/plugin-uploads.ts+++ b/src/server/routes/plugin-uploads.ts@@ -29,8 +29,14 @@ export function registerPluginUploadRoute(try {const encodedName = headerValue(request.headers['x-motrix-file-name'])const fileName = decodeURIComponent(encodedName)- const fileHash = headerValue(request.headers['x-motrix-file-sha256'])- const reference = await store.put(request.body, fileHash, fileName)+ // The server is the authority for the retained package digest. Older+ // clients may still send a claimed digest, which is verified when+ // present; omitting it keeps uploads usable on plain LAN HTTP where+ // browser Web Crypto is not exposed.+ const claimedHash =+ headerValue(request.headers['x-motrix-file-sha256']).trim() ||+ undefined+ const reference = await store.put(request.body, claimedHash, fileName)return reply.code(201).send(reference)} catch (cause) {request.log.warn({ err: cause }, 'plugin upload rejected')diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex bef48be8..35e0eb41 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -6,6 +6,57 @@"error": "Invalid operator token. Check MOTRIX_OPERATOR_TOKEN or <dataDir>/operator-token on the host and try again.","submit": "Unlock"},+ "operatorAdmin": {+ "help": "Usage:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n\nThe command talks only to the running Motrix server over container loopback.",+ "errorPrefix": "motrix-admin: {{message}}",+ "usageHint": "Run 'motrix-admin --help' for usage.",+ "pending": {+ "none": "No pending pairing requests.",+ "row": "{{userCode}} {{clientName}} {{clientVersion}} expires in {{ttl}}",+ "ttl": "{{minutes}}m {{seconds}}s"+ },+ "decision": {+ "approve": "Approved {{userCode}} for {{clientName}} ({{clientVersion}}).",+ "deny": "Denied {{userCode}} for {{clientName}} ({{clientVersion}})."+ },+ "errors": {+ "usage": {+ "jsonRepeated": "--json may only be specified once.",+ "unknownOption": "Unknown command-line option.",+ "pairingCommandRequired": "Expected the pairing command.",+ "pairingOperationRequired": "Expected pairing pending, pairing approve CODE, or pairing deny CODE.",+ "pairingCodeInvalid": "Pairing code must contain eight ASCII characters and cannot use I, O, 0, or 1.",+ "portInvalid": "PORT must be an integer between 1 and 65535."+ },+ "credential": {+ "tokenHeaderInvalid": "MOTRIX_OPERATOR_TOKEN cannot be used in an HTTP header.",+ "dataDirNotAbsolute": "MOTRIX_DATA_DIR must be an absolute path.",+ "unavailable": "Operator credential is unavailable. Set MOTRIX_OPERATOR_TOKEN or ensure operator-token exists in the data directory.",+ "notFile": "Operator credential path is not a regular file.",+ "unreadable": "Operator credential could not be read.",+ "invalid": "Operator credential file is invalid.",+ "rejected": "Operator credential was rejected by Motrix."+ },+ "server": {+ "responseUnreadable": "Motrix returned an unreadable response.",+ "responseOversized": "Motrix returned an oversized response.",+ "responseInvalidJson": "Motrix returned an invalid JSON response.",+ "rpcHttp": "Motrix pairing RPC failed with HTTP {{status}}.",+ "approvalUnavailable": "Pairing approval is not available in the running Motrix server.",+ "pendingResponseInvalid": "Motrix returned an invalid pending-pairing response.",+ "decisionOutcomeUnknown": "The pairing decision outcome is unknown. Run pairing pending before trying again.",+ "decisionResponseInvalid": "Motrix returned an invalid pairing-decision response.",+ "requestNoLongerPending": "Pairing request is no longer pending.",+ "noMatchingRequest": "No pending pairing request matches {{userCode}}.",+ "ambiguousRequest": "More than one pending pairing request matches {{userCode}}; no decision was applied.",+ "unexpected": "Unexpected motrix-admin failure."+ },+ "unavailable": {+ "loopback": "The running Motrix server is unavailable on container loopback.",+ "approvalNotReady": "Pairing approval is not ready in the running Motrix server."+ }+ }+ },"common": {"download": "Download","cancel": "Cancel",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 452460ff..c1cabc8c 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -6,6 +6,57 @@"error": "operator token 无效。请核对 host 上的 MOTRIX_OPERATOR_TOKEN 或 <dataDir>/operator-token 后重试。","submit": "解锁"},+ "operatorAdmin": {+ "help": "用法:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <配对码> [--json]\n motrix-admin pairing deny <配对码> [--json]\n\n此命令仅通过容器内的本机回环地址与正在运行的 Motrix 服务器通信。",+ "errorPrefix": "motrix-admin:{{message}}",+ "usageHint": "运行“motrix-admin --help”查看用法。",+ "pending": {+ "none": "没有待处理的配对请求。",+ "row": "{{userCode}} {{clientName}} {{clientVersion}} 剩余 {{ttl}}",+ "ttl": "{{minutes}} 分 {{seconds}} 秒"+ },+ "decision": {+ "approve": "已允许 {{clientName}}({{clientVersion}})使用配对码 {{userCode}}。",+ "deny": "已拒绝 {{clientName}}({{clientVersion}})使用配对码 {{userCode}}。"+ },+ "errors": {+ "usage": {+ "jsonRepeated": "--json 只能指定一次。",+ "unknownOption": "未知的命令行选项。",+ "pairingCommandRequired": "需要使用 pairing 命令。",+ "pairingOperationRequired": "需要使用 pairing pending、pairing approve 配对码或 pairing deny 配对码。",+ "pairingCodeInvalid": "配对码必须包含 8 个 ASCII 字符,且不能使用 I、O、0 或 1。",+ "portInvalid": "PORT 必须是 1 到 65535 之间的整数。"+ },+ "credential": {+ "tokenHeaderInvalid": "MOTRIX_OPERATOR_TOKEN 不能用于 HTTP 请求头。",+ "dataDirNotAbsolute": "MOTRIX_DATA_DIR 必须是绝对路径。",+ "unavailable": "Operator 凭据不可用。请设置 MOTRIX_OPERATOR_TOKEN,或确保数据目录中存在 operator-token 文件。",+ "notFile": "Operator 凭据路径不是普通文件。",+ "unreadable": "无法读取 Operator 凭据。",+ "invalid": "Operator 凭据文件无效。",+ "rejected": "Motrix 拒绝了 Operator 凭据。"+ },+ "server": {+ "responseUnreadable": "无法读取 Motrix 返回的响应。",+ "responseOversized": "Motrix 返回的响应过大。",+ "responseInvalidJson": "Motrix 返回了无效的 JSON 响应。",+ "rpcHttp": "Motrix 配对 RPC 请求失败,HTTP 状态码为 {{status}}。",+ "approvalUnavailable": "正在运行的 Motrix 服务器不支持配对审批。",+ "pendingResponseInvalid": "Motrix 返回了无效的待处理配对响应。",+ "decisionOutcomeUnknown": "配对决定的结果未知。请先运行 pairing pending,再决定是否重试。",+ "decisionResponseInvalid": "Motrix 返回了无效的配对决定响应。",+ "requestNoLongerPending": "配对请求已不再处于待处理状态。",+ "noMatchingRequest": "没有待处理的配对请求与 {{userCode}} 匹配。",+ "ambiguousRequest": "有多个待处理的配对请求与 {{userCode}} 匹配,因此未执行任何决定。",+ "unexpected": "motrix-admin 遇到意外故障。"+ },+ "unavailable": {+ "loopback": "无法通过容器内的本机回环地址连接正在运行的 Motrix 服务器。",+ "approvalNotReady": "正在运行的 Motrix 服务器尚未准备好配对审批。"+ }+ }+ },"common": {"download": "下载","cancel": "取消",diff --git a/tests/scripts/audit-server-runtime.test.ts b/tests/scripts/audit-server-runtime.test.tsindex 33dc0309..5da9e392 100644--- a/tests/scripts/audit-server-runtime.test.ts+++ b/tests/scripts/audit-server-runtime.test.ts@@ -210,6 +210,14 @@ describe('Server package contracts', () => {expect(() => validateServerRuntimeContract(duplicateDestination)).toThrow('duplicate input destinations')+ const unsortedEntries = fixtureContract()+ const serverInput = unsortedEntries.buildInputs[2] as {+ entry: string | string[] | null+ }+ serverInput.entry = ['motrix-admin.mjs', 'index.mjs']+ expect(() => validateServerRuntimeContract(unsortedEntries)).toThrow(+ 'unique paths in sorted order'+ )})it('requires exact non-negative size budgets', () => {@@ -242,6 +250,10 @@ describe('Server package contracts', () => {'dist/renderer-web','dist/server',])+ expect(contract.buildInputs.at(-1)?.entry).toEqual([+ 'index.mjs',+ 'motrix-admin.mjs',+ ])expect(contract.resourceInputs.map((entry) => entry.source)).toEqual(['THIRD_PARTY_LICENSES','THIRD_PARTY_NOTICES.md',@@ -252,7 +264,7 @@ describe('Server package contracts', () => {'dist/builtin-plugins','extra/aria2.conf',])- expect(contract.runtimeRoots).toHaveLength(20)+ expect(contract.runtimeRoots).toHaveLength(21)expect(contract.runtimeRoots).not.toContain('electron-updater')expect(contract.runtimeRoots).not.toContain('@motrix/nat')})@@ -325,4 +337,62 @@ describe('Server built external audit', () => {})).rejects.toThrow('missing build entry: dist/server/index.mjs')})++ it('audits every declared entry in a multi-entry build directory', async () => {+ const root = await createFixture()+ await writeFixtureFile(+ root,+ 'dist/server/motrix-admin.mjs',+ 'import gamma from "gamma"; export default gamma;'+ )+ const contract = fixtureContract()+ const serverInput = contract.buildInputs[2] as {+ entry: string | string[] | null+ }+ serverInput.entry = ['index.mjs', 'motrix-admin.mjs']++ await expect(+ auditServerRuntime({+ repoRoot: root,+ contract,+ budgets: fixtureBudgets(),+ })+ ).rejects.toThrow('unexpected runtime roots: gamma')++ await rm(path.join(root, 'dist/server/motrix-admin.mjs'))+ await expect(+ auditServerRuntime({+ repoRoot: root,+ contract,+ budgets: fixtureBudgets(),+ })+ ).rejects.toThrow('missing build entry: dist/server/motrix-admin.mjs')+ })++ it('audits generated JavaScript chunks beside declared entries', async () => {+ const root = await createFixture()+ await writeFixtureFile(+ root,+ 'dist/server/motrix-admin.mjs',+ 'import path from "node:path"; export default path.sep;'+ )+ await writeFixtureFile(+ root,+ 'dist/server/chunks/shared.mjs',+ 'import gamma from "gamma"; export default gamma;'+ )+ const contract = fixtureContract()+ const serverInput = contract.buildInputs[2] as {+ entry: string | string[] | null+ }+ serverInput.entry = ['index.mjs', 'motrix-admin.mjs']++ await expect(+ auditServerRuntime({+ repoRoot: root,+ contract,+ budgets: fixtureBudgets(),+ })+ ).rejects.toThrow('unexpected runtime roots: gamma')+ })})diff --git a/tests/scripts/compose-server.test.ts b/tests/scripts/compose-server.test.tsindex b68d3b30..18964a70 100644--- a/tests/scripts/compose-server.test.ts+++ b/tests/scripts/compose-server.test.ts@@ -12,10 +12,12 @@ const require = createRequire(import.meta.url)const parseYaml = require('js-yaml').load as (source: string) => unknownconst 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 LEGACY_BIND_IP = interpolation('MOTRIX_BIND_IP:-0.0.0.0')+const WEB_BIND_IP = interpolation(`MOTRIX_WEB_BIND_IP:-${LEGACY_BIND_IP}`)+const MDXP_BIND_IP = interpolation(`MOTRIX_MDXP_BIND_IP:-${LEGACY_BIND_IP}`)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')+const PUBLIC_URL = interpolation('MOTRIX_PUBLIC_URL:-')function record(value: unknown, label: string): LooseRecord {if (value === null || typeof value !== 'object' || Array.isArray(value)) {@@ -51,8 +53,8 @@ describe('NAS-importable Compose contract', () => {'/tmp:rw,noexec,nosuid,size=64m,mode=1777',])expect(service.ports).toEqual([- `${BIND_IP}:${HTTP_PORT}:8080`,- `${BIND_IP}:${MDXP_PORT}:16801`,+ `${WEB_BIND_IP}:${HTTP_PORT}:8080`,+ `${MDXP_BIND_IP}:${MDXP_PORT}:16801`,])expect(service.environment).toEqual({MOTRIX_ALLOWED_SAVE_DIRS: '/downloads',@@ -91,4 +93,15 @@ describe('NAS-importable Compose contract', () => {'motrix-downloads': null,})})++ it('offers a host reverse-proxy environment without changing container listeners', async () => {+ const environment = await readFile(+ path.join(ROOT, 'compose.reverse-proxy.env'),+ 'utf8'+ )+ expect(environment).toContain('MOTRIX_WEB_BIND_IP=127.0.0.1')+ expect(environment).toContain('MOTRIX_MDXP_BIND_IP=127.0.0.1')+ expect(environment).not.toContain('MOTRIX_MDXP_HOST=127.0.0.1')+ expect(environment).not.toMatch(/^MOTRIX_PUBLIC_URL=/m)+ })})diff --git a/tests/scripts/docker-server-docs.test.ts b/tests/scripts/docker-server-docs.test.tsindex e19bf802..2628b354 100644--- a/tests/scripts/docker-server-docs.test.ts+++ b/tests/scripts/docker-server-docs.test.ts@@ -23,12 +23,17 @@ describe('public Docker Server documentation', () => {'latest','compose.yaml','compose.named-volumes.yaml',+ 'compose.reverse-proxy.env','/data','/downloads','MOTRIX_UID','MOTRIX_GID','operator-token',+ 'motrix-admin pairing approve ABCD-EFGH','MOTRIX_PUBLIC_URL',+ 'MOTRIX_WEB_BIND_IP',+ 'MOTRIX_MDXP_BIND_IP',+ 'MOTRIX_BIND_IP','/mdxp/events','/healthz','/api/diagnostics',@@ -50,6 +55,7 @@ describe('public Docker Server documentation', () => {const document = await text(file)expect(document).toContain('docker compose pull server')expect(document).toContain('docker compose up -d --wait')+ expect(document).toContain('motrix-admin pairing approve ABCD-EFGH')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 36c49010..045762c7 100644--- a/tests/scripts/docker-server-runtime.test.ts+++ b/tests/scripts/docker-server-runtime.test.ts@@ -59,6 +59,10 @@ describe('Docker Server runtime staging contract', () => {expect(runtime).toContain('COPY --from=build --chown=node:node /app/dist/server-app/ ./')+ expect(runtime).toContain(+ 'exec node /app/dist/server/motrix-admin.mjs "$@"'+ )+ expect(runtime).toContain('chmod 0755 /usr/local/bin/motrix-admin')expect(runtime.match(/^COPY /gm)).toHaveLength(1)expect(runtime).toContain('apk add --no-cache aria2 ca-certificates')expect(runtime).toContain('MOTRIX_ARIA2_BIN=/usr/bin/aria2c')@@ -136,6 +140,9 @@ describe('Docker Server runtime staging contract', () => {expect(imageSmoke).toContain("'command:setTaskBtTracker'")expect(imageSmoke).toContain("'command:installPlugin'")expect(imageSmoke).toContain("'command:uninstallPlugin'")+ expect(imageSmoke).toContain("'motrix-admin'")+ expect(imageSmoke).toContain("'pairing'")+ expect(imageSmoke).toContain("'pending'")expect(imageSmoke).toContain('Save directory is not writable: /downloads')expect(imageSmoke).toContain('did not survive container restart')})diff --git a/tests/scripts/release-signing-input.test.ts b/tests/scripts/release-signing-input.test.tsnew file mode 100644index 00000000..e85d2505--- /dev/null+++ b/tests/scripts/release-signing-input.test.ts@@ -0,0 +1,303 @@+import { createHash } from 'node:crypto'+import {+ cp,+ lstat,+ mkdir,+ mkdtemp,+ readdir,+ readFile,+ rm,+ truncate,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript release script intentionally has no declarations+import {+ createSigningArchive,+ SIGNING_ARCHIVE_LIMITS,+ verifySigningInput,+} from '../../scripts/release-signing-input.mjs'++const ROOT = process.cwd()+const COMMIT = 'a'.repeat(40)+const temporaryDirectories: string[] = []+const TRUSTED_FIXTURES = [+ ['electron-builder.signing.json', 'electron-builder.signing.json'],+ ['build/256x256.png', 'signing-build-resources/256x256.png'],+ ['build/background.tiff', 'signing-build-resources/background.tiff'],+ [+ 'build/entitlements.mac.plist',+ 'signing-build-resources/entitlements.mac.plist',+ ],+ ['build/icon.icns', 'signing-build-resources/icon.icns'],+ ['build/icon.ico', 'signing-build-resources/icon.ico'],+ ['build/torrent.icns', 'signing-build-resources/torrent.icns'],+ ['build/torrent.ico', 'signing-build-resources/torrent.ico'],+ ['build/installer.nsh', 'signing-policy/installer.nsh'],+ ['scripts/release-signing-tool/package.json', 'signing-tool/package.json'],+ [+ 'scripts/release-signing-tool/package-lock.json',+ 'signing-tool/package-lock.json',+ ],+ ['scripts/release-signing-input.mjs', 'scripts/release-signing-input.mjs'],+ [+ 'scripts/electron-package-size-budgets.json',+ 'scripts/electron-package-size-budgets.json',+ ],+ ['scripts/electron-package-utils.mjs', 'scripts/electron-package-utils.mjs'],+ ['scripts/native-binary-target.mjs', 'scripts/native-binary-target.mjs'],+ [+ 'scripts/verify-electron-package.mjs',+ 'scripts/verify-electron-package.mjs',+ ],+] as const++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true }))+ )+})++describe('isolated release signing input', () => {+ it('accepts a digest-complete data-only fixture', async () => {+ const directory = await createFixture()++ await expect(verify(directory)).resolves.toMatchObject({+ commit: COMMIT,+ target: { key: 'win32-x64', platform: 'win32', arch: 'x64' },+ tools: { electronBuilder: '26.15.7', electron: '43.3.0' },+ limits: SIGNING_ARCHIVE_LIMITS,+ })+ })++ it.each([+ 'trusted/electron.zip',+ 'release/preseeded.exe',+ 'package.json',+ 'electron-builder.env',+ 'dist/electron-app/electron-builder.env',+ 'dist/electron-app/ELECTRON-BUILDER.ENV',+ 'dist/electron-app/Package-Lock.json',+ 'dist/electron-app/pnpm-lock.yaml',+ 'dist/electron-app/yarn.lock',+ 'dist/electron-app/bun.lockb',+ 'dist/electron-app/.npmrc',+ 'dist/electron-app/.yarn/cache/package.zip',+ 'unreviewed-root-file.json',+ 'signing-build-resources/installer.nsi',+ 'signing-build-resources/installer.nsh',+ 'signing-build-resources/messages.yml',+ 'signing-build-resources/x86-unicode/plugin.dll',+ 'signing-build-resources/x86-ansi/plugin.dll',+ ])('rejects reserved signing input path %s', async (reservedPath) => {+ const directory = await createFixture({+ files: [[reservedPath, 'untrusted']],+ })++ await expect(verify(directory)).rejects.toThrow(+ /invalid file entry|reserved file|reserved directory/+ )+ })++ it.each(['trusted', 'release'])(+ 'rejects an empty reserved directory %s',+ async (reservedPath) => {+ const directory = await createFixture()+ await mkdir(path.join(directory, reservedPath))++ await expect(verify(directory)).rejects.toThrow(/reserved directory/)+ }+ )++ it('rejects a trusted config whose digest changed', async () => {+ const directory = await createFixture({+ mutateConfig: (config) => {+ config.beforePack = './untrusted.mjs'+ },+ })++ await expect(verify(directory)).rejects.toThrow(+ /trusted signing input digest mismatch/+ )+ })++ it('rejects a signing lock redirected away from the npm registry', async () => {+ const directory = await createFixture({+ mutateLock: (lock) => {+ const packages = lock.packages as Record<+ string,+ Record<string, unknown>+ >+ packages['node_modules/electron-builder']!.resolved =+ 'https://example.invalid/electron-builder.tgz'+ },+ })++ await expect(verify(directory)).rejects.toThrow(+ /trusted signing input digest mismatch/+ )+ })++ it('writes a deterministic bounded tar with manifest file modes', async () => {+ const directory = await createFixture()+ const executable = path.join(directory, 'extra/win32/x64/aria2c.exe')+ await mkdir(path.dirname(executable), { recursive: true })+ await writeFile(executable, 'binary', { mode: 0o755 })+ await refreshManifest(directory)+ const transport = await temporaryDirectory('motrix-signing-transport-')+ const archiveA = path.join(transport, 'signing-a.tar')+ const archiveB = path.join(transport, 'signing-b.tar')+ const options = { platform: 'win32', arch: 'x64' }++ await createSigningArchive(directory, archiveA, options)+ await createSigningArchive(directory, archiveB, options)++ const [left, right] = await Promise.all([+ readFile(archiveA),+ readFile(archiveB),+ ])+ expect(createHash('sha256').update(left).digest('hex')).toBe(+ createHash('sha256').update(right).digest('hex')+ )+ expect(left.length).toBeLessThanOrEqual(SIGNING_ARCHIVE_LIMITS.archiveBytes)+ expect(left.length % 512).toBe(0)+ expect(left.subarray(-1024).equals(Buffer.alloc(1024))).toBe(true)+ expect(left.includes(Buffer.from('0000755\0'))).toBe(true)+ })++ it('rejects a file above the per-file tar limit before reading it', async () => {+ const directory = await createFixture()+ const oversized = path.join(directory, 'dist/electron-app/oversized.bin')+ await mkdir(path.dirname(oversized), { recursive: true })+ await writeFile(oversized, '')+ await truncate(oversized, SIGNING_ARCHIVE_LIMITS.fileBytes + 1)+ const transport = await temporaryDirectory('motrix-signing-transport-')++ await expect(+ createSigningArchive(directory, path.join(transport, 'oversized.tar'), {+ platform: 'win32',+ arch: 'x64',+ })+ ).rejects.toThrow(/file exceeds limit/)+ })+})++async function verify(directory: string) {+ return verifySigningInput({+ mode: 'verify',+ directory,+ platform: 'win32',+ arch: 'x64',+ commit: COMMIT,+ })+}++async function temporaryDirectory(prefix: string): Promise<string> {+ const directory = await mkdtemp(path.join(os.tmpdir(), prefix))+ temporaryDirectories.push(directory)+ return directory+}++async function createFixture(+ options: {+ files?: Array<[string, string]>+ mutateConfig?: (config: Record<string, unknown>) => void+ mutateLock?: (lock: Record<string, unknown>) => void+ } = {}+): Promise<string> {+ const directory = await temporaryDirectory('motrix-signing-input-')++ for (const [source, destination] of TRUSTED_FIXTURES) {+ const target = path.join(directory, destination)+ await mkdir(path.dirname(target), { recursive: true })+ await cp(path.join(ROOT, source), target)+ }++ if (options.mutateConfig) {+ const configPath = path.join(directory, 'electron-builder.signing.json')+ const config = JSON.parse(await readFile(configPath, 'utf8')) as Record<+ string,+ unknown+ >+ options.mutateConfig(config)+ await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`)+ }+ if (options.mutateLock) {+ const lockPath = path.join(directory, 'signing-tool/package-lock.json')+ const lock = JSON.parse(await readFile(lockPath, 'utf8')) as Record<+ string,+ unknown+ >+ options.mutateLock(lock)+ await writeFile(lockPath, `${JSON.stringify(lock, null, 2)}\n`)+ }+ for (const [relativePath, content] of options.files ?? []) {+ await writeFixtureFile(directory, relativePath, content)+ }++ await refreshManifest(directory)+ return directory+}++async function refreshManifest(directory: string) {+ const manifestPath = path.join(directory, 'signing-input-manifest.json')+ await rm(manifestPath, { force: true })+ const manifest = {+ schemaVersion: 2,+ commit: COMMIT,+ target: { key: 'win32-x64', platform: 'win32', arch: 'x64' },+ tools: { electronBuilder: '26.15.7', electron: '43.3.0' },+ limits: SIGNING_ARCHIVE_LIMITS,+ files: await inventory(directory),+ }+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)+}++async function writeFixtureFile(+ root: string,+ relativePath: string,+ content: string+) {+ const destination = path.join(root, relativePath)+ await mkdir(path.dirname(destination), { recursive: true })+ await writeFile(destination, content)+}++async function inventory(root: string) {+ const files: Array<{+ path: string+ bytes: number+ mode: number+ sha256: string+ }> = []+ async function walk(directory: string, relative = ''): Promise<void> {+ const entries = await readdir(directory, { withFileTypes: true })+ entries.sort((left, right) =>+ left.name < right.name ? -1 : left.name > right.name ? 1 : 0+ )+ for (const entry of entries) {+ const absolute = path.join(directory, entry.name)+ const portable = path.posix.join(relative, entry.name)+ if (entry.isDirectory()) {+ await walk(absolute, portable)+ } else {+ const [bytes, info] = await Promise.all([+ readFile(absolute),+ lstat(absolute),+ ])+ files.push({+ path: portable,+ bytes: bytes.length,+ mode: (info.mode & 0o111) === 0 ? 0o644 : 0o755,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ })+ }+ }+ }+ await walk(root)+ return files+}diff --git a/tests/scripts/smoke-server-package.test.ts b/tests/scripts/smoke-server-package.test.tsindex 49807555..7f42429f 100644--- a/tests/scripts/smoke-server-package.test.ts+++ b/tests/scripts/smoke-server-package.test.ts@@ -95,6 +95,11 @@ async function createFixture(): Promise<{"process.once('SIGTERM', () => server.close(() => process.exit(0)))",].join('\n'))+ await writeFixtureFile(+ stageRoot,+ 'dist/server/motrix-admin.mjs',+ "console.log('motrix-admin pairing pending')\n"+ )await writeFixtureFile(stageRoot,'dist/renderer-web/index.html',@@ -123,6 +128,7 @@ describe('smokeServerPackage', () => {quickJsWorker: true,health: true,operatorAuth: true,+ operatorCli: true,shutdown: 'SIGTERM',}))diff --git a/tests/scripts/stage-server-app.test.ts b/tests/scripts/stage-server-app.test.tsindex 7f93ae9f..4a9631e9 100644--- a/tests/scripts/stage-server-app.test.ts+++ b/tests/scripts/stage-server-app.test.ts@@ -164,7 +164,7 @@ function fixtureContract() {source: 'dist/server',destination: 'dist/server',type: 'directory',- entry: 'index.mjs',+ entry: ['index.mjs', 'motrix-admin.mjs'],scanExternals: true,},],@@ -229,6 +229,11 @@ async function createFixture(): Promise<string> {'export { alpha, gamma };',].join('\n'))+ await writeFixtureFile(+ root,+ 'dist/server/motrix-admin.mjs',+ 'import path from "node:path"; export default path.sep;\n'+ )await writeFixtureFile(root,'dist/core/plugin/host/quick-js-worker.cjs',@@ -341,6 +346,11 @@ async function addBetterSqliteFixture(root: string): Promise<void> {'export { alpha, Database, gamma };',].join('\n'))+ await writeFixtureFile(+ root,+ 'dist/server/motrix-admin.mjs',+ 'import path from "node:path"; export default path.sep;\n'+ )}async function listSymlinks(root: string): Promise<string[]> {diff --git a/tests/scripts/verify-server-package.test.ts b/tests/scripts/verify-server-package.test.tsindex 9b889c80..fc34a826 100644--- a/tests/scripts/verify-server-package.test.ts+++ b/tests/scripts/verify-server-package.test.ts@@ -85,7 +85,7 @@ function fixtureContract() {source: 'dist/server',destination: 'dist/server',type: 'directory',- entry: 'index.mjs',+ entry: ['index.mjs', 'motrix-admin.mjs'],scanExternals: true,},],@@ -139,6 +139,11 @@ async function createStagedFixture(): Promise<{'dist/server/index.mjs','import Database from "better-sqlite3"; export default Database\n')+ await writeFixtureFile(+ root,+ 'dist/server/motrix-admin.mjs',+ 'import path from "node:path"; export default path.sep;\n'+ )await writeFixtureFile(root,'dist/core/plugin/host/quick-js-worker.cjs',@@ -243,6 +248,13 @@ describe('verifyServerPackage', () => {)})+ it('rejects a missing operator CLI bundle', async () => {+ const fixture = await createStagedFixture()+ await rm(path.join(fixture.stageRoot, 'dist/server/motrix-admin.mjs'))++ await expect(verifyFixture(fixture)).rejects.toThrow()+ })+it('rejects target drift and foreign native binaries', async () => {const fixture = await createStagedFixture()const stageManifestPath = path.join(diff --git a/tests/scripts/workflow-release-matrix.test.ts b/tests/scripts/workflow-release-matrix.test.tsindex 154ee5dd..3aef48fd 100644--- a/tests/scripts/workflow-release-matrix.test.ts+++ b/tests/scripts/workflow-release-matrix.test.ts@@ -1,6 +1,8 @@+import { createHash } from 'node:crypto'import { readdirSync, readFileSync } from 'node:fs'import { createRequire } from 'node:module'import path from 'node:path'+import { Script } from 'node:vm'import { describe, expect, it } from 'vitest'// @ts-expect-error -- JavaScript build script intentionally has no declarationsimport { BUILD_TARGETS } from '../../packages/native-host/build.mjs'@@ -182,6 +184,22 @@ const releaseSource = readFileSync(path.join(ROOT, '.github/workflows/release.yml'),'utf8')+const signingConfigSource = readFileSync(+ path.join(ROOT, 'electron-builder.signing.json'),+ 'utf8'+)+const signingInputSource = readFileSync(+ path.join(ROOT, 'scripts/release-signing-input.mjs'),+ 'utf8'+)+const signingToolPackageSource = readFileSync(+ path.join(ROOT, 'scripts/release-signing-tool/package.json'),+ 'utf8'+)+const signingToolLockSource = readFileSync(+ path.join(ROOT, 'scripts/release-signing-tool/package-lock.json'),+ 'utf8'+)const cargoConfigSource = readFileSync(path.join(ROOT, '.cargo/config.toml'),'utf8'@@ -893,28 +911,61 @@ describe('release workflow publication contract', () => {})it('isolates signing credentials behind platform-specific environments', () => {- const { job } = targetMatrix(releaseWorkflow)- const environment = asRecord(job.environment, 'build environment')- const environmentName = stringField(environment, 'name')- expect(environmentName).toContain("matrix.platform == 'darwin'")- expect(environmentName).toContain('macos-release-signing')- expect(environmentName).toContain("matrix.platform == 'win32'")- expect(environmentName).toContain('windows-release-signing')- expect(environmentName).toContain('release-build')- expect(environmentName).toContain("github.event_name == 'push'")- expect(environment.deployment).toBe(false)-- const builderSteps = jobSteps(job).filter((step) =>- stringField(step, 'run', '').includes('electron-builder')+ const jobs = workflowJobs(releaseWorkflow)+ const build = asRecord(jobs.build, 'build job')+ expect(+ stringField(asRecord(build.environment, 'build environment'), 'name')+ ).toBe('release-build')+ expect(JSON.stringify(build)).not.toContain('secrets.')++ const sign = asRecord(jobs.sign, 'sign job')+ expect(stringField(sign, 'if')).toContain("github.event_name == 'push'")+ expect(jobNeeds(sign)).toEqual(+ expect.arrayContaining(['preflight', 'build'])+ )+ const entries = matrixEntries(sign, 'sign')+ expect(entries.map((entry) => stringField(entry, 'target')).sort()).toEqual(+ ['darwin-arm64', 'darwin-x64', 'win32-x64'])+ for (const entry of entries) {+ expect(stringField(entry, 'electron_sha256')).toMatch(/^[0-9a-f]{64}$/)+ }+ const steps = jobSteps(sign)+ expect(JSON.stringify(steps)).not.toContain('actions/checkout@')+ expect(JSON.stringify(steps)).not.toContain('pnpm/action-setup@')+ expect(releaseSource).not.toContain('downloadBuilderToolset')+ const verifyIndex = steps.findIndex(+ (step) => step.name === 'Verify signing input before secrets'+ )+ const electronIndex = steps.findIndex(+ (step) => step.name === 'Download digest-pinned Electron distribution'+ )+ const firstSecretIndex = steps.findIndex((step) =>+ JSON.stringify(step).includes('secrets.')+ )+ expect(verifyIndex).toBeGreaterThanOrEqual(0)+ expect(electronIndex).toBeGreaterThan(verifyIndex)+ expect(firstSecretIndex).toBeGreaterThan(electronIndex)+ expect(JSON.stringify(steps.slice(0, firstSecretIndex))).not.toContain(+ 'secrets.'+ )++ const install = steps.find(+ (step) => step.name === 'Install exact signing dependency closure'+ )+ const installCommand = stringField(install as LooseRecord, 'run')+ expect(installCommand).toContain('npm ci')+ expect(installCommand).toContain('--ignore-scripts')+ expect(installCommand).not.toContain('npm install')++ const builderSteps = steps.filter((step) =>+ stringField(step, 'run', '').includes('electron-builder')+ )const macStep = platformBuilderStep(builderSteps, 'darwin')const windowsStep = platformBuilderStep(builderSteps, 'win32')- const linuxStep = platformBuilderStep(builderSteps, 'linux')const macEnv = asRecord(macStep.env, 'macOS builder environment')const windowsEnv = asRecord(windowsStep.env, 'Windows builder environment')- const linuxEnv = optionalRecord(linuxStep.env)-expect(stringField(macEnv, 'CSC_LINK')).toContain('secrets.MAC_CERTS')expect(stringField(macEnv, 'CSC_KEY_PASSWORD')).toContain('secrets.MAC_CERTS_PASSWORD'@@ -929,18 +980,14 @@ describe('release workflow publication contract', () => {)expect(JSON.stringify(windowsEnv)).not.toContain('MAC_CERTS')- expect(linuxEnv).not.toHaveProperty('CSC_LINK')- expect(linuxEnv).not.toHaveProperty('CSC_KEY_PASSWORD')- expect(JSON.stringify(linuxEnv)).not.toContain('secrets.')-expect(releaseSource).toContain('APPLE_API_ISSUER')expect(releaseSource).not.toContain('secrets.TEAM_ID')expect(releaseSource).not.toContain('APPLE_TEAM_ID')})it('verifies notarization stapling in addition to macOS signatures', () => {- const buildJob = targetMatrix(releaseWorkflow).job- const verification = jobSteps(buildJob).find(+ const signJob = asRecord(workflowJobs(releaseWorkflow).sign, 'sign job')+ const verification = jobSteps(signJob).find((step) => step.name === 'Verify macOS signatures')@@ -950,6 +997,127 @@ describe('release workflow publication contract', () => {expect(command).toContain('xcrun stapler validate')})+ it('keeps manual assembly unsigned and tag assembly signing-gated', () => {+ const jobs = workflowJobs(releaseWorkflow)+ const build = asRecord(jobs.build, 'build job')+ const upload = jobSteps(build).find(+ (step) => step.name === 'Upload target release input'+ )+ const uploadCondition = stringField(upload as LooseRecord, 'if')+ expect(uploadCondition).toContain("matrix.platform == 'linux'")+ expect(uploadCondition).toContain(+ "github.event_name == 'workflow_dispatch'"+ )++ const assemble = asRecord(jobs.assemble, 'assemble job')+ expect(jobNeeds(assemble)).toContain('sign')+ const condition = stringField(assemble, 'if')+ expect(condition).toContain('always()')+ expect(condition).toContain("needs.sign.result == 'success'")+ expect(condition).toContain("needs.sign.result == 'skipped'")+ })++ it('uses a bounded tar and a hook-free exact signing tool closure', () => {+ const config = asRecord(+ JSON.parse(signingConfigSource) as unknown,+ 'restricted signing config'+ )+ expect(config.extends).toBeNull()+ expect(config.npmRebuild).toBe(false)+ expect(stringField(config, 'electronDist')).toBe('trusted/electron.zip')+ expect(stringField(config, 'electronVersion')).toBe('43.3.0')+ for (const hook of [+ 'afterAllArtifactBuild',+ 'afterExtract',+ 'afterPack',+ 'afterSign',+ 'beforeBuild',+ 'beforePack',+ 'onNodeModuleFile',+ ]) {+ expect(config).not.toHaveProperty(hook)+ }++ const tool = asRecord(+ JSON.parse(signingToolPackageSource) as unknown,+ 'signing tool package'+ )+ expect(tool).not.toHaveProperty('scripts')+ expect(+ stringField(+ asRecord(tool.dependencies, 'signing tool dependencies'),+ 'electron-builder'+ )+ ).toBe('26.15.7')+ const lock = asRecord(+ JSON.parse(signingToolLockSource) as unknown,+ 'signing tool lock'+ )+ expect(lock.lockfileVersion).toBe(3)++ const sign = asRecord(workflowJobs(releaseWorkflow).sign, 'sign job')+ const extraction = jobSteps(sign).find(+ (step) => step.name === 'Safely extract bounded signing input'+ )+ const source = stringField(extraction as LooseRecord, 'run')+ expect(source).toContain('archiveBytes')+ expect(source).toContain('inputBytes')+ expect(source).toContain('fileBytes')+ expect(source).toContain('fileCount')+ expect(source).toContain('tar requires two zero end blocks')+ expect(source).toContain('tar contains trailing bytes')+ expect(source).toContain('unsupported tar entry type')++ expect(releaseSource).toContain(+ createHash('sha256').update(signingInputSource).digest('hex')+ )+ })++ it('keeps the signing Electron runtime aligned with project metadata', () => {+ const metadata = asRecord(+ JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8')),+ 'package metadata'+ )+ const version = stringField(+ asRecord(metadata.devDependencies, 'dev dependencies'),+ 'electron'+ )+ expect(version).toBe('43.3.0')+ expect(+ stringField(+ asRecord(+ JSON.parse(signingConfigSource) as unknown,+ 'restricted signing config'+ ),+ 'electronVersion'+ )+ ).toBe(version)+ expect(signingInputSource).toContain(+ `const ELECTRON_VERSION = '${version}'`+ )+ expect(releaseSource).toContain(`/electron/releases/download/v${version}/`)+ })++ it('keeps inline Node workflow steps syntactically executable', () => {+ let checked = 0+ for (const [jobName, value] of Object.entries(+ workflowJobs(releaseWorkflow)+ )) {+ for (const step of jobSteps(asRecord(value, `${jobName} job`))) {+ if (step.shell !== 'node {0}') continue+ const source = stringField(step, 'run').replace(+ /\$\{\{[\s\S]*?\}\}/gu,+ 'github_expression'+ )+ expect(+ () => new Script(source, { filename: `${jobName}.js` })+ ).not.toThrow()+ checked += 1+ }+ }+ expect(checked).toBeGreaterThan(0)+ })+it('pins the packaged macOS baseline to Electron 43 support', () => {const builderConfig = asRecord(JSON.parse(@@ -1070,10 +1238,6 @@ function asRecord(value: unknown, label: string): LooseRecord {return value as LooseRecord}-function optionalRecord(value: unknown): LooseRecord {- return value === undefined ? {} : asRecord(value, 'optional value')-}-function stringField(record: LooseRecord,field: string,@@ -1137,7 +1301,9 @@ function targetMatrix(workflow: LooseRecord): {if (!entries.every((entry) =>- typeof entry.platform === 'string' && typeof entry.arch === 'string'+ typeof entry.platform === 'string' &&+ typeof entry.arch === 'string' &&+ typeof entry.rust_target === 'string')) {return []@@ -1154,6 +1320,15 @@ function targetMatrix(workflow: LooseRecord): {return candidates[0] as (typeof candidates)[number]}+function matrixEntries(job: LooseRecord, label: string): LooseRecord[] {+ const strategy = asRecord(job.strategy, `${label} strategy`)+ const matrix = asRecord(strategy.matrix, `${label} matrix`)+ if (!Array.isArray(matrix.include)) {+ throw new TypeError(`${label} matrix include must be an array`)+ }+ return matrix.include.map((entry) => asRecord(entry, `${label} matrix entry`))+}+function platformBuilderStep(steps: LooseRecord[],platform: stringdiff --git a/vite.server.config.ts b/vite.server.config.tsindex e288b012..a507a4cb 100644--- a/vite.server.config.ts+++ b/vite.server.config.ts@@ -30,14 +30,17 @@ export default defineConfig({target: 'node22',ssr: true,lib: {- entry: 'src/server/index.ts',+ entry: {+ index: 'src/server/index.ts',+ 'motrix-admin': 'src/server/operator-cli.ts',+ },formats: ['es'],- fileName: 'index',},rollupOptions: {external: isExternal,output: {- entryFileNames: 'index.mjs',+ entryFileNames: '[name].mjs',+ chunkFileNames: 'chunks/[name]-[hash].mjs',},},},