A full-featured download manager.
feat(synology): add native DSM 7 packages for x86_64 and ARM64 (#2513)
Dr_rOot057662a00598
diff --git a/.github/workflows/fnos.yml b/.github/workflows/fnos.ymlindex d11d67cb..55734091 100644--- a/.github/workflows/fnos.yml+++ b/.github/workflows/fnos.yml@@ -14,6 +14,7 @@ on:- '.github/workflows/fnos.yml'- '.github/workflows/fnos-publish.yml'- 'scripts/fnos_publication.py'+ - 'scripts/nas_release.py'permissions:contents: readdiff --git a/.github/workflows/synology-publish.yml b/.github/workflows/synology-publish.ymlnew file mode 100644index 00000000..18e2dbff--- /dev/null+++ b/.github/workflows/synology-publish.yml@@ -0,0 +1,87 @@+name: Publish DSM SPK++on:+ workflow_run:+ workflows: ['Build/Release']+ types: [completed]+ workflow_dispatch:+ inputs:+ release_tag:+ description: Existing stable release tag whose exact source will be packaged+ required: true+ type: string++permissions:+ contents: read+ actions: read++concurrency:+ group: synology-publication+ cancel-in-progress: false++jobs:+ preflight:+ if: >-+ github.event_name == 'workflow_dispatch' ||+ (github.event.workflow_run.conclusion == 'success' &&+ github.event.workflow_run.event == 'push')+ name: Verify stable release provenance+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ outputs:+ publish: ${{ steps.source.outputs.publish }}+ tag: ${{ steps.source.outputs.tag }}+ version: ${{ steps.source.outputs.version }}+ source_sha: ${{ steps.source.outputs.source_sha }}+ release_run_id: ${{ steps.source.outputs.release_run_id }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0+ - name: Verify exact tag, ancestry and completed formal release+ id: source+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 scripts/synology_publication.py preflight++ build:+ needs: preflight+ if: needs.preflight.outputs.publish == 'true'+ uses: ./.github/workflows/synology.yml+ with:+ source_sha: ${{ needs.preflight.outputs.source_sha }}++ publish:+ name: Publish complete verified SPK set+ needs: [preflight, build]+ if: needs.preflight.outputs.publish == 'true'+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ environment: github-release+ permissions:+ contents: write+ actions: read+ steps:+ - name: Checkout trusted publication tools+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ fetch-depth: 0+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: motrix-synology-x64+ path: release/synology-publish+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ with:+ name: motrix-synology-arm64+ path: release/synology-publish+ - name: Revalidate provenance and publish without overwriting assets+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ needs.preflight.outputs.tag }}+ SOURCE_SHA: ${{ needs.preflight.outputs.source_sha }}+ RELEASE_RUN_ID: ${{ needs.preflight.outputs.release_run_id }}+ run: >-+ python3 scripts/synology_publication.py publish+ release/synology-publish "$RELEASE_TAG" "$SOURCE_SHA" "$RELEASE_RUN_ID"diff --git a/.github/workflows/synology.yml b/.github/workflows/synology.ymlnew file mode 100644index 00000000..56fe4e57--- /dev/null+++ b/.github/workflows/synology.yml@@ -0,0 +1,102 @@+name: DSM native SPK++on:+ workflow_dispatch:+ workflow_call:+ inputs:+ source_sha:+ description: Exact commit of a verified stable release+ required: true+ type: string+ pull_request:+ branches: [main]+ paths:+ - 'packaging/synology/**'+ - 'packaging/synology-abi.Dockerfile'+ - 'scripts/*synology*'+ - 'scripts/nas_release.py'+ - 'scripts/*server-app.mjs'+ - 'scripts/*server-package*'+ - 'scripts/server-runtime-dependencies.json'+ - 'scripts/fnos-runtime.lock.json'+ - 'scripts/engine.lock.json'+ - 'scripts/prepare-fnos-project.mjs'+ - 'packages/finalize-fs/**'+ - 'src/renderer/routes/dashboard/**'+ - 'tests/scripts/*synology*'+ - 'package.json'+ - 'pnpm-lock.yaml'+ - '.github/workflows/synology-publish.yml'+ - 'scripts/spk_archive.py'+ - 'src/server/**'+ - 'src/core/task/**'+ - '.github/workflows/synology.yml'++permissions:+ contents: read++concurrency:+ group: synology-build-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ build:+ name: Native SPK / ${{ matrix.arch }}+ runs-on: ${{ matrix.os }}+ timeout-minutes: 45+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: x64+ os: ubuntu-24.04+ rust_target: x86_64-unknown-linux-musl+ - arch: arm64+ os: ubuntu-24.04-arm+ rust_target: aarch64-unknown-linux-musl+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ inputs.source_sha || github.sha }}+ persist-credentials: false+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.16.1+ run_install: false+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 24.18.0+ cache: pnpm+ - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable+ with:+ toolchain: 1.94.1+ targets: ${{ matrix.rust_target }}+ - name: Install ARM instruction-set verifier+ if: matrix.arch == 'arm64'+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends qemu-user+ - name: Install dependencies+ run: pnpm install --frozen-lockfile+ env:+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'+ MOTRIX_SKIP_ENGINE_FETCH: '1'+ - name: Test SPK publication verifier+ if: matrix.arch == 'x64'+ run: python3 -B -m unittest discover -s tests/scripts -p test_synology_publication.py+ - name: Build and verify native package+ run: |+ pnpm run fetch:engine -- --platform linux --arch '${{ matrix.arch }}'+ pnpm run build:server+ pnpm run check:third-party-notices+ pnpm run stage:server -- --platform linux --arch '${{ matrix.arch }}' --libc gnu --strict+ pnpm run build:synology -- --arch '${{ matrix.arch }}' --output-dir release/synology/project+ - name: Upload verified packages+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2+ with:+ name: motrix-synology-${{ matrix.arch }}+ path: |+ release/synology/*.spk+ release/synology/*.sha256+ release/synology/*.abi.json+ if-no-files-found: error+ retention-days: 14+ overwrite: truediff --git a/e2e/activity-tile.spec.ts b/e2e/activity-tile.spec.tsindex 3171c504..c49d9855 100644--- a/e2e/activity-tile.spec.ts+++ b/e2e/activity-tile.spec.ts@@ -1212,6 +1212,25 @@ test.describe('Activity Tile production renderer', () => {width: (element as HTMLElement).style.width,height: (element as HTMLElement).style.height,}))+ // The deployed DSM Dashboard measured a 597 × 186 CSS-pixel calendar.+ await referenceCard.evaluate((element) => {+ const card = element as HTMLElement+ card.style.width = '629px'+ card.style.height = '238px'+ })+ await expect+ .poll(async () => {+ const p = await readRendererProfile(mainWindow)+ return [+ p.calendarClientWidth,+ p.monthLabels.length >= 11,+ p.weekdayLabels.length,+ ]+ })+ .toEqual([597, true, 3])+ await referenceCard.screenshot({+ path: testInfo.outputPath('activity-dsm-597-calendar.png'),+ })await referenceCard.evaluate((element) => {const card = element as HTMLElementcard.style.width = '690px'diff --git a/package.json b/package.jsonindex 9325e663..6f714755 100644--- a/package.json+++ b/package.json@@ -91,7 +91,10 @@"test:browser:torrent": "node tests/browser/torrent-file.mjs","prepare:fnos": "node scripts/prepare-fnos-project.mjs","verify:fnos": "node scripts/verify-fnos-package.mjs",- "build:fnos": "node scripts/build-fnos-package.mjs"+ "build:fnos": "node scripts/build-fnos-package.mjs",+ "prepare:synology": "node scripts/prepare-synology-project.mjs",+ "verify:synology": "node scripts/verify-synology-package.mjs",+ "build:synology": "node scripts/build-synology-package.mjs"},"devDependencies": {"@biomejs/biome": "~2.6.4",diff --git a/packaging/synology-abi.Dockerfile b/packaging/synology-abi.Dockerfilenew file mode 100644index 00000000..7a4b9b93--- /dev/null+++ b/packaging/synology-abi.Dockerfile@@ -0,0 +1,4 @@+FROM rust:1.94.1+RUN apt-get update \+ && apt-get install -y --no-install-recommends qemu-user \+ && rm -rf /var/lib/apt/lists/*diff --git a/packaging/synology/INFO b/packaging/synology/INFOnew file mode 100644index 00000000..abf68c6a--- /dev/null+++ b/packaging/synology/INFO@@ -0,0 +1,26 @@+package="Motrix"+version="@VERSION@-@REVISION@"+arch="@ARCH@"+os_min_ver="7.2.2-72806"+description="Download files and torrents with Motrix. All DSM administrators share one download list."+description_chs="使用 Motrix 下载文件和种子。所有 DSM 管理员共同管理同一组下载任务。"+description_cht="使用 Motrix 下載檔案和種子。所有 DSM 管理員共同管理同一組下載任務。"+displayname="Motrix"+maintainer="Dr_rOot"+maintainer_url="https://github.com/agalwood"+distributor="Dr_rOot"+distributor_url="https://github.com/agalwood"+support_url="https://github.com/agalwood/Motrix/issues"+thirdparty="yes"+beta="yes"+install_type="volume"+startable="yes"+precheckstartstop="no"+silent_install="no"+silent_upgrade="yes"+silent_uninstall="no"+dsmuidir="ui"+dsmappname="com.motrix.app"+instuninst_restart_services="nginx.service"+startstop_restart_services="nginx.service"+checksum="@CHECKSUM@"diff --git a/packaging/synology/PACKAGE_ICON.PNG b/packaging/synology/PACKAGE_ICON.PNGnew file mode 100644index 00000000..4681c586Binary files /dev/null and b/packaging/synology/PACKAGE_ICON.PNG differdiff --git a/packaging/synology/PACKAGE_ICON_256.PNG b/packaging/synology/PACKAGE_ICON_256.PNGnew file mode 100644index 00000000..8220abb6Binary files /dev/null and b/packaging/synology/PACKAGE_ICON_256.PNG differdiff --git a/packaging/synology/README.md b/packaging/synology/README.mdnew file mode 100644index 00000000..748175b3--- /dev/null+++ b/packaging/synology/README.md@@ -0,0 +1,324 @@+# Motrix for Synology DSM++Motrix downloads files and torrents directly on your NAS. This experimental native+SPK includes Node.js, Motrix Server and Web UI, aria2, and the filesystem helper.+It does not need Docker at runtime, download dependencies during installation,+or run npm on the NAS. Author: [Dr_rOot](https://github.com/agalwood).++Install the matching SPK with **Package Center → Manual Install**. This package+has **not** been published to Synology's package store. Do not describe it as a+store listing. Verify its adjacent `.sha256` file before installation.++## Supported scope++Native x86_64 and ARM64 SPKs target **DSM 7.2.2-72806 or later**. It is an+**administrator-shared instance**: all authorized local DSM administrators can+manage the same tasks, settings and plugins. Ordinary, disabled, domain and LDAP+accounts are denied. There is no per-user task isolation or quota accounting.++One ARM64 SPK contains one AArch64 payload. Its INFO lists the three Package Arch values below, based on the [official DSM firmware archive](https://archive.synology.com/download/Os/DSM/7.2.2-72806-9).++| Package Arch | Models |+| --- | --- |+| rtd1296 | DS118, DS218, DS218play, DS220j, DS418, DS418j, DS420j, RS819 |+| rtd1619b | DS124, DS223, DS223j, DS423 |+| armada37xx | DS119j, DS120j |++The builder checks the same archive against all three official sysroots and exercises its binaries under Cortex-A53 CPU emulation. Low-memory models need hardware memory-pressure testing. The separate `rtd1619` platform lacks a matching toolchain in the pinned SDK directory. ARMv7/32-bit is outside this package. DS718+ and DS423+ take the x86_64 build. [Toolchain directory](https://archive.synology.com/download/ToolChain/toolchain/7.2-72806) · [Synology platform mapping](https://help.synology.com/developer-guide/appendix/platarchs.html)++**Dashboard in 2.3.0-11.** On a DS718+ running revision 10, a healthy activity refresh showed a stale notice and shrank the calendar from 186 to 162 pixels high. In isolated Chromium, the final revision 11 ARM64 SPK completed a ticket renewal through a simulated DSM gateway. At 597 pixels wide the calendar showed 12 month labels and three weekday labels, and the engine title stayed Ready. When the snapshot request failed, the notice and Retry appeared in the header without moving or resizing the grid. This test ran in a Linux container. Revision 11 hardware acceptance remains open.++**Dashboard in 2.3.0-12 on DSM 7.4.1.** After upgrading the DS718+ from+revision 10, a fresh Dashboard requested one opening ticket. A listener attached+to the same open WebSocket observed three renewal challenges over 110 seconds.+Each received HTTP 204, with no socket closure or additional opening ticket.+Across 180 seconds of layout observation, the calendar stayed 597 × 186 CSS+pixels with 12 visible month labels and three weekday labels. Their positions+stayed fixed, no stale notice appeared, and the Engine title stayed Ready.++++On 2026-11-07, **2.3.0-10** passed a directory replacement test on a **DS718++(DSM 7.4.1)** after a manual upgrade from 2.3.0-9. A completed HTTP task had+written 27,648 bytes to an explicitly authorized test directory. Substituting+a different directory and file at the same paths caused Motrix to deny reading+and deleting the old task’s file. Both files retained their original hashes.+Restarting with the substitute in place opened the recovery page and stopped+the engine. Saving the same folder list could not transfer the grant. After+restoring the original directory and restarting, HEAD and GET returned 200+and the downloaded bytes matched the source SHA-256. Removing the test task+with its file then succeeded.++On 2026-11-07, Package Center upgraded **2.3.0-8 to 2.3.0-9** on a **DS718++(Apollo Lake) running DSM 7.4.1**. The installed build matched the verified SPK.+Opening Motrix from DSM loaded the administrator dashboard. Renaming an empty+authorized test directory put Motrix into folder recovery on the next start.+The engine stopped, the direct client port closed and anonymous requests could+not see the path. The administrator restored the original folder list in the+recovery page. Restarting Motrix returned the server and engine to ready.+The Web UI downloaded a 33,280-byte HTTP file into the restored directory.+Its owner was `motrix`, its SHA-256 matched the source, and removing the task+with its file cleared both.++With the installed Chrome extension 0.1.23, two tabs signed in as the same administrator saw the+same pairing request in Integration settings. Only the page that claimed the+request received the code. The extension submitted it 99 seconds after starting+the request, connected over WSS and read the active task list. Revoking the test+credential disconnected the extension. After acceptance, the extension used+its original backend, Motrix had no test tasks, HTTP pairing codes and the WSS+entry were off, and the direct client port was 16802.++Earlier revision **2.3.0-8** passed native checks for administrator login, package settings,+configurable client port, NAS torrent selection, File Station navigation, file+streaming with HEAD/Range, selected-file deletion and retained historical tasks.+A 4 MiB HTTP download resumed across the 2.3.0-6 → 2.3.0-7 upgrade with the+expected SHA-256. Revision 8 also restored the single-file metadata missing+from older HTTP history.++Earlier revision 2.3.0-5 passed real HTTP/BT downloads, redownload, directory and+symlink denial, nonroot process checks, and CLI protocol pairing/revocation.+Synthetic tasks/files and temporary servers were removed after acceptance. The+direct client port was restored to 16802, and the extension entry remains off.+This does not establish support for every DSM release or model.++Linux simulation and checksum-pinned Gemini Lake/Apollo Lake DSM 7.2.2 userspace+ABI checks also passed. The minimum version records the toolchain/resource+contract. The actual device uses Linux 4.4.302; [Node 24's upstream supported+Linux kernel baseline](https://github.com/nodejs/node/blob/v24.x/BUILDING.md) is+newer. Basic device operations passed, but long-running downloads, live account+disable/recreation, ACL revocation, physical volume removal or replacement and interrupted+finalization still need controlled device tests. The published Motrix CLI 0.5.0+paired through the DSM HTTPS gateway and ran `list` and `stats`. Across a package+restart the same credential received HTTP 403 until the administrator reopened+Motrix, then HTTP 200. Revocation returned HTTP 401. The test container resolved+the certificate hostname to the NAS LAN IP and verified the TLS chain and name.+Chrome extension 0.1.23 paired through WSS after the Mac resolved the DSM+certificate hostname to the NAS LAN address. The administrator claimed the code+and entered it in the extension. The extension reconnected after a package+restart and fresh Web authentication, ran task and stats queries, and added+and deleted a 51-byte test download. Its SHA-256 matched the source. Revocation+disconnected the extension and denied subsequent task queries.+ARM64 userspace coverage is listed above. Physical ARM NAS acceptance remains open.++## Use and permissions++Open Motrix from the DSM desktop while signed in as a local administrator. The+entry uses the same DSM host and port, at `/motrix/`, including HTTP, WebSocket+and static asset paths. Web Station is not required; File Station must be available for effective ACL queries. The application has no+separate password and does not collect DSM passwords. The package joins DSM’s `http` group using the official privilege mechanism.+Only the upstream socket is shared as `motrix:http`, mode `0660`, so the+unprivileged Nginx gateway can connect. Private settings and application data+remain owner-only; group membership never replaces session/account authentication.++The `motrix` package account runs the Web service, download engine, plugins and+filesystem helper. No package process is elevated to root; the SPK requests no+setuid program, Linux capability, sudo rule or privileged helper. DSM's resource+workers create the `motrix` shared folder and register the Nginx configuration.+The `http` group also provides access to DSM's existing local SCGI socket. The+adapter calls only fixed vendor routes: `login.cgi` retrieves the current+session's SynoToken, `SYNO.Core.NormalUser.get` identifies its owner, and+`SYNO.Core.User.get` queries that local account's `expired` status. Nonprivileged+`id` queries independently check UID and current membership of group 101.+File Station `List.getinfo` supplies effective ACL rights for the exact requested+path; the returned physical path must match. No API can read file contents or+mutate DSM settings through this adapter. Raw responses and credentials are+never returned in diagnostics.++Downloads are restricted to existing, mounted, canonical configured roots and+the permissions of both the account and the package user. The default root is+resolved from DSM's `/var/packages/Motrix/shares/motrix` link. An unavailable+volume is never created as a replacement directory on the system volume.+Revision 10 records the filesystem device and inode of each authorized root.+The package checks those identities when it starts and during file operations.+A different directory at the same path cannot inherit the old grant, including+when the directory changes between saving settings and restarting. Restore the+original directory, or authorize a different path for the replacement.+When upgrading a path-only configuration, the first startup with every root+available records the directories present at that point.+If a configured download folder is missing or inaccessible at startup, Motrix+opens an administrator-only recovery page. Restore the affected folders or edit+the list, then restart Motrix in Package Center. While that page is active, the+engine, plugins and client listeners stay stopped and task storage stays intact.+The package volume and package data directory must still be available.++Use **Settings → NAS** to manage authorized directories and client connections.+First grant the internal system user `motrix` access in DSM's shared-folder+permissions. Add an existing path such as `/volume1/downloads` to Motrix's+root list, apply, then stop and start Motrix in Package Center. Changes are+queued and take effect after the old engine has stopped; the interface shows+pending changes and currently active connection addresses. Concurrent edits+require reloading the latest settings instead of silently overwriting them.+The folder picker only browses authorized roots; selection never grants access.+Backend checks cover new tasks, resume, redownload, BT selection and file removal.++Upload a local `.torrent`, or choose a torrent from an authorized NAS directory.+Completed single-file tasks offer **Download to this device**; the server streams+from a verified file handle and supports resumable HTTP ranges. **Show in File+Station** opens the task folder in DSM. Its launch URL was verified on DS718++with DSM 7.4.1; other DSM versions still require device acceptance. No File Station+`.torrent` context-menu association is registered.++Revision 13 binds each task to its physical download directory. Before serving a completed file or deleting its payload, Motrix checks the original publication record or a verified torrent. If an older task or partial download has no ownership record, you can remove the task while keeping its files. Use **Locate** or **Recheck** with the original torrent to verify an existing BT download. A multi-file torrent directory containing an unrelated file is preserved.++Engine startup loads persisted work paused, verifies task ownership and actual+output paths against current grants, then resumes authorized tasks that were+previously running. Unknown or unauthorized engine rows remain paused. Automatic+reconstruction of lost tasks also checks the host's directory grants.+Directory grants and account/ACL state are refreshed on admission. Removal uses+the existing descriptor-relative filesystem helper, file identity checks and+persistent removal recovery journal. Revoking a grant does not instantly cancel+an engine file that is already open; stop the package before withdrawing a+background download grant. Device tests must cover DSM ACL inheritance, mount+replacement, offline storage and interrupted finalization.++## Pair clients++The installation wizard selects the direct client port (default **16802**).+In **Settings → NAS**, copy the CLI address using the DSM HTTPS origin and+`/motrix/client`. The gateway forwards only the existing CLI protocol routes;+it does not forward DSM cookies. The direct port remains available and configurable.++Browser extension access is disabled by default. Enable it in **Settings → NAS**;+the suggested address uses the current DSM origin and `/motrix/bridge` with WSS+for HTTPS. Advanced connection fields support a separately configured public+origin. Set the full Motrix Web address including `/motrix/`.+Use a hostname covered by DSM’s HTTPS certificate for both client addresses.+On a LAN, configure DNS so that hostname resolves to the NAS LAN IP. An IP-based+address requires that exact IP in the certificate. Chrome’s extension background+process validates its own TLS connection even when a DSM tab is already open.+Displaying pairing codes over HTTP requires explicit trusted-network consent.+The configured origin must match the current page; an HTTPS address never+permits code delivery to an HTTP page. Apply and restart the package for changes+to take effect. Invalid configuration closes the extension entry.+The existing CLI device-code protocol and Extension MBP1 protocol are unchanged.+Open **Settings → Integration → Browser pairing requests** to find a pending+request while its code is valid. The pairing UI shows the current account and+**Pair with current account**.+Next, enter the code in the browser extension. The server checks the page's+expected account against the current trusted account. Shared notifications+contain no pairing code; only the claimant receives it.++Client credentials bind to a local account ID and an account-database generation.+Every client request rechecks authoritative account state. Disable, expiration,+demotion, missing records or an authority failure deny access. Any change to the+root-owned local passwd/group database conservatively invalidates all existing+bindings, including after UID reuse; pair again. Explicit credential revocation+continues to use the existing protocol. DSM session cookies are neither saved in+pairing state nor used as CLI credentials. At most 64 session contexts are kept+in memory with bounded least-recently-used eviction; every client operation+revalidates the actual DSM session and account. A DSM logout, session expiry,+evicted context or Motrix restart requires the corresponding administrator to reopen+Motrix. Paired credentials and tasks survive an upgrade, but no client is allowed+to act until its account has supplied a fresh verified session. Web event tickets are one-use,+origin-bound and short-lived. Starting with revision 12, the DSM Dashboard keeps its+event WebSocket open across successful account checks. About 45 seconds into a+60-second authorization window, the server sends a one-use challenge to that+socket. The browser answers via same-origin HTTPS using its current DSM session.+Only the same verified administrator, account revision and origin can extend+the window. A missed deadline, rejected session or changed account closes the+stream. A lost network connection or package restart still requires reconnecting.+Clients without renewal support reconnect when the window expires.++If the account cannot be verified, the page shows a bounded diagnostic such as+`account / rejected` or `account / commandFailed / accessDenied`.+The same metadata is available at `/motrix/rpc/auth/status` in the signed-in+browser. It contains no Cookie, token, account name or raw command output.+Session and account checks still fail closed; a diagnostic is not an authorization+fallback. The proxy forwards the CGI scheme and port, while the backend supplies+the bounded host/user-agent context to DSM’s authentication program.++## Lifecycle and retained data++Package lifecycle scripts run as the package user and serialize with `flock`.+PID records include process birth time, boot identity and executable/entrypoint+checks. Stop waits for orderly shutdown and retains the record on timeout.+Upgrade stops the old process before replacement and preserves the DSM FHS+`var` directory: task database, configuration, plugins, pairing bindings and+removal recovery state. Downloads remain in the shared folder.++Uninstall defaults to keeping application data. The explicit **Delete tasks,+settings and paired clients** option deletes only package-owned state after a+successful stop. Downloaded files are always retained. Reinstalling with retained+data restores the same shared instance, subject to current account and directory+permissions. In a Linux simulation using the final revision 9 SPK, reinstalling+with retained data preserved database and engine files byte for byte and+restored the existing task and settings. The old CLI credential could query the+task after the administrator reopened Motrix. Reinstalling after explicit data+deletion started with an empty task list and rejected the old credential. Both+reinstall paths preserved the HTTP and BitTorrent downloads. DSM controls the+lifecycle sequence and resource cleanup. Fresh install, repair and uninstall+retention still need acceptance on a physical NAS.++## Controlled DSM device acceptance++Use a spare DSM or isolated Virtual DSM. Create a test administrator, disposable shared folder and completed synthetic download. Record the task ID, file SHA-256, settings and a successful test client query. Keep a separate administrator session. Use temporary client profiles for credentials.++| Scenario | Procedure and pass criteria | Effect on data |+| --- | --- | --- |+| Account demotion or disablement | Pair the test CLI and extension. Remove the test account from administrators using the other administrator session. Requests from its existing Web session and clients must be denied. Repeat with account disablement. Restore membership, sign in again and pair again as needed. Check the task and file hash. | Downloads remain on disk. Changes to the account database may invalidate other existing pairings. |+| Volume loss and recovery | Install the package and its data on test volume A. Put the test download root on a separate disposable volume B. Stop Motrix, power down and safely detach only the disk for B. Boot DSM and start Motrix. Expect the recovery page, a stopped engine, a closed client port and no recreated folder. Power down, restore B, then verify the folder identity, task and file hash. If device identity changes, explicitly authorize another path in recovery. | All services and shares on B lose access while offline. Removing a pool or volume erases data. Use a test disk independent of production, system and RAID-member disks. [Synology storage pool guide](https://kb.synology.com/en-id/DSM/help/DSM/StorageManager/storage_pool_create_storage_pool?version=7) |+| Uninstall and reinstall | Back up the disposable instance's package state and download. Uninstall keeping application data and reinstall the same version and architecture. Reopen Motrix and verify the task, settings, old credential and file hash. On a disposable instance repeat with explicit data deletion. Expect an empty task list and a rejected old credential, with the shared file unchanged. | Both paths stop the service. Explicit data deletion clears all tasks, settings and pairings for that instance. |++## Build and verification++Use Node 24.18.0, the repository's pinned pnpm and Rust versions, Python 3.12++(or Python 3.11 with tar extraction filters), and Docker for isolated acceptance.+Use a native Linux runner with its Rust musl target and GNU binutils. ARM64 also requires qemu-user. To build x86_64, set `arch=x64` in this example.++```sh+arch=arm64+MOTRIX_SKIP_ELECTRON_REBUILD=1 MOTRIX_SKIP_ENGINE_FETCH=1 pnpm install --frozen-lockfile+pnpm run fetch:engine -- --platform linux --arch "$arch"+pnpm run build:server+pnpm run stage:server -- --platform linux --arch "$arch" --libc gnu --strict+pnpm run build:synology -- --arch "$arch" --output-dir "release/synology-$arch/project"+pnpm run verify:synology -- --spk "release/synology-$arch/Motrix-2.3.0-13-dsm-$arch.spk"+```++The `synology.yml` GitHub Actions workflow builds on native x64 and ARM64 runners and verifies each final archive. After a successful stable release, `synology-publish.yml` rebuilds the exact tagged commit for both architectures. The protected publication job checks the tag, source commit, complete SPKs, digests and per-platform ABI reports before attaching them to the existing GitHub Release. Retries preserve existing assets. Synology Package Center store publication is separate.++For local read-only verification, place the `.spk`, `.spk.sha256` and `.spk.abi.json` files for both architectures in one directory. Use the application version and full source commit from the SPK receipt.++```sh+python3 scripts/synology_publication.py verify "$asset_dir" "$version" "$source_sha"+```++Use a fresh output directory for every build. A higher numeric revision creates+an upgradeable SPK while retaining the application version. Cross-building on+macOS additionally requires building the Linux helper from the locked Rust+source; do not substitute a host binary. The build reuses Server staging,+external-module pruning, engine integrity checks, signed builtin verification+and license generation. Node's archive is pinned by the existing NAS runtime+lock. No Electron, npm, source compiler or toolchain is installed on the NAS.++The SPK builder unpacks the actual outer archive and nested `package.tgz`, rejects+traversal/links/duplicate names/macOS metadata, verifies payload hashes and+executable modes, then reruns Server package verification. It checks every ELF's+architecture, dynamic dependencies and symbol versions against the checksum-pinned+Synology sysroots for the package targets. It also loads bundled Node and SQLite through the+DSM loader and exercises SQLite read/write. aria2 and the filesystem helper are+static. The SDK is a build input and is not redistributed inside the SPK.++The build runs ordinary Server smoke and DSM lifecycle simulation against the+**extracted SPK bytes**. A simulated DSM SCGI API exists only inside+a disposable container. It validates integration behavior, not the availability,+output format or permissions of DSM's real API. The package receipt records the source commit and whether the source tree was+dirty. Keep `.abi.json` and test+logs with the SPK and its SHA-256. Do not publish a release or claim device+compatibility based on those reports alone.++## Implementation evidence and limits++Sources reviewed for DSM 7.2.2 and DSM 7.4.1; device checks updated 2026-11-07:++| Area | Basis and implementation boundary |+| --- | --- |+| Package layout and metadata | [SPK layout](https://help.synology.com/developer-guide/synology_package/introduction.html), [INFO](https://help.synology.com/developer-guide/synology_package/INFO.html), and [localized fields](https://help.synology.com/developer-guide/synology_package/INFO_optional_fields.html). English fallback plus `chs`/`cht` descriptions and wizard files. |+| Least privilege | [Privilege configuration](https://help.synology.com/developer-guide/privilege/privilege_config.html) and the [official web-package group example](https://help.synology.com/developer-guide/examples/compile_web_package.html). Use `run-as: package` and `join-groupname: http`; root packages require additional Synology authorization. |+| Storage and lifecycle | [DSM FHS](https://help.synology.com/developer-guide/integrate_dsm/fhs.html), [data-share](https://help.synology.com/developer-guide/resource_acquisition/data_share.html), and [wizard contracts](https://help.synology.com/developer-guide/synology_package/wizard/WIZARD_UIFILES_v2.html). FHS data survives upgrades; the resource worker does not delete the download share. |+| Desktop and proxy | [Desktop config](https://help.synology.com/developer-guide/integrate_dsm/config.html), [web-config](https://help.synology.com/developer-guide/resource_acquisition/web_config.html), and [Web Station alternative](https://help.synology.com/developer-guide/resource_acquisition/web_service.html). Use DSM's Nginx worker with a Unix upstream and explicit WebSocket forwarding. No fnOS identity Header. |+| Session identity | [Application authentication](https://help.synology.com/developer-guide/integrate_dsm/web_authentication.html) establishes the cookie/CGI context. Direct `authenticate.cgi` execution and the privileged r4 broker are not used. The `login.cgi` bootstrap and `SYNO.Core.NormalUser.get` read calls were verified with a real DSM 7.4.1 browser session. The local SCGI transport remains version-sensitive and must be tested on each DSM release. |+| Account/ACL status | `SYNO.Core.User.get` with only `additional=["expired"]` was verified on DSM 7.4.1; requesting `groups` additionally returns error 3106. Local UID and administrator membership use nonprivileged `id`. The [official File Station API](https://global.download.synology.com/download/Document/Software/DeveloperGuide/Package/FileStation/All/enu/Synology_File_Station_API_Guide.pdf) documents `List.getinfo` and effective ACL fields; browser requests were verified against two explicitly authorized shares. Those API checks do not establish complete SPK/device acceptance. |+| Architecture | [Official architecture mapping](https://help.synology.com/developer-guide/appendix/platarchs.html) and [model/CPU list](https://kb.synology.com/en-global/DSM/tutorial/What_kind_of_CPU_does_my_NAS_have). DS920+/DS220+ are Gemini Lake; DS220j is RTD1296 (ARMv8), not x86_64. |+| Toolchain | [Official toolchain selection](https://help.synology.com/developer-guide/compile_applications/download_dsm_tool_chain.html), [environment preparation](https://help.synology.com/developer-guide/getting_started/prepare_environment.html), and [spksrc Gemini Lake inputs](https://github.com/SynoCommunity/spksrc/tree/master/toolchain/syno-geminilake-7.2). The exact archive SHA-256 is recorded in `scripts/synology-runtime.lock.json`. |+| Mature packaging reference | [SynoCommunity/spksrc](https://github.com/SynoCommunity/spksrc) and its [Transmission lifecycle](https://github.com/SynoCommunity/spksrc/blob/master/spk/transmission/src/service-setup.sh) informed FHS persistence and isolated package-user execution. No install-time dependency fetching is copied. |diff --git a/packaging/synology/README.zh-CN.md b/packaging/synology/README.zh-CN.mdnew file mode 100644index 00000000..3ad3d3fe--- /dev/null+++ b/packaging/synology/README.zh-CN.md@@ -0,0 +1,252 @@+# 群晖 DSM 原生 Motrix++Motrix 可直接在 NAS 上下载文件和种子。这个实验性原生 SPK 内置 Node.js、+Motrix Server/Web UI、aria2 和文件系统辅助程序。运行时不依赖 Docker,安装时+不下载依赖、不运行 npm。作者:[Dr_rOot](https://github.com/agalwood)。++请通过**套件中心 → 手动安装**安装对应 SPK,并先核对旁边的 `.sha256` 文件。+本套件**尚未上架群晖套件商店**,不能将它描述为可从官方商店安装。++## 支持范围++提供 **DSM 7.2.2-72806 及以上**的 x86_64 和 ARM64 手动安装包。第一版采用**管理员共享实例**:+所有获授权的本地 DSM 管理员共同管理同一组任务、设置和插件。普通账号、已停用+账号、域账号和 LDAP 账号不能访问。目前没有按用户隔离任务或分别计算配额。++同一个 ARM64 SPK 包含一套 AArch64 程序,套件中心按下表中的三个 Package Arch 识别兼容平台。机型来自[群晖 DSM 固件归档](https://archive.synology.com/download/Os/DSM/7.2.2-72806-9)。++| Package Arch | 机型 |+| --- | --- |+| rtd1296 | DS118、DS218、DS218play、DS220j、DS418、DS418j、DS420j、RS819 |+| rtd1619b | DS124、DS223、DS223j、DS423 |+| armada37xx | DS119j、DS120j |++这三个官方 sysroot 分别验证同一个包,CPU 指令测试使用 Cortex-A53 模拟。低内存机型还需要实测内存压力。单独的 `rtd1619` 在锁定的 DSM SDK 目录中缺少对应工具链。ARMv7/32 位不在本包范围内。DS718+ 和 DS423+ 使用 x86_64 包。[工具链目录](https://archive.synology.com/download/ToolChain/toolchain/7.2-72806) · [群晖平台映射](https://help.synology.com/developer-guide/appendix/platarchs.html)++**2.3.0-11 仪表盘**。DS718+ 上的 2.3.0-10 在健康的活动记录刷新期间也显示过期提示,实测日历高度从 186 降至 162 像素。新版最终 ARM64 SPK 在隔离 Chromium 和模拟 DSM 网关中经过了同样的票据续期。597 像素宽的日历显示 12 个月份标签和 3 个星期标签,引擎标题保持 Ready。真正的快照请求失败时,提示与重试按钮出现在标题栏,网格位置和大小保持稳定。此项验证使用 Linux 容器,尚无 2.3.0-11 实机验收。++**2.3.0-12 仪表盘实机验收**。DS718+(DSM 7.4.1)从第 10 版升级后,新加载的+Dashboard 只申请了 1 次建连票据。在同一条已打开的 WebSocket 上直接监听了 110 秒,+收到 3 次续期通知,每次均返回 HTTP 204,期间没有关闭连接或申请新建连票据。+连续 180 秒观测中,Activity 日历始终为 597 × 186 CSS 像素,12 个月份和 3 个星期标签+均可见,位置稳定。没有出现过期提示,Engine 标题始终为 Ready。++++2026-11-07,**DS718+(DSM 7.4.1)** 从 2.3.0-9 手动升级到 **2.3.0-10** 后,+通过了同名目录替换测试。HTTP 任务向明确授权的测试目录写入 27,648 字节。+把目录移走,在原路径放入另一个目录和同名文件后,Motrix 拒绝了旧任务的读取和删除,+两份文件的哈希均未改变。重启后套件进入修复页,引擎停止,再次保存相同路径也无法+转移原授权。放回原目录并重启后,原任务的 HEAD 和 GET 都返回 200,+下载内容的 SHA-256 与源文件一致,此时可以正常删除任务及原文件。++2026-11-07,**DS718+(Apollo Lake,DSM 7.4.1)** 通过套件中心从 **2.3.0-8+原位升级到 2.3.0-9**。实机上的构建提交与已校验的 SPK 一致,从 DSM 打开 Motrix+可进入管理员仪表盘。将一个已授权的空测试目录改名后,重启套件进入目录修复页,+下载引擎停止,直连端口关闭,匿名请求看不到目录路径。管理员在修复页恢复原授权+列表并重启套件后,服务和引擎均恢复就绪。+通过 Web UI 下载的 33,280 字节 HTTP 文件写入了恢复后的目录,文件属主为 `motrix`,+SHA-256 与源文件一致。勾选同时删除文件后,任务和文件均已移除。++实机安装的 Chrome 扩展 0.1.23 发起配对后,同一管理员的两个标签页都在集成设置中看到+请求,只有点击认领的页面收到配对码。扩展在请求发起 99 秒后提交配对码,成功+通过 WSS 连接并读取活动任务列表。撤销测试凭据后,连接断开。验收结束时,扩展+已切回原后端,Motrix 没有测试任务,HTTP 配对码和 WSS 入口已关闭,直连端口为 16802。++此前 **2.3.0-8** 已通过管理员登录、套件设置、客户端端口配置、NAS 种子选择、+File Station 定位、HEAD/Range 文件读取、定向文件删除及历史任务保留。+4 MiB HTTP 下载在 2.3.0-6 → 2.3.0-7 原位升级后继续完成,SHA-256 与源文件一致,+2.3.0-8 还修复了旧 HTTP 历史任务缺失的单文件元数据。++此前 2.3.0-5 已通过实机 HTTP/BT 下载、重新下载、目录与符号链接拒绝、非 root+进程检查,以及 CLI 协议配对和撤销。验收后已清理合成任务、测试文件及临时服务,+直连端口恢复为 16802,扩展入口保持关闭。这不表示所有 DSM 版本或机型均已兼容。++Linux 模拟和固定校验和的 Gemini Lake/Apollo Lake DSM 7.2.2 用户态 ABI 检查也已+通过。最低版本表示工具链与资源接口范围。实机内核为 Linux 4.4.302,+[Node 24 官方支持的 Linux 内核基线](https://github.com/nodejs/node/blob/v24.x/BUILDING.md)+更高;基础操作已通过,但长时间下载、真实账号停用/重建、ACL 撤销、物理存储卷卸载或替换、+文件提交中断等仍需受控实机测试。官方 Motrix CLI 0.5.0 已通过 DSM HTTPS 网关+完成配对并执行 `list` 和 `stats`。重启套件后,同一凭据先收到 HTTP 403,管理员+重新打开 Motrix 后恢复为 HTTP 200。撤销凭据后收到 HTTP 401。测试容器将证书域名+解析到 NAS 内网 IP,并验证了 TLS 证书链和名称。Mac 将证书域名解析到 NAS 内网 IP 后,+Chrome 扩展 0.1.23 已通过 WSS 配对。管理员认领配对码后在扩展中输入。套件重启并+重新验证 DSM 会话后,扩展使用原凭据重连,成功查询任务和统计,通过弹窗添加并删除+了 51 字节测试下载,文件 SHA-256 与源文件一致。撤销后连接断开,任务查询被拒绝。+ARM64 的验证范围见下方机型表,尚无 ARM 群晖实机验收。++## 使用与权限++使用本地管理员账号登录 DSM 后,从桌面打开 Motrix。入口沿用 DSM 的主机名和+端口,路径为 `/motrix/`,包括 HTTP、WebSocket 和静态资源。无需安装 Web Station;有效 ACL 查询需要 File Station 可用。+应用没有单独的登录密码,也不收集 DSM 密码。套件通过 DSM 官方权限机制加入 `http` 组,+仅将上游 socket 设为 `motrix:http`、权限 `0660`,供非 root Nginx 网关连接。+配置和应用数据仍仅限套件账号访问;组成员身份不能替代会话和账号认证。++Web 服务、下载引擎、插件和文件系统辅助程序均以 `motrix` 套件账号运行。+套件没有 root 进程,不申请 setuid、Linux capability、sudo 规则或特权辅助服务。+DSM 资源管理器负责创建 `motrix` 共享文件夹和注册 Nginx 配置。+`http` 组还允许连接 DSM 已有的本地 SCGI socket。适配层只调用固定的系统接口:+`login.cgi` 获取当前会话的 SynoToken,`SYNO.Core.NormalUser.get` 识别会话所有者,+`SYNO.Core.User.get` 查询该本地账号的 `expired` 状态。非特权 `id` 命令独立核对+UID 和当前是否属于管理员组 101。File Station `List.getinfo` 返回指定路径的+有效 ACL 权限,返回的实际路径必须与请求完全一致。适配层不能调用读取文件内容或+修改 DSM 设置的接口;诊断不会返回原始响应或凭据。++下载范围同时受已配置目录、管理员账号权限和套件账号权限约束。授权目录必须+存在、位于已挂载存储卷中,且不能通过符号链接改指其他位置。默认目录从+`/var/packages/Motrix/shares/motrix` 解析;存储离线时不会在系统卷重建替代目录。+从第 10 版开始,套件会记录每个授权根目录的文件系统设备号和 inode,在启动和文件操作时核对。+即使在保存设置后、重启前换入同名目录,新目录也不能继承原授权。可将原目录放回原位,+或为替代目录选择不同的路径并重新授权。旧版配置只有路径,升级后首次确认所有根目录+均可用时,套件才会记录当时的目录身份。+启动时如果有已配置的下载目录缺失或不可访问,Motrix 会打开管理员恢复页面。请恢复+这些目录或修改授权列表,再到套件中心重启 Motrix。恢复页面运行期间,下载引擎、+插件和客户端入口暂停,任务数据库和恢复日志保持原样。套件所在存储卷及套件自己的+数据目录仍须可用。++在 **设置 → NAS** 中管理授权目录和客户端连接。先在 DSM 共享文件夹权限中,+给内部系统用户 `motrix` 授权;再将 `/volume1/downloads` 等已有路径加入 Motrix+授权目录列表,点击应用,并在套件中心停止后重新启动 Motrix。变更会等待旧引擎+停止后生效,界面会显示待生效设置和当前连接地址。多人同时修改时,需要重新+加载最新配置,避免覆盖他人的变更。目录选择器只浏览已授权范围,选择本身不会授权。+后端会在新增任务、恢复、重新下载、BT 文件选择和删除时重新检查权限。++可上传本机 `.torrent` 文件,也可从已授权的 NAS 目录选择种子。已完成的单文件+任务支持 **下载到本机**,服务端使用经过身份核对的文件句柄读取,并支持 HTTP+Range 续传。**在 File Station 中显示** 会打开任务所在目录;该启动链接已在+DS718+、DSM 7.4.1 验证,其他版本仍需实机验收。尚未注册 File Station 的+`.torrent` 右键关联。++第 13 版会记录每个任务实际使用的下载目录。打开已完成的文件或删除下载内容时,Motrix 会核对原始落盘记录或经过校验的种子文件。旧任务或未完成的下载如果缺少文件归属记录,可以选择仅移除任务并保留文件。已有的 BT 下载可以使用原始种子重新定位或校验。多文件种子目录内有其他文件时,Motrix 会保留整个目录。++引擎启动时先暂停载入持久化任务,核对任务归属、实际落盘路径及当前目录授权,+再恢复之前正在运行的合法任务。无法确认归属或已失去授权的引擎任务保持暂停。+自动重建引擎中丢失的任务时,也会重新检查目录授权。+目录授权和账号/ACL 状态会在操作入口刷新。删除复用现有基于目录句柄的文件+系统辅助程序、文件身份检查和持久化恢复日志。撤回授权不会立即取消下载引擎+已经打开的文件;撤回后台下载目录授权前请先停止套件。实机仍需验证 DSM ACL+继承、挂载点替换、存储离线和文件提交中断。++## 客户端配对++安装向导设置直连客户端端口,默认 **16802**。在 **设置 → NAS** 中可复制+沿用 DSM HTTPS 地址的 CLI 入口,路径为 `/motrix/client`。网关仅转发既有 CLI+协议接口,不转发 DSM Cookie;直连端口仍可使用和调整。++浏览器扩展入口默认关闭。可在 **设置 → NAS** 中启用,建议地址沿用当前 DSM+地址和 `/motrix/bridge` 路径,HTTPS 对应 WSS。高级连接设置支持另行配置的公网+地址,Motrix Web 地址必须包含 `/motrix/`。两个客户端地址应使用 DSM HTTPS 证书+覆盖的域名,并在局域网 DNS 中将该域名解析到 NAS 内网 IP。直接填写 IP 时,证书+必须包含该 IP。即使浏览器已打开 DSM 页面,Chrome 扩展后台也会独立校验 TLS 连接。+通过 HTTP 显示配对码需要明确许可。+配置的 Origin 必须与当前页面一致,填写 HTTPS 地址不代表可在 HTTP 页面显示码。+应用设置后需停止并重新启动套件。无效配置会关闭扩展入口。+沿用现有 CLI device-code 和扩展 MBP1 协议。在 **设置 → 集成 → 浏览器扩展配对请求**+可找到仍在有效期内的请求。配对界面显示当前账号,按钮为+**使用当前账号配对**;下一步需要在浏览器扩展中输入配对码。服务端核对页面+预期账号与当前可信身份。共享通知不包含配对码,只有认领者能取得配对码。++客户端凭据绑定本地账号 ID 和账号数据库版本。每次客户端请求均重新查询可信+账号状态;停用、过期、降权、记录缺失或查询失败都会拒绝访问。root 所有的+passwd/group 数据库发生任何变化时,会保守地让全部既有绑定失效,包括 UID+被复用的情况,此时需要重新配对。明确撤销凭据仍走既有协议。DSM 会话 Cookie+不会写入配对状态,也不能作为 CLI 凭据使用。内存中最多保留 64 个会话上下文,+达到上限时淘汰最久未使用的上下文;每次客户端操作都会实时核对 DSM 会话和账号。+退出 DSM、会话过期、上下文被淘汰或 Motrix 重启后,对应管理员需重新打开 Motrix。+升级保留配对凭据和任务,但账号提供新的已验证会话前,客户端操作均被拒绝。Web 事件票据只能使用一次,绑定+当前 Origin 并短期有效。从第 12 版起,DSM 仪表盘可以在同一条 WebSocket 上持续接收事件。+每个授权窗口最长 60 秒。约 45 秒时,服务器只向该连接发送一次性随机值,浏览器通过+同源 HTTPS 携带当前 DSM 会话应答。账号、账号版本和 Origin 均匹配后续期。+错过期限、会话失效或账号变化会关闭事件流。网络断开或套件重启后仍需重新连接。+旧版页面缺少续期支持,会在原期限到达时重连。++无法验证账号时,页面会显示有限的诊断,例如+`account / rejected` 或 `account / commandFailed / accessDenied`。+已登录的浏览器访问 `/motrix/rpc/auth/status` 也可获取这些状态;其中不包含 Cookie、+令牌、账号名或命令原始输出。认证和账号检查失败时仍拒绝访问,诊断不是授权回退。+代理会传递 CGI 协议和端口,后端补充经过长度校验的主机与浏览器信息,供 DSM 本地 API 使用。++## 生命周期与数据保留++套件生命周期脚本以套件账号执行,通过 `flock` 串行化。进程记录包含 PID、+进程出生时间、启动标识,以及可执行文件和入口检查。停止会等待正常退出,+超时则保留进程记录。升级先停止旧进程,再替换文件,并保留 DSM FHS `var`+目录中的任务数据库、配置、插件、配对绑定和删除恢复状态。下载文件留在共享目录。++卸载默认保留应用数据。明确选择**删除任务、配置和配对信息**后,才会在成功+停止服务后删除套件自己的状态。下载文件始终保留。保留数据后重新安装可恢复+同一个共享实例,但仍需满足当前账号和目录权限。使用第 9 版最终 SPK 的 Linux+模拟验证了两种重装方式。保留数据后,任务数据库和引擎持久化文件的内容逐字节一致,+原任务和设置可用。管理员重新打开 Motrix 后,旧 CLI 凭据可以查询原任务。+选择删除数据后,重装得到空任务列表,旧凭据失效。两种方式均保留了 HTTP 和+BT 下载文件。DSM 负责实际的生命周期顺序和资源清理,全新安装、修复及卸载后的+数据保留仍需实机验收。++## 受控 DSM 实机验收++使用备用 DSM 或隔离的 Virtual DSM。准备一个独立测试管理员和测试共享文件夹,创建一个已完成的小任务,记录文件 SHA-256、任务标识、目录设置和测试客户端的查询结果。保留另一名可登录的管理员。测试凭据只存于临时客户端配置中。++| 场景 | 操作与通过条件 | 对数据的影响 |+| --- | --- | --- |+| 账号降权或停用 | 用测试管理员登录并配对 CLI/扩展,先确认能查询合成任务。从另一个管理员会话将测试账号移出 administrators,再用原网页及原客户端查询,应拒绝;另行重复停用场景。恢复组成员身份并重新登录,按需要重新配对。核对任务及文件哈希。 | 不删除下载文件。账号数据库版本变化可能使其他已有配对也需要重新授权。 |+| 卷离线与恢复 | 套件及应用数据位于测试卷 A,唯一测试下载根目录位于独立测试卷 B。停止套件,关机,在测试环境中安全分离仅承载 B 的磁盘,再启动 DSM 和套件。确认修复页可访问、引擎停止、客户端端口关闭、原路径未被重建。关机接回原盘,再次验证卷和根目录身份、任务和哈希。若设备号已变化,按修复页提示明确授权其他路径。 | B 上所有服务和共享文件夹在离线期间均不可用。删除卷或存储池会擦除数据。生产卷、系统盘和 RAID 成员不得用作试验盘。[群晖存储池说明](https://kb.synology.com/en-id/DSM/help/DSM/StorageManager/storage_pool_create_storage_pool?version=7) |+| 卸载并重装 | 在测试实例先做可恢复的套件状态及下载文件备份。保留数据卸载,再装回相同架构和版本的 SPK。重新打开 Motrix 后检查原任务、设置、旧凭据和文件哈希。再在可丢弃的实例勾选删除应用数据卸载重装,验证任务列表为空、旧凭据被拒绝、共享目录内合成文件的哈希不变。 | 两种方式均停止服务。清除选项会删除整个实例的任务、设置和配对信息。 |++## 构建与验证++使用 Node 24.18.0、仓库锁定的 pnpm 和 Rust 版本、Python 3.12++(或支持 tar extraction filter 的 Python 3.11),以及用于隔离验收的 Docker。+在对应架构的 Linux 构建机安装 Rust musl target(x64 或 aarch64)和 GNU binutils。ARM64 还需安装 qemu-user。示例构建 ARM64,x86_64 使用 `arch=x64`。++```sh+arch=arm64+MOTRIX_SKIP_ELECTRON_REBUILD=1 MOTRIX_SKIP_ENGINE_FETCH=1 pnpm install --frozen-lockfile+pnpm run fetch:engine -- --platform linux --arch "$arch"+pnpm run build:server+pnpm run stage:server -- --platform linux --arch "$arch" --libc gnu --strict+pnpm run build:synology -- --arch "$arch" --output-dir "release/synology-$arch/project"+pnpm run verify:synology -- --spk "release/synology-$arch/Motrix-2.3.0-13-dsm-$arch.spk"+```++GitHub Actions 的 `synology.yml` 在原生 x64 和 ARM64 runner 上分别构建,再从最终 SPK 解包测试。稳定版发布成功后,`synology-publish.yml` 用该 tag 的确切提交重建两种架构。受保护的发布作业校验 tag、构建提交、两份安装包、校验和和逐平台 ABI 报告,再附加到已有 GitHub Release。失败重试不覆盖已有文件。输出不等同于群晖商店上架。++本地可将两种架构各自的 `.spk`、`.spk.sha256` 和 `.spk.abi.json` 放入同一个目录,用只读命令复核。传入 SPK 收据中记录的版本和完整源码提交。++```sh+python3 scripts/synology_publication.py verify "$asset_dir" "$version" "$source_sha"+```++每次构建使用新的输出目录。增加数字 revision 可生成支持原位升级的 SPK,同时+保持应用版本不变。在 macOS 交叉构建时,还必须从锁定 Rust 源码构建 Linux+文件系统辅助程序,不能放入 macOS 二进制。构建复用 Server staging、依赖裁剪、+引擎完整性检查、内置插件签名校验和许可证生成流程。Node 归档使用现有 NAS+runtime lock 校验。NAS 上不安装 Electron、npm、编译器或工具链。++SPK 构建器会解包实际外层归档和 `package.tgz`,拒绝目录穿越、链接、重复成员+及 macOS 元数据,检查文件哈希和执行权限,并重新执行 Server 包验证。+每个 ELF 的架构、动态依赖和符号版本都与该包声明平台对应的官方 sysroot+比对;包内 Node 和 SQLite 还会经 DSM loader 加载并执行 SQLite 读写。+aria2 和文件系统辅助程序为静态程序。SDK 仅用于构建,不包含在分发 SPK 中。++普通 Server smoke 和 DSM 生命周期模拟均针对**最终 SPK 解包后的文件**运行。+模拟 DSM SCGI API 仅存在于一次性容器中,验证的是集成行为,不能证明真实 DSM+接口的可用性、输出格式或访问权限。包内构建记录包含源码 commit 和工作区是否有未提交改动。+请将 `.abi.json` 和测试日志与 SPK、SHA-256+一同保留,不要仅凭这些结果发布正式版本或宣称实机兼容。++## 实现依据与边界++以下资料覆盖 DSM 7.2.2 和 DSM 7.4.1;实机核对更新于 2026-11-07:++| 范围 | 依据与实现边界 |+| --- | --- |+| 套件结构与元信息 | [SPK 结构](https://help.synology.com/developer-guide/synology_package/introduction.html)、[INFO](https://help.synology.com/developer-guide/synology_package/INFO.html)、[多语言字段](https://help.synology.com/developer-guide/synology_package/INFO_optional_fields.html)。英文默认值,另提供 `chs`/`cht` 介绍和向导。 |+| 最小权限 | [权限配置](https://help.synology.com/developer-guide/privilege/privilege_config.html)、[官方 Web 套件分组示例](https://help.synology.com/developer-guide/examples/compile_web_package.html)。使用 `run-as: package` 和 `join-groupname: http`;root 套件需要群晖额外授权。 |+| 存储与生命周期 | [FHS](https://help.synology.com/developer-guide/integrate_dsm/fhs.html)、[data-share](https://help.synology.com/developer-guide/resource_acquisition/data_share.html)、[向导规范](https://help.synology.com/developer-guide/synology_package/wizard/WIZARD_UIFILES_v2.html)。FHS 状态跨升级保留,资源管理器不删除下载共享目录。 |+| 桌面与代理 | [桌面配置](https://help.synology.com/developer-guide/integrate_dsm/config.html)、[web-config](https://help.synology.com/developer-guide/resource_acquisition/web_config.html)、[Web Station 方案](https://help.synology.com/developer-guide/resource_acquisition/web_service.html)。采用 DSM Nginx worker、Unix upstream 和明确的 WebSocket 转发,不接受 fnOS 身份 Header。 |+| 登录身份 | [应用认证](https://help.synology.com/developer-guide/integrate_dsm/web_authentication.html)说明 Cookie 和 CGI 上下文。新版不再直接执行 `authenticate.cgi`,也不使用 r4 提权辅助程序。已用 DSM 7.4.1 的真实浏览器会话验证 `login.cgi` 和 `SYNO.Core.NormalUser.get`;本地 SCGI 传输仍依赖 DSM 版本,需要逐版本验收。 |+| 账号与 ACL 状态 | DSM 7.4.1 已验证 `SYNO.Core.User.get` 单独查询 `additional=["expired"]`;附带 `groups` 会报 3106。UID 和管理员组通过非特权 `id` 核对。[官方 File Station API](https://global.download.synology.com/download/Document/Software/DeveloperGuide/Package/FileStation/All/enu/Synology_File_Station_API_Guide.pdf)规定了 `List.getinfo` 和有效 ACL 字段,已在两个明确授权的共享目录完成浏览器查询。这些接口检查不等同于完整 SPK 实机验收。 |+| 架构 | [官方架构映射](https://help.synology.com/developer-guide/appendix/platarchs.html)、[机型 CPU 列表](https://kb.synology.com/en-global/DSM/tutorial/What_kind_of_CPU_does_my_NAS_have)。DS920+/DS220+ 属于 Gemini Lake;DS220j 是 RTD1296(ARMv8),不能安装 x86_64 包。 |+| 工具链 | [官方选择说明](https://help.synology.com/developer-guide/compile_applications/download_dsm_tool_chain.html)、[环境准备](https://help.synology.com/developer-guide/getting_started/prepare_environment.html)、[spksrc Gemini Lake 输入](https://github.com/SynoCommunity/spksrc/tree/master/toolchain/syno-geminilake-7.2)。准确归档 SHA-256 记录在 `scripts/synology-runtime.lock.json`。 |+| 成熟开源参考 | [SynoCommunity/spksrc](https://github.com/SynoCommunity/spksrc) 及其 [Transmission 生命周期](https://github.com/SynoCommunity/spksrc/blob/master/spk/transmission/src/service-setup.sh),用于核对 FHS 保留和套件账号运行;没有照搬安装时下载依赖的做法。 |diff --git a/packaging/synology/WIZARD_UIFILES/install_uifile b/packaging/synology/WIZARD_UIFILES/install_uifilenew file mode 100644index 00000000..1260f34d--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/install_uifile@@ -0,0 +1,28 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "All DSM administrators share one download list. Downloads default to the motrix shared folder. After installation, open Motrix Settings → Synology NAS to configure folders and browser extensions; no configuration-file editing is needed."+ },+ {+ "type": "textfield",+ "desc": "Client port",+ "subitems": [+ {+ "key": "wizard_client_port",+ "defaultValue": "16802",+ "validator": {+ "allowBlank": false,+ "regex": {+ "expr": "/^\\d{4,5}$/",+ "errorText": "Enter a port from 1024 to 65535"+ }+ }+ }+ ]+ }+ ],+ "invalid_next_disabled_v2": true+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/install_uifile_chs b/packaging/synology/WIZARD_UIFILES/install_uifile_chsnew file mode 100644index 00000000..b4bd4f58--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/install_uifile_chs@@ -0,0 +1,28 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "所有 DSM 管理员共同管理同一组任务。默认下载目录为 motrix 共享文件夹。安装后可在 Motrix 的“设置 → 群晖套件”中配置目录和浏览器扩展,无需编辑配置文件。"+ },+ {+ "type": "textfield",+ "desc": "客户端端口",+ "subitems": [+ {+ "key": "wizard_client_port",+ "defaultValue": "16802",+ "validator": {+ "allowBlank": false,+ "regex": {+ "expr": "/^\\d{4,5}$/",+ "errorText": "请输入 1024–65535 之间的端口号"+ }+ }+ }+ ]+ }+ ],+ "invalid_next_disabled_v2": true+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/install_uifile_cht b/packaging/synology/WIZARD_UIFILES/install_uifile_chtnew file mode 100644index 00000000..5d99a046--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/install_uifile_cht@@ -0,0 +1,28 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "所有 DSM 管理員共同管理同一組任務。預設下載目錄為 motrix 共用資料夾。安裝後可在 Motrix 的「設定 → 群暉套件」中設定目錄和瀏覽器擴充功能,無需編輯設定檔。"+ },+ {+ "type": "textfield",+ "desc": "用戶端連接埠",+ "subitems": [+ {+ "key": "wizard_client_port",+ "defaultValue": "16802",+ "validator": {+ "allowBlank": false,+ "regex": {+ "expr": "/^\\d{4,5}$/",+ "errorText": "請輸入 1024–65535 之間的連接埠號碼"+ }+ }+ }+ ]+ }+ ],+ "invalid_next_disabled_v2": true+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/uninstall_uifile b/packaging/synology/WIZARD_UIFILES/uninstall_uifilenew file mode 100644index 00000000..26259671--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/uninstall_uifile@@ -0,0 +1,20 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "Tasks, settings and paired clients are kept by default. Downloaded files are always kept."+ },+ {+ "type": "multiselect",+ "subitems": [+ {+ "key": "wizard_delete_data",+ "desc": "Delete tasks, settings and paired clients",+ "defaultValue": false+ }+ ]+ }+ ]+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/uninstall_uifile_chs b/packaging/synology/WIZARD_UIFILES/uninstall_uifile_chsnew file mode 100644index 00000000..05eca006--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/uninstall_uifile_chs@@ -0,0 +1,20 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "默认保留任务、配置和配对信息。下载文件始终保留。"+ },+ {+ "type": "multiselect",+ "subitems": [+ {+ "key": "wizard_delete_data",+ "desc": "删除任务、配置和配对信息",+ "defaultValue": false+ }+ ]+ }+ ]+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/uninstall_uifile_cht b/packaging/synology/WIZARD_UIFILES/uninstall_uifile_chtnew file mode 100644index 00000000..6b109502--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/uninstall_uifile_cht@@ -0,0 +1,20 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "預設保留任務、設定和配對資訊。下載檔案一律保留。"+ },+ {+ "type": "multiselect",+ "subitems": [+ {+ "key": "wizard_delete_data",+ "desc": "刪除任務、設定和配對資訊",+ "defaultValue": false+ }+ ]+ }+ ]+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/upgrade_uifile b/packaging/synology/WIZARD_UIFILES/upgrade_uifilenew file mode 100644index 00000000..e7f8a0a4--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/upgrade_uifile@@ -0,0 +1,10 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "The upgrade stops downloads and keeps tasks, settings, paired clients and files."+ }+ ]+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/upgrade_uifile_chs b/packaging/synology/WIZARD_UIFILES/upgrade_uifile_chsnew file mode 100644index 00000000..a126aaa5--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/upgrade_uifile_chs@@ -0,0 +1,10 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "升级将停止下载,保留任务、配置、配对信息和文件。"+ }+ ]+ }+]diff --git a/packaging/synology/WIZARD_UIFILES/upgrade_uifile_cht b/packaging/synology/WIZARD_UIFILES/upgrade_uifile_chtnew file mode 100644index 00000000..a8157dc4--- /dev/null+++ b/packaging/synology/WIZARD_UIFILES/upgrade_uifile_cht@@ -0,0 +1,10 @@+[+ {+ "step_title": "Motrix",+ "items": [+ {+ "desc": "升級將停止下載,保留任務、設定、配對資訊和檔案。"+ }+ ]+ }+]diff --git a/packaging/synology/app/lifecycle.mjs b/packaging/synology/app/lifecycle.mjsnew file mode 100644index 00000000..f989bc77--- /dev/null+++ b/packaging/synology/app/lifecycle.mjs@@ -0,0 +1,430 @@+import { spawn } from 'node:child_process'+import { randomUUID } from 'node:crypto'+import { once } from 'node:events'+import { constants } from 'node:fs'+import {+ access,+ chmod,+ mkdir,+ open,+ readFile,+ realpath,+ rename,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises'+import { request } from 'node:http'+import path from 'node:path'+import { setTimeout as delay } from 'node:timers/promises'+import { pathToFileURL } from 'node:url'++async function readPackageDocument(file, limit = 32 * 1024) {+ const handle = await open(+ file,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK+ )+ try {+ const info = await handle.stat()+ if (+ !info.isFile() ||+ info.uid !== process.getuid() ||+ (info.mode & 0o077) !== 0 ||+ info.size > limit+ )+ throw new Error('Untrusted DSM package configuration')+ const data = Buffer.alloc(limit + 1)+ let offset = 0+ while (offset < data.length) {+ const { bytesRead } = await handle.read(+ data,+ offset,+ data.length - offset,+ offset+ )+ if (!bytesRead) break+ offset += bytesRead+ }+ if (offset > limit) throw new Error('DSM package configuration too large')+ try {+ return JSON.parse(data.subarray(0, offset).toString('utf8'))+ } catch {+ throw new Error('Invalid DSM package configuration')+ }+ } finally {+ await handle.close()+ }+}++export async function runtimeEnvironment(env) {+ const target = env.SYNOPKG_PKGDEST+ const variable = env.SYNOPKG_PKGVAR+ if (![target, variable].every((p) => p && path.isAbsolute(p)))+ throw new Error('Missing DSM package paths')+ const settings = await readPackageDocument(+ path.join(variable, 'package-settings.json')+ )+ const configFile = path.join(variable, 'directories.json')+ let directories+ try {+ directories = await readPackageDocument(configFile, 36 * 1024)+ } catch (error) {+ if (error.code !== 'ENOENT') throw error+ const share = await realpath('/var/packages/Motrix/shares/motrix')+ directories = { roots: [share] }+ await writeFile(configFile, JSON.stringify(directories), {+ flag: 'wx',+ mode: 0o600,+ })+ }+ const server = path.join(target, 'server')+ const data = path.join(variable, 'data')+ return {+ PATH: `${target}/runtime/bin:/usr/bin:/bin`,+ NODE_ENV: 'production',+ HOME: env.SYNOPKG_PKGHOME || variable,+ SYNOPKG_PKGVAR: variable,+ SYNOPKG_PKGDEST: target,+ MOTRIX_AUTH_MODE: 'synologyDsm',+ MOTRIX_WEB_BASE_PATH: '/motrix',+ MOTRIX_MDXP_HOST: '0.0.0.0',+ MOTRIX_MDXP_PORT: String(settings.clientPort),+ MOTRIX_REMOTE_EXTENSION_ENABLED: settings.extensionUrl ? 'true' : 'false',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: settings.extensionUrl,+ MOTRIX_PUBLIC_URL: settings.operatorUrl,+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: settings.allowHttp ? 'true' : 'false',+ MOTRIX_DATA_DIR: data,+ MOTRIX_TEMP_DIR: `${data}/tmp`,+ MOTRIX_PLUGIN_DIR: `${data}/plugins`,+ MOTRIX_EXTRA_DIR: `${server}/extra`,+ MOTRIX_ARIA2_BIN: `${server}/bin/aria2c`,+ MOTRIX_FINALIZE_FS_BIN: `${server}/bin/motrix-finalize-fs`,+ MOTRIX_RENDERER_DIR: `${server}/dist/renderer-web`,+ MOTRIX_BUILTIN_PLUGIN_DIR: `${server}/builtin-plugins`,+ MOTRIX_DEFAULT_SAVE_DIR: directories.roots[0],+ MOTRIX_ALLOWED_SAVE_DIRS: directories.roots.join(':'),+ }+}++export async function configure(env) {+ const destination = path.join(env.SYNOPKG_PKGVAR, 'package-settings.json')+ if (await stat(destination).catch(() => undefined)) return+ const port = env.wizard_client_port || '16802'+ if (!/^[0-9]{4,5}$/.test(port) || Number(port) < 1024 || Number(port) > 65535)+ throw new Error('Client port must be between 1024 and 65535')+ await writeFile(+ destination,+ JSON.stringify({+ clientPort: Number(port),+ extensionUrl: env.wizard_extension_url || '',+ operatorUrl: env.wizard_operator_url || '',+ allowHttp: env.wizard_allow_operator_http === 'true',+ }),+ { flag: 'wx', mode: 0o600 }+ )+}++/** Apply the administrator's restart journal before any new application process+ * starts. Retain it on failure so interrupted two-file application is replayable. */+export async function applyPendingSettings(env) {+ const variable = env.SYNOPKG_PKGVAR+ const pending = path.join(variable, 'pending-settings.json')+ let value+ try {+ value = await readPackageDocument(pending, 36 * 1024)+ } catch (error) {+ if (error.code === 'ENOENT') return+ throw error+ }+ if (+ !value ||+ Object.keys(value)+ .filter((key) => key !== 'directoryIdentities')+ .sort()+ .join(',') !== 'allowHttp,clientPort,extensionUrl,operatorUrl,roots' ||+ !Number.isInteger(value.clientPort) ||+ value.clientPort < 1024 ||+ value.clientPort > 65535 ||+ typeof value.allowHttp !== 'boolean' ||+ !['extensionUrl', 'operatorUrl'].every(+ (key) =>+ typeof value[key] === 'string' &&+ value[key].length <= 2048 &&+ !/\p{Cc}/u.test(value[key])+ ) ||+ !Array.isArray(value.roots) ||+ value.roots.length < 1 ||+ value.roots.length > 64 ||+ !value.roots.every(+ (root) =>+ typeof root === 'string' &&+ root.length <= 4096 &&+ /^\/volume[1-9]\d*\/[^:]+$/.test(root) &&+ !/\p{Cc}/u.test(root) &&+ root+ .split('/')+ .slice(1)+ .every((part) => part && part !== '.' && part !== '..')+ )+ )+ throw new Error('Invalid pending package settings')+ const { roots, directoryIdentities: pendingIdentities, ...settings } = value+ let directoryIdentities = pendingIdentities+ if (directoryIdentities === undefined) {+ // A replay of an old path-only journal must not discard a grant that+ // already has an identity. First upgrades from path-only grants still work.+ const previous = await readPackageDocument(+ path.join(variable, 'directories.json'),+ 36 * 1024+ ).catch((error) => {+ if (error.code === 'ENOENT') return undefined+ throw error+ })+ if (previous?.directoryIdentities !== undefined) {+ directoryIdentities = roots.map(+ (root) => previous.directoryIdentities[previous.roots.indexOf(root)]+ )+ }+ }+ if (+ directoryIdentities !== undefined &&+ (!Array.isArray(directoryIdentities) ||+ directoryIdentities.length !== roots.length ||+ !directoryIdentities.every(+ (id) => typeof id === 'string' && /^\d{1,20}:\d{1,20}$/.test(id)+ ))+ ) {+ throw new Error('Invalid pending directory identities')+ }+ for (const [name, data] of [+ ['package-settings.json', settings],+ ['directories.json', { roots, directoryIdentities }],+ ]) {+ const temporary = path.join(variable, `${name}.${randomUUID()}.next`)+ try {+ const handle = await open(temporary, 'wx', 0o600)+ try {+ await handle.writeFile(`${JSON.stringify(data)}\n`)+ await handle.sync()+ } finally {+ await handle.close()+ }+ await rename(temporary, path.join(variable, name))+ } finally {+ await rm(temporary, { force: true })+ }+ }+ const directory = await open(variable, 'r')+ try {+ await directory.sync()+ } finally {+ await directory.close()+ }+ await rm(pending)+}++export function processStartTime(contents) {+ const fields = contents+ .slice(contents.lastIndexOf(')') + 2)+ .trim()+ .split(/\s+/)+ return fields[0] === 'Z' ? undefined : fields[19]+}++export function matchesEntrypoint(command, entry) {+ const args = command.split('\0')+ if (args.at(-1) === '') args.pop()+ let index = 1+ // Execution wrappers may prepend Node preload/optimization options. Match+ // the script operand, never a later argument to an unrelated script.+ while (index < args.length) {+ if (args[index] === '--no-opt' || args[index].startsWith('--require='))+ index += 1+ else if (args[index] === '-r' || args[index] === '--require') index += 2+ else break+ }+ return args[index] === entry && index === args.length - 1+}++async function identity(pid, executable, entry) {+ if (!Number.isSafeInteger(pid) || pid <= 1) return undefined+ try {+ const [info, command, exe, boot] = await Promise.all([+ readFile(`/proc/${pid}/stat`, 'utf8'),+ readFile(`/proc/${pid}/cmdline`, 'utf8'),+ realpath(`/proc/${pid}/exe`),+ readFile('/proc/sys/kernel/random/boot_id', 'utf8'),+ ])+ const started = processStartTime(info)+ if (+ !started ||+ exe !== (await realpath(executable)) ||+ !matchesEntrypoint(command, entry)+ )+ return undefined+ return { pid, started, boot: boot.trim() }+ } catch (error) {+ if (['ENOENT', 'ESRCH', 'EACCES', 'EPERM'].includes(error.code))+ return undefined+ throw error+ }+}++export async function healthy(socketPath) {+ return new Promise((resolve) => {+ const req = request({ socketPath, path: '/motrix/healthz' }, (res) => {+ res.resume()+ resolve(res.statusCode === 200)+ })+ req.setTimeout(1_000, () => req.destroy())+ req.on('error', () => resolve(false))+ req.end()+ })+}++export async function lifecycle(action, env = process.env) {+ // Stop/status must work even when downloads are unmounted or API tokens expire.+ const target = env.SYNOPKG_PKGDEST+ const variable = env.SYNOPKG_PKGVAR+ if (!target || !variable) throw new Error('Missing DSM application paths')+ const executable = path.join(target, 'runtime/bin/node')+ const entry = path.join(target, 'server/dist/server/index.mjs')+ const pidFile = path.join(variable, 'server-process.json')+ const socketPath = path.join(variable, 'web.sock')+ const readRecord = async () => {+ try {+ return JSON.parse(await readFile(pidFile, 'utf8'))+ } catch (error) {+ if (error.code === 'ENOENT') return undefined+ throw error+ }+ }+ const alive = async (record) => {+ if (!record) return false+ const current = await identity(record.pid, executable, entry)+ return (+ current?.started === record.started &&+ current?.boot === record.boot &&+ current !== undefined+ )+ }+ const stop = async (record) => {+ if (await alive(record)) {+ process.kill(record.pid, 'SIGTERM')+ const deadline = Date.now() + 60_000+ while (await alive(record)) {+ if (Date.now() >= deadline)+ throw new Error(+ 'Motrix did not stop within 60 seconds; process record retained'+ )+ await delay(200)+ }+ }+ await rm(pidFile, { force: true })+ }+ if (process.getuid?.() === 0)+ throw new Error('DSM lifecycle must run as the package account')+ if (action === 'postinst' || action === 'postupgrade') {+ await configure(env)+ return 0+ }+ const record = await readRecord()+ if (action === 'preupgrade' || action === 'preuninst') {+ await stop(record)+ if (+ action === 'preuninst' &&+ env.SYNOPKG_PKG_STATUS === 'UNINSTALL' &&+ env.wizard_delete_data === 'true'+ ) {+ await rm(path.join(variable, 'data'), { recursive: true, force: true })+ for (const name of [+ 'package-settings.json',+ 'directories.json',+ 'pending-settings.json',+ ])+ await rm(path.join(variable, name), { force: true })+ }+ return 0+ }+ if (action === 'status')+ return (await alive(record)) && (await healthy(socketPath)) ? 0 : 3+ if (action === 'stop') {+ await stop(record)+ return 0+ }+ if (action !== 'start') throw new Error('Expected start, stop or status')+ if (await alive(record)) {+ if (!(await healthy(socketPath)))+ throw new Error(+ 'Motrix is running but is not healthy; inspect server.log'+ )+ return 0+ }+ await configure(env)+ await applyPendingSettings(env)+ const runtime = await runtimeEnvironment(env)+ // The Server checks existing shares before opening its database or engine.+ // Unavailable grants start the authenticated settings surface only.+ await access(executable)+ await mkdir(runtime.MOTRIX_DATA_DIR, { recursive: true, mode: 0o700 })+ await chmod(runtime.MOTRIX_DATA_DIR, 0o700)+ const logPath = path.join(variable, 'server.log')+ const logStat = await stat(logPath).catch(() => undefined)+ if (logStat?.size > 8 * 1024 * 1024) await rename(logPath, `${logPath}.1`)+ const log = await open(logPath, 'a', 0o600)+ let child+ try {+ child = spawn(executable, [entry], {+ cwd: path.dirname(entry),+ env: runtime,+ detached: true,+ stdio: ['ignore', log.fd, log.fd],+ })+ await once(child, 'spawn')+ } finally {+ await log.close()+ }+ child.unref()+ const started = await identity(child.pid, executable, entry)+ if (!started)+ throw new Error('Motrix exited during startup; inspect server.log')+ const temporary = `${pidFile}.${process.pid}.tmp`+ try {+ await writeFile(temporary, `${JSON.stringify(started)}\n`, {+ mode: 0o600,+ flag: 'wx',+ })+ await rename(temporary, pidFile)+ const deadline = Date.now() + 60_000+ while (Date.now() < deadline && (await alive(started))) {+ if (await healthy(socketPath)) return 0+ await delay(250)+ }+ throw new Error('Motrix startup health check failed; inspect server.log')+ } catch (error) {+ await stop(started)+ throw error+ } finally {+ await rm(temporary, { force: true })+ }+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ process.umask(0o077)+ lifecycle(process.argv[2])+ .then((code) => {+ process.exitCode = code+ })+ .catch(async (error) => {+ const message = `${error.message}\n`+ if (process.env.SYNOPKG_TEMP_LOGFILE)+ await writeFile(process.env.SYNOPKG_TEMP_LOGFILE, message).catch(+ () => {}+ )+ process.stderr.write(message)+ process.exitCode = 1+ })+}diff --git a/packaging/synology/app/nginx/motrix.conf b/packaging/synology/app/nginx/motrix.confnew file mode 100644index 00000000..8bb988cf--- /dev/null+++ b/packaging/synology/app/nginx/motrix.conf@@ -0,0 +1,37 @@+location = /motrix { return 302 /motrix/; }+location ^~ /motrix/bridge/ {+ proxy_pass http://unix:/var/packages/Motrix/var/client.sock;+ proxy_http_version 1.1;+ proxy_set_header Host $http_host;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ proxy_set_header Cookie "";+ proxy_set_header Authorization "";+ # Allow the full MBP1 code-entry and credential-exchange deadlines.+ proxy_read_timeout 210s;+ client_max_body_size 1m;+ proxy_buffering off;+}+location ^~ /motrix/client/ {+ proxy_pass http://unix:/var/packages/Motrix/var/client.sock;+ proxy_http_version 1.1;+ proxy_set_header Host $http_host;+ proxy_set_header Cookie "";+ proxy_read_timeout 75s;+ client_max_body_size 4m;+ proxy_buffering off;+}+location ^~ /motrix/ {+ proxy_pass http://unix:/var/packages/Motrix/var/web.sock;+ proxy_http_version 1.1;+ proxy_set_header Host $http_host;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ proxy_set_header X-Motrix-Dsm-Remote-Addr $remote_addr;+ proxy_set_header X-Motrix-Dsm-Server-Addr $server_addr;+ proxy_set_header X-Motrix-Dsm-Server-Port $server_port;+ proxy_set_header X-Motrix-Dsm-Scheme $scheme;+ proxy_read_timeout 75s;+ client_max_body_size 64m;+ proxy_buffering off;+}diff --git a/packaging/synology/app/ui/config b/packaging/synology/app/ui/confignew file mode 100644index 00000000..f39f6eb9--- /dev/null+++ b/packaging/synology/app/ui/config@@ -0,0 +1,8 @@+{+ ".url": {+ "com.motrix.app": {+ "type": "url", "title": "Motrix", "desc": "Motrix",+ "icon": "images/icon_256.png", "url": "/motrix/", "allUsers": false+ }+ }+}diff --git a/packaging/synology/app/ui/images/icon_256.png b/packaging/synology/app/ui/images/icon_256.pngnew file mode 100644index 00000000..8220abb6Binary files /dev/null and b/packaging/synology/app/ui/images/icon_256.png differdiff --git a/packaging/synology/app/ui/images/icon_64.png b/packaging/synology/app/ui/images/icon_64.pngnew file mode 100644index 00000000..4681c586Binary files /dev/null and b/packaging/synology/app/ui/images/icon_64.png differdiff --git a/packaging/synology/conf/privilege b/packaging/synology/conf/privilegenew file mode 100644index 00000000..addfbb41--- /dev/null+++ b/packaging/synology/conf/privilege@@ -0,0 +1,8 @@+{+ "defaults": {+ "run-as": "package"+ },+ "username": "motrix",+ "groupname": "motrix",+ "join-groupname": "http"+}diff --git a/packaging/synology/conf/resource b/packaging/synology/conf/resourcenew file mode 100644index 00000000..a04f8513--- /dev/null+++ b/packaging/synology/conf/resource@@ -0,0 +1,10 @@+{+ "data-share": {+ "shares": [{ "name": "motrix", "permission": { "rw": ["motrix"] }, "once": true }]+ },+ "web-config": {+ "nginx-static-config": {+ "enable": [{ "type": "dsm", "relpath": "nginx/motrix.conf" }]+ }+ }+}diff --git a/packaging/synology/scripts/postinst b/packaging/synology/scripts/postinstnew file mode 100755index 00000000..7d696fac--- /dev/null+++ b/packaging/synology/scripts/postinst@@ -0,0 +1,9 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exec 9>"${SYNOPKG_PKGVAR:?}/lifecycle.lock"+flock -w 90 9+exec "${SYNOPKG_PKGDEST:?}/runtime/bin/node" "$SYNOPKG_PKGDEST/lifecycle.mjs" postinstdiff --git a/packaging/synology/scripts/postuninst b/packaging/synology/scripts/postuninstnew file mode 100755index 00000000..cbbee427--- /dev/null+++ b/packaging/synology/scripts/postuninst@@ -0,0 +1,7 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exit 0diff --git a/packaging/synology/scripts/postupgrade b/packaging/synology/scripts/postupgradenew file mode 100755index 00000000..d071b3b1--- /dev/null+++ b/packaging/synology/scripts/postupgrade@@ -0,0 +1,9 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exec 9>"${SYNOPKG_PKGVAR:?}/lifecycle.lock"+flock -w 90 9+exec "${SYNOPKG_PKGDEST:?}/runtime/bin/node" "$SYNOPKG_PKGDEST/lifecycle.mjs" postupgradediff --git a/packaging/synology/scripts/preinst b/packaging/synology/scripts/preinstnew file mode 100755index 00000000..cbbee427--- /dev/null+++ b/packaging/synology/scripts/preinst@@ -0,0 +1,7 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exit 0diff --git a/packaging/synology/scripts/preuninst b/packaging/synology/scripts/preuninstnew file mode 100755index 00000000..64387e50--- /dev/null+++ b/packaging/synology/scripts/preuninst@@ -0,0 +1,9 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exec 9>"${SYNOPKG_PKGVAR:?}/lifecycle.lock"+flock -w 90 9+exec "${SYNOPKG_PKGDEST:?}/runtime/bin/node" "$SYNOPKG_PKGDEST/lifecycle.mjs" preuninstdiff --git a/packaging/synology/scripts/preupgrade b/packaging/synology/scripts/preupgradenew file mode 100755index 00000000..9db00e7c--- /dev/null+++ b/packaging/synology/scripts/preupgrade@@ -0,0 +1,9 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exec 9>"${SYNOPKG_PKGVAR:?}/lifecycle.lock"+flock -w 90 9+exec "${SYNOPKG_PKGDEST:?}/runtime/bin/node" "$SYNOPKG_PKGDEST/lifecycle.mjs" preupgradediff --git a/packaging/synology/scripts/start-stop-status b/packaging/synology/scripts/start-stop-statusnew file mode 100755index 00000000..1111f6d1--- /dev/null+++ b/packaging/synology/scripts/start-stop-status@@ -0,0 +1,9 @@+#!/bin/sh+set -eu+umask 077+export PATH=/usr/bin:/bin+unset NODE_OPTIONS NODE_PATH LD_PRELOAD LD_LIBRARY_PATH+[ "$(id -u)" != 0 ] || { echo 'Motrix must run as the package account' >&2; exit 1; }+exec 9>"${SYNOPKG_PKGVAR:?}/lifecycle.lock"+flock -w 90 9+exec "${SYNOPKG_PKGDEST:?}/runtime/bin/node" "$SYNOPKG_PKGDEST/lifecycle.mjs" "${1:?Missing action}"diff --git a/screenshots/motrix-dsm-dashboard-activity.png b/screenshots/motrix-dsm-dashboard-activity.pngnew file mode 100644index 00000000..433ee7b7Binary files /dev/null and b/screenshots/motrix-dsm-dashboard-activity.png differdiff --git a/scripts/build-synology-package.mjs b/scripts/build-synology-package.mjsnew file mode 100644index 00000000..50bcada5--- /dev/null+++ b/scripts/build-synology-package.mjs@@ -0,0 +1,201 @@+import { createHash } from 'node:crypto'+import {+ chmod,+ lstat,+ mkdir,+ readdir,+ readFile,+ rm,+ writeFile,+} from 'node:fs/promises'+import path from 'node:path'+import { parseArgs } from 'node:util'+import {+ lockedDownload,+ repositoryRoot,+ run,+ sha256,+} from './prepare-fnos-project.mjs'+import { prepareSynologyProject } from './prepare-synology-project.mjs'+import { synologyTarget } from './synology-target.mjs'+import {+ payloadInventory,+ verifySynologyPackage,+ verifySynologyProject,+} from './verify-synology-package.mjs'++const { values } = parseArgs({+ args: process.argv.slice(2).filter((arg) => arg !== '--'),+ options: {+ arch: { type: 'string' },+ 'app-dir': { type: 'string' },+ 'output-dir': { type: 'string' },+ revision: { type: 'string' },+ },+})+const project = await prepareSynologyProject({+ appDir: values['app-dir'],+ arch: values.arch,+ outputDir: values['output-dir'],+ revision: values.revision,+})+const app = path.join(project, 'app')+const inventory = await payloadInventory(app)+await writeFile(+ path.join(app, 'payload-sha256.json'),+ `${JSON.stringify(inventory, null, 2)}\n`+)+const receipt = await verifySynologyProject(project)+const output = path.dirname(project)+const arch = receipt.architecture+const target = synologyTarget(arch)+const sdk = path.join(output, 'sdk')+async function writableDirectories(directory) {+ if (!(await lstat(directory)).isDirectory()) return+ await chmod(directory, 0o755)+ for (const name of await readdir(directory)) {+ const file = path.join(directory, name)+ if ((await lstat(file)).isDirectory()) await writableDirectories(file)+ }+}+const invoke = async (root) => {+ const mounts = [+ 'run',+ '--rm',+ '--platform',+ target.dockerPlatform,+ '--network=none',+ '--mount',+ `type=bind,source=${root},target=/spk,readonly`,+ '--mount',+ `type=bind,source=${path.join(repositoryRoot, 'scripts')},target=/scripts,readonly`,+ ]+ const native = process.platform === 'linux' && process.arch === arch+ const image = arch === 'arm64' ? 'motrix-dsm-abi:arm64' : 'rust:1.94.1'+ if (!native && arch === 'arm64') {+ run('docker', [+ 'build',+ '--platform',+ target.dockerPlatform,+ '--tag',+ image,+ '--file',+ path.join(repositoryRoot, 'packaging/synology-abi.Dockerfile'),+ path.join(repositoryRoot, 'packaging/synology'),+ ])+ }+ const reports = {}+ for (const [platform, profile] of Object.entries(target.platforms)) {+ const sdkArchive = await lockedDownload(+ profile.toolchain,+ path.join(repositoryRoot, 'node_modules/.cache/synology')+ )+ await mkdir(sdk)+ try {+ run('tar', ['-xJf', sdkArchive, '-C', sdk])+ await writableDirectories(sdk)+ const reportName = `synology-${platform}-abi.json`+ if (native) {+ run('python3', [+ path.join(repositoryRoot, 'scripts/verify_synology_abi.py'),+ path.join(root, 'app'),+ sdk,+ path.join(output, reportName),+ arch,+ platform,+ ])+ } else {+ run('docker', [+ ...mounts,+ '--mount',+ `type=bind,source=${sdk},target=/sdk,readonly`,+ '--mount',+ `type=bind,source=${output},target=/reports`,+ image,+ 'python3',+ '/scripts/verify_synology_abi.py',+ '/spk/app',+ '/sdk',+ `/reports/${reportName}`,+ arch,+ platform,+ ])+ }+ reports[platform] = JSON.parse(+ await readFile(path.join(output, reportName), 'utf8')+ )+ } finally {+ await rm(sdk, { recursive: true, force: true })+ }+ }+ run('docker', [+ ...mounts,+ 'rust:1.94.1',+ '/spk/app/runtime/bin/node',+ '/scripts/smoke-server-package.mjs',+ '--app-dir',+ '/spk/app/server',+ '--timeout-ms',+ '120000',+ ])+ run('docker', [+ ...mounts,+ '--tmpfs',+ '/volume1:rw,nosuid,nodev',+ 'rust:1.94.1',+ '/spk/app/runtime/bin/node',+ '/scripts/smoke-synology-package.mjs',+ '--project-dir',+ '/spk',+ ])+ return reports+}+const payload = path.join(project, 'package.tgz')+run('tar', ['-czf', payload, '-C', app, '.'], {+ env: { ...process.env, COPYFILE_DISABLE: '1' },+})+const infoPath = path.join(project, 'INFO')+await writeFile(+ infoPath,+ (await readFile(infoPath, 'utf8')).replace(+ '@CHECKSUM@',+ createHash('md5')+ .update(await readFile(payload))+ .digest('hex')+ )+)+const file = path.join(+ output,+ `Motrix-${receipt.version}-${receipt.revision}-dsm-${arch}.spk`+)+run(+ 'tar',+ [+ '-cf',+ file,+ '-C',+ project,+ 'INFO',+ 'package.tgz',+ 'scripts',+ 'conf',+ 'WIZARD_UIFILES',+ 'LICENSE',+ 'PACKAGE_ICON.PNG',+ 'PACKAGE_ICON_256.PNG',+ ],+ { env: { ...process.env, COPYFILE_DISABLE: '1' } }+)+// Execute every profile against this single extracted SPK before writing its+// checksum and release ABI receipt.+let platforms+await verifySynologyPackage(file, async (root) => {+ platforms = await invoke(root)+})+const digest = sha256(await readFile(file))+await writeFile(+ `${file}.abi.json`,+ `${JSON.stringify({ schemaVersion: 3, architecture: arch, spkSha256: digest, platforms }, null, 2)}\n`+)+await writeFile(`${file}.sha256`, `${digest} ${path.basename(file)}\n`)+console.log(`Built and verified ${file}`)diff --git a/scripts/fnos-runtime.lock.json b/scripts/fnos-runtime.lock.jsonindex 437b7c35..f35b2e66 100644--- a/scripts/fnos-runtime.lock.json+++ b/scripts/fnos-runtime.lock.json@@ -3,11 +3,13 @@"node": {"x64": {"url": "https://nodejs.org/dist/v24.18.0/node-v24.18.0-linux-x64.tar.xz",- "sha256": "55aa7153f9d88f28d765fcdad5ae6945b5c0f98a36881703817e4c450fa76742"+ "sha256": "55aa7153f9d88f28d765fcdad5ae6945b5c0f98a36881703817e4c450fa76742",+ "binarySha256": "41a74efb34cbde5c7632cdac0cf8bd1a14d0b8d73dc1e82755014d9a9ce70f5c"},"arm64": {"url": "https://nodejs.org/dist/v24.18.0/node-v24.18.0-linux-arm64.tar.xz",- "sha256": "58c9520501f6ae2b52d5b210444e24b9d0c029a58c5011b797bc1fe7105886f6"+ "sha256": "58c9520501f6ae2b52d5b210444e24b9d0c029a58c5011b797bc1fe7105886f6",+ "binarySha256": "6bf69d0eda41a12030d5f28d958cd09ce323bc0c13f1ab4d8bb426933aa08812"}},"fnpackVersion": "1.2.1",diff --git a/scripts/fnos_publication.py b/scripts/fnos_publication.pyindex 7f724460..dfb570eb 100644--- a/scripts/fnos_publication.py+++ b/scripts/fnos_publication.py@@ -5,109 +5,14 @@ import ioimport jsonimport osfrom pathlib import Path-import reimport subprocessimport sysimport tarfile-REPOSITORY = 'agalwood/Motrix'-VERSION = re.compile(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\Z')-SHA = re.compile(r'[a-f0-9]{40}\Z')---def run(*args):- return subprocess.check_output(args, text=True).strip()---def api(endpoint):- return json.loads(run('gh', 'api', f'repos/{REPOSITORY}/{endpoint}'))---def stable_version(tag):- if not isinstance(tag, str) or not tag.startswith('v') or not VERSION.fullmatch(tag[1:]):- raise ValueError('fnOS publication requires a strict stable v<major.minor.patch> tag')- return tag[1:]---def validate_run(value, tag, sha, workflow_id):- if not (value.get('event') == 'push'- and value.get('status') == 'completed'- and value.get('conclusion') == 'success'- and value.get('head_branch') == tag- and value.get('head_sha') == sha- and value.get('workflow_id') == workflow_id- and value.get('path') == '.github/workflows/release.yml'- and value.get('head_repository', {}).get('full_name') == REPOSITORY):- raise ValueError('Missing successful protected-tag Build/Release provenance')---def validate_release(value, tag):- if value.get('tag_name') != tag or value.get('draft') is not False or value.get('prerelease') is not False:- raise ValueError('Target must be an existing public stable GitHub Release')---def source(tag, source_run_id=None):- version = stable_version(tag)- subprocess.run(['git', 'fetch', '--no-tags', 'origin',- 'refs/heads/main:refs/remotes/origin/main'], check=True)- subprocess.run(['git', 'fetch', '--no-tags', 'origin',- f'refs/tags/{tag}:refs/remotes/origin/fnos-source-tag'], check=True)- sha = run('git', 'rev-parse', 'refs/remotes/origin/fnos-source-tag^{commit}')- if not SHA.fullmatch(sha):- raise ValueError('Invalid source commit')- subprocess.run(['git', 'merge-base', '--is-ancestor', sha, 'origin/main'], check=True)- manifest = json.loads(run('git', 'show', f'{sha}:package.json'))- if manifest.get('version') != version:- raise ValueError('Tag and package version differ')- workflow = api('actions/workflows/release.yml')- if source_run_id:- if not str(source_run_id).isdigit():- raise ValueError('Invalid release workflow run ID')- release_run = api(f'actions/runs/{source_run_id}')- validate_run(release_run, tag, sha, workflow['id'])- else:- runs = api(f'actions/workflows/release.yml/runs?branch={tag}&event=push&status=success&per_page=100')['workflow_runs']- release_run = None- for candidate in runs:- try:- validate_run(candidate, tag, sha, workflow['id'])- release_run = candidate- break- except ValueError:- continue- if release_run is None:- raise ValueError('No successful formal release workflow for this exact tag and commit')- validate_release(api(f'releases/tags/{tag}'), tag)- return {'tag': tag, 'version': version, 'source_sha': sha,- 'release_run_id': str(release_run['id'])}---def preflight():- if os.environ.get('GITHUB_REPOSITORY') != REPOSITORY:- raise ValueError('Publication is restricted to the official repository')- if os.environ.get('GITHUB_REF') != 'refs/heads/main' or os.environ.get('GITHUB_REF_PROTECTED') != 'true':- raise ValueError('Publication tooling must run from protected main')- event = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text())- event_name = os.environ.get('GITHUB_EVENT_NAME')- if event_name == 'workflow_run':- triggering_run = event['workflow_run']- tag = triggering_run.get('head_branch', '')- # Beta releases have no native fnOS package version.- if re.fullmatch(r'v(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)-beta\.(?:0|[1-9][0-9]*)', tag):- return {'publish': 'false'}- result = source(tag, triggering_run['id'])- elif event_name == 'workflow_dispatch':- result = source(event.get('inputs', {}).get('release_tag', ''))- else:- raise ValueError('Unsupported publication trigger')- return {'publish': 'true', **result}---def archive_file(archive, name, limit):- matches = [m for m in archive.getmembers() if m.name.removeprefix('./') == name]- if len(matches) != 1 or not matches[0].isfile() or not 0 < matches[0].size <= limit:- raise ValueError(f'Invalid archive member: {name}')- return archive.extractfile(matches[0]).read()+from nas_release import (+ REPOSITORY, archive_file, preflight, source, stable_version, upload_verified_assets,+ validate_release, validate_run,+)def verify_bundle(directory, version):@@ -149,30 +54,7 @@ def publish(directory, tag, sha, release_run_id):if current['source_sha'] != sha:raise ValueError('Release tag changed since build preflight')records = verify_bundle(directory, current['version'])- release = api(f'releases/tags/{tag}')- files = sorted(Path(directory).iterdir())- # Preflight every collision before uploading anything. Never replace assets.- missing = []- for file in files:- matches = [a for a in release['assets'] if a['name'] == file.name]- if len(matches) > 1:- raise ValueError('Duplicate existing release asset')- if not matches:- missing.append(file)- continue- asset = matches[0]- digest = 'sha256:' + hashlib.file_digest(file.open('rb'), 'sha256').hexdigest()- if asset.get('size') != file.stat().st_size or asset.get('digest') != digest:- raise ValueError(f'Existing immutable release asset differs: {file.name}')- if missing:- subprocess.run(['gh', 'release', 'upload', tag, '--repo', REPOSITORY,- *map(str, missing)], check=True)- published = api(f'releases/tags/{tag}')- for file in files:- asset = next(a for a in published['assets'] if a['name'] == file.name)- digest = 'sha256:' + hashlib.file_digest(file.open('rb'), 'sha256').hexdigest()- if asset.get('digest') != digest or asset['size'] != file.stat().st_size:- raise ValueError('Published fnOS asset digest or size mismatch')+ upload_verified_assets(directory, tag)print(json.dumps({'source': current, 'packages': records}, indent=2))diff --git a/scripts/nas_release.py b/scripts/nas_release.pynew file mode 100644index 00000000..256c65f6--- /dev/null+++ b/scripts/nas_release.py@@ -0,0 +1,133 @@+"""Shared stable-tag provenance and immutable GitHub asset upload for NAS packages."""+import hashlib+import json+import os+from pathlib import Path+import re+import subprocess++REPOSITORY = 'agalwood/Motrix'+VERSION = re.compile(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\Z')+SHA = re.compile(r'[a-f0-9]{40}\Z')+++def run(*args):+ return subprocess.check_output(args, text=True).strip()+++def api(endpoint):+ return json.loads(run('gh', 'api', f'repos/{REPOSITORY}/{endpoint}'))+++def stable_version(tag):+ if not isinstance(tag, str) or not tag.startswith('v') or not VERSION.fullmatch(tag[1:]):+ raise ValueError('NAS package publication requires a strict stable v<major.minor.patch> tag')+ return tag[1:]+++def validate_run(value, tag, sha, workflow_id):+ if not (value.get('event') == 'push'+ and value.get('status') == 'completed'+ and value.get('conclusion') == 'success'+ and value.get('head_branch') == tag+ and value.get('head_sha') == sha+ and value.get('workflow_id') == workflow_id+ and value.get('path') == '.github/workflows/release.yml'+ and value.get('head_repository', {}).get('full_name') == REPOSITORY):+ raise ValueError('Missing successful protected-tag Build/Release provenance')+++def validate_release(value, tag):+ if value.get('tag_name') != tag or value.get('draft') is not False or value.get('prerelease') is not False:+ raise ValueError('Target must be an existing public stable GitHub Release')+++def source(tag, source_run_id=None):+ version = stable_version(tag)+ subprocess.run(['git', 'fetch', '--no-tags', 'origin',+ 'refs/heads/main:refs/remotes/origin/main'], check=True)+ subprocess.run(['git', 'fetch', '--no-tags', 'origin',+ f'refs/tags/{tag}:refs/remotes/origin/nas-source-tag'], check=True)+ sha = run('git', 'rev-parse', 'refs/remotes/origin/nas-source-tag^{commit}')+ if not SHA.fullmatch(sha):+ raise ValueError('Invalid source commit')+ subprocess.run(['git', 'merge-base', '--is-ancestor', sha, 'origin/main'], check=True)+ manifest = json.loads(run('git', 'show', f'{sha}:package.json'))+ if manifest.get('version') != version:+ raise ValueError('Tag and package version differ')+ workflow = api('actions/workflows/release.yml')+ if source_run_id:+ if not str(source_run_id).isdigit():+ raise ValueError('Invalid release workflow run ID')+ release_run = api(f'actions/runs/{source_run_id}')+ validate_run(release_run, tag, sha, workflow['id'])+ else:+ runs = api(f'actions/workflows/release.yml/runs?branch={tag}&event=push&status=success&per_page=100')['workflow_runs']+ release_run = None+ for candidate in runs:+ try:+ validate_run(candidate, tag, sha, workflow['id'])+ release_run = candidate+ break+ except ValueError:+ continue+ if release_run is None:+ raise ValueError('No successful formal release workflow for this exact tag and commit')+ validate_release(api(f'releases/tags/{tag}'), tag)+ return {'tag': tag, 'version': version, 'source_sha': sha,+ 'release_run_id': str(release_run['id'])}+++def preflight():+ if os.environ.get('GITHUB_REPOSITORY') != REPOSITORY:+ raise ValueError('Publication is restricted to the official repository')+ if os.environ.get('GITHUB_REF') != 'refs/heads/main' or os.environ.get('GITHUB_REF_PROTECTED') != 'true':+ raise ValueError('Publication tooling must run from protected main')+ event = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text())+ event_name = os.environ.get('GITHUB_EVENT_NAME')+ if event_name == 'workflow_run':+ triggering_run = event['workflow_run']+ tag = triggering_run.get('head_branch', '')+ # Native NAS packages currently use stable application versions.+ if re.fullmatch(r'v(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)-beta\.(?:0|[1-9][0-9]*)', tag):+ return {'publish': 'false'}+ result = source(tag, triggering_run['id'])+ elif event_name == 'workflow_dispatch':+ result = source(event.get('inputs', {}).get('release_tag', ''))+ else:+ raise ValueError('Unsupported publication trigger')+ return {'publish': 'true', **result}+++def archive_file(archive, name, limit):+ matches = [m for m in archive.getmembers() if m.name.removeprefix('./') == name]+ if len(matches) != 1 or not matches[0].isfile() or not 0 < matches[0].size <= limit:+ raise ValueError(f'Invalid archive member: {name}')+ return archive.extractfile(matches[0]).read()+++def upload_verified_assets(directory, tag):+ release = api(f'releases/tags/{tag}')+ files = sorted(Path(directory).iterdir())+ # Preflight every collision before uploading anything. Never replace assets.+ missing = []+ for file in files:+ matches = [a for a in release['assets'] if a['name'] == file.name]+ if len(matches) > 1:+ raise ValueError('Duplicate existing release asset')+ if not matches:+ missing.append(file)+ continue+ asset = matches[0]+ digest = 'sha256:' + hashlib.file_digest(file.open('rb'), 'sha256').hexdigest()+ if asset.get('size') != file.stat().st_size or asset.get('digest') != digest:+ raise ValueError(f'Existing immutable release asset differs: {file.name}')+ if missing:+ subprocess.run(['gh', 'release', 'upload', tag, '--repo', REPOSITORY,+ *map(str, missing)], check=True)+ published = api(f'releases/tags/{tag}')+ for file in files:+ asset = next(a for a in published['assets'] if a['name'] == file.name)+ digest = 'sha256:' + hashlib.file_digest(file.open('rb'), 'sha256').hexdigest()+ if asset.get('digest') != digest or asset['size'] != file.stat().st_size:+ raise ValueError('Published release asset digest or size mismatch')diff --git a/scripts/prepare-synology-project.mjs b/scripts/prepare-synology-project.mjsnew file mode 100644index 00000000..fe441ae0--- /dev/null+++ b/scripts/prepare-synology-project.mjs@@ -0,0 +1,155 @@+import { execFileSync } from 'node:child_process'+import {+ cp,+ mkdir,+ mkdtemp,+ readFile,+ rename,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { parseArgs } from 'node:util'+import nodeLock from './fnos-runtime.lock.json' with { type: 'json' }+import {+ lockedDownload,+ repositoryRoot,+ run,+ sha256,+ verifyFnosBinary,+} from './prepare-fnos-project.mjs'+import dsmLock from './synology-runtime.lock.json' with { type: 'json' }+import { synologyTarget } from './synology-target.mjs'+import { verifyServerPackage } from './verify-server-package.mjs'++export async function prepareSynologyProject({+ appDir = 'dist/server-app',+ outputDir = 'release/synology/project',+ revision = String(dsmLock.revision),+ arch = 'x64',+} = {}) {+ const target = synologyTarget(arch)+ const source = path.resolve(appDir)+ const output = path.resolve(outputDir)+ if (!/^[1-9]\d{0,7}$/.test(revision)) throw new Error('Invalid SPK revision')+ if (+ !path.relative(source, output).startsWith(`..${path.sep}`) ||+ !path.relative(output, repositoryRoot).startsWith(`..${path.sep}`)+ )+ throw new Error('Overlapping SPK output directory')+ if (await stat(output).catch(() => undefined))+ throw new Error('Choose a fresh SPK output directory')+ await verifyServerPackage({+ appDir: source,+ platform: 'linux',+ arch,+ libc: 'gnu',+ })+ const manifest = JSON.parse(+ await readFile(path.join(source, 'package.json'), 'utf8')+ )+ const project = JSON.parse(+ await readFile(path.join(repositoryRoot, 'package.json'), 'utf8')+ )+ if (+ manifest.version !== project.version ||+ !/^\d+\.\d+\.\d+$/.test(project.version)+ )+ throw new Error('SPK requires the current stable application version')+ await mkdir(path.dirname(output), { recursive: true })+ const temporary = await mkdtemp(path.join(path.dirname(output), '.spk-'))+ try {+ await cp(path.join(repositoryRoot, 'packaging/synology'), temporary, {+ recursive: true,+ })+ for (const name of ['README.md', 'README.zh-CN.md'])+ await rm(path.join(temporary, name), { force: true })+ await cp(source, path.join(temporary, 'app/server'), {+ recursive: true,+ dereference: true,+ })+ await cp(+ path.join(repositoryRoot, 'LICENSE'),+ path.join(temporary, 'LICENSE')+ )+ const archive = await lockedDownload(+ nodeLock.node[arch],+ path.join(repositoryRoot, 'node_modules/.cache/fnos')+ )+ const runtime = path.join(temporary, 'app/runtime')+ await mkdir(runtime, { recursive: true })+ const prefix = `node-v${nodeLock.nodeVersion}-linux-${arch}`+ run('tar', [+ '-xJf',+ archive,+ '--strip-components=1',+ '-C',+ runtime,+ `${prefix}/bin/node`,+ `${prefix}/LICENSE`,+ ])+ await verifyFnosBinary(path.join(runtime, 'bin/node'), arch)+ const git = (args) =>+ execFileSync('git', args, {+ cwd: repositoryRoot,+ encoding: 'utf8',+ }).trim()+ const receipt = {+ sourceCommit: git(['rev-parse', 'HEAD']),+ sourceDirty:+ git(['status', '--porcelain', '--untracked-files=normal']) !== '',+ schemaVersion: 2,+ version: project.version,+ revision: Number(revision),+ architecture: arch,+ platforms: Object.keys(target.platforms),+ minimumDsm: dsmLock.dsmVersion,+ nodeVersion: nodeLock.nodeVersion,+ nodeArchiveSha256: nodeLock.node[arch].sha256,+ nodeSha256: sha256(await readFile(path.join(runtime, 'bin/node'))),+ toolchainDigests: target.toolchainDigests,+ deviceAcceptance: 'not-run',+ }+ await writeFile(+ path.join(temporary, 'app/synology-build.json'),+ `${JSON.stringify(receipt, null, 2)}\n`+ )+ const info = path.join(temporary, 'INFO')+ await writeFile(+ info,+ (await readFile(info, 'utf8'))+ .replaceAll('@ARCH@', target.infoArch)+ .replaceAll('@VERSION@', project.version)+ .replaceAll('@REVISION@', revision)+ )+ await rename(temporary, output)+ return output+ } finally {+ await rm(temporary, { recursive: true, force: true })+ }+}++if (+ process.argv[1] &&+ fileURLToPath(import.meta.url) === path.resolve(process.argv[1])+) {+ const { values } = parseArgs({+ args: process.argv.slice(2).filter((arg) => arg !== '--'),+ options: {+ arch: { type: 'string' },+ 'app-dir': { type: 'string' },+ 'output-dir': { type: 'string' },+ revision: { type: 'string' },+ },+ })+ console.log(+ await prepareSynologyProject({+ appDir: values['app-dir'],+ arch: values.arch,+ outputDir: values['output-dir'],+ revision: values.revision,+ })+ )+}diff --git a/scripts/smoke-synology-package.mjs b/scripts/smoke-synology-package.mjsnew file mode 100644index 00000000..f06788e6--- /dev/null+++ b/scripts/smoke-synology-package.mjs@@ -0,0 +1,1096 @@+import assert from 'node:assert/strict'+import { execFileSync, spawn } from 'node:child_process'+import { createHash, randomBytes } from 'node:crypto'+import { on, once } from 'node:events'+import {+ access,+ chmod,+ chown,+ cp,+ mkdir,+ readFile,+ rename,+ rm,+ stat,+ symlink,+ writeFile,+} from 'node:fs/promises'+import { createServer, request } from 'node:http'+import { createRequire } from 'node:module'+import { createServer as createSocketServer } from 'node:net'+import path from 'node:path'+import { setTimeout as delay } from 'node:timers/promises'+import { pathToFileURL } from 'node:url'+import { parseArgs } from 'node:util'++const { values } = parseArgs({ options: { 'project-dir': { type: 'string' } } })+const project = path.resolve(values['project-dir'])+if (process.platform !== 'linux' || process.getuid() !== 0)+ throw new Error('Run only in a disposable root Linux container')+await access('/.dockerenv')+const root = '/var/packages/Motrix'+if (await stat(root).catch(() => null))+ throw new Error('Existing package: refusing smoke')+const target = path.join(root, 'target')+const variable = path.join(root, 'var')+const downloads = '/volume1/motrix'+const replacement = '/volume1/motrix-storage-recovery'+execFileSync('groupadd', ['--gid', '1650', 'http'])+execFileSync('useradd', [+ '--uid',+ '1600',+ '--groups',+ 'http',+ '--no-create-home',+ 'motrix',+])+execFileSync('useradd', [+ '--uid',+ '1601',+ '--gid',+ 'http',+ '--no-create-home',+ 'gateway',+])+execFileSync('useradd', ['--uid', '1602', '--no-create-home', 'unrelated'])+for (const folder of [target, variable, downloads, `${root}/shares`])+ await mkdir(folder, { recursive: true })+await cp(path.join(project, 'app'), target, { recursive: true })+await symlink(downloads, `${root}/shares/motrix`)+execFileSync('chown', ['-R', '1600:1600', root, downloads])+// Simulate only the fixed DSM read APIs with real unprivileged socket access.+// No helper capabilities, root package processes, real cookies or passwords.+execFileSync('groupadd', ['--non-unique', '--gid', '101', 'administrators'])+execFileSync('useradd', [+ '--uid',+ '1700',+ '--groups',+ 'administrators',+ '--no-create-home',+ 'alice',+])+await writeFile('/tmp/dsm-session-state', 'active')+await writeFile('/tmp/dsm-account-state', 'active')+await writeFile('/tmp/dsm-acl-state', 'allow')+const authority = createSocketServer((socket) => {+ let input = Buffer.alloc(0),+ handled = false+ socket.on('data', async (chunk) => {+ if (handled) return+ input = Buffer.concat([input, chunk])+ const colon = input.indexOf(':')+ if (colon < 0) return+ const length = Number(input.subarray(0, colon).toString())+ assert.ok(length > 0 && length < 32768)+ if (input.length < colon + length + 2) return+ const parts = input+ .subarray(colon + 1, colon + 1 + length)+ .toString()+ .split('\0')+ parts.pop()+ const env = Object.fromEntries(+ Array.from({ length: parts.length / 2 }, (_, i) =>+ parts.slice(i * 2, i * 2 + 2)+ )+ )+ if (input.length < colon + length + 2 + Number(env.CONTENT_LENGTH)) return+ handled = true+ assert.equal(env.SCGI, '1')+ assert.equal(env.REMOTE_ADDR, '127.0.0.1')+ assert.equal(env.SERVER_PORT, '5000')+ assert.equal(env.REQUEST_SCHEME, 'http')+ assert.equal(env.LD_PRELOAD, undefined)+ const reply = (data) =>+ socket.end(+ `Content-Type: application/json\r\n\r\n${JSON.stringify(data)}`+ )+ if (+ env.HTTP_COOKIE !== 'id=synthetic-session' ||+ (await readFile('/tmp/dsm-session-state', 'utf8')) !== 'active'+ )+ return reply({ success: false, error: { code: 119 } })+ if (env.SCRIPT_FILENAME === '/usr/syno/synoman/webman/login.cgi')+ return reply({ success: true, SynoToken: 'synthetic-token' })+ assert.equal(env.SCRIPT_FILENAME, '/usr/syno/synoman/webapi/entry.cgi')+ assert.equal(env.HTTP_X_SYNO_TOKEN, 'synthetic-token')+ const params = new URLSearchParams(+ input.subarray(colon + length + 2).toString()+ )+ if (params.get('api') === 'SYNO.Core.NormalUser')+ return reply({ success: true, data: { username: 'alice' } })+ if (params.get('api') === 'SYNO.Core.User') {+ assert.equal(params.get('name'), 'alice')+ assert.equal(params.get('additional'), '["expired"]')+ const state = await readFile('/tmp/dsm-account-state', 'utf8')+ return reply(+ state === 'unavailable'+ ? { success: false, error: { code: 105 } }+ : {+ success: true,+ data: {+ users: [+ {+ name: 'alice',+ uid: 1700,+ expired: state === 'disabled' ? 'now' : 'normal',+ },+ ],+ },+ }+ )+ }+ assert.equal(params.get('api'), 'SYNO.FileStation.List')+ assert.equal(params.get('method'), 'getinfo')+ const names = JSON.parse(params.get('path'))+ assert.equal(names.length, 1)+ const file = `/volume1${names[0]}`+ assert.ok(+ [downloads, replacement].some(+ (root) => file === root || file.startsWith(`${root}/`)+ )+ )+ const info = await stat(file).catch(() => null)+ if (!info) return reply({ success: false, error: { code: 408 } })+ const writable = (await readFile('/tmp/dsm-acl-state', 'utf8')) === 'allow'+ reply({+ success: true,+ data: {+ files: [+ {+ path: names[0],+ isdir: info.isDirectory(),+ additional: {+ real_path: file,+ perm: {+ acl: {+ read: true,+ exec: true,+ write: writable,+ append: writable,+ del: writable,+ },+ },+ },+ },+ ],+ },+ })+ })+})+await new Promise((resolve) => authority.listen('/run/synoscgi.sock', resolve))+await chown('/run/synoscgi.sock', 1023, 1650)+await chmod('/run/synoscgi.sock', 0o770)+const env = {+ PATH: '/usr/sbin:/usr/bin:/sbin:/bin',+ SYNOPKG_PKGDEST: target,+ SYNOPKG_PKGVAR: variable,+ SYNOPKG_PKG_STATUS: 'INSTALL',+ wizard_client_port: '16812',+}+const execute = (script, action, extra = {}) =>+ new Promise((resolve, reject) => {+ const child = spawn(+ 'runuser',+ [+ '-u',+ 'motrix',+ '--',+ path.join(project, 'scripts', script),+ ...(action ? [action] : []),+ ],+ { env: { ...env, ...extra }, stdio: ['ignore', 'pipe', 'pipe'] }+ )+ let output = ''+ child.stdout.on('data', (data) => {+ output += data+ })+ child.stderr.on('data', (data) => {+ output += data+ })+ const timer = setTimeout(() => child.kill(), 75000)+ child.once('error', reject)+ child.once('exit', (code) => {+ clearTimeout(timer)+ resolve({ code, output })+ })+ })+const life = async (action, expectBridge = true) => {+ const result = await execute('start-stop-status', action)+ if (result.code !== 0)+ throw new Error(+ `${action}: ${result.output}\n${await readFile(path.join(variable, 'server.log'), 'utf8').catch(() => '')}`+ )+ if (action === 'start' && expectBridge)+ for (let i = 0; i < 150; i++) {+ try {+ await fetch('http://127.0.0.1:16812/discovery')+ break+ } catch {+ await delay(100)+ }+ }+}+const admin = {+ cookie: 'id=synthetic-session',+ 'x-motrix-dsm-remote-addr': '127.0.0.1',+ 'x-motrix-dsm-server-addr': '127.0.0.1',+ 'x-motrix-dsm-server-port': '5000',+ 'x-motrix-dsm-scheme': 'http',+ 'x-motrix-web-origin': 'http://nas.test',+ origin: 'http://nas.test',+ 'content-type': 'application/json',+}+const web = (route, headers = admin, body, client = false) =>+ new Promise((resolve, reject) => {+ const req = request(+ {+ socketPath: `${variable}/${client ? 'client' : 'web'}.sock`,+ path: `/motrix${route}`,+ headers,+ method: body ? 'POST' : 'GET',+ },+ (res) => {+ let text = ''+ res.on('data', (chunk) => {+ text += chunk+ })+ res.on('end', () => resolve({ status: res.statusCode, body: text }))+ }+ )+ req.on('error', reject).end(body ? JSON.stringify(body) : undefined)+ })++async function verifyEventSessionRenewal() {+ const WebSocket = createRequire(path.join(target, 'server/package.json'))(+ 'ws'+ )+ const issued = await web('/rpc/auth/event-ticket', admin, {})+ assert.equal(issued.status, 200)+ const ws = new WebSocket(+ `ws+unix://${variable}/web.sock:/motrix/rpc/events`,+ [+ 'motrix.fnos.events',+ `motrix.fnos.ticket.${JSON.parse(issued.body).ticket}`,+ ],+ { headers: admin }+ )+ const signal = AbortSignal.timeout(110_000)+ const closed = once(ws, 'close', { signal })+ // Socket errors can reject this promise before the iterator reaches it.+ void closed.catch(() => {})+ let renewed = false+ try {+ for await (const [raw] of on(ws, 'message', { signal, close: ['close'] })) {+ const frame = JSON.parse(raw.toString())+ if (frame.type !== 'session-renewal') continue+ if (renewed) await writeFile('/tmp/dsm-session-state', 'expired')+ const response = await web('/rpc/auth/event-renew', admin, frame)+ if (!renewed) {+ assert.equal(response.status, 204)+ renewed = true+ continue+ }+ assert.equal(response.status, 401)+ assert.equal((await closed)[0], 4401)+ console.log(+ 'DSM event stream renewed on one socket beyond its initial authorization and closed on revoked session'+ )+ return+ }+ throw Error('DSM event stream closed before reauthentication')+ } finally {+ ws.terminate()+ await writeFile('/tmp/dsm-session-state', 'active')+ }+}+const post = (route, body, token) =>+ fetch(`http://127.0.0.1:16812${route}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ ...(token ? { authorization: `Bearer ${token}` } : {}),+ },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(10000),+ })+const { Methods } = await import(+ pathToFileURL(+ path.join(target, 'server/node_modules/@motrix/mdxp/dist/index.js')+ ).href+)+const rpc = (method, params, token) =>+ post('/mdxp', { jsonrpc: '2.0', id: 1, method, params }, token)+const payload = randomBytes(256 * 1024)+let announces = 0+const fixture = createServer((req, res) => {+ if (req.url.startsWith('/announce')) {+ announces+++ const peer = Buffer.from([127, 0, 0, 1, 0, 0])+ peer.writeUInt16BE(16813, 4)+ res.end(+ Buffer.concat([+ Buffer.from('d8:intervali1e5:peers6:'),+ peer,+ Buffer.from('e'),+ ])+ )+ return+ }+ if (req.url === '/tiny.txt') {+ res.end('tiny native download')+ return+ }+ res.writeHead(200, { 'content-length': payload.length })+ res.end(payload)+})+await new Promise((resolve) => fixture.listen(0, '127.0.0.1', resolve))+function bencode(value) {+ if (typeof value === 'number') return Buffer.from(`i${value}e`)+ if (typeof value === 'string' || Buffer.isBuffer(value)) {+ const bytes = Buffer.from(value)+ return Buffer.concat([Buffer.from(`${bytes.length}:`), bytes])+ }+ return Buffer.concat([+ Buffer.from('d'),+ ...Object.keys(value)+ .sort()+ .flatMap((key) => [bencode(key), bencode(value[key])]),+ Buffer.from('e'),+ ])+}+const pieces = []+for (let offset = 0; offset < payload.length; offset += 16384)+ pieces.push(+ createHash('sha1')+ .update(payload.subarray(offset, offset + 16384))+ .digest()+ )+const torrent = bencode({+ announce: `http://127.0.0.1:${fixture.address().port}/announce`,+ info: {+ length: payload.length,+ name: 'bt-fixture.bin',+ 'piece length': 16384,+ pieces: Buffer.concat(pieces),+ },+})+await mkdir('/tmp/dsm-seed')+await writeFile('/tmp/dsm-seed/bt-fixture.bin', payload)+await writeFile('/tmp/dsm-seed/fixture.torrent', torrent)+execFileSync('chown', ['-R', '1600:1600', '/tmp/dsm-seed'])+const seeder = spawn(+ 'runuser',+ [+ '-u',+ 'motrix',+ '--',+ `${target}/server/bin/aria2c`,+ '--no-conf=true',+ '--enable-dht=false',+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ '--enable-peer-exchange=false',+ '--check-integrity=true',+ '--file-allocation=none',+ '--listen-port=16813',+ '--seed-time=10',+ '--seed-ratio=0.0',+ '--dir=/tmp/dsm-seed',+ '/tmp/dsm-seed/fixture.torrent',+ ],+ { stdio: 'ignore' }+)+const pair = async () => {+ const pending = await (+ await post('/mdxp/pair/request', { clientName: 'DSM smoke CLI' })+ ).json()+ const decision = await web('/rpc/command/bridge%3AresolvePair', admin, {+ args: [{ kind: 'cli', requestId: pending.requestId, decision: 'allow' }],+ })+ assert.equal(decision.status, 200, decision.body)+ assert.equal(JSON.parse(decision.body).ok, true)+ const result = await (+ await post('/mdxp/pair/poll', { requestId: pending.requestId })+ ).json()+ assert.equal(result.status, 'approved')+ return result.token+}+const replacePayload = async () => {+ await rm(target, { recursive: true, force: true })+ await cp(path.join(project, 'app'), target, { recursive: true })+ execFileSync('chown', ['-R', '1600:1600', target])+}++const reinstall = async (wizardPort) => {+ assert.equal(+ (+ await execute('postuninst', undefined, {+ SYNOPKG_PKG_STATUS: 'UNINSTALL',+ })+ ).code,+ 0+ )+ assert.equal((await execute('preinst')).code, 0)+ await replacePayload()+ assert.equal(+ (await execute('postinst', undefined, { wizard_client_port: wizardPort }))+ .code,+ 0+ )+}+try {+ assert.equal((await execute('postinst')).code, 0)+ await life('start')+ await life('status')+ // Exercise a separate unprivileged gateway account, not the root test driver.+ // Root bypasses Unix permissions and would miss the DSM 502 regression.+ const gatewayProbe = `const http=require('node:http');const fs=require('node:fs');const req=http.get({socketPath:process.argv[1],path:'/motrix/healthz'},res=>{res.resume();res.on('end',()=>{if(res.statusCode!==200)process.exit(2);for(const p of process.argv.slice(2)){try{fs.accessSync(p,fs.constants.R_OK);process.exit(3)}catch(e){if(e.code!=='EACCES')process.exit(4)}}})});req.on('error',e=>{console.error(e.code);process.exit(5)})`+ execFileSync(+ 'runuser',+ [+ '-u',+ 'gateway',+ '--',+ `${target}/runtime/bin/node`,+ '-e',+ gatewayProbe,+ `${variable}/web.sock`,+ `${variable}/data`,+ `${variable}/package-settings.json`,+ ],+ { stdio: 'pipe' }+ )+ const unrelatedProbe = `require('node:http').get({socketPath:process.argv[1],path:'/motrix/healthz'},()=>process.exit(2)).on('error',e=>process.exit(e.code==='EACCES'?0:3))`+ execFileSync(+ 'runuser',+ [+ '-u',+ 'unrelated',+ '--',+ `${target}/runtime/bin/node`,+ '-e',+ unrelatedProbe,+ `${variable}/web.sock`,+ ],+ { stdio: 'pipe' }+ )+ const status = JSON.parse((await web('/rpc/auth/status')).body)+ await writeFile('/tmp/dsm-session-state', 'unavailable')+ const rejectedSession = JSON.parse((await web('/rpc/auth/status')).body)+ assert.equal(rejectedSession.authed, false)+ assert.deepEqual(rejectedSession.nasAuthDiagnostic, {+ stage: 'account',+ code: 'rejected',+ })+ assert.equal(JSON.stringify(rejectedSession).includes('alice'), false)+ assert.equal(+ JSON.stringify(rejectedSession).includes('synthetic-session'),+ false+ )+ await writeFile('/tmp/dsm-session-state', 'active')+ assert.equal(status.username, 'alice')+ assert.deepEqual(status.clientPairing, { cli: true, extension: false })+ await verifyEventSessionRenewal()+ assert.equal(+ (+ await web(+ '/rpc/query/app%3AgetSettings',+ {+ 'x-trim-userid': '1700',+ 'x-trim-isadmin': 'true',+ 'x-trim-username': 'alice',+ },+ { args: [] }+ )+ ).status,+ 401+ )+ let token = await pair()+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 200)+ const client = (route, body, bearer) =>+ web(+ route,+ {+ host: 'nas.test',+ 'content-type': 'application/json',+ ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),+ },+ body,+ true+ )+ assert.equal(+ (+ await client(+ '/client/mdxp',+ { jsonrpc: '2.0', id: 1, method: Methods.TaskList, params: {} },+ token+ )+ ).status,+ 200+ )+ assert.equal((await client('/bridge/discovery')).status, 404)+ assert.equal(+ (+ await client('/client/mdxp', {+ jsonrpc: '2.0',+ id: 1,+ method: Methods.TaskList,+ params: {},+ })+ ).status,+ 401+ )+ const nativeSettings = JSON.parse(+ (await web('/rpc/query/query%3AgetNasSettings', admin, { args: [] })).body+ )+ assert.equal(nativeSettings.ok, true)+ assert.equal(nativeSettings.value.active.extensionUrl, '')+ for (const state of ['disabled', 'unavailable']) {+ await writeFile('/tmp/dsm-account-state', state)+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 403)+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, false)+ }+ await writeFile('/tmp/dsm-account-state', 'active')+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ // Real group removal must reject the same account, including paired clients.+ execFileSync('gpasswd', ['-d', 'alice', 'administrators'])+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 403)+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, false)+ execFileSync('usermod', ['-a', '-G', 'administrators', 'alice'])+ token = await pair()+ const add = (saveDir) =>+ rpc(+ Methods.DownloadAdd,+ {+ kind: 'url',+ saveDir,+ filename: 'fixture.bin',+ uris: [`http://127.0.0.1:${fixture.address().port}/fixture.bin`],+ },+ token+ )+ await writeFile('/tmp/dsm-acl-state', 'readonly')+ assert.ok((await (await add(`${downloads}/denied`)).json()).error)+ assert.equal(await stat(`${downloads}/denied`).catch(() => null), null)+ await writeFile('/tmp/dsm-acl-state', 'allow')+ assert.ok((await (await add('/tmp')).json()).error)+ // Only the parent share is explicitly granted. A task must keep ownership+ // of its own directory and published file across restart and name reuse.+ const child = path.join(downloads, 'nested-task')+ const childFile = path.join(child, 'nested.txt')+ const created = JSON.parse(+ (+ await web('/rpc/command/command%3AcreateTask', admin, {+ args: [+ {+ type: 'http',+ uris: [`http://127.0.0.1:${fixture.address().port}/nested-proof`],+ saveDir: child,+ filename: 'nested.txt',+ connections: 1,+ },+ ],+ })+ ).body+ )+ assert.ok(created.taskId)+ for (let attempt = 0; attempt < 120; attempt++) {+ const query = await (+ await rpc(Methods.TaskGet, { taskId: created.taskId }, token)+ ).json()+ if (query.result?.task?.status === 'completed') break+ await delay(100)+ }+ const childRoute = `/api/nas/tasks/${created.taskId}/file`+ assert.equal((await web(childRoute)).status, 200)+ assert.deepEqual(await readFile(childFile), payload)+ const assertSubstituteProtected = async () => {+ assert.equal((await web(childRoute)).status, 403)+ const result = await (+ await rpc(+ Methods.TaskRemove,+ { taskId: created.taskId, deleteFiles: true },+ token+ )+ ).json()+ assert.ok(result.error)+ assert.equal(await readFile(childFile, 'utf8'), 'substitute')+ }+ await rename(childFile, `${childFile}.original`)+ await writeFile(childFile, 'substitute')+ await chown(childFile, 1600, 1600)+ await assertSubstituteProtected()+ await rm(childFile)+ await rename(`${childFile}.original`, childFile)+ await rename(child, `${child}.original`)+ await mkdir(child)+ await chown(child, 1600, 1600)+ await writeFile(childFile, 'substitute')+ await chown(childFile, 1600, 1600)+ await assertSubstituteProtected()+ await life('stop')+ await life('start')+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ await assertSubstituteProtected()+ await rename(child, `${child}.substitute`)+ await rename(`${child}.original`, child)+ assert.equal((await web(childRoute)).status, 200)+ assert.deepEqual(await readFile(childFile), payload)+ const removed = await (+ await rpc(+ Methods.TaskRemove,+ { taskId: created.taskId, deleteFiles: true },+ token+ )+ ).json()+ assert.equal(removed.error, undefined)+ await assert.rejects(stat(childFile), { code: 'ENOENT' })+ assert.equal(+ await readFile(path.join(`${child}.substitute`, 'nested.txt'), 'utf8'),+ 'substitute'+ )+ console.log(+ 'Replacement file and nested task directory denied before and after restart; original restored and removed'+ )+ const tiny = JSON.parse(+ (+ await web('/rpc/command/command%3AcreateTask', admin, {+ args: [+ {+ type: 'http',+ uris: [`http://127.0.0.1:${fixture.address().port}/tiny.txt`],+ saveDir: downloads,+ filename: 'tiny.txt',+ connections: 1,+ },+ ],+ })+ ).body+ )+ assert.ok(tiny.taskId)+ let tinyTask+ for (let i = 0; i < 100; i++) {+ tinyTask = (+ await (await rpc(Methods.TaskGet, { taskId: tiny.taskId }, token)).json()+ ).result?.task+ if (tinyTask?.status === 'completed') break+ await delay(100)+ }+ assert.equal(tinyTask?.status, 'completed')+ assert.equal(+ (+ await web('/api/nas/task-action', admin, {+ taskId: tiny.taskId,+ action: 'open',+ })+ ).status,+ 200+ )+ await symlink('/tmp', `${downloads}/escape`)+ assert.ok((await (await add(`${downloads}/escape`)).json()).error)+ const added = await (await add(downloads)).json()+ assert.ok(added.result?.id, JSON.stringify(added))+ let task+ for (let i = 0; i < 250; i++) {+ task = (+ await (+ await rpc(Methods.TaskGet, { taskId: added.result.id }, token)+ ).json()+ ).result?.task+ if (task?.status === 'completed' || task?.status === 'error') break+ await delay(100)+ }+ assert.equal(task?.status, 'completed', JSON.stringify(task))+ assert.deepEqual(await readFile(`${downloads}/fixture.bin`), payload)+ assert.equal((await stat(`${downloads}/fixture.bin`)).uid, 1600)+ const opened = await web('/api/nas/task-action', admin, {+ taskId: task.id,+ action: 'open',+ })+ assert.equal(opened.status, 200, opened.body)+ const fileUrl = JSON.parse(opened.body).url+ const ranged = await web(fileUrl.replace(/^\/motrix/, ''), {+ ...admin,+ range: 'bytes=0-15',+ })+ assert.equal(ranged.status, 206)+ assert.equal(ranged.body, payload.subarray(0, 16).toString())+ const revealed = JSON.parse(+ (+ await web('/api/nas/task-action', admin, {+ taskId: task.id,+ action: 'reveal',+ })+ ).body+ )+ assert.equal(revealed.kind, 'file-manager')+ assert.ok(revealed.url.startsWith('/?launchApp='))+ await writeFile(`${downloads}/selection.torrent`, torrent)+ await chown(`${downloads}/selection.torrent`, 1600, 1600)+ assert.equal(+ (+ await web('/api/nas/torrent', admin, {+ path: `${downloads}/selection.torrent`,+ })+ ).status,+ 200+ )+ await writeFile('/tmp/dsm-acl-state', 'readonly')+ assert.ok(+ (+ await (+ await rpc(+ Methods.TaskRemove,+ { taskId: task.id, deleteFiles: true },+ token+ )+ ).json()+ ).error+ )+ await writeFile('/tmp/dsm-acl-state', 'allow')+ const btRequest = await web('/rpc/command/command%3AcreateTask', admin, {+ args: [+ {+ type: 'bt',+ payload: { kind: 'torrent-base64', base64: torrent.toString('base64') },+ selectedFiles: [0],+ saveDir: downloads,+ displayName: 'bt-fixture.bin',+ },+ ],+ })+ assert.equal(btRequest.status, 200, btRequest.body)+ const btId = JSON.parse(btRequest.body).taskId+ assert.ok(btId, btRequest.body)+ let btTask+ for (let i = 0; i < 600; i++) {+ btTask = (+ await (await rpc(Methods.TaskGet, { taskId: btId }, token)).json()+ ).result?.task+ if (['completed', 'seeding', 'error'].includes(btTask?.status)) break+ await delay(100)+ }+ assert.ok(+ ['completed', 'seeding'].includes(btTask?.status),+ JSON.stringify(btTask)+ )+ assert.deepEqual(await readFile(`${downloads}/bt-fixture.bin`), payload)+ assert.ok(announces >= 2)+ const settingsBeforeUpgrade = JSON.parse(+ (await web('/rpc/query/query%3AgetNasSettings', admin, { args: [] })).body+ ).value+ const savedSettings = JSON.parse(+ (+ await web('/rpc/command/command%3AsaveNasSettings', admin, {+ args: [+ {+ revision: settingsBeforeUpgrade.revision,+ settings: {+ ...settingsBeforeUpgrade.settings,+ operatorUrl: 'http://nas.test/motrix/',+ },+ },+ ],+ })+ ).body+ )+ assert.equal(savedSettings.ok, true, JSON.stringify(savedSettings))+ assert.equal(savedSettings.value.restartRequired, true)+ assert.equal(+ (await execute('preupgrade', undefined, { SYNOPKG_PKG_STATUS: 'UPGRADE' }))+ .code,+ 0+ )+ // Model an earlier package with no per-task path claims and incomplete file counts.+ // Mutate only this synthetic row, while the package is stopped, as its user.+ execFileSync('runuser', [+ '-u',+ 'motrix',+ '--',+ `${target}/runtime/bin/node`,+ '-e',+ `const DB=require(process.argv[1]);const db=new DB(process.argv[2]);db.prepare('UPDATE tasks SET file_count=0 WHERE motrix_id=?').run(process.argv[3]);db.exec('DROP TABLE synology_task_paths');db.close()`,+ `${target}/server/node_modules/better-sqlite3`,+ `${variable}/data/motrix.db`,+ tiny.taskId,+ ])+ await replacePayload()+ assert.equal(+ (await execute('postupgrade', undefined, { SYNOPKG_PKG_STATUS: 'UPGRADE' }))+ .code,+ 0+ )+ await life('start')+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 403)+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 200)+ assert.deepEqual(await readFile(`${downloads}/fixture.bin`), payload)+ const appliedSettings = JSON.parse(+ (await web('/rpc/query/query%3AgetNasSettings', admin, { args: [] })).body+ ).value+ assert.equal(appliedSettings.active.operatorUrl, 'http://nas.test/motrix/')+ assert.equal(appliedSettings.restartRequired, false)+ // A regular directory at the old pathname can pass both account and package+ // ACL checks. Existing tasks must not read or delete the replacement's files.+ const heldDownloads = `${downloads}.original-directory`+ await rename(downloads, heldDownloads)+ await mkdir(downloads)+ await chown(downloads, 1600, 1600)+ await writeFile(`${downloads}/tiny.txt`, 'replacement payload')+ await chown(`${downloads}/tiny.txt`, 1600, 1600)+ const oldTaskFile = `/api/nas/tasks/${tiny.taskId}/file`+ assert.equal((await web(oldTaskFile)).status, 403)+ const refusedSaveDir = `${downloads}/refused-new-task`+ assert.ok((await (await add(refusedSaveDir)).json()).error)+ await assert.rejects(stat(refusedSaveDir), { code: 'ENOENT' })+ assert.ok(+ (+ await (+ await rpc(+ Methods.TaskRemove,+ { taskId: tiny.taskId, deleteFiles: true },+ token+ )+ ).json()+ ).error+ )+ assert.equal(+ await readFile(`${downloads}/tiny.txt`, 'utf8'),+ 'replacement payload'+ )+ await life('stop')+ await life('start', false)+ assert.equal(+ JSON.parse((await web('/healthz')).body).status,+ 'storage-recovery'+ )+ await life('stop')+ await rename(downloads, `${downloads}.replacement-directory`)+ await rename(heldDownloads, downloads)+ await life('start')+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ assert.equal((await web(oldTaskFile)).body, 'tiny native download')+ assert.equal(+ (+ await web('/api/nas/task-action', admin, {+ taskId: tiny.taskId,+ action: 'open',+ })+ ).status,+ 200+ )+ assert.ok(+ !(+ await (+ await rpc(+ Methods.TaskRemove,+ { taskId: task.id, deleteFiles: true },+ token+ )+ ).json()+ ).error+ )+ assert.equal(await stat(`${downloads}/fixture.bin`).catch(() => null), null)+ // Any account database replacement conservatively invalidates old bindings.+ execFileSync('useradd', ['--no-create-home', 'epoch-change'])+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 403)+ token = await pair()+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 200)+ const processRecord = JSON.parse(+ await readFile(`${variable}/server-process.json`, 'utf8')+ )+ assert.equal((await stat(`/proc/${processRecord.pid}`)).uid, 1600)+ await life('stop')+ await writeFile(+ `${variable}/server-process.json`,+ JSON.stringify({ pid: process.pid, started: '1', boot: 'stale' })+ )+ await life('stop')+ await life('start')+ // An unavailable share must leave all recovery journals and engine state+ // untouched while an administrator can repair grants through the Web UI.+ await life('stop')+ const durableFiles = [+ 'motrix.db',+ 'motrix.db-wal',+ 'aria2.session',+ 'aria2.db',+ 'aria2.db-wal',+ ]+ const durableHashes = () =>+ Promise.all(+ durableFiles.map(async (name) => {+ try {+ return createHash('sha256')+ .update(await readFile(path.join(variable, 'data', name)))+ .digest('hex')+ } catch (error) {+ if (error.code === 'ENOENT') return null+ throw error+ }+ })+ )+ const beforeRecovery = await durableHashes()+ assert.ok(beforeRecovery[0])+ const offline = `${downloads}.offline-fixture`+ await rename(downloads, offline)+ // A directory left behind on the system filesystem is not a mounted share,+ // even when the package can traverse it and it has the old pathname.+ const unmounted = '/volume2/motrix-offline-fixture'+ await mkdir(unmounted, { recursive: true })+ await chown(unmounted, 1600, 1600)+ await writeFile(+ `${variable}/directories.json`,+ JSON.stringify({ roots: [downloads, unmounted] })+ )+ await life('start', false)+ const recoveryHealth = JSON.parse((await web('/healthz')).body)+ assert.equal(recoveryHealth.status, 'storage-recovery')+ assert.equal(recoveryHealth.engine.state, 'stopped')+ const recoveryStatus = JSON.parse((await web('/rpc/auth/status')).body)+ assert.deepEqual(recoveryStatus.nasUnavailableDownloadRoots, [+ downloads,+ unmounted,+ ])+ assert.deepEqual(recoveryStatus.clientPairing, {+ cli: false,+ extension: false,+ })+ const anonymous = JSON.parse((await web('/rpc/auth/status', {})).body)+ assert.equal(anonymous.authed, false)+ assert.equal(anonymous.nasUnavailableDownloadRoots, undefined)+ assert.equal(+ (await web('/rpc/query/query%3AgetNasSettings', {}, { args: [] })).status,+ 401+ )+ assert.equal(+ (await web('/rpc/query/query%3AlistTasks', admin, { args: [] })).status,+ 404+ )+ assert.equal(+ (await web('/rpc/command/command%3AcreateTask', admin, { args: [] }))+ .status,+ 404+ )+ await assert.rejects(fetch('http://127.0.0.1:16812/discovery'))+ const view = JSON.parse(+ (await web('/rpc/query/query%3AgetNasSettings', admin, { args: [] })).body+ ).value+ const queue = async (roots) =>+ JSON.parse(+ (+ await web('/rpc/command/command%3AsaveNasSettings', admin, {+ args: [+ { revision: view.revision, settings: { ...view.settings, roots } },+ ],+ })+ ).body+ )+ assert.equal((await queue([downloads])).error.code, 'folderUnavailable')+ assert.equal((await queue([unmounted])).error.code, 'folderUnavailable')+ assert.equal(await stat(downloads).catch(() => null), null)+ await mkdir(replacement)+ await chown(replacement, 1600, 1600)+ const queued = await queue([replacement])+ assert.equal(queued.ok, true)+ assert.equal(queued.value.settings.directoryIdentities, undefined)+ // Substitution between Save and restart must not change the identity that+ // passed the account's ACL check, even when the replacement is writable.+ await rename(replacement, `${replacement}.authorized`)+ await mkdir(replacement)+ await chown(replacement, 1600, 1600)+ const resave = await web('/rpc/command/command%3AsaveNasSettings', admin, {+ args: [+ { revision: queued.value.revision, settings: queued.value.settings },+ ],+ })+ assert.equal(JSON.parse(resave.body).error.code, 'folderUnavailable')+ await life('stop')+ assert.deepEqual(await durableHashes(), beforeRecovery)+ await life('start', false)+ assert.equal(+ JSON.parse((await web('/healthz')).body).status,+ 'storage-recovery'+ )+ await life('stop')+ await rename(replacement, `${replacement}.substitute`)+ await rename(`${replacement}.authorized`, replacement)+ await life('start')+ assert.equal(JSON.parse((await web('/healthz')).body).status, 'ready')+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 200)+ assert.equal(await stat(downloads).catch(() => null), null)+ assert.deepEqual(await readFile(`${offline}/bt-fixture.bin`), payload)+ await life('stop')+ await rename(offline, downloads)+ const beforeUninstall = await durableHashes()+ const readConfig = () =>+ Promise.all(+ ['package-settings.json', 'directories.json'].map((name) =>+ readFile(path.join(variable, name), 'utf8')+ )+ )+ const retainedConfig = await readConfig()+ assert.equal(+ (await execute('preuninst', undefined, { SYNOPKG_PKG_STATUS: 'UNINSTALL' }))+ .code,+ 0+ )+ // DSM replaces target and retains var. An install wizard default must not+ // override the retained instance. Check the actual task and its credential.+ await reinstall('16814')+ assert.deepEqual(await durableHashes(), beforeUninstall)+ assert.deepEqual(await readConfig(), retainedConfig)+ await life('start')+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 403)+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ const retainedTask = await (+ await rpc(Methods.TaskGet, { taskId: tiny.taskId }, token)+ ).json()+ assert.equal(retainedTask.result?.task?.id, tiny.taskId)+ assert.equal(retainedTask.result.task.status, 'completed')+ assert.equal(+ await readFile(`${downloads}/tiny.txt`, 'utf8'),+ 'tiny native download'+ )+ assert.equal(+ (+ await execute('preuninst', undefined, {+ SYNOPKG_PKG_STATUS: 'UNINSTALL',+ wizard_delete_data: 'true',+ })+ ).code,+ 0+ )+ for (const name of [+ 'data',+ 'package-settings.json',+ 'directories.json',+ 'pending-settings.json',+ ]) {+ await assert.rejects(stat(path.join(variable, name)), { code: 'ENOENT' })+ }+ await reinstall('16812')+ await life('start')+ assert.equal(JSON.parse((await web('/rpc/auth/status')).body).authed, true)+ assert.equal((await rpc(Methods.TaskList, {}, token)).status, 401)+ const freshTasks = await web('/rpc/query/query%3AlistTasks', admin, {+ args: [],+ })+ assert.equal(freshTasks.status, 200)+ assert.deepEqual(JSON.parse(freshTasks.body), [])+ assert.deepEqual(await readFile(`${downloads}/bt-fixture.bin`), payload)+ assert.equal(+ await readFile(`${downloads}/tiny.txt`, 'utf8'),+ 'tiny native download'+ )+ console.log(+ 'DSM Linux simulation passed: nonroot lifecycle and gateway socket isolation, cookie authentication, CLI pairing, account revocation, HTTP/BT download, ACL and symlink denial, replaced grant denied live and after restart, grant substitution before pending settings apply denied, file deletion, upgrade persistence, stale PID, retained-data reinstall and clean reinstall after purge'+ )+} finally {+ await execute('start-stop-status', 'stop')+ seeder.kill('SIGTERM')+ fixture.close()+ authority.close()+ await rm(root, { recursive: true, force: true })+}diff --git a/scripts/spk_archive.py b/scripts/spk_archive.pynew file mode 100644index 00000000..0fedfe24--- /dev/null+++ b/scripts/spk_archive.py@@ -0,0 +1,31 @@+"""Build-time SPK archive handling: regular files/directories only, no traversal."""+import pathlib+import sys+import tarfile+++def extract(source, destination):+ root = pathlib.Path(destination)+ root.mkdir(parents=True, exist_ok=False)+ with tarfile.open(source, "r:*") as archive:+ names = set()+ total = 0+ for member in archive.getmembers():+ name = pathlib.PurePosixPath(member.name)+ if (name.is_absolute() or ".." in name.parts or "\\" in member.name+ or not (member.isfile() or member.isdir())+ or any(part.startswith("._") or part == ".DS_Store" for part in name.parts)+ or member.mode & 0o7022 or name in names):+ raise ValueError("Unsafe or duplicate SPK member: " + member.name)+ names.add(name)+ total += member.size+ if total > 1024 * 1024 * 1024 or len(names) > 50000:+ raise ValueError("SPK exceeds extraction limits")+ for member in archive.getmembers():+ archive.extract(member, root, set_attrs=False, filter="data")+ target = root / member.name+ target.chmod(0o755 if member.isdir() or member.mode & 0o111 else 0o644)+++if __name__ == "__main__":+ extract(sys.argv[1], sys.argv[2])diff --git a/scripts/synology-runtime.lock.json b/scripts/synology-runtime.lock.jsonnew file mode 100644index 00000000..8f79d64b--- /dev/null+++ b/scripts/synology-runtime.lock.json@@ -0,0 +1,61 @@+{+ "schemaVersion": 2,+ "dsmVersion": "7.2.2-72806",+ "glibc": "2.36",+ "revision": 13,+ "targets": {+ "x64": {+ "infoArch": "x86_64",+ "dockerPlatform": "linux/amd64",+ "machine": 62,+ "sysroot": "x86_64-pc-linux-gnu/x86_64-pc-linux-gnu/sys-root",+ "loader": "lib/ld-linux-x86-64.so.2",+ "platforms": {+ "geminilake": {+ "toolchain": {+ "url": "https://global.synologydownload.com/download/ToolChain/toolchain/7.2-72806/Intel%20x86%20Linux%204.4.302%20%28GeminiLake%29/geminilake-gcc1220_glibc236_x86_64-GPL.txz",+ "sha256": "9ffb02cbaa206fe822f437d78058e10755f03c5b974e0be3a5b61b44f49c8ee0"+ },+ "digestSource": "https://github.com/SynoCommunity/spksrc/blob/master/toolchain/syno-geminilake-7.2/digests"+ },+ "apollolake": {+ "toolchain": {+ "url": "https://global.synologydownload.com/download/ToolChain/toolchain/7.2-72806/Intel%20x86%20Linux%204.4.180%20%28Apollolake%29/apollolake-gcc1220_glibc236_x86_64-GPL.txz",+ "sha256": "025b1c0f16bac1bd2e369b0012ce2b3c310c740c7a00a2b3cf92c3f982347bb0"+ },+ "digestSource": "https://github.com/SynoCommunity/spksrc/blob/master/toolchain/syno-apollolake-7.2/digests"+ }+ }+ },+ "arm64": {+ "dockerPlatform": "linux/arm64",+ "machine": 183,+ "sysroot": "aarch64-unknown-linux-gnu/aarch64-unknown-linux-gnu/sysroot",+ "loader": "lib/ld-linux-aarch64.so.1",+ "cpu": "cortex-a53",+ "platforms": {+ "rtd1296": {+ "toolchain": {+ "url": "https://global.synologydownload.com/download/ToolChain/toolchain/7.2-72806/Realtek%20RTD129x%20Linux%204.4.302/rtd1296-gcc1220_glibc236_armv8-GPL.txz",+ "sha256": "a4613ecf97679a510f1d2dff78560e30b1371fd711fc498fbca39bc2a47ac3a0"+ },+ "digestSource": "https://github.com/SynoCommunity/spksrc/blob/master/toolchain/syno-rtd1296-7.2/digests"+ },+ "armada37xx": {+ "toolchain": {+ "url": "https://global.synologydownload.com/download/ToolChain/toolchain/7.2-72806/Marvell%20Armada%2037xx%20Linux%204.4.302/armada37xx-gcc1220_glibc236_armv8-GPL.txz",+ "sha256": "ef07b681fab0e7b5c94dd596fa949803d87dc2ac1c74e6623ec46d68bb515f39"+ },+ "digestSource": "https://github.com/SynoCommunity/spksrc/blob/master/toolchain/syno-armada37xx-7.2/digests"+ },+ "rtd1619b": {+ "toolchain": {+ "url": "https://global.synologydownload.com/download/ToolChain/toolchain/7.2-72806/Realtek%20RTD16xxb%20Linux%205.10.55/rtd1619b-gcc1220_glibc236_armv8-GPL.txz",+ "sha256": "016f4c36fc366319811962d3bde936000c2034c29acf04d1d4c4259c36681a30"+ },+ "digestSource": "https://github.com/SynoCommunity/spksrc/blob/master/toolchain/syno-rtd1619b-7.2/digests"+ }+ }+ }+ }+}diff --git a/scripts/synology-target.mjs b/scripts/synology-target.mjsnew file mode 100644index 00000000..12295e57--- /dev/null+++ b/scripts/synology-target.mjs@@ -0,0 +1,17 @@+import lock from './synology-runtime.lock.json' with { type: 'json' }++export function synologyTarget(arch) {+ if (!Object.hasOwn(lock.targets, arch))+ throw new Error('Unsupported DSM architecture')+ const target = lock.targets[arch]+ return {+ ...target,+ infoArch: target.infoArch ?? Object.keys(target.platforms).join(' '),+ toolchainDigests: Object.fromEntries(+ Object.entries(target.platforms).map(([platform, sdk]) => [+ platform,+ sdk.toolchain.sha256,+ ])+ ),+ }+}diff --git a/scripts/synology_publication.py b/scripts/synology_publication.pynew file mode 100644index 00000000..c1471e2d--- /dev/null+++ b/scripts/synology_publication.py@@ -0,0 +1,209 @@+#!/usr/bin/env python3+"""Verify both native SPKs and attach immutable assets to a protected stable release."""+from functools import lru_cache+import hashlib+import io+import json+import os+from pathlib import Path, PurePosixPath+import sys+import subprocess+import tarfile++from nas_release import SHA, preflight, run, source, stable_version, upload_verified_assets+++@lru_cache(maxsize=2)+def package_templates(sha):+ """Read DSM-controlled files from the approved Git tree, independent of the SPK."""+ prefix = 'packaging/synology/'+ entries = subprocess.check_output(['git', 'ls-tree', '-rz', sha, '--', prefix, 'LICENSE'])+ result = {}+ for entry in entries.split(b'\0'):+ if not entry:+ continue+ meta, raw_name = entry.split(b'\t', 1)+ mode, kind, oid = meta.decode().split()+ name = raw_name.decode().removeprefix(prefix)+ if name in ('README.md', 'README.zh-CN.md'):+ continue+ if kind != 'blob' or mode not in ('100644', '100755'):+ raise ValueError('Unsafe DSM template in source tree')+ result[name] = (subprocess.check_output(['git', 'cat-file', 'blob', oid]), mode == '100755')+ return result+++def member_name(member, seen):+ name = member.name.removeprefix('./')+ path = PurePosixPath(name)+ if (not name or path.is_absolute() or '..' in path.parts or str(path) != name or name in seen+ or member.mode & 0o7022 or not (member.isfile() or member.isdir())):+ raise ValueError('Unsafe or duplicate SPK member')+ seen.add(name)+ if len(seen) > 50000:+ raise ValueError('Too many SPK members')+ return name+++def render_info(template, version, rev, arch, payload):+ for key, value in {'VERSION': version, 'REVISION': str(rev), 'ARCH': arch,+ 'CHECKSUM': hashlib.md5(payload).hexdigest()}.items():+ template = template.replace(f'@{key}@'.encode(), value.encode())+ return template+++def verify_outer(package, templates, version, rev, arch):+ expected = {k: v for k, v in templates.items() if not k.startswith('app/')}+ directories = {str(parent) for name in expected for parent in PurePosixPath(name).parents}+ seen = set()+ info = payload = None+ with tarfile.open(package, 'r|*') as outer:+ for member in outer:+ name = member_name(member, seen)+ if member.isdir() and name in directories:+ continue+ if not member.isfile():+ raise ValueError('Unexpected SPK directory')+ if name == 'package.tgz' and 0 < member.size <= 256 * 1024 * 1024 and not member.mode & 0o111:+ payload = outer.extractfile(member).read()+ elif name == 'INFO' and member.size <= 65536 and not member.mode & 0o111:+ info = outer.extractfile(member).read()+ elif name in expected:+ blob, executable = expected[name]+ if (member.size != len(blob) or bool(member.mode & 0o111) != executable+ or outer.extractfile(member).read() != blob):+ raise ValueError(f'SPK template differs from release source: {name}')+ else:+ raise ValueError(f'Unexpected SPK member: {name}')+ if not expected.keys() <= seen or payload is None or info != render_info(expected['INFO'][0], version, rev, arch, payload):+ raise ValueError('Missing source template or incorrect SPK INFO')+ return payload+++def verify_payload(payload, templates, machine):+ """Stream members once, checking bounds before reading or skipping their data."""+ seen, files, elf = set(), {}, {}+ static = {k.removeprefix('app/'): v for k, v in templates.items() if k.startswith('app/')}+ total = 0+ inventory = receipt = None+ with tarfile.open(fileobj=io.BytesIO(payload), mode='r|gz') as app:+ for member in app:+ name = member_name(member, seen)+ if member.isdir():+ continue+ total += member.size+ if total > 512 * 1024 * 1024:+ raise ValueError('Oversized SPK payload')+ with app.extractfile(member) as stream:+ if name == 'payload-sha256.json':+ if member.size > 8 * 1024 * 1024:+ raise ValueError('Oversized SPK inventory')+ inventory = json.load(stream)+ continue+ header = stream.read(20)+ digest = hashlib.sha256(header)+ if name == 'synology-build.json':+ if member.size > 65536:+ raise ValueError('Oversized SPK build receipt')+ tail = stream.read()+ receipt = json.loads(header + tail)+ digest.update(tail)+ else:+ for block in iter(lambda: stream.read(1024 * 1024), b''):+ digest.update(block)+ actual = digest.hexdigest()+ executable = bool(member.mode & 0o111)+ files[name] = {'sha256': actual, 'executable': executable}+ if name in static:+ blob, expected_mode = static[name]+ if actual != hashlib.sha256(blob).hexdigest() or executable != expected_mode:+ raise ValueError(f'SPK app template differs from release source: {name}')+ if header.startswith(b'\x7fELF'):+ if len(header) < 20 or header[4:6] != b'\x02\x01' or int.from_bytes(header[18:20], 'little') != machine:+ raise ValueError('Foreign ELF in SPK payload')+ elf[name] = actual+ if inventory != files or not static.keys() <= files.keys() or receipt is None:+ raise ValueError('Payload inventory mismatch')+ return receipt, elf+++def verify_bundle(directory, version, sha):+ stable_version('v' + version)+ if not SHA.fullmatch(sha):+ raise ValueError('Invalid source commit')+ lock = json.loads(run('git', 'show', f'{sha}:scripts/synology-runtime.lock.json'))+ node = json.loads(run('git', 'show', f'{sha}:scripts/fnos-runtime.lock.json'))+ engines = json.loads(run('git', 'show', f'{sha}:scripts/engine.lock.json'))['assets']+ templates = package_templates(sha)+ rev = lock['revision']+ root = Path(directory)+ names = {arch: f'Motrix-{version}-{rev}-dsm-{arch}.spk' for arch in ['x64', 'arm64']}+ expected = {f + suffix for f in names.values() for suffix in ('', '.sha256', '.abi.json')}+ if {p.name for p in root.iterdir()} != expected or any(p.is_symlink() or not p.is_file() for p in root.iterdir()):+ raise ValueError('Both complete SPK/checksum/ABI sets of regular files are required')+ records = []+ for arch, name in names.items():+ path = root / name+ if path.stat().st_size > 300 * 1024 * 1024:+ raise ValueError('Oversized SPK')+ with path.open('rb') as stream:+ digest = hashlib.file_digest(stream, 'sha256').hexdigest()+ if (root / (name + '.sha256')).read_text() != f'{digest} {name}\n':+ raise ValueError('SPK checksum mismatch')+ target = lock['targets'][arch]+ platforms = target['platforms']+ sdk = {key: profile['toolchain']['sha256'] for key, profile in platforms.items()}+ payload = verify_outer(path, templates, version, rev, target.get('infoArch', ' '.join(platforms)))+ receipt, shipped_elf = verify_payload(payload, templates, target['machine'])+ node_digest = node['node'][arch].get('binarySha256')+ if ((rev >= 13 and not node_digest) or (node_digest and shipped_elf.get('runtime/bin/node') != node_digest)+ or shipped_elf.get('server/bin/aria2c') != engines[f'linux-{arch}']['binarySha256']):+ raise ValueError('SPK binary differs from the release lock')+ required = dict(schemaVersion=2, architecture=arch, revision=rev, version=version, sourceCommit=sha,+ sourceDirty=False, minimumDsm=lock['dsmVersion'], nodeArchiveSha256=node['node'][arch]['sha256'],+ platforms=list(platforms), toolchainDigests=sdk)+ if any(receipt.get(k) != v for k, v in required.items()) or receipt.get('sourceDirty') is not False:+ raise ValueError('SPK source, runtime or architecture receipt mismatch')+ abi = json.loads((root / (name + '.abi.json')).read_text())+ if (abi.get('schemaVersion') != 3 or abi.get('spkSha256') != digest or abi.get('architecture') != arch+ or set(abi.get('platforms', {})) != set(platforms)):+ raise ValueError('ABI report does not cover this exact SPK')+ for platform, report in abi['platforms'].items():+ loaded = report['loaded']+ if (report['platform'] != platform or report['architecture'] != arch or report['toolchainSha256'] != sdk[platform]+ or loaded != dict(arch=arch, glibc=lock['glibc'], node='v'+node['nodeVersion'], sqlite='read-write-ok')+ or report.get('cpuEmulation') != target.get('cpu')):+ raise ValueError('DSM userspace or CPU validation mismatch')+ elf = {item['file']: item['sha256'] for item in report['elf']}+ required_elf = {'runtime/bin/node', 'server/bin/aria2c', 'server/bin/motrix-finalize-fs'}+ if (not required_elf <= elf.keys() or not any(f.endswith('.node') for f in elf)+ or elf != shipped_elf or len(elf) != len(report['elf'])):+ raise ValueError('ABI evidence does not match the package inventory')+ records.append({'file': name, 'sha256': digest, 'arch': arch, 'platforms': list(platforms)})+ return records+++def main():+ command, *args = sys.argv[1:]+ if command == 'preflight':+ values = preflight()+ with open(os.environ['GITHUB_OUTPUT'], 'a') as output:+ for key, value in values.items():+ output.write(f'{key}={value}\n')+ print(json.dumps(values))+ elif command == 'verify':+ print(json.dumps(verify_bundle(*args), indent=2))+ elif command == 'publish':+ directory, tag, sha, run_id = args+ current = source(tag, run_id)+ if current['source_sha'] != sha:+ raise ValueError('Release tag changed since preflight')+ records = verify_bundle(directory, current['version'], sha)+ upload_verified_assets(directory, tag)+ print(json.dumps({'source': current, 'packages': records}, indent=2))+ else:+ raise ValueError('Unsupported command')+++if __name__ == '__main__':+ main()diff --git a/scripts/verify-synology-package.mjs b/scripts/verify-synology-package.mjsnew file mode 100644index 00000000..6901c099--- /dev/null+++ b/scripts/verify-synology-package.mjs@@ -0,0 +1,175 @@+import assert from 'node:assert/strict'+import { createHash } from 'node:crypto'+import { lstat, mkdtemp, readdir, readFile, rm } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { parseArgs } from 'node:util'+import nodeLock from './fnos-runtime.lock.json' with { type: 'json' }+import {+ repositoryRoot,+ run,+ sha256,+ verifyFnosBinary,+} from './prepare-fnos-project.mjs'+import dsmLock from './synology-runtime.lock.json' with { type: 'json' }+import { synologyTarget } from './synology-target.mjs'+import { verifyServerPackage } from './verify-server-package.mjs'++export async function payloadInventory(root) {+ const files = {}+ async function walk(directory, prefix = '') {+ for (const name of (await readdir(directory)).sort()) {+ const absolute = path.join(directory, name)+ const relative = `${prefix}${name}`+ if (relative === 'payload-sha256.json') continue+ const info = await lstat(absolute)+ if (info.isDirectory()) await walk(absolute, `${relative}/`)+ else if (!info.isFile() || (info.mode & 0o7022) !== 0)+ throw new Error(`Unsafe SPK member: ${relative}`)+ else+ files[relative] = {+ sha256: sha256(await readFile(absolute)),+ executable: Boolean(info.mode & 0o111),+ }+ }+ }+ await walk(root)+ return files+}++export async function verifySynologyProject(root) {+ const app = path.join(root, 'app')+ const readJson = async (name) =>+ JSON.parse(await readFile(path.join(root, name), 'utf8'))+ const receipt = await readJson('app/synology-build.json')+ assert.match(receipt.sourceCommit, /^[a-f0-9]{40}$/)+ assert.equal(typeof receipt.sourceDirty, 'boolean')+ const arch = receipt.architecture+ const target = synologyTarget(arch)+ if (receipt.schemaVersion === 1) {+ // Previously shipped x64 archives recorded only the Gemini Lake build SDK.+ assert.equal(arch, 'x64')+ assert.equal(+ receipt.toolchainSha256,+ target.platforms.geminilake.toolchain.sha256+ )+ } else {+ assert.equal(receipt.schemaVersion, 2)+ assert.deepEqual(receipt.platforms, Object.keys(target.platforms))+ assert.deepEqual(receipt.toolchainDigests, target.toolchainDigests)+ }+ assert.equal(receipt.minimumDsm, dsmLock.dsmVersion)+ assert.equal(receipt.nodeArchiveSha256, nodeLock.node[arch].sha256)+ assert.equal(+ sha256(await readFile(path.join(app, 'runtime/bin/node'))),+ receipt.nodeSha256+ )+ assert.equal(receipt.nodeSha256, nodeLock.node[arch].binarySha256)+ assert.deepEqual(await readJson('conf/privilege'), {+ defaults: { 'run-as': 'package' },+ username: 'motrix',+ groupname: 'motrix',+ 'join-groupname': 'http',+ })+ const info = await readFile(path.join(root, 'INFO'), 'utf8')+ for (const field of [+ `version="${receipt.version}-${receipt.revision}"`,+ `arch="${target.infoArch}"`,+ `os_min_ver="${dsmLock.dsmVersion}"`,+ 'maintainer="Dr_rOot"',+ 'maintainer_url="https://github.com/agalwood"',+ ])+ assert.ok(info.split('\n').includes(field), field)+ for (const file of [+ 'runtime/bin/node',+ 'server/bin/aria2c',+ 'server/bin/motrix-finalize-fs',+ ])+ await verifyFnosBinary(path.join(app, file), arch)+ for (const file of [+ 'LICENSE',+ 'runtime/LICENSE',+ 'server/legal/THIRD_PARTY_LICENSES.txt',+ ])+ assert.ok(+ (+ await readFile(+ path.join(app, file === 'LICENSE' ? 'server/LICENSE' : file)+ )+ ).length > 0+ )+ for (const action of [+ 'preinst',+ 'postinst',+ 'preupgrade',+ 'postupgrade',+ 'preuninst',+ 'postuninst',+ 'start-stop-status',+ ]) {+ const file = path.join(root, 'scripts', action)+ assert.ok((await lstat(file)).mode & 0o111)+ assert.ok(!(await readFile(file, 'utf8')).includes('npm '))+ }+ for (const language of ['', '_chs', '_cht'])+ for (const action of ['install', 'upgrade', 'uninstall'])+ assert.ok(+ Array.isArray(+ await readJson(`WIZARD_UIFILES/${action}_uifile${language}`)+ )+ )+ await verifyServerPackage({+ appDir: path.join(app, 'server'),+ platform: 'linux',+ arch,+ libc: 'gnu',+ })+ assert.deepEqual(+ await payloadInventory(app),+ await readJson('app/payload-sha256.json')+ )+ return receipt+}++export async function verifySynologyPackage(file, inspect = async () => {}) {+ const temporary = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-verify-'))+ try {+ const unpacked = path.join(temporary, 'spk')+ run('python3', [+ path.join(repositoryRoot, 'scripts/spk_archive.py'),+ file,+ unpacked,+ ])+ const archive = path.join(unpacked, 'package.tgz')+ const checksum = createHash('md5')+ .update(await readFile(archive))+ .digest('hex')+ assert.ok(+ (await readFile(path.join(unpacked, 'INFO'), 'utf8'))+ .split('\n')+ .includes(`checksum="${checksum}"`)+ )+ run('python3', [+ path.join(repositoryRoot, 'scripts/spk_archive.py'),+ archive,+ path.join(unpacked, 'app'),+ ])+ const receipt = await verifySynologyProject(unpacked)+ await inspect(unpacked)+ return receipt+ } finally {+ await rm(temporary, { recursive: true, force: true })+ }+}++if (+ process.argv[1] &&+ fileURLToPath(import.meta.url) === path.resolve(process.argv[1])+) {+ const { values } = parseArgs({+ args: process.argv.slice(2).filter((arg) => arg !== '--'),+ options: { spk: { type: 'string' } },+ })+ console.log(await verifySynologyPackage(path.resolve(values.spk)))+}diff --git a/scripts/verify_synology_abi.py b/scripts/verify_synology_abi.pynew file mode 100644index 00000000..6e1cfb1d--- /dev/null+++ b/scripts/verify_synology_abi.py@@ -0,0 +1,84 @@+"""Inspect the final SPK ELF files, then run them against the target DSM sysroot."""+import hashlib+import json+import os+from pathlib import Path+import re+import subprocess+import sys+++def run(*args, **kwargs):+ return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT, timeout=120, **kwargs)+++def verify(app_dir, sdk_dir, arch, platform):+ lock = json.loads(Path(__file__).with_name('synology-runtime.lock.json').read_text())+ target = lock['targets'][arch]+ profile = target['platforms'][platform]+ app = Path(app_dir).resolve()+ sysroot = Path(sdk_dir).resolve() / target['sysroot']+ libraries = [sysroot / 'lib', sysroot / 'usr/lib']+ loader = sysroot / target['loader']+ loader_args = [str(loader), '--inhibit-cache', '--library-path', ':'.join(map(str, libraries))]+ emulator = ['qemu-aarch64', '-cpu', target['cpu']] if arch == 'arm64' else []+ files = []+ for file in sorted(app.rglob('*')):+ if not file.is_file():+ continue+ with file.open('rb') as stream:+ header = stream.read(20)+ if not header.startswith(b'\x7fELF'):+ continue+ if header[4:6] != b'\x02\x01' or int.from_bytes(header[18:20], 'little') != target['machine']:+ raise ValueError('Foreign ELF: ' + str(file))+ # The cross SDK tools themselves may be x86 executables. Native GNU+ # readelf can inspect both targets without executing anything from the SDK.+ dynamic = run('readelf', '-d', str(file))+ needed = re.findall(r'\(NEEDED\).*\[([^\]]+)\]', dynamic)+ missing = [name for name in needed if not any((directory / name).is_file() for directory in libraries)]+ versions = run('readelf', '--version-info', str(file))+ required = set(re.findall(r'Name: ((?:GLIBC|GLIBCXX|CXXABI)_[\w.]+)', versions))+ if missing or 'RPATH' in dynamic or 'RUNPATH' in dynamic:+ raise ValueError(f'{file.name}: missing DSM libraries {missing} or embedded search paths')+ for soname, section in re.findall(r'File: (\S+).*?Cnt: \d+(.*?)(?=\n\s*0x[\da-f]+:\s+Version:|\Z)', versions, re.S):+ demands = set(re.findall(r'Name: ((?:GLIBC|GLIBCXX|CXXABI)_[\w.]+)', section))+ if not demands:+ continue+ library = next((directory / soname for directory in libraries if (directory / soname).is_file()), None)+ if not library:+ raise ValueError(f'{file.name}: missing DSM library {soname}')+ supplied = set(re.findall(r'Name: (\S+)', run('readelf', '--version-info', str(library))))+ if demands - supplied:+ raise ValueError(f'{file.name}: {soname} lacks {sorted(demands - supplied)}')+ files.append({'file': str(file.relative_to(app)), 'sha256': hashlib.sha256(file.read_bytes()).hexdigest(),+ 'needed': needed, 'versions': sorted(required)})+ by_name = {item['file']: item for item in files}+ entries = ['runtime/bin/node', 'server/bin/aria2c', 'server/bin/motrix-finalize-fs']+ if not all(name in by_name for name in entries) or not any(name.endswith('.node') for name in by_name):+ raise ValueError('Missing required runtime ELF or SQLite addon')++ def execute(name, *args):+ prefix = loader_args if by_name[name]['needed'] else []+ return run(*emulator, *prefix, str(app / name), *args, cwd=app, input='',+ env={'PATH': '/usr/bin:/bin', 'HOME': '/tmp', 'LANG': 'C'})++ code = """const DB=require('./server/node_modules/better-sqlite3');+const db=new DB(':memory:'); db.exec('create table t(v);insert into t values(42)');+if(db.prepare('select v from t').get().v!==42)process.exit(1);+console.log(JSON.stringify({node:process.version, arch:process.arch,+glibc:process.report.getReport().header.glibcVersionRuntime,sqlite:'read-write-ok'}));db.close()"""+ loaded = json.loads(execute(entries[0], '-e', code))+ if loaded['glibc'] != lock['glibc'] or loaded['arch'] != arch:+ raise ValueError('Node did not load the target DSM libc and SQLite')+ aria = execute(entries[1], '--version').splitlines()[0]+ execute(entries[2])+ return {'schemaVersion': 2, 'scope': f"DSM {lock['dsmVersion']} {platform} userspace on Linux host kernel",+ 'platform': platform, 'toolchainSha256': profile['toolchain']['sha256'],+ 'architecture': arch, 'cpuEmulation': target.get('cpu'), 'deviceAcceptance': 'not-run',+ 'hostKernel': os.uname().release, 'loaded': loaded, 'aria2': aria, 'elf': files}+++if __name__ == '__main__':+ app, sdk, output, arch, platform = sys.argv[1:]+ Path(output).write_text(json.dumps(verify(app, sdk, arch, platform), indent=2) + '\n')diff --git a/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts b/src/core/engine/aria2/completed-task-startup-guard.integration.test.tsindex 516de60c..765f66f7 100644--- a/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts+++ b/src/core/engine/aria2/completed-task-startup-guard.integration.test.ts@@ -21,9 +21,14 @@ import { CompletedTaskStartupGuard } from './completed-task-startup-guard'describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())('completed RPC lifecycle with real aria2',() => {- it.each([false, true])(- 'blocks old completed rows before requests, preserves run intent and accepts fresh work (sqlite=%s)',- async (sqlite) => {+ it.each([+ { sqlite: false, hostGrants: false },+ { sqlite: true, hostGrants: false },+ { sqlite: false, hostGrants: true },+ { sqlite: true, hostGrants: true },+ ])(+ 'blocks completed or unauthorized rows before requests and preserves run intent (%j)',+ async ({ sqlite, hostGrants }) => {const root = await mkdtemp(path.join(tmpdir(), 'motrix-completed-real-'))@@ -94,7 +99,10 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(: [...args, `--input-file=${session}`]const guard = new CompletedTaskStartupGuard({completedGids: () => new Set([done]),- heldGids: () => new Set([held]),+ heldGids: () => new Set(hostGrants ? [] : [held]),+ authorizeResume: hostGrants+ ? async (gid) => gid !== held+ : undefined,get rpc() {return wired.rpc},diff --git a/src/core/engine/aria2/completed-task-startup-guard.test.ts b/src/core/engine/aria2/completed-task-startup-guard.test.tsindex 7b1ac339..26cd4fb2 100644--- a/src/core/engine/aria2/completed-task-startup-guard.test.ts+++ b/src/core/engine/aria2/completed-task-startup-guard.test.ts@@ -73,6 +73,47 @@ afterEach(async () => {})describe('CompletedTaskStartupGuard', () => {+ it.each([false, true])(+ 'checks host grants even without completed tasks (sqlite=%s)',+ async (sqlite) => {+ const h = await setup(sqlite)+ const authorizeResume = vi.fn(async (gid: string) => gid === RUN)+ const guard = new CompletedTaskStartupGuard({+ completedGids: () => new Set(),+ rpc: h.rpc,+ removeResult: h.removeResult,+ authorizeResume,+ })+ const prepared = await guard.prepare(h.args)+ expect(prepared?.args).toContain('--pause=true')+ expect(prepared?.args).toContain('--pause-metadata=true')+ await prepared?.reconcile(() => false)+ expect(authorizeResume.mock.calls.flat()).toEqual([DONE, RUN])+ expect(h.rpc.unpause).toHaveBeenCalledExactlyOnceWith(RUN)+ expect(h.rpc.forceRemove).not.toHaveBeenCalled()+ await expect(readFile(h.journal)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ }+ )++ it('keeps the recovery journal if host authorization fails unexpectedly', async () => {+ const h = await setup()+ const guard = new CompletedTaskStartupGuard({+ completedGids: () => new Set(),+ rpc: h.rpc,+ removeResult: h.removeResult,+ authorizeResume: async () => {+ throw new Error('authority unavailable')+ },+ })+ const prepared = await guard.prepare(h.args)+ await expect(prepared?.reconcile(() => false)).rejects.toThrow(+ 'authority unavailable'+ )+ expect(h.rpc.unpause).not.toHaveBeenCalled()+ expect(await readFile(h.journal, 'utf8')).toContain(RUN)+ })it.each([false, true])('purges completed rows before resuming only originally running tasks (sqlite=%s)',async (sqlite) => {diff --git a/src/core/engine/aria2/completed-task-startup-guard.ts b/src/core/engine/aria2/completed-task-startup-guard.tsindex ca67de1b..f30054a4 100644--- a/src/core/engine/aria2/completed-task-startup-guard.ts+++ b/src/core/engine/aria2/completed-task-startup-guard.ts@@ -152,6 +152,8 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {completedGids: () => ReadonlySet<string>/** Pending ownership reconciliation: pause at boot, never purge or auto-resume. */heldGids?: () => ReadonlySet<string>+ /** Hosts with directory grants authorize persisted work before it can write. */+ authorizeResume?: (gid: string) => Promise<boolean>rpc: Pick<Aria2RpcClient,'tellStatus' | 'forceRemove' | 'unpause' | 'changeGlobalOption'@@ -186,19 +188,33 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {}const completed = this.deps.completedGids()const held = new Set(this.deps.heldGids?.())- if (!previous && completed.size === 0 && held.size === 0) return null+ const authorizeResume = this.deps.authorizeResume+ if (+ !previous &&+ completed.size === 0 &&+ held.size === 0 &&+ !authorizeResume+ )+ return nullconst intent = await readRunIntent(source,sqlite,(gids) =>previous !== null ||+ authorizeResume !== undefined ||gids.some((gid) => completed.has(gid) || held.has(gid)))const targets = [...intent.keys()].filter((gid) => completed.has(gid) && !held.has(gid))const hasHeldTask = [...intent.keys()].some((gid) => held.has(gid))- if (!previous && targets.length === 0 && !hasHeldTask) return null+ if (+ !previous &&+ targets.length === 0 &&+ !hasHeldTask &&+ (!authorizeResume || intent.size === 0)+ )+ return nullconst resume = (previous? previous.resume.filter((gid) => intent.has(gid))@@ -212,8 +228,13 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {return {args: [- ...args.filter((value) => !value.startsWith('--pause=')),+ ...args.filter(+ (value) =>+ !value.startsWith('--pause=') &&+ (!authorizeResume || !value.startsWith('--pause-metadata='))+ ),'--pause=true',+ ...(authorizeResume ? ['--pause-metadata=true'] : []),],reconcile: async (isStopping) => {for (const gid of targets) {@@ -238,12 +259,19 @@ export class CompletedTaskStartupGuard implements EngineStartupGuard {}// Do not release any remaining task if even one required purge failed.if (isStopping()) return- await this.deps.rpc.changeGlobalOption({ pause: 'false' })+ await this.deps.rpc.changeGlobalOption({+ pause: 'false',+ ...(authorizeResume+ ? { 'pause-metadata': argument(args, 'pause-metadata') ?? 'false' }+ : {}),+ })const completedNow = this.deps.completedGids()for (const gid of resume) {if (isStopping()) returnif (completedNow.has(gid) || this.deps.heldGids?.().has(gid)) continuetry {+ if (authorizeResume && !(await authorizeResume(gid))) continue+ if (isStopping()) returnif ((await this.deps.rpc.tellStatus(gid)).status === 'paused' &&!this.deps.heldGids?.().has(gid)diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.tsindex 3b5403b5..5e847755 100644--- a/src/core/session/session-manager.test.ts+++ b/src/core/session/session-manager.test.ts@@ -295,6 +295,7 @@ function seedAsPair(errorMessage?: string | nullerrorCode?: DownloadErrorCode | nullpayload?: Record<string, unknown>+ phase?: TaskInstancePhase}): void {const isBtLike =@@ -303,9 +304,9 @@ function seedAsPair(opts.kind === TaskKind.Bt ||!!opts.infoHash ||!!opts.torrentMetaPath- const phase = isBtLike- ? TaskInstancePhase.BtDownload- : TaskInstancePhase.HttpDownload+ const phase =+ opts.phase ??+ (isBtLike ? TaskInstancePhase.BtDownload : TaskInstancePhase.HttpDownload)const kind = opts.kind ?? (isBtLike ? TaskKind.Bt : TaskKind.Direct)const status = opts.status ?? TaskStatus.Queueddb.saveTaskWithInstances({@@ -2336,6 +2337,42 @@ describe('SessionManager', () => {}})+ it.each([+ TaskInstancePhase.HttpDownload,+ TaskInstancePhase.MagnetMetadataResolution,+ ])(+ 'does not reconstruct lost work when host grants are revoked (%s)',+ async (phase) => {+ seedAsPair(db, {+ motrixId: 'revoked',+ gid: 'lost-revoked',+ diskPath: '/tmp/revoked.bin.motrix',+ finalPath: '/tmp/revoked.bin',+ uris: ['http://example.com/revoked.bin'],+ status: TaskStatus.Downloading,+ phase,+ payload: { metadataDir: '/tmp/motrix-magnet-metadata-test' },+ })+ rpc.tellActive = vi.fn(async () => [])+ rpc.tellWaiting = vi.fn(async () => [])+ rpc.tellStopped = vi.fn(async () => [])+ rpc.addUri = vi.fn()+ const authorize = vi.fn(async () => {+ throw new Error('revoked')+ })+ sessionManager.setRecoveryWriteAuthorization(authorize)+ await sessionManager.restore()+ expect(authorize).toHaveBeenCalled()+ expect(adapter.createDownload).not.toHaveBeenCalled()+ expect(adapter.addTorrent).not.toHaveBeenCalled()+ expect(rpc.addUri).not.toHaveBeenCalled()+ expect(taskManager.getById('revoked')).toMatchObject({+ status: TaskStatus.Error,+ errorDetailKey: 'task.recovery.startup.resumePathInvalid',+ })+ }+ )+it('re-adds HTTP task via adapter.createDownload when aria2 has lost it', async () => {seedAsPair(db, {motrixId: 'm-http-004',@@ -3093,6 +3130,7 @@ describe('SessionManager', () => {.find((t) => t.id === 'm-legacy-completed')expect(restored?.diskPath).toBe('/dl/movie-final.mkv')expect(restored?.saveDir).toBe('/dl')+ expect(restored?.fileCount).toBe(1)// Instances heal too, so the next save() rewrites the DB row and// the stale placeholder is gone for good.expect(restored?.instances[0]?.diskPath).toBe('/dl/movie-final.mkv')diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.tsindex 020a302e..c3bc8981 100644--- a/src/core/session/session-manager.ts+++ b/src/core/session/session-manager.ts@@ -85,7 +85,10 @@ import { restoreMediaProgress } from '../task/media-task-progress'import { isTempPath } from '../task/paths'import { setTaskTransitionPhase } from '../task/task-instance'import type { TaskManager } from '../task/task-manager'-import { taskRowToDownloadTask } from '../task/task-row-to-download-task'+import {+ restoredTaskFileCount,+ taskRowToDownloadTask,+} from '../task/task-row-to-download-task'import { restoreTaskSaveDirectory } from '../task/task-save-directory'import { isMagnetCleanupTombstoneHidden } from '../torrent/magnet-cleanup-quarantine'import { computeUriHash, deriveInfoHash } from './content-key'@@ -302,6 +305,26 @@ export class SessionManager {null) {}+ private authorizeRecoveryWrite?: (task: DownloadTask) => Promise<void>++ /** Host grants apply to automatic reconstruction as well as explicit resume. */+ setRecoveryWriteAuthorization(+ authorize: (task: DownloadTask) => Promise<void>+ ): void {+ this.authorizeRecoveryWrite = authorize+ }++ private async canRecoverWrite(pair: TaskWithInstances): Promise<boolean> {+ try {+ await this.authorizeRecoveryWrite?.(+ taskRowToDownloadTask(pair.task, pair.instances)+ )+ return true+ } catch {+ return false+ }+ }+/*** Binds the shared plugin terminal boundary after the Hook runtime is built.* Session restore owns a few terminal transitions internally; routing those@@ -1633,7 +1656,7 @@ export class SessionManager {uris: primary?.uris ?? [],uploadedBytes,uploadedBytesBaseline,- fileCount: taskPart.fileCount,+ fileCount: restoredTaskFileCount(taskPart),connections: 0,pieceLength: taskPart.pieceLength,infoHash: taskPart.infoHash,@@ -1670,6 +1693,11 @@ export class SessionManager {pair: TaskWithInstances,assertProxyCurrent?: () => void): Promise<DownloadTask> {+ if (!(await this.canRecoverWrite(pair)))+ return this.markRecoverErrorFromPair(+ pair,+ 'task.recovery.startup.resumePathInvalid'+ )const taskPart = pair.taskconst primary = pair.instances[0]@@ -2090,6 +2118,11 @@ export class SessionManager {private async recoverMagnetMetadata(pair: TaskWithInstances): Promise<DownloadTask> {+ if (!(await this.canRecoverWrite(pair)))+ return this.markRecoverErrorFromPair(+ pair,+ 'task.recovery.startup.resumePathInvalid'+ )const now = Date.now()const taskPart = pair.taskconst primary = pair.instances[0]diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.tsindex ea36f4ab..a9c7ad89 100644--- a/src/core/task/actions/finalize-task.test.ts+++ b/src/core/task/actions/finalize-task.test.ts@@ -587,6 +587,17 @@ describe('finalizeTask failure-path publication routing', () => {// and persists Completed with Size 0 / 0%. The fix is a pre-finalize// tellStatus refresh before removeDownloadResult retires the gid.describe('finalizeTask HTTP pre-refresh transfer metadata', () => {+ it('keeps a known single-file output when the final metadata probe fails', async () => {+ const deps = makeDeps()+ const task = makeTask({ fileCount: 0 })+ vi.mocked(deps.taskManager.getById).mockReturnValue(task)+ vi.mocked(deps.adapter.getTaskStatus).mockRejectedValue(+ new Error('engine row retired')+ )+ await finalizeTask('t1', deps)+ expect(task.status).toBe(TaskStatus.Completed)+ expect(task.fileCount).toBe(1)+ })it('fills byte counters and piece length when polling never observed them', async () => {const deps = makeDeps()const task = makeTask({diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.tsindex 082e5243..319f4f7d 100644--- a/src/core/task/actions/finalize-task.ts+++ b/src/core/task/actions/finalize-task.ts@@ -63,6 +63,12 @@ import {const finalizationsInFlight = new Set<string>()export interface FinalizeTaskDeps {+ authorizeDirectoryForTask?: (task: DownloadTask) => Promise<void>+ removeTaskOutput?: (task: DownloadTask, file: string) => Promise<void>+ recordInPlaceOutput?: (+ task: DownloadTask,+ metadata: Uint8Array+ ) => Promise<void>taskManager: {getById(id: string): DownloadTask | undefinedgetAll(): DownloadTask[]@@ -202,6 +208,7 @@ async function finalizeTaskSerialized(const publishedTask = getTaskOrWarn(deps, taskId, 'finalizeTask')if (!publishedTask) returnconst task = structuredClone(publishedTask)+ await deps.authorizeDirectoryForTask?.(task)if (hasLegacyImport(task)) {if (isInactiveLegacyTask(task)) return// An authorized in-place task never renames, deletes unselected files, or@@ -376,7 +383,7 @@ async function finalizeHttp(// `Size 0 / 0%`. Pull once here so syncCompletionMetrics has real// numbers to seal. Best-effort: any failure (race with another retire,// RPC error) is logged and we fall through with whatever we already had.- await refreshTaskBytesBeforeFinalize(task, deps)+ await refreshHttpMetadataBeforeFinalize(task, deps)// removeDownloadResult before rename so aria2 releases the file// handle — on Windows an open handle causes a sharing violation.@@ -563,10 +570,13 @@ function syncCompletionMetrics(task: DownloadTask): void {* swallowed: the caller's existing task state remains the source of* truth and syncCompletionMetrics will still do what it can.*/-async function refreshTaskBytesBeforeFinalize(+async function refreshHttpMetadataBeforeFinalize(task: DownloadTask,deps: FinalizeTaskDeps): Promise<void> {+ // HTTP/FTP finalization publishes one file even when the metadata poll was+ // missed. Preserve that cardinality before committing the rename journal.+ if (task.fileCount === 0) task.fileCount = 1try {const refreshed = await deps.adapter.getTaskStatus(task.engineTaskId)if (!refreshed) return@@ -774,7 +784,9 @@ async function finalizeBt(!isSameOrDescendant(publishedFinalPath, storageLayout.workspacePath)) {try {- await deps.fs.removePathRecursive(storageLayout.workspacePath)+ if (deps.removeTaskOutput)+ await deps.removeTaskOutput(task, storageLayout.workspacePath)+ else await deps.fs.removePathRecursive(storageLayout.workspacePath)} catch (err) {deps.log.warn({ err, taskId: task.id, workspacePath: storageLayout.workspacePath },@@ -1087,6 +1099,11 @@ async function finalizeBtInPlace(false)}+ if (deps.recordInPlaceOutput && task.torrentMetaPath)+ await deps.recordInPlaceOutput(+ task,+ await deps.torrentMetaStore.read(task.torrentMetaPath)+ )const unselected = live ? await snapshotUnselectedRelPaths(task, deps) : []await cleanupUnselectedAfterRename(task, unselected, deps)const completedAt = Date.now()@@ -1344,7 +1361,8 @@ async function cleanupUnselectedAfterRename(if (rel === '' || rel === '.') continueconst target = path.join(task.finalPath, rel)try {- await deps.fs.removePathRecursive(target)+ if (deps.removeTaskOutput) await deps.removeTaskOutput(task, target)+ else await deps.fs.removePathRecursive(target)removed += 1} catch (err) {deps.log.warn(diff --git a/src/core/task/actions/remove-task.ts b/src/core/task/actions/remove-task.tsindex d620e3b0..0804b359 100644--- a/src/core/task/actions/remove-task.ts+++ b/src/core/task/actions/remove-task.ts@@ -44,6 +44,7 @@ export interface RemoveTaskDeps extends TaskActionDeps {runTaskMutation: NonNullable<TaskActionDeps['runTaskMutation']>taskPersistence: Pick<SessionManager, 'runExclusivePersistence'>fileCleanupService: FileCleanupService+ fileCleanupForTask?: (task: DownloadTask) => FileCleanupServicetorrentMetaStore: TorrentMetaStoremediaMetaStore?: Pick<MediaMetaStore, 'remove'>// Structural slice of MotrixDatabase. Removal needs `deleteTask` for@@ -110,7 +111,11 @@ async function removeTaskUnderMutation('Cannot remove task while it is being finalized')}- if (options.deleteWithFiles) await deps.authorizeTaskRemoval?.(task)+ if (options.deleteWithFiles) {+ await deps.authorizeTaskRemoval?.(task)+ if (deps.fileCleanupForTask)+ deps = { ...deps, fileCleanupService: deps.fileCleanupForTask(task) }+ }// Both removal paths delete the durable parent row under one// exclusive-persistence window, with the Inspector Activity deletiondiff --git a/src/core/task/bt-storage-service.ts b/src/core/task/bt-storage-service.tsindex c8ef65ce..338c9ada 100644--- a/src/core/task/bt-storage-service.ts+++ b/src/core/task/bt-storage-service.ts@@ -42,6 +42,12 @@ import {} from './task-instance'export interface BtStorageServiceDeps extends ReAddTaskDeps {+ authorizeRecheck?: (task: DownloadTask) => Promise<void>+ prepareStorageBinding?: (+ task: DownloadTask,+ mode: 'locate' | 'recheck' | 'move',+ members: readonly string[]+ ) => Promise<{ bindVerified(): Promise<void>; bindMoved(): Promise<void> }>authorizeOutputWrite?: (output: string) => Promise<void>runtime: Pick<DurableFinalizeRuntime,@@ -159,7 +165,10 @@ export class BtStorageService {throw new StorageFault('busy')if (original.finalPath !== expectedPath)throw new StorageFault('unavailable')- if (request.mode !== 'locate') await deps.authorizeTaskWrite?.(original)+ if (request.mode === 'recheck' && deps.authorizeRecheck)+ await deps.authorizeRecheck(original)+ else if (request.mode !== 'locate')+ await deps.authorizeTaskWrite?.(original)if (request.mode === 'move') await deps.authorizeTaskRemoval?.(original)if ((await deps.authorizeDirectory(directory)) !== directory)throw new StorageFault('destination')@@ -360,6 +369,21 @@ export class BtStorageService {delete primary.payload.btOutputReservationslet verification!: BtVerificationResulttry {+ const binding = await deps.prepareStorageBinding?.(+ candidate,+ request.mode,+ layout.files+ .filter(+ (f) =>+ !candidate.bt?.selectedFiles?.length ||+ candidate.bt.selectedFiles.includes(f.fileIndex)+ )+ .map((file) =>+ file.pathInsideRoot+ ? path.join(target, file.pathInsideRoot)+ : target+ )+ )if (request.mode === 'move') {await deps.runtime.commit({task: candidate,@@ -372,6 +396,7 @@ export class BtStorageService {fileRebase: { sourceRoot: sourcePath, targetRoot: target },verifySource: async () => {verification = await verify(source)+ await binding?.bindVerified()running.controller.signal.throwIfAborted()running.cancellable = falseprogress('moving')@@ -379,11 +404,13 @@ export class BtStorageService {onCommitted: () =>deps.taskManager.set(candidate.id, structuredClone(candidate)),})+ await binding?.bindMoved()} else {await deps.runtime.withArtifactLease(stopped.id, async () => {verification = await verify(target)running.controller.signal.throwIfAborted()running.cancellable = false+ await binding?.bindVerified()await deps.persistStorage(candidate, sourcePath, target)})}diff --git a/src/core/task/completed-engine-task-cleanup.test.ts b/src/core/task/completed-engine-task-cleanup.test.tsindex 92e9c067..f698d5c8 100644--- a/src/core/task/completed-engine-task-cleanup.test.ts+++ b/src/core/task/completed-engine-task-cleanup.test.ts@@ -88,6 +88,21 @@ function harness(afterEach(() => vi.useRealTimers())describe('CompletedEngineTaskCleanup', () => {+ it('retains single-file metadata when a tiny HTTP download completes before polling', async () => {+ const h = harness()+ h.taskManager.set(+ 'task-1',+ output({ status: TaskStatus.Downloading, fileCount: 0, finishedAt: null })+ )+ await h.cleanup.observe(output({ fileCount: 0 }))+ expect(h.taskManager.getById('task-1')?.fileCount).toBe(1)+ expect(h.persist).toHaveBeenCalledWith(+ expect.objectContaining({ fileCount: 1 }),+ expect.anything()+ )+ expect(h.adapter.removeDownloadResult).toHaveBeenCalledOnce()+ await h.cleanup.stopAndDrain()+ })it('retains completion observed before the first HTTP resume becomes durable', async () => {vi.useFakeTimers()const active = makeLegacyHttpTask({ status: TaskStatus.Downloading })diff --git a/src/core/task/completed-engine-task-cleanup.ts b/src/core/task/completed-engine-task-cleanup.tsindex 268a5db3..51029c38 100644--- a/src/core/task/completed-engine-task-cleanup.ts+++ b/src/core/task/completed-engine-task-cleanup.ts@@ -74,6 +74,9 @@ function isPendingLegacyHttpResume(task: DownloadTask): boolean {}function completeMetrics(task: DownloadTask): void {+ // HTTP/FTP final-path output is one file, even if completion beats the first+ // metadata poll. Keep that fact after the engine row is retired.+ if (task.fileCount === 0) task.fileCount = 1task.totalBytes = Math.max(task.totalBytes, task.downloadedBytes)task.downloadedBytes = task.totalBytestask.sizeWhenDone = task.totalBytesdiff --git a/src/core/task/task-row-to-download-task.test.ts b/src/core/task/task-row-to-download-task.test.tsindex 0d5f0b16..d3eb6619 100644--- a/src/core/task/task-row-to-download-task.test.ts+++ b/src/core/task/task-row-to-download-task.test.ts@@ -71,6 +71,26 @@ function makeInstance(phase: TaskInstancePhase): TaskInstanceRow {}describe('taskRowToDownloadTask', () => {+ it.each([+ [TaskType.Http, 1],+ [TaskType.Ftp, 1],+ [TaskType.Metalink, 0],+ [TaskType.Bt, 0],+ ] as const)(+ 'restores known single-file history without guessing multifile output (%s)',+ (taskType, count) => {+ const task = taskRowToDownloadTask(+ makeTaskRow({+ kind: TaskKind.Direct,+ taskType,+ aggStatus: TaskStatus.Completed,+ fileCount: 0,+ }),+ [makeInstance(TaskInstancePhase.HttpDownload)]+ )+ expect(task.fileCount).toBe(count)+ }+ )it('restores media progress from the phase payload even when instance order differs', () => {const primary = makeInstance(TaskInstancePhase.HlsSegment)primary.payload.mediaProgress = makeMediaProgress()diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.tsindex 91372116..475c2861 100644--- a/src/core/task/task-row-to-download-task.ts+++ b/src/core/task/task-row-to-download-task.ts@@ -3,7 +3,9 @@ import { legacyTaskMetadataSchema } from '@shared/schemas/legacy-import'import {type DownloadTask,makeDefaultBtExtension,+ TaskKind,TaskStatus,+ TaskType,TransitionPhase,} from '@shared/types/task'import { isTorrentLikeType } from '@shared/types/task-actions'@@ -12,6 +14,16 @@ import { unsettledBtUpload } from './bt-upload-settlement'import { restoreMediaProgress } from './media-task-progress'import { restoreTaskSaveDirectory } from './task-save-directory'+/** Older HTTP/FTP history can predate the first file metadata poll. */+export function restoredTaskFileCount(task: TaskRow): number {+ return task.fileCount === 0 &&+ task.kind === TaskKind.Direct &&+ task.aggStatus === TaskStatus.Completed &&+ (task.taskType === TaskType.Http || task.taskType === TaskType.Ftp)+ ? 1+ : task.fileCount+}+/** Build a generic DownloadTask domain object from canonical TaskRow data.** Runtime-only speed, ETA, and connection values start at zero until the next@@ -71,7 +83,7 @@ export function taskRowToDownloadTask(uris: primary?.uris ?? [],uploadedBytes,uploadedBytesBaseline: task.uploadedBytesBaseline,- fileCount: task.fileCount,+ fileCount: restoredTaskFileCount(task),connections: 0,pieceLength: task.pieceLength,infoHash: task.infoHash,diff --git a/src/renderer/components/add-task/drop-zone.tsx b/src/renderer/components/add-task/drop-zone.tsxindex 2fa889db..f6f5b9be 100644--- a/src/renderer/components/add-task/drop-zone.tsx+++ b/src/renderer/components/add-task/drop-zone.tsx@@ -1,13 +1,15 @@import { ImportFileIcon } from '@renderer/components/icons'+import { Button } from '@renderer/components/ui/button'import {type ParsedTorrentFile,readTorrentFile,} from '@renderer/lib/parse-torrent-file'import { cn } from '@renderer/lib/utils'+import { hasNasTorrentPicker, nasRequest } from '@renderer/platform/nas'import { usePlatformServices } from '@renderer/platform/services'import { torrentFileErrorKey } from '@shared/lib/engine-torrent'import type { AddTaskFormValues } from '@shared/schemas/add-task'-import { useCallback, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import { useFormContext } from 'react-hook-form'import { useTranslation } from 'react-i18next'@@ -21,6 +23,14 @@ export function DropZone({const platform = usePlatformServices()const [dragOver, setDragOver] = useState(false)const fileRef = useRef<HTMLInputElement>(null)+ const [selectingNas, setSelectingNas] = useState(false)+ const active = useRef(true)+ useEffect(() => {+ active.current = true+ return () => {+ active.current = false+ }+ }, [])const loadFiles = useCallback(async (files: FileList | File[]) => {@@ -35,6 +45,7 @@ export function DropZone({}for (const key of failures) platform.notify('error', key)if (parsed.length === 0) return+ if (!active.current) returnconst first = parsed[0]setValue('torrentMeta' as never, first.meta as never, {@@ -52,6 +63,31 @@ export function DropZone({[onFilesLoaded, platform, setValue])+ const selectNasTorrent = async () => {+ if (selectingNas || !platform.pickFile) return+ setSelectingNas(true)+ try {+ const candidate = await platform.pickFile({+ kind: 'open',+ extensions: ['torrent'],+ })+ if (!candidate || !active.current) return+ const response = await nasRequest('torrent', { path: candidate })+ if (!active.current) return+ await loadFiles([+ new File(+ [await response.blob()],+ candidate.split('/').at(-1) ?? 'download.torrent'+ ),+ ])+ } catch {+ if (active.current)+ platform.notify('error', 'panel.downloads.action.nasFileUnavailable')+ } finally {+ if (active.current) setSelectingNas(false)+ }+ }+return (<><button@@ -85,6 +121,17 @@ export function DropZone({</span></span></button>+ {hasNasTorrentPicker() && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={selectingNas}+ onClick={() => void selectNasTorrent()}+ >+ {t('task.add.selectNasTorrent')}+ </Button>+ )}<inputref={fileRef}type="file"diff --git a/src/renderer/components/nas-storage-recovery.tsx b/src/renderer/components/nas-storage-recovery.tsxnew file mode 100644index 00000000..247a736e--- /dev/null+++ b/src/renderer/components/nas-storage-recovery.tsx@@ -0,0 +1,43 @@+import { Button } from '@renderer/components/ui/button'+import { applyRendererLocale } from '@renderer/lib/i18n'+import { NasDialog } from '@renderer/routes/settings/cards/nas-dialog'+import { useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'++export function NasStorageRecovery({ roots }: { roots: readonly string[] }) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ useEffect(() => {+ void applyRendererLocale(navigator.language)+ }, [])+ return (+ <main className="flex min-h-svh items-center justify-center bg-background p-6 text-foreground">+ <div className="w-full max-w-lg space-y-4">+ <h1 className="text-lg font-semibold">+ {t('settings.nas.storageUnavailable')}+ </h1>+ <p className="text-sm text-muted-foreground">+ {t('settings.nas.storageRecoveryHint')}+ </p>+ <ul className="max-h-48 overflow-auto rounded border p-3 font-mono text-xs">+ {roots.map((root) => (+ <li className="select-text break-all" key={root}>+ {root}+ </li>+ ))}+ </ul>+ <Button size="sm" onClick={() => setOpen(true)}>+ {t('settings.nas.roots')}+ </Button>+ {open && (+ <NasDialog+ open+ onClose={() => setOpen(false)}+ labelKey="settings.nas.roots"+ descKey="settings.nas.rootsHint"+ />+ )}+ </div>+ </main>+ )+}diff --git a/src/renderer/components/operator-unlock-gate.test.tsx b/src/renderer/components/operator-unlock-gate.test.tsxindex 5a9f7e93..fa287136 100644--- a/src/renderer/components/operator-unlock-gate.test.tsx+++ b/src/renderer/components/operator-unlock-gate.test.tsx@@ -76,3 +76,27 @@ describe('OperatorUnlockGate', () => {await waitFor(() => expect(screen.getByTestId('app')).toBeTruthy())})})++it('shows a safe DSM failure code while keeping the app locked without requesting a password', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ authed: false,+ mode: 'synologyDsm',+ canLogout: false,+ nasAuthDiagnostic: {+ stage: 'session',+ code: 'commandFailed',+ failure: 'exit',+ exitCode: 5,+ },+ })+ )+ )+ render(<OperatorUnlockGate>{child}</OperatorUnlockGate>)+ expect(+ await screen.findByText('session / commandFailed / exit / 5')+ ).toBeTruthy()+ expect(screen.queryByTestId('app')).toBeNull()+ expect(screen.queryByPlaceholderText('Operator token')).toBeNull()+})diff --git a/src/renderer/components/operator-unlock-gate.tsx b/src/renderer/components/operator-unlock-gate.tsxindex a005b80d..5b312cbe 100644--- a/src/renderer/components/operator-unlock-gate.tsx+++ b/src/renderer/components/operator-unlock-gate.tsx@@ -6,9 +6,26 @@ import {watchOperatorSession,} from '@renderer/lib/operator-auth'import { transport } from '@renderer/lib/transport'-import { type FormEvent, type ReactNode, useEffect, useState } from 'react'+import { isNasAuthMode } from '@shared/schemas/operator-auth'+import {+ type FormEvent,+ lazy,+ type ReactNode,+ Suspense,+ useEffect,+ useState,+} from 'react'import { useTranslation } from 'react-i18next'+const StorageRecovery =+ __MOTRIX_TARGET__ === 'web'+ ? lazy(() =>+ import('./nas-storage-recovery').then((module) => ({+ default: module.NasStorageRecovery,+ }))+ )+ : () => null+/*** Gates the app on the server (web) build behind operator authentication* (Spec 9). The desktop build talks to the core over IPC and never hits `/rpc`,@@ -22,7 +39,12 @@ export function OperatorUnlockGate({ children }: { children: ReactNode }) {function WebGate({ children }: { children: ReactNode }) {const { t } = useTranslation()const state = useOperatorSession((s) => s.state)- const fnos = useOperatorSession((s) => s.status?.mode === 'fnosGateway')+ const fnos = useOperatorSession((s) => isNasAuthMode(s.status?.mode))+ const synology = useOperatorSession((s) => s.status?.mode === 'synologyDsm')+ const diagnostic = useOperatorSession((s) => s.status?.nasAuthDiagnostic)+ const unavailableRoots = useOperatorSession(+ (s) => s.status?.nasUnavailableDownloadRoots+ )const [token, setToken] = useState('')const [error, setError] = useState(false)const [busy, setBusy] = useState(false)@@ -42,15 +64,38 @@ function WebGate({ children }: { children: ReactNode }) {</Button></div>)+ if (state === 'authenticated' && synology && unavailableRoots?.length)+ return (+ <Suspense fallback={null}>+ <StorageRecovery roots={unavailableRoots} />+ </Suspense>+ )if (state === 'authenticated' || state === 'logging-out')return <>{children}</>if (fnos)return (<div className="flex h-svh flex-col items-center justify-center gap-4 p-6">- <p>{t('operatorUnlock.fnosSessionExpired')}</p>+ <p>{t('operatorUnlock.nasSessionExpired')}</p>+ {diagnostic && (+ <code className="select-text text-xs text-muted-foreground">+ {[+ diagnostic.stage,+ diagnostic.code,+ diagnostic.failure,+ diagnostic.exitCode,+ ]+ .filter((value) => value !== undefined)+ .join(' / ')}+ </code>+ )}<Button onClick={() => window.location.reload()}>{t('applicationMenu.retry')}</Button>+ {synology && (+ <Button variant="outline" onClick={() => window.location.assign('/')}>+ {t('operatorUnlock.openDsm')}+ </Button>+ )}</div>)diff --git a/src/renderer/components/renderer-recovery-notice.tsx b/src/renderer/components/renderer-recovery-notice.tsxindex 281a8daa..205ec340 100644--- a/src/renderer/components/renderer-recovery-notice.tsx+++ b/src/renderer/components/renderer-recovery-notice.tsx@@ -6,7 +6,7 @@ import { transport } from '@renderer/lib/transport'import { cn } from '@renderer/lib/utils'import { Commands } from '@shared/protocol/commands'import type { RendererSession } from '@shared/schemas/renderer-health'-import { useEffect, useState } from 'react'+import { type ReactNode, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'// A session belongs to this document. Remounts and locale changes must not@@ -14,7 +14,7 @@ import { useTranslation } from 'react-i18next'const notifiedSessions = new WeakSet<RendererSession>()/** Mount the host before publishing recovery feedback to its toast manager. */-export function RendererToaster() {+export function RendererToaster({ children }: { children?: ReactNode }) {const { t } = useTranslation()useEffect(() => {@@ -35,7 +35,7 @@ export function RendererToaster() {return () => document.removeEventListener('visibilitychange', notify)}, [t])- return <Toaster />+ return <Toaster>{children}</Toaster>}/** Submission uncertainty stays beside the form until explicitly dismissed. */diff --git a/src/renderer/components/ui/toast.tsx b/src/renderer/components/ui/toast.tsxindex fb70a67f..44f8821e 100644--- a/src/renderer/components/ui/toast.tsx+++ b/src/renderer/components/ui/toast.tsx@@ -15,6 +15,7 @@ import type {IdentityTriState,PairRequestPayload,} from '@shared/protocol/bridge'+import type { ReactNode } from 'react'import { useTranslation } from 'react-i18next'export type AppToastType = 'success' | 'info' | 'warning' | 'error'@@ -187,103 +188,9 @@ function ToastList() {)}- const copy = pairRequestCopy(pairRequest, t)- const identityMeta = IDENTITY_BADGE_META[pairRequest.identity]- const isUnverified = pairRequest.identity === 'unverified'return (<Toast.Root key={item.id} toast={item} className={rootClassName}>- <div className="flex min-w-0 flex-1 flex-col gap-1.5 wrap-anywhere">- <div className="flex items-center gap-1.5">- {isUnverified && (- <SEVERITY_ICONS.warning.icon- className={cn(- 'size-3.5 shrink-0',- SEVERITY_ICONS.warning.iconClassName- )}- aria-hidden="true"- />- )}- <Badge- variant={identityMeta.badgeVariant}- className="rounded text-[10px]"- >- {t(identityMeta.labelKey)}- </Badge>- </div>- <Toast.Title className="text-sm font-medium">- {copy.title}- </Toast.Title>- {/* Raw id, not the self-reported name (§5) — same font-mono- * truncate treatment as the trusted-extensions table. */}- <Toast.Description className="truncate font-mono text-[11px] text-muted-foreground">- {copy.description}- </Toast.Description>- {pairRequest.accountName && (- <p className="text-xs font-medium wrap-anywhere">- {t('settings.integration.browser.pairToast.account', {- name: pairRequest.accountName,- })}- </p>- )}- {isUnverified && (- <p className="text-xs text-amber-700 dark:text-amber-400">- {t(- 'settings.integration.browser.pairToast.identityUnverifiedWarning'- )}- </p>- )}- {pairRequest.kind === 'extension-claim' ? (- <div className="mt-1 flex flex-col items-start gap-2">- <p className="text-xs text-muted-foreground">- {t('settings.integration.browser.pairToast.claimDesc')}- </p>- <Button- type="button"- size="xs"- onClick={pairRequest.onClaim}- disabled={pairRequest.claiming || !pairRequest.accountName}- aria-busy={pairRequest.claiming}- >- {t('settings.integration.browser.pairToast.claim')}- </Button>- </div>- ) : (- <div className="mt-1 flex flex-col gap-1 rounded border border-border bg-muted/30 px-2 py-1.5">- <div className="flex items-center justify-between">- <span className="text-[10px] tracking-wide text-muted-foreground uppercase">- {t('settings.integration.browser.pairToast.pairCode')}- </span>- <CopyButton- content={pairRequest.code}- size="xs"- variant="ghost"- aria-label={t(- 'settings.integration.browser.pairToast.copyCode'- )}- className="-my-0.5 -me-1 size-6 p-0 text-muted-foreground hover:text-foreground"- />- </div>- {/* The §7.1 PAKE password, rendered verbatim — never- * reformatted and never logged (§7.1/§11). */}- <span className="text-center font-mono text-base font-semibold tracking-widest">- {pairRequest.code}- </span>- <span className="text-[11px] text-muted-foreground">- {t('settings.integration.browser.pairToast.pairCodeHint')}- </span>- </div>- )}- <div className="mt-1.5 flex gap-2">- <Button- type="button"- size="xs"- variant="outline"- onClick={pairRequest.onDeny}- >- {copy.denyLabel}- </Button>- </div>- </div>+ <ExtensionPairRequestContent pairRequest={pairRequest} />{closeButton}</Toast.Root>)@@ -319,7 +226,132 @@ function ToastList() {})}-export function Toaster() {+type ExtensionPrompt = Exclude<+ PairRequestToastData['pairRequest'],+ { kind: 'cli' }+>++/** Both views use this document’s existing prompt and claim callback. A code+ * only becomes available here after this operator explicitly claims it. */+export function usePageExtensionPrompts(accountName: string) {+ const { toasts } = Toast.useToastManager<PairRequestToastData>()+ return toasts.flatMap((item) => {+ const prompt = item.data?.pairRequest+ return item.transitionStatus !== 'ending' &&+ prompt &&+ prompt.kind !== 'cli' &&+ prompt.accountName === accountName+ ? [{ id: item.id, prompt }]+ : []+ })+}++export function ExtensionPairRequestContent({+ pairRequest,+ inline = false,+}: {+ pairRequest: ExtensionPrompt+ inline?: boolean+}) {+ const { t } = useTranslation()+ const copy = pairRequestCopy(pairRequest, t)+ const identityMeta = IDENTITY_BADGE_META[pairRequest.identity]+ const isUnverified = pairRequest.identity === 'unverified'+ const Title = inline ? 'h4' : Toast.Title+ const Description = inline ? 'p' : Toast.Description+ return (+ <div className="flex min-w-0 flex-1 flex-col gap-1.5 wrap-anywhere">+ <div className="flex items-center gap-1.5">+ {isUnverified && (+ <SEVERITY_ICONS.warning.icon+ className={cn(+ 'size-3.5 shrink-0',+ SEVERITY_ICONS.warning.iconClassName+ )}+ aria-hidden="true"+ />+ )}+ <Badge+ variant={identityMeta.badgeVariant}+ className="rounded text-[10px]"+ >+ {t(identityMeta.labelKey)}+ </Badge>+ </div>+ <Title className="text-sm font-medium">{copy.title}</Title>+ {/* Raw id, not the self-reported name (§5) — same font-mono+ * truncate treatment as the trusted-extensions table. */}+ <Description className="truncate font-mono text-[11px] text-muted-foreground">+ {copy.description}+ </Description>+ {pairRequest.accountName && (+ <p className="text-xs font-medium wrap-anywhere">+ {t('settings.integration.browser.pairToast.account', {+ name: pairRequest.accountName,+ })}+ </p>+ )}+ {isUnverified && (+ <p className="text-xs text-amber-700 dark:text-amber-400">+ {t(+ 'settings.integration.browser.pairToast.identityUnverifiedWarning'+ )}+ </p>+ )}+ {pairRequest.kind === 'extension-claim' ? (+ <div className="mt-1 flex flex-col items-start gap-2">+ <p className="text-xs text-muted-foreground">+ {t('settings.integration.browser.pairToast.claimDesc')}+ </p>+ <Button+ type="button"+ size="xs"+ onClick={pairRequest.onClaim}+ disabled={pairRequest.claiming || !pairRequest.accountName}+ aria-busy={pairRequest.claiming}+ >+ {t('settings.integration.browser.pairToast.claim')}+ </Button>+ </div>+ ) : (+ <div className="mt-1 flex flex-col gap-1 rounded border border-border bg-muted/30 px-2 py-1.5">+ <div className="flex items-center justify-between">+ <span className="text-[10px] tracking-wide text-muted-foreground uppercase">+ {t('settings.integration.browser.pairToast.pairCode')}+ </span>+ <CopyButton+ content={pairRequest.code}+ size="xs"+ variant="ghost"+ aria-label={t('settings.integration.browser.pairToast.copyCode')}+ className="-my-0.5 -me-1 size-6 p-0 text-muted-foreground hover:text-foreground"+ />+ </div>+ {/* The §7.1 PAKE password, rendered verbatim — never+ * reformatted and never logged (§7.1/§11). */}+ <span className="text-center font-mono text-base font-semibold tracking-widest">+ {pairRequest.code}+ </span>+ <span className="text-[11px] text-muted-foreground">+ {t('settings.integration.browser.pairToast.pairCodeHint')}+ </span>+ </div>+ )}+ <div className="mt-1.5 flex gap-2">+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={pairRequest.onDeny}+ >+ {copy.denyLabel}+ </Button>+ </div>+ </div>+ )+}++export function Toaster({ children }: { children?: ReactNode }) {const { t } = useTranslation()const avoidDesktopChrome =__MOTRIX_TARGET__ === 'electron' &&@@ -335,6 +367,7 @@ export function Toaster() {// auto-deny. 5 gives enough headroom for a pairing prompt plus a// handful of transient toasts to coexist visibly.<Toast.Provider toastManager={toast} limit={5}>+ {children}<Toast.Portal><Toast.Viewportaria-label={t('notification.center.toastRegionAria')}diff --git a/src/renderer/features/application-menu/web-menu-button.tsx b/src/renderer/features/application-menu/web-menu-button.tsxindex dc9d0f80..2d26c9ce 100644--- a/src/renderer/features/application-menu/web-menu-button.tsx+++ b/src/renderer/features/application-menu/web-menu-button.tsx@@ -1,4 +1,5 @@import { torrentFileErrorKey } from '@shared/lib/engine-torrent'+import { isNasAuthMode } from '@shared/schemas/operator-auth'import './application-menu.css'import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'import { ArrowLeftIcon, ChevronRightIcon } from '@renderer/components/icons'@@ -80,7 +81,7 @@ export function WebMenuButton() {useState<MenuConfirmationRequest | null>(null)const canLogout = useOperatorSession((s) => s.status?.canLogout === true)const username = useOperatorSession((s) =>- s.status?.mode === 'fnosGateway' ? s.status.username : undefined+ isNasAuthMode(s.status?.mode) ? s.status?.username : undefined)const content = useRef<HTMLDivElement>(null)const trigger = useRef<HTMLButtonElement>(null)diff --git a/src/renderer/hooks/use-engine-display-status.test.tsx b/src/renderer/hooks/use-engine-display-status.test.tsxindex 6bb4a1ae..33a50e0b 100644--- a/src/renderer/hooks/use-engine-display-status.test.tsx+++ b/src/renderer/hooks/use-engine-display-status.test.tsx@@ -66,12 +66,13 @@ beforeEach(() => {})})-it('shows the same periodic-update state on both surfaces and restores engine readiness', async () => {+it('keeps the engine tile ready during a brief Web transport renewal', async () => {const { rerender } = render(<Surfaces />)await waitFor(() => expect(screen.getByText('Engine ready')).toBeVisible())health.realtimeConnected = falsererender(<Surfaces />)- expect(screen.getAllByText('Periodic updates')).toHaveLength(2)+ expect(screen.getByText('Ready')).toBeVisible()+ expect(screen.getAllByText('Periodic updates')).toHaveLength(1)expect(screen.queryByText('Engine offline')).not.toBeInTheDocument()health.realtimeConnected = truererender(<Surfaces />)diff --git a/src/renderer/hooks/use-task-activity.test.tsx b/src/renderer/hooks/use-task-activity.test.tsxindex 9efb1f8a..309e34b9 100644--- a/src/renderer/hooks/use-task-activity.test.tsx+++ b/src/renderer/hooks/use-task-activity.test.tsx@@ -285,7 +285,7 @@ describe('useTaskActivity external store', () => {vi.advanceTimersByTime(100)await Promise.resolve()})- expect(hook.result.current.status).toBe('stale')+ expect(hook.result.current.status).toBe('refreshFailed')const sundayRange = paramsForCall(1)const currentSunday = sundayRange.days.at(-7)expect(currentSunday).toBeDefined()@@ -297,8 +297,8 @@ describe('useTaskActivity external store', () => {)expect(transportMock.invoke).toHaveBeenCalledTimes(3)- expect(hook.result.current.status).toBe('stale')- if (hook.result.current.status !== 'stale') return+ expect(hook.result.current.status).toBe('refreshFailed')+ if (hook.result.current.status !== 'refreshFailed') returnexpect(hook.result.current.snapshot).toBe(oldSnapshot)expect(hook.result.current.snapshot.revision).toBe(1)expect(@@ -308,7 +308,7 @@ describe('useTaskActivity external store', () => {).toBe(true)})- it('publishes a fresh stale state when a same-week midnight refresh fails', async () => {+ it('updates the calendar day even if a same-week midnight refresh fails', async () => {vi.useFakeTimers()vi.setSystemTime(new Date(2026, 7, 3, 23, 59, 59, 900))__resetTaskActivityStoreForTests()@@ -327,7 +327,7 @@ describe('useTaskActivity external store', () => {await act(async () => {await Promise.resolve()})- expect(hook.result.current.status).toBe('stale')+ expect(hook.result.current.status).toBe('refreshFailed')const beforeMidnight = hook.result.currentawait act(async () => {@@ -336,7 +336,7 @@ describe('useTaskActivity external store', () => {})expect(transportMock.invoke).toHaveBeenCalledTimes(3)- expect(hook.result.current.status).toBe('stale')+ expect(hook.result.current.status).toBe('refreshFailed')expect(hook.result.current).not.toBe(beforeMidnight)})@@ -370,7 +370,45 @@ describe('useTaskActivity external store', () => {expect(transportMock.invoke).toHaveBeenCalledTimes(2)})- it('distinguishes initial unavailable from cached stale and retries', async () => {+ it.each(['reconnect', 'revision gap'])(+ 'keeps the previous calendar quiet during %s, then recovers after a failed read',+ async (cause) => {+ const refresh = deferred<TaskActivitySnapshot>()+ transportMock.invoke+ .mockImplementationOnce(async (_query, params: GetTaskActivityParams) =>+ makeSnapshot('generation-a', 1, params)+ )+ .mockReturnValueOnce(refresh.promise)+ .mockImplementationOnce(async (_query, params: GetTaskActivityParams) =>+ makeSnapshot('generation-a', 3, params)+ )+ const hook = renderHook(() => useTaskActivity())+ await waitFor(() => expect(hook.result.current.status).toBe('ready'))+ const before = hook.result.current+ act(() => {+ if (cause === 'reconnect') emitConnection()+ else+ emitActivity(+ inserted('generation-a', 3, paramsForCall(0).days[0].fromMs + 1)+ )+ })+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)+ expect(hook.result.current).toBe(before)+ await act(async () => {+ refresh.reject(new Error('refresh failed'))+ })+ expect(hook.result.current.status).toBe('refreshFailed')+ await act(async () => {+ await hook.result.current.retry()+ })+ expect(hook.result.current).toMatchObject({+ status: 'ready',+ snapshot: { revision: 3 },+ })+ }+ )++ it('distinguishes an unavailable first load from a failed refresh with cached data', async () => {transportMock.invoke.mockRejectedValueOnce(new Error('offline')).mockImplementationOnce(async (_query, params: GetTaskActivityParams) =>@@ -392,8 +430,10 @@ describe('useTaskActivity external store', () => {: undefinedact(() => window.dispatchEvent(new Event('focus')))- await waitFor(() => expect(hook.result.current.status).toBe('stale'))- if (hook.result.current.status !== 'stale') return+ await waitFor(() =>+ expect(hook.result.current.status).toBe('refreshFailed')+ )+ if (hook.result.current.status !== 'refreshFailed') returnexpect(hook.result.current.snapshot).toBe(readySnapshot)expect(hook.result.current.retry).toBe(retry)})diff --git a/src/renderer/hooks/use-task-activity.ts b/src/renderer/hooks/use-task-activity.tsindex c5fcc779..96c7156f 100644--- a/src/renderer/hooks/use-task-activity.ts+++ b/src/renderer/hooks/use-task-activity.ts@@ -23,12 +23,7 @@ type StoreListener = () => voidexport type TaskActivityState =| { status: 'loading'; retry: () => Promise<void> }| {- status: 'ready'- snapshot: TaskActivitySnapshot- retry: () => Promise<void>- }- | {- status: 'stale'+ status: 'ready' | 'refreshFailed'snapshot: TaskActivitySnapshotretry: () => Promise<void>}@@ -82,7 +77,10 @@ function publish(next: TaskActivityState, force = false): void {notify()}-function publishFromSnapshot(status: 'ready' | 'stale', force = false): void {+function publishFromSnapshot(+ status: 'ready' | 'refreshFailed',+ force = false+): void {if (!activitySnapshot) returnpublish({ status, snapshot: activitySnapshot, retry }, force)}@@ -116,13 +114,19 @@ function refreshRange(now = new Date()): boolean {if (next.signature === rangeEnvironment.signature) return falserangeEnvironment = nextrangeEpoch += 1- // A snapshot is meaningful only for the range that produced it. Even when- // an already-stale fetch fails across midnight, publish a fresh state- // identity so the calendar recomputes today/future presentation.- if (activitySnapshot) publishFromSnapshot('stale', true)+ republishCalendarDay()return true}+// Re-render today/future cells at midnight without changing the outcome of+// the last fetch while the new calendar range is being reconciled.+function republishCalendarDay(): void {+ publishFromSnapshot(+ state.status === 'refreshFailed' ? 'refreshFailed' : 'ready',+ true+ )+}+function scheduleMidnight(): void {if (midnightTimer !== null) clearTimeout(midnightTimer)const now = new Date()@@ -137,7 +141,7 @@ function scheduleMidnight(): void {if (!rangeChanged && activitySnapshot) {// The 53-week request range changes only on Sunday, but the Canvas// model's today/future state changes at every local midnight.- publishFromSnapshot('stale', true)+ republishCalendarDay()}scheduleMidnight()void requestSnapshot('authoritative')@@ -228,10 +232,6 @@ function applyContiguousEvent(payload: TaskActivityUpdatedPayload): boolean {return true}-function markDirty(): void {- if (pendingRequest) trailingRequested = true-}-function processEvent(payload: TaskActivityUpdatedPayload): void {const current = activitySnapshotif (@@ -242,20 +242,15 @@ function processEvent(payload: TaskActivityUpdatedPayload): void {return}- markDirty()- if (current) publishFromSnapshot('stale')- if (!pendingRequest) void requestSnapshot()+ void requestSnapshot()}function queueEvent(payload: TaskActivityUpdatedPayload): void {- if (queueOverflowed) {- markDirty()- return- }+ if (queueOverflowed) returnif (queuedEvents.length >= MAX_QUEUED_EVENTS) {queuedEvents = []queueOverflowed = true- markDirty()+ trailingRequested = truereturn}queuedEvents.push(payload)@@ -274,7 +269,7 @@ function drainQueuedEvents(): void {if (queueOverflowed) {queuedEvents = []queueOverflowed = false- markDirty()+ trailingRequested = truereturn}if (queuedEvents.length === 0) return@@ -289,11 +284,11 @@ function drainQueuedEvents(): void {for (const payload of matching) {if (!applyContiguousEvent(payload)) {- markDirty()+ trailingRequested = truebreak}}- if (hasOtherGeneration) markDirty()+ if (hasOtherGeneration) trailingRequested = true}// Detach and replacement both clear `pendingRequest`, so request identity@@ -316,7 +311,7 @@ function requestSnapshot(reason === 'authoritative' ||pendingRequest.rangeEpoch !== rangeEpoch) {- markDirty()+ trailingRequested = true}return pendingRequest.promise}@@ -324,8 +319,8 @@ function requestSnapshot(const capturedRangeEpoch = rangeEpochconst capturedRangeSignature = rangeEnvironment.signatureconst params = rangeEnvironment.params- if (activitySnapshot) publishFromSnapshot('stale')- else publish({ status: 'loading', retry })+ // Keep the cached calendar visible while automatic reconciliation runs.+ if (!activitySnapshot) publish({ status: 'loading', retry })let request!: PendingRequestconst work = transport@@ -337,7 +332,7 @@ function requestSnapshot(activitySnapshot?.generation === incoming.generation &&incoming.revision < activitySnapshot.revision) {- markDirty()+ trailingRequested = truereturn}activitySnapshot = incoming@@ -347,7 +342,7 @@ function requestSnapshot(}).catch(() => {if (!canPublish(request)) return- if (activitySnapshot) publishFromSnapshot('stale')+ if (activitySnapshot) publishFromSnapshot('refreshFailed')else publish({ status: 'unavailable', retry })drainQueuedEvents()})diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsxindex 5bb2bad8..336c5c2d 100644--- a/src/renderer/layouts/app-layout.tsx+++ b/src/renderer/layouts/app-layout.tsx@@ -88,83 +88,84 @@ export function AppLayout() {return (<TooltipProvider>- <PlatformServicesProvider services={platformServices}>- {__MOTRIX_TARGET__ === 'web' && <FnosEntry />}- {/* Unconditional bg-sidebar: below the md breakpoint the Sidebar+ <RendererToaster>+ <PlatformServicesProvider services={platformServices}>+ {__MOTRIX_TARGET__ === 'web' && <FnosEntry />}+ {/* Unconditional bg-sidebar: below the md breakpoint the Sidebarrenders as a portaled Sheet without data-variant="inset", so thewrapper's built-in has-data-[variant=inset]:bg-sidebar stopsmatching and transparent-inset pages would fall through to thewhite body background. */}- <SidebarProvider- className={cn(- 'h-svh overflow-hidden bg-sidebar',- __MOTRIX_TARGET__ === 'web' && 'web-window-chrome',- __MOTRIX_TARGET__ === 'electron' && 'electron-window-chrome',- __MOTRIX_TARGET__ === 'electron' &&- __MOTRIX_PREVIEW_MAC_MENU__ &&- 'preview-desktop-window-controls'- )}- >- <WindowChrome- variant="overlay"- leading={<MotrixMenuButton />}- previewDesktopControls={__MOTRIX_PREVIEW_MAC_MENU__}- >- <div className="flex items-center gap-1.5">- <SidebarTriggerButton />- <AddTaskTriggerButton />- </div>- </WindowChrome>- <AppSidebar />- <SidebarInset+ <SidebarProviderclassName={cn(- 'min-h-0 overflow-hidden bg-sidebar-inset',- // Keep the inset card look below the md breakpoint too —- // upstream gates these behind md:peer-data-[variant=inset]:,- // which stops matching once the sidebar renders as a Sheet.- // At md+ the built-in ms-0 / collapsed ms-2 still win over- // m-2 (Tailwind orders ms-* after m-*).- 'm-2 rounded-xl shadow-sm',- // Suppress BOTH shadow forms: tailwind-merge only collapses- // identical-modifier classes, so a bare shadow-none would- // leave the component's built-in- // md:peer-data-[variant=inset]:shadow-sm alive at md+.- transparentInset &&- 'bg-transparent shadow-none md:peer-data-[variant=inset]:shadow-none'+ 'h-svh overflow-hidden bg-sidebar',+ __MOTRIX_TARGET__ === 'web' && 'web-window-chrome',+ __MOTRIX_TARGET__ === 'electron' && 'electron-window-chrome',+ __MOTRIX_TARGET__ === 'electron' &&+ __MOTRIX_PREVIEW_MAC_MENU__ &&+ 'preview-desktop-window-controls')}>- <RendererSubmissionNotice- className="mx-4 mb-2 mt-12"- onOpenDownloads={() => void navigate('/downloads/all')}- />- <div className="min-h-0 flex-1 overflow-hidden">- <div hidden={!migrationActive} className="h-full min-h-0">- <MigrationPage active={migrationActive} />- </div>- <div hidden={!settingsActive} className="h-full min-h-0">- {retainedSettings.current}+ <WindowChrome+ variant="overlay"+ leading={<MotrixMenuButton />}+ previewDesktopControls={__MOTRIX_PREVIEW_MAC_MENU__}+ >+ <div className="flex items-center gap-1.5">+ <SidebarTriggerButton />+ <AddTaskTriggerButton /></div>- <div- hidden={migrationActive || settingsActive}- className="h-full min-h-0"- >- {!settingsActive && outlet}+ </WindowChrome>+ <AppSidebar />+ <SidebarInset+ className={cn(+ 'min-h-0 overflow-hidden bg-sidebar-inset',+ // Keep the inset card look below the md breakpoint too —+ // upstream gates these behind md:peer-data-[variant=inset]:,+ // which stops matching once the sidebar renders as a Sheet.+ // At md+ the built-in ms-0 / collapsed ms-2 still win over+ // m-2 (Tailwind orders ms-* after m-*).+ 'm-2 rounded-xl shadow-sm',+ // Suppress BOTH shadow forms: tailwind-merge only collapses+ // identical-modifier classes, so a bare shadow-none would+ // leave the component's built-in+ // md:peer-data-[variant=inset]:shadow-sm alive at md+.+ transparentInset &&+ 'bg-transparent shadow-none md:peer-data-[variant=inset]:shadow-none'+ )}+ >+ <RendererSubmissionNotice+ className="mx-4 mb-2 mt-12"+ onOpenDownloads={() => void navigate('/downloads/all')}+ />+ <div className="min-h-0 flex-1 overflow-hidden">+ <div hidden={!migrationActive} className="h-full min-h-0">+ <MigrationPage active={migrationActive} />+ </div>+ <div hidden={!settingsActive} className="h-full min-h-0">+ {retainedSettings.current}+ </div>+ <div+ hidden={migrationActive || settingsActive}+ className="h-full min-h-0"+ >+ {!settingsActive && outlet}+ </div></div>- </div>- <WebConnectionNotice />- </SidebarInset>- </SidebarProvider>- {__MOTRIX_TARGET__ === 'electron' && <DesktopMenuContext />}- <MenuNavigationFocus />- <RemoveTasksDialogHost />- <RedownloadOverwriteDialogHost />- <RetryParametersDialogHost />- <OperationDialogHost />- <EngineDiagnosticsDialogHost />- {__MOTRIX_TARGET__ === 'web' && <AddTaskDialogHost />}- {__MOTRIX_TARGET__ === 'web' && <WindowTorrentDrop />}- </PlatformServicesProvider>- <RendererToaster />+ <WebConnectionNotice />+ </SidebarInset>+ </SidebarProvider>+ {__MOTRIX_TARGET__ === 'electron' && <DesktopMenuContext />}+ <MenuNavigationFocus />+ <RemoveTasksDialogHost />+ <RedownloadOverwriteDialogHost />+ <RetryParametersDialogHost />+ <OperationDialogHost />+ <EngineDiagnosticsDialogHost />+ {__MOTRIX_TARGET__ === 'web' && <AddTaskDialogHost />}+ {__MOTRIX_TARGET__ === 'web' && <WindowTorrentDrop />}+ </PlatformServicesProvider>+ </RendererToaster></TooltipProvider>)}diff --git a/src/renderer/lib/operator-auth.ts b/src/renderer/lib/operator-auth.tsindex 3160deea..d3091ab8 100644--- a/src/renderer/lib/operator-auth.ts+++ b/src/renderer/lib/operator-auth.ts@@ -1,4 +1,5 @@import {+ isNasAuthMode,type OperatorStatus,operatorStatusSchema,} from '@shared/schemas/operator-auth'@@ -36,7 +37,9 @@ function locked(): void {useOperatorSession.setState((s) => ({state: 'locked',status:- s.status?.mode === 'fnosGateway' ? { ...s.status, authed: false } : null,+ s.status && isNasAuthMode(s.status.mode)+ ? { ...s.status, authed: false }+ : null,epoch: s.epoch + 1,}))for (const reset of resetters) {@@ -66,7 +69,7 @@ export async function refreshOperatorSession(})if ((res.status === 401 || res.status === 403) &&- useOperatorSession.getState().status?.mode === 'fnosGateway'+ isNasAuthMode(useOperatorSession.getState().status?.mode)) {if (request === statusRequest &&@@ -82,8 +85,10 @@ export async function refreshOperatorSession(expectedEpoch !== useOperatorSession.getState().epoch)return- if (!status.authed) locked()- else useOperatorSession.setState({ state: 'authenticated', status })+ if (!status.authed) {+ useOperatorSession.setState({ status })+ locked()+ } else useOperatorSession.setState({ state: 'authenticated', status })} catch {if (request !== statusRequest ||@@ -109,7 +114,7 @@ export function watchOperatorSession(): () => void {window.addEventListener('focus', check)document.addEventListener('visibilitychange', check)const timer = window.setInterval(() => {- if (useOperatorSession.getState().status?.mode === 'fnosGateway') check()+ if (isNasAuthMode(useOperatorSession.getState().status?.mode)) check()}, 30_000)return () => {window.clearInterval(timer)diff --git a/src/renderer/lib/transport/http-ws-fnos.test.ts b/src/renderer/lib/transport/http-ws-fnos.test.tsindex b9f61bfb..42458bc5 100644--- a/src/renderer/lib/transport/http-ws-fnos.test.ts+++ b/src/renderer/lib/transport/http-ws-fnos.test.ts@@ -6,7 +6,7 @@ import {FNOS_EVENT_TICKET_PREFIX,WEB_ORIGIN_HEADER,} from '@shared/schemas/operator-auth'-import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { HttpWsTransport } from './http-ws'class Socket {@@ -25,71 +25,127 @@ class Socket {for (const listener of this.listeners.get('close') ?? [])listener(new Event('close'))}+ receive(data: unknown) {+ for (const listener of this.listeners.get('message') ?? [])+ listener(new MessageEvent('message', { data: JSON.stringify(data) }))+ }}-beforeEach(() => {- Socket.opened = []- useOperatorSession.setState({- state: 'authenticated',- status: { authed: true, mode: 'fnosGateway', canLogout: false },- })-})-afterEach(() => {- useOperatorSession.setState({ state: 'locked' })- vi.unstubAllGlobals()-})+describe.each(['fnosGateway', 'synologyDsm'] as const)(+ '%s transport',+ (mode) => {+ const base =+ mode === 'fnosGateway'+ ? 'http://nas.local:5666/app/motrix'+ : 'http://nas.local:5000/motrix'+ beforeEach(() => {+ Socket.opened = []+ useOperatorSession.setState({+ state: 'authenticated',+ status: { authed: true, mode, canLogout: false },+ })+ })+ afterEach(() => {+ useOperatorSession.setState({ state: 'locked' })+ vi.unstubAllGlobals()+ })-it('marks fnOS HTTP calls with their actual browser origin', async () => {- const fetch = vi.fn().mockResolvedValue(new Response('{}'))- const transport = new HttpWsTransport('http://nas.local:5666/app/motrix', {- fetch,- })- await transport.invoke(Commands.PauseTask, 'task')- expect(fetch.mock.calls[0][1].headers[WEB_ORIGIN_HEADER]).toBe(- location.origin- )-})-it('gets one fresh ticket before connecting and never includes it in the URL', async () => {- const ticket = 'a'.repeat(32)- const fetch = vi- .fn()- .mockResolvedValue(new Response(JSON.stringify({ ticket })))- const transport = new HttpWsTransport('http://nas.local:5666/app/motrix', {- fetch,- WebSocketCtor: Socket as unknown as typeof WebSocket,- })- const callback = vi.fn()- transport.on(Events.TaskUpdated, callback)- transport.on(Events.EngineStateChanged, callback)- await vi.waitFor(() => expect(Socket.opened).toHaveLength(1))- expect(fetch).toHaveBeenCalledOnce()- expect(fetch.mock.calls[0][0]).toBe(- 'http://nas.local:5666/app/motrix/rpc/auth/event-ticket'- )- expect(Socket.opened[0].url).toBe('ws://nas.local:5666/app/motrix/rpc/events')- expect(Socket.opened[0].protocols).toEqual([- FNOS_EVENT_PROTOCOL,- `${FNOS_EVENT_TICKET_PREFIX}${ticket}`,- ])- transport.off(Events.TaskUpdated, callback)- transport.off(Events.EngineStateChanged, callback)-})-it('discards late tickets after the last listener unsubscribes', async () => {- let complete!: (response: Response) => void- const fetch = vi.fn().mockImplementation(- () =>- new Promise<Response>((resolve) => {- complete = resolve+ it('marks NAS HTTP calls with their actual browser origin', async () => {+ const fetch = vi.fn().mockResolvedValue(new Response('{}'))+ const transport = new HttpWsTransport(base, {+ fetch,+ })+ await transport.invoke(Commands.PauseTask, 'task')+ expect(fetch.mock.calls[0][1].headers[WEB_ORIGIN_HEADER]).toBe(+ location.origin+ )+ })+ it('gets one fresh ticket before connecting and never includes it in the URL', async () => {+ const ticket = 'a'.repeat(32)+ const fetch = vi+ .fn()+ .mockResolvedValue(new Response(JSON.stringify({ ticket })))+ const transport = new HttpWsTransport(base, {+ fetch,+ WebSocketCtor: Socket as unknown as typeof WebSocket,})- )- const transport = new HttpWsTransport('http://nas.local:5666/app/motrix', {- fetch,- WebSocketCtor: Socket as unknown as typeof WebSocket,- })- const callback = vi.fn()- transport.on(Events.TaskUpdated, callback)- transport.off(Events.TaskUpdated, callback)- expect(fetch.mock.calls[0][1].signal.aborted).toBe(true)- complete(new Response(JSON.stringify({ ticket: 'b'.repeat(32) })))- await new Promise((resolve) => setTimeout(resolve, 0))- expect(Socket.opened).toHaveLength(0)-})+ const callback = vi.fn()+ transport.on(Events.TaskUpdated, callback)+ transport.on(Events.EngineStateChanged, callback)+ await vi.waitFor(() => expect(Socket.opened).toHaveLength(1))+ expect(fetch).toHaveBeenCalledOnce()+ expect(fetch.mock.calls[0][0]).toBe(`${base}/rpc/auth/event-ticket`)+ expect(Socket.opened[0].url).toBe(+ `${base.replace('http:', 'ws:')}/rpc/events`+ )+ expect(Socket.opened[0].protocols).toEqual([+ FNOS_EVENT_PROTOCOL,+ `${FNOS_EVENT_TICKET_PREFIX}${ticket}`,+ ])+ transport.off(Events.TaskUpdated, callback)+ transport.off(Events.EngineStateChanged, callback)+ })+ it('discards late tickets after the last listener unsubscribes', async () => {+ let complete!: (response: Response) => void+ const fetch = vi.fn().mockImplementation(+ () =>+ new Promise<Response>((resolve) => {+ complete = resolve+ })+ )+ const transport = new HttpWsTransport(base, {+ fetch,+ WebSocketCtor: Socket as unknown as typeof WebSocket,+ })+ const callback = vi.fn()+ transport.on(Events.TaskUpdated, callback)+ transport.off(Events.TaskUpdated, callback)+ expect(fetch.mock.calls[0][1].signal.aborted).toBe(true)+ complete(new Response(JSON.stringify({ ticket: 'b'.repeat(32) })))+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(Socket.opened).toHaveLength(0)+ })+ it('renews DSM authority on the existing connection and still delivers events', async () => {+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ ticket: 'a'.repeat(32) }))+ )+ .mockResolvedValueOnce(new Response(null, { status: 204 }))+ const transport = new HttpWsTransport(base, {+ fetch,+ WebSocketCtor: Socket as unknown as typeof WebSocket,+ })+ const task = vi.fn()+ transport.on(Events.TaskUpdated, task)+ await vi.waitFor(() => expect(Socket.opened).toHaveLength(1))+ const socket = Socket.opened[0]+ for (const listener of socket.listeners.get('open') ?? [])+ listener(new Event('open'))+ const renewal = {+ type: 'session-renewal',+ version: 1,+ challenge: 'b'.repeat(32),+ }+ socket.receive(renewal)+ if (mode === 'synologyDsm') {+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2))+ expect(fetch.mock.calls[1]).toEqual([+ `${base}/rpc/auth/event-renew`,+ expect.objectContaining({+ method: 'POST',+ credentials: 'same-origin',+ headers: expect.objectContaining({+ [WEB_ORIGIN_HEADER]: location.origin,+ }),+ body: JSON.stringify(renewal),+ }),+ ])+ } else expect(fetch).toHaveBeenCalledTimes(1)+ socket.receive({ channel: Events.TaskUpdated, args: ['after renewal'] })+ expect(task).toHaveBeenCalledWith('after renewal')+ expect(transport.getConnectionState()).toBe('connected')+ expect(Socket.opened).toEqual([socket])+ transport.off(Events.TaskUpdated, task)+ })+ }+)diff --git a/src/renderer/lib/transport/http-ws.ts b/src/renderer/lib/transport/http-ws.tsindex b044c977..d8147c92 100644--- a/src/renderer/lib/transport/http-ws.ts+++ b/src/renderer/lib/transport/http-ws.ts@@ -3,6 +3,7 @@ import {useOperatorSession,} from '@renderer/lib/operator-auth'import { fnosFileAction, isFnos } from '@renderer/platform/fnos'+import { isSynology, synologyFileAction } from '@renderer/platform/nas'import { ErrorCode } from '@shared/errors'import { BridgeCommands, BridgeQueries } from '@shared/protocol/bridge'import { Commands } from '@shared/protocol/commands'@@ -18,12 +19,15 @@ import {FNOS_EVENT_PROTOCOL,FNOS_EVENT_TICKET_PREFIX,fnosEventTicketSchema,+ isNasAuthMode,} from '@shared/schemas/operator-auth'import {WEB_EVENT_CONNECT_TIMEOUT_MS,WEB_EVENT_STALE_MS,+ type WebEventRenewal,webEventFrameSchema,webEventHeartbeatSchema,+ webEventRenewalSchema,} from '@shared/schemas/web-event-stream'import { webOriginHeaders } from '../web-base-url'import type {@@ -116,6 +120,17 @@ export class HttpWsTransport implements Transport {const session = useOperatorSession.getState()if (session.state === 'locked' || session.state === 'logging-out')throw new Error('Operator session is locked')+ if (+ isSynology() &&+ session.status?.nasCapabilities?.fileActions &&+ (channel === Commands.OpenTaskFile || channel === Commands.RevealInFolder)+ ) {+ const { taskId } = openTaskFilePayloadSchema.parse(args[0])+ return synologyFileAction(+ taskId,+ channel === Commands.OpenTaskFile ? 'open' : 'reveal'+ )+ }if (isFnos() &&(channel === Commands.OpenTaskFile || channel === Commands.RevealInFolder)@@ -134,7 +149,7 @@ export class HttpWsTransport implements Transport {method: 'POST',headers: {'content-type': 'application/json',- ...(isFnos() ? webOriginHeaders() : {}),+ ...(isNasAuthMode(session.status?.mode) ? webOriginHeaders() : {}),},// Send the operator session cookie (Spec 9). Same-origin is the fetch// default, but set it explicitly so the control-plane auth is obvious.@@ -208,7 +223,7 @@ export class HttpWsTransport implements Transport {return}- if (isFnos()) {+ if (isNasAuthMode(useOperatorSession.getState().status?.mode)) {const pending = new AbortController()this.fnosTicketRequest = pendingconst sessionEpoch = useOperatorSession.getState().epoch@@ -279,6 +294,37 @@ export class HttpWsTransport implements Transport {)this.publishConnectionState('connecting')+ const lifetime = new AbortController()+ let renewing = false+ const renew = async (frame: WebEventRenewal) => {+ if (renewing) return+ renewing = true+ const session = useOperatorSession.getState()+ try {+ const res = await this.fetchFn(`${this.baseUrl}/rpc/auth/event-renew`, {+ method: 'POST',+ credentials: 'same-origin',+ headers: {+ ...webOriginHeaders(),+ 'content-type': 'application/json',+ },+ body: JSON.stringify(frame),+ signal: AbortSignal.any([+ lifetime.signal,+ AbortSignal.timeout(12_000),+ ]),+ })+ if (!this.isCurrentSocket(socket, epoch)) return+ if (res.status === 401 || res.status === 403)+ void refreshOperatorSession(session.epoch)+ if (!res.ok) this.retireSocket(socket, epoch)+ } catch {+ this.retireSocket(socket, epoch)+ } finally {+ renewing = false+ }+ }+socket.addEventListener('open', () => {if (!this.isCurrentSocket(socket, epoch)) returnthis.clearDeadline()@@ -294,6 +340,14 @@ export class HttpWsTransport implements Transport {this.receivedMessage(socket, epoch)return}+ if (useOperatorSession.getState().status?.mode === 'synologyDsm') {+ const renewal = webEventRenewalSchema.safeParse(data)+ if (renewal.success) {+ this.receivedMessage(socket, epoch)+ void renew(renewal.data)+ return+ }+ }const parsed = webEventFrameSchema.safeParse(data)if (!parsed.success) returnthis.receivedMessage(socket, epoch)@@ -312,6 +366,7 @@ export class HttpWsTransport implements Transport {}})socket.addEventListener('close', () => {+ lifetime.abort()if (!this.isCurrentSocket(socket, epoch)) returnthis.clearDeadline()this.socket = nulldiff --git a/src/renderer/platform/fnos.ts b/src/renderer/platform/fnos.tsindex 923bc89e..d744d807 100644--- a/src/renderer/platform/fnos.ts+++ b/src/renderer/platform/fnos.ts@@ -5,8 +5,8 @@ import { z } from 'zod'export const isFnos = () =>useOperatorSession.getState().status?.mode === 'fnosGateway'-export const hasHostFileActions = () =>- __MOTRIX_TARGET__ === 'electron' || isFnos()+export { hasHostFileActions } from './nas'+let instance: Promise<TrimApp> | undefinedexport function fnosSdk(): Promise<TrimApp> {instance ??=diff --git a/src/renderer/platform/nas.test.ts b/src/renderer/platform/nas.test.tsnew file mode 100644index 00000000..547712ca--- /dev/null+++ b/src/renderer/platform/nas.test.ts@@ -0,0 +1,70 @@+import '@renderer/lib/i18n'+import { useOperatorSession } from '@renderer/lib/operator-auth'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { synologyFileAction } from './nas'++const fetchMock = vi.fn()+beforeEach(() => {+ vi.stubGlobal('fetch', fetchMock)+ fetchMock.mockReset()+ useOperatorSession.setState({+ state: 'authenticated',+ status: {+ authed: true,+ mode: 'synologyDsm',+ canLogout: false,+ nasCapabilities: {+ settings: true,+ fileActions: true,+ torrentPicker: true,+ clientGateway: true,+ },+ },+ })+})+afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it('opens File Station only after the task-scoped backend check and clears the opener', async () => {+ const popup = { opener: {}, location: { replace: vi.fn() }, close: vi.fn() }+ vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window)+ const url =+ '/?launchApp=SYNO.SDS.App.FileStation3.Instance&launchParam=openfile%3D%252Fmotrix%252F'+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ kind: 'file-manager', url }))+ )+ await synologyFileAction('task-123', 'reveal')+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({+ taskId: 'task-123',+ action: 'reveal',+ })+ expect(popup.opener).toBeNull()+ expect(popup.location.replace).toHaveBeenCalledExactlyOnceWith(+ `${location.origin}${url}`+ )+})++it.each(['/motrix/api/nas/tasks/other-task/file', '//outside.test/file'])(+ 'rejects a substituted download target: %s',+ async (url) => {+ const click = vi+ .spyOn(HTMLAnchorElement.prototype, 'click')+ .mockImplementation(() => {})+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ kind: 'download', url }))+ )+ await expect(synologyFileAction('task-123', 'open')).rejects.toThrow()+ expect(click).not.toHaveBeenCalled()+ }+)++it('closes the preopened window when permissions have changed', async () => {+ const popup = { opener: {}, location: { replace: vi.fn() }, close: vi.fn() }+ vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window)+ fetchMock.mockResolvedValue(new Response('', { status: 403 }))+ await expect(synologyFileAction('task-123', 'reveal')).rejects.toThrow()+ expect(popup.close).toHaveBeenCalledOnce()+ expect(popup.location.replace).not.toHaveBeenCalled()+})diff --git a/src/renderer/platform/nas.ts b/src/renderer/platform/nas.tsnew file mode 100644index 00000000..aa5a9b8f--- /dev/null+++ b/src/renderer/platform/nas.ts@@ -0,0 +1,96 @@+import { i18n } from '@renderer/lib/i18n'+import { useOperatorSession } from '@renderer/lib/operator-auth'+import { webBaseUrl, webOriginHeaders } from '@renderer/lib/web-base-url'+import {+ NAS_FILE_API,+ nasFileActionResultSchema,+} from '@shared/schemas/nas-files'++export const isSynology = () =>+ useOperatorSession.getState().status?.mode === 'synologyDsm'+export const hasHostFileActions = () =>+ __MOTRIX_TARGET__ === 'electron' ||+ useOperatorSession.getState().status?.mode === 'fnosGateway' ||+ useOperatorSession.getState().status?.nasCapabilities?.fileActions === true+export const hasNasTorrentPicker = () =>+ useOperatorSession.getState().status?.mode === 'fnosGateway' ||+ useOperatorSession.getState().status?.nasCapabilities?.torrentPicker === true+export const hostOpenFileLabelKey = () =>+ isSynology()+ ? 'panel.downloads.action.downloadToDevice'+ : 'panel.downloads.action.openFile'+export const hostRevealFolderLabelKey = () =>+ isSynology()+ ? 'panel.downloads.action.revealInFileStation'+ : 'panel.downloads.action.openFolder'++export async function nasRequest(+ route: 'task-action' | 'torrent',+ body: object+): Promise<Response> {+ const prefix =+ useOperatorSession.getState().status?.mode === 'fnosGateway'+ ? '/api/fnos'+ : NAS_FILE_API+ const response = await fetch(`${webBaseUrl()}${prefix}/${route}`, {+ method: 'POST',+ credentials: 'same-origin',+ headers: { 'content-type': 'application/json', ...webOriginHeaders() },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(15000),+ })+ if (!response.ok) throw new Error('NAS file request rejected')+ return response+}++export async function synologyFileAction(+ taskId: string,+ action: 'open' | 'reveal'+): Promise<void> {+ const popup =+ action === 'reveal' ? window.open('about:blank', '_blank') : null+ if (action === 'reveal' && !popup)+ throw new Error(i18n.t('panel.downloads.action.fileStationWindowBlocked'))+ if (popup) popup.opener = null+ try {+ const result = nasFileActionResultSchema.parse(+ await (await nasRequest('task-action', { taskId, action })).json()+ )+ const url = new URL(result.url, location.origin)+ if (+ url.origin !== location.origin ||+ url.username ||+ url.password ||+ url.hash+ )+ throw new Error('Invalid NAS file target')+ if (action === 'reveal') {+ if (+ result.kind !== 'file-manager' ||+ url.pathname !== '/' ||+ url.searchParams.get('launchApp') !==+ 'SYNO.SDS.App.FileStation3.Instance'+ )+ throw new Error('Invalid File Station target')+ popup?.location.replace(url.href)+ } else {+ if (+ result.kind !== 'download' ||+ url.pathname !==+ `/motrix${NAS_FILE_API}/tasks/${encodeURIComponent(taskId)}/file` ||+ url.search+ )+ throw new Error('Invalid download target')+ const link = document.createElement('a')+ link.href = url.href+ link.download = ''+ link.rel = 'noopener noreferrer'+ document.body.append(link)+ link.click()+ link.remove()+ }+ } catch {+ popup?.close()+ throw new Error(i18n.t('panel.downloads.action.nasFileUnavailable'))+ }+}diff --git a/src/renderer/platform/web-services.ts b/src/renderer/platform/web-services.tsindex 2c6e852a..ff42e28f 100644--- a/src/renderer/platform/web-services.ts+++ b/src/renderer/platform/web-services.ts@@ -1,7 +1,9 @@import { toast } from '@renderer/components/ui/toast'import { i18n } from '@renderer/lib/i18n'+import { useOperatorSession } from '@renderer/lib/operator-auth'import { webBaseUrl, webOriginHeaders } from '@renderer/lib/web-base-url'import type { FilePickerOptions } from '@shared/schemas/file-picker'+import { isNasAuthMode } from '@shared/schemas/operator-auth'import { isFnos, pickFnosDirectory } from './fnos'import type { PlatformServices } from './services'@@ -96,7 +98,9 @@ export function createWebServices(method: 'POST',credentials: 'same-origin',headers: {- ...(isFnos() ? webOriginHeaders() : {}),+ ...(isNasAuthMode(useOperatorSession.getState().status?.mode)+ ? webOriginHeaders()+ : {}),'content-type': 'application/vnd.motrix.moext','x-motrix-file-name': encodeURIComponent(file.name),},diff --git a/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts b/src/renderer/routes/dashboard/activity/activity-calendar-model.test.tsindex 2a72d372..fa0781b1 100644--- a/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts+++ b/src/renderer/routes/dashboard/activity/activity-calendar-model.test.ts@@ -204,7 +204,12 @@ describe('activity calendar geometry', () => {contentLevel: 'compact',})- expect(geometry).toMatchObject({ weeks: 13, cellSize: 12 })+ expect(geometry).toMatchObject({+ weeks: 13,+ cellSize: 12,+ showMonthLabels: true,+ showWeekdayLabels: true,+ })})it('fits airy 9px cells in the 690x172 activity card budget', () => {@@ -332,31 +337,32 @@ describe('activity calendar geometry', () => {})})- it('restores chrome only when it does not shrink the grid stride', () => {- const beforeThreshold = selectActivityGeometry({- width: 658,- height: 86,- contentLevel: 'focus',- })- const afterThreshold = selectActivityGeometry({- width: 658,- height: 87,- contentLevel: 'focus',- })-- for (const geometry of [beforeThreshold, afterThreshold]) {+ it.each([+ [597, 186],+ [596, 162],+ [658, 86],+ [658, 87],+ ])(+ 'keeps both date axes in an intermediate %i × %i calendar',+ (width, height) => {+ const geometry = selectActivityGeometry({+ width,+ height,+ contentLevel: 'focus',+ })expect(geometry).toMatchObject({weeks: 53,- cellSize: 9,- gap: 3,- stride: 12,- gridWidth: 633,- showLegend: false,- showMonthLabels: false,+ showMonthLabels: true,showWeekdayLabels: true,})+ expect(geometry!.gridLeft + geometry!.gridWidth).toBeLessThanOrEqual(+ width+ )+ expect(geometry!.gridTop + geometry!.gridHeight).toBeLessThanOrEqual(+ height+ )}- })+ )it('uses a bounded whole-week emergency fallback below 13', () => {const geometry = selectActivityGeometry({diff --git a/src/renderer/routes/dashboard/activity/activity-calendar-model.ts b/src/renderer/routes/dashboard/activity/activity-calendar-model.tsindex f35334ea..4df9f4b9 100644--- a/src/renderer/routes/dashboard/activity/activity-calendar-model.ts+++ b/src/renderer/routes/dashboard/activity/activity-calendar-model.ts@@ -204,19 +204,23 @@ export function projectActivityCells(}function maximumChrome(- contentLevel: DashboardTileContentLevel+ contentLevel: DashboardTileContentLevel,+ width: number,+ height: number): ActivityCalendarChrome {switch (contentLevel) {case 'compact':return {- showMonthLabels: false,- showWeekdayLabels: false,+ showMonthLabels:+ height >= 7 * PREFERRED_CELL_SIZE + 6 * 2 + MONTH_LABEL_HEIGHT,+ showWeekdayLabels:+ width >= 13 * PREFERRED_CELL_SIZE + 12 * 2 + WEEKDAY_LABEL_WIDTH,showLegend: false,}case 'summary':return {showMonthLabels: true,- showWeekdayLabels: false,+ showWeekdayLabels: true,showLegend: false,}case 'detailed':@@ -235,15 +239,23 @@ function maximumChrome(}function chromePlans(- contentLevel: DashboardTileContentLevel+ contentLevel: DashboardTileContentLevel,+ width: number,+ height: number): ActivityCalendarChrome[] {- const plans: ActivityCalendarChrome[] = [maximumChrome(contentLevel)]+ const plans: ActivityCalendarChrome[] = [+ maximumChrome(contentLevel, width, height),+ ]const current = { ...plans[0] }if (current.showLegend) {current.showLegend = falseplans.push({ ...current })}+ if (current.showWeekdayLabels && current.showMonthLabels) {+ // Narrow boxes can retain the month axis even without a weekday gutter.+ plans.push({ ...current, showWeekdayLabels: false })+ }if (current.showMonthLabels) {current.showMonthLabels = falseplans.push({ ...current })@@ -274,6 +286,13 @@ function isBetterStandardGeometry(): boolean {if (!best) return true+ // Keep the calendar readable before spending space on larger gutters or+ // the legend. All standard candidates already meet the minimum cell size.+ const axes = (g: ActivityCalendarGeometry) =>+ Number(g.showMonthLabels) + Number(g.showWeekdayLabels)+ if (axes(candidate) !== axes(best)) return axes(candidate) > axes(best)+ if (candidate.weeks !== best.weeks) return candidate.weeks > best.weeks+const candidatePreferred = hasPreferredDensity(candidate)const bestPreferred = hasPreferredDensity(best)if (candidatePreferred !== bestPreferred) return candidatePreferred@@ -352,14 +371,14 @@ export function selectActivityGeometry({const maxWeeks = maxActivityWeeks(contentLevel)const requestedWeeks = [53, 26, 13].filter((weeks) => weeks <= maxWeeks)- const plans = chromePlans(contentLevel)+ const plans = chromePlans(contentLevel, width, height)const bandOptions =height >= 220 && (contentLevel === 'detailed' || contentLevel === 'focus')? [2, 1]: [1]+ let best: ActivityCalendarGeometry | null = nullfor (const weeks of requestedWeeks) {- let best: ActivityCalendarGeometry | null = nullfor (const chrome of plans) {for (const bands of bandOptions) {for (const gap of GAP_PREFERENCES) {@@ -380,10 +399,9 @@ export function selectActivityGeometry({}}}- if (best) return best}+ if (best) return best- let best: ActivityCalendarGeometry | null = nullfor (const chrome of plans) {const labelWidth = chrome.showWeekdayLabels ? WEEKDAY_LABEL_WIDTH : 0const availableWidth = width - labelWidthdiff --git a/src/renderer/routes/dashboard/tiles/activity-tile.test.tsx b/src/renderer/routes/dashboard/tiles/activity-tile.test.tsxindex 327e031b..d7fdb3b8 100644--- a/src/renderer/routes/dashboard/tiles/activity-tile.test.tsx+++ b/src/renderer/routes/dashboard/tiles/activity-tile.test.tsx@@ -96,6 +96,8 @@ describe('ActivityTile', () => {}render(<ActivityTile viewport={detailedViewport} interactive={false} />)+ expect(screen.queryByRole('status')).toBeNull()+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()expect(screen@@ -114,10 +116,10 @@ describe('ActivityTile', () => {).toBe(true)})- it('keeps stale data, coverage disclosure, and Retry together', () => {+ it('keeps cached data and offers Retry after a refresh failure', () => {const retry = vi.fn().mockResolvedValue(undefined)hookHarness.state = {- status: 'stale',+ status: 'refreshFailed',snapshot: snapshot(new Date(2026, 6, 29, 10).getTime()),retry,}@@ -126,13 +128,12 @@ describe('ActivityTile', () => {expect(screen.getByTestId('activity-calendar-stub')).not.toBeNull()const status = screen.getByRole('status')- expect(status.textContent).toContain('Activity may be out of date')+ expect(status.textContent).toContain('Refresh failed')expect(status.textContent).toContain('Activity may be incomplete since')+ expect(status.closest('header')).not.toBeNull()expect(- screen- .getByTestId('activity-calendar-stub')- .getAttribute('data-class-name')- ).toContain('min-h-12')+ screen.getByTestId('activity-calendar-stub').closest('header')+ ).toBeNull()fireEvent.click(screen.getByRole('button', { name: 'Retry' }))expect(retry).toHaveBeenCalledTimes(1)})diff --git a/src/renderer/routes/dashboard/tiles/activity-tile.tsx b/src/renderer/routes/dashboard/tiles/activity-tile.tsxindex d2c89e54..4efd2d70 100644--- a/src/renderer/routes/dashboard/tiles/activity-tile.tsx+++ b/src/renderer/routes/dashboard/tiles/activity-tile.tsx@@ -27,6 +27,7 @@ export function ActivityTile({void activity.retry()}+ let notice: ReactNodelet content: ReactNodeif (activity.status === 'loading') {content = (@@ -55,7 +56,9 @@ export function ActivityTile({} else {const { snapshot } = activityconst statusMessages = [- activity.status === 'stale' ? t(`${KEY_ROOT}.stale`) : null,+ activity.status === 'refreshFailed'+ ? t(`${KEY_ROOT}.refreshFailed`)+ : null,snapshot.coverage.coverageGapAt !== null? t(`${KEY_ROOT}.coverageDegraded`, {time: formatDateTime(@@ -65,42 +68,45 @@ export function ActivityTile({}): null,].filter((message): message is string => message !== null)- content = (- <div className="flex min-h-0 flex-1 flex-col overflow-hidden">- <ActivityCalendar- snapshot={snapshot}- contentLevel={viewport.contentLevel}- interactive={interactive}- className={statusMessages.length > 0 ? 'min-h-12 flex-1' : 'flex-1'}- />- {statusMessages.length > 0 ? (- <div- role="status"- aria-live="polite"- className="flex shrink-0 items-center justify-between gap-2 pt-1 text-[9px] leading-3 text-muted-foreground"+ notice = statusMessages.length > 0 && (+ <div+ role="status"+ aria-live="polite"+ className="flex max-w-[64cqw] items-center gap-1 text-[10px] leading-3 text-muted-foreground"+ >+ <span className="min-w-0 truncate" title={statusMessages.join(' · ')}>+ {statusMessages.join(' · ')}+ </span>+ {activity.status === 'refreshFailed' && (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ className="h-5 shrink-0 px-1.5 text-[10px]"+ onClick={retry}>- <span className="min-w-0 truncate">- {statusMessages.join('; ')}- </span>- {activity.status === 'stale' ? (- <Button- type="button"- size="sm"- variant="ghost"- className="h-5 shrink-0 px-1.5 text-[9px]"- onClick={retry}- >- {t(`${KEY_ROOT}.retry`)}- </Button>- ) : null}- </div>- ) : null}+ {t(`${KEY_ROOT}.retry`)}+ </Button>+ )}</div>)+ content = (+ <ActivityCalendar+ snapshot={snapshot}+ contentLevel={viewport.contentLevel}+ interactive={interactive}+ className="min-h-0 flex-1"+ />+ )}return (- <TileShell label={t(`${KEY_ROOT}.title`)} bodyClassName="overflow-hidden">+ <TileShell+ label={t(`${KEY_ROOT}.title`)}+ bodyClassName="overflow-hidden"+ className="@container"+ action={notice}+ ><span className="sr-only">{t(`${KEY_ROOT}.completedIntensity`)}</span>{content}</TileShell>diff --git a/src/renderer/routes/dashboard/tiles/engine-tile.test.tsx b/src/renderer/routes/dashboard/tiles/engine-tile.test.tsxindex 933c7791..b9ab3113 100644--- a/src/renderer/routes/dashboard/tiles/engine-tile.test.tsx+++ b/src/renderer/routes/dashboard/tiles/engine-tile.test.tsx@@ -1,7 +1,7 @@import '@testing-library/jest-dom/vitest'import { i18n } from '@renderer/lib/i18n'-import { render, screen } from '@testing-library/react'-import { afterEach, describe, expect, it } from 'vitest'+import { act, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'import { dashboardTileViewport } from '../layout/dashboard-registry'import { type EngineDisplayStatus, EngineTile } from './engine-tile'@@ -70,6 +70,33 @@ describe('EngineTile', () => {expect(screen.getByText(/Disconnected|未连接/)).toBeInTheDocument()})+ it('reports sustained polling separately from the engine state', () => {+ vi.useFakeTimers()+ try {+ const { rerender } = render(+ <EngineTile+ status={{ ...baseStatus, connection: 'polling' }}+ viewport={compactViewport}+ />+ )+ expect(screen.getByText('Ready')).toBeVisible()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ act(() => vi.advanceTimersByTime(2000))+ expect(screen.getByRole('status')).toHaveTextContent('Periodic updates')+ expect(screen.getByText('Ready')).toBeVisible()+ rerender(+ <EngineTile+ status={{ ...baseStatus, state: 'failed' }}+ viewport={compactViewport}+ />+ )+ expect(screen.getByText('Failed')).toBeVisible()+ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ } finally {+ vi.useRealTimers()+ }+ })+it('exposes an engine diagnosis action', () => {render(<EngineTile status={baseStatus} viewport={summaryViewport} />)expect(diff --git a/src/renderer/routes/dashboard/tiles/engine-tile.tsx b/src/renderer/routes/dashboard/tiles/engine-tile.tsxindex adda6c4f..8309bed2 100644--- a/src/renderer/routes/dashboard/tiles/engine-tile.tsx+++ b/src/renderer/routes/dashboard/tiles/engine-tile.tsx@@ -12,6 +12,7 @@ export type {} from '@renderer/hooks/use-engine-display-status'import { DiagnosticsIcon } from '@renderer/components/icons'+import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { StatusDot } from '../components/status-dot'import { TileShell } from '../components/tile-shell'@@ -47,17 +48,27 @@ export function EngineTile({status.state === 'ready' ||status.state === 'starting' ||status.state === 'reconnecting'- const connectionLabel = status.connection- ? t(`panel.connection.${status.connection}`)+ // A normal NAS event-ticket renewal briefly uses HTTP polling while the+ // engine is still ready. Expose sustained transport issues separately.+ const connection = status.connection ?? null+ const [sustained, setSustained] = useState<typeof connection>(null)+ useEffect(() => {+ setSustained(null)+ if (!connection) return+ const timer = setTimeout(() => setSustained(connection), 2000)+ return () => clearTimeout(timer)+ }, [connection])+ const visibleConnection =+ connection === 'unavailable' ||+ connection === 'originMismatch' ||+ sustained === connection+ ? connection+ : null+ const connectionLabel = visibleConnection+ ? t(`panel.connection.${visibleConnection}`): null- const stateLabel =- status.state === 'ready' && connectionLabel- ? connectionLabel- : t(`panel.dashboard.engine.state.${status.state}`)- const dot =- status.connection && status.state !== 'failed'- ? 'bg-amber-500'- : DOT[status.state]+ const stateLabel = t(`panel.dashboard.engine.state.${status.state}`)+ const dot = DOT[status.state]// 'aria2c 1.37.0-motrix.1' only show '1.37.0'const shortVersion = String(status.version).split('-')[0]@@ -103,7 +114,7 @@ export function EngineTile({<TileTitle variant="text" title={stateLabel}>{stateLabel}</TileTitle>- {connectionLabel && status.state !== 'ready' && !compact && (+ {connectionLabel && (<prole="status"title={connectionLabel}@@ -138,10 +149,7 @@ export function EngineTile({/>))}</div>- <StatusDot- pulse={pulse && !status.connection}- className={cn(dot, tall && 'self-end')}- />+ <StatusDot pulse={pulse} className={cn(dot, tall && 'self-end')} /></div>) : (<div@@ -151,7 +159,7 @@ export function EngineTile({<div className="flex shrink-0 items-center gap-3 text-muted-foreground text-[11px]">{`aria2 v${shortVersion}`}</div>- <StatusDot pulse={pulse && !status.connection} className={cn(dot)} />+ <StatusDot pulse={pulse} className={cn(dot)} /></div>)}</TileShell>diff --git a/src/renderer/routes/downloads/inspector/can-reveal-task-folder.ts b/src/renderer/routes/downloads/inspector/can-reveal-task-folder.tsindex eeae4b22..7787a9e8 100644--- a/src/renderer/routes/downloads/inspector/can-reveal-task-folder.ts+++ b/src/renderer/routes/downloads/inspector/can-reveal-task-folder.ts@@ -1,17 +1 @@-import type { DownloadTask } from '@shared/types/task'-import { TaskStatus } from '@shared/types/task'--export function canRevealTaskFolder(task: DownloadTask): boolean {- if (task.status === TaskStatus.FetchingMetadata) return false-- const diskPath = task.diskPath.trim()- if (diskPath === '') return false-- return !isRootPath(diskPath)-}--function isRootPath(diskPath: string): boolean {- const normalized = diskPath.replace(/[\\/]+$/, '')- if (normalized === '') return true- return /^[A-Za-z]:$/.test(normalized)-}+export { canRevealTaskFolder } from '@shared/types/task-actions'diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsxindex 9d5b189c..ea31dbe3 100644--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx@@ -19,7 +19,11 @@ import { openTaskFile } from '@renderer/lib/open-task-file'import { rtlMirror } from '@renderer/lib/task-status-ui'import { transport } from '@renderer/lib/transport'import { cn } from '@renderer/lib/utils'-import { hasHostFileActions } from '@renderer/platform/fnos'+import {+ hasHostFileActions,+ hostOpenFileLabelKey,+ hostRevealFolderLabelKey,+} from '@renderer/platform/nas'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'@@ -118,7 +122,7 @@ function OpenTaskFileButton({ task }: { task: DownloadTask }) {onClick={() => void open()}><OpenFileIcon />- {t('panel.downloads.action.openFile')}+ {t(hostOpenFileLabelKey())}</Button>)}@@ -149,7 +153,7 @@ function FinalizingActionBar({}><RevealFolderIcon />- {t('panel.downloads.action.openFolder')}+ {t(hostRevealFolderLabelKey())}</Button>)}<CopyButton@@ -326,7 +330,7 @@ export function TaskInspectorActionBar({}><RevealFolderIcon />- {t('panel.downloads.action.openFolder')}+ {t(hostRevealFolderLabelKey())}</Button>)}{single && (diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsxindex b6714932..001b58b5 100644--- a/src/renderer/routes/downloads/task-actions-menu.tsx+++ b/src/renderer/routes/downloads/task-actions-menu.tsx@@ -28,7 +28,11 @@ import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'import { openTaskFile } from '@renderer/lib/open-task-file'import { transport } from '@renderer/lib/transport'-import { hasHostFileActions } from '@renderer/platform/fnos'+import {+ hasHostFileActions,+ hostOpenFileLabelKey,+ hostRevealFolderLabelKey,+} from '@renderer/platform/nas'import { CommandIds } from '@shared/commands-catalog'import { formatNativePath } from '@shared/lib/path-display'import { Commands } from '@shared/protocol/commands'@@ -289,7 +293,7 @@ export function TaskActionsMenu({)}>- {t('panel.downloads.action.openFile')}+ {t(hostOpenFileLabelKey())}</DropdownMenuItem>)}{single && hasHostFileActions() && canRevealTaskFolder(single) && (@@ -308,7 +312,7 @@ export function TaskActionsMenu({)}}>- {t('panel.downloads.action.openFolder')}+ {t(hostRevealFolderLabelKey())}</DropdownMenuItem>)}<OperationTaskMenuItems selected={selected} open={menuOpen} />diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex 961fab0b..52a776df 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -28,7 +28,7 @@ import {import { LegacyFreshDownload } from '@renderer/features/legacy-import/legacy-fresh-download'import { createTaskInspectorActivitySnapshotCache } from '@renderer/hooks/use-task-inspector-activity'import { transport } from '@renderer/lib/transport'-import { hasHostFileActions } from '@renderer/platform/fnos'+import { hasHostFileActions } from '@renderer/platform/nas'import { formatNativePath } from '@shared/lib/path-display'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'diff --git a/src/renderer/routes/settings/card-registry.tsx b/src/renderer/routes/settings/card-registry.tsxindex 7aeb7ebb..f7ff034a 100644--- a/src/renderer/routes/settings/card-registry.tsx+++ b/src/renderer/routes/settings/card-registry.tsx@@ -1,4 +1,4 @@-import type { ComponentType, ReactElement } from 'react'+import { type ComponentType, lazy, type ReactElement, Suspense } from 'react'import { AboutDialog } from './cards/about-dialog'import { AdvancedDialog } from './cards/advanced-dialog'import { AppearanceDialog } from './cards/appearance-dialog'@@ -9,6 +9,15 @@ import { GeneralDialog } from './cards/general-dialog'import { IntegrationDialog } from './cards/integration/integration-dialog'import { NetworkDialog } from './cards/network-dialog'+const NasDialog =+ __MOTRIX_TARGET__ === 'web'+ ? lazy(() =>+ import('./cards/nas-dialog').then((module) => ({+ default: module.NasDialog,+ }))+ )+ : () => null+const iconGeneral1x = new URL('./icons/[email protected]', import.meta.url).hrefconst iconGeneral2x = new URL('./icons/[email protected]', import.meta.url)@@ -145,7 +154,22 @@ export const SETTINGS_CARDS: readonly SettingsCard[] = [},] as const-export function findCard(id: string | undefined): SettingsCard | undefined {+export const NAS_SETTINGS_CARD: SettingsCard = {+ id: 'nas',+ icon: createSettingsIcon('nas', iconNetwork1x, iconNetwork2x),+ labelKey: 'settings.cards.nas.title',+ descKey: 'settings.cards.nas.desc',+ Dialog: (props) => (+ <Suspense fallback={null}>+ <NasDialog {...props} />+ </Suspense>+ ),+}++export function findCard(+ id: string | undefined,+ cards: readonly SettingsCard[] = SETTINGS_CARDS+): SettingsCard | undefined {if (!id) return undefined- return SETTINGS_CARDS.find((c) => c.id === id)+ return cards.find((c) => c.id === id)}diff --git a/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsx b/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsxindex c0175ffa..8ff9f34e 100644--- a/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsx+++ b/src/renderer/routes/settings/cards/integration/browser-extensions-section.test.tsx@@ -1,5 +1,7 @@import '@testing-library/jest-dom/vitest'+import { Toaster, toast } from '@renderer/components/ui/toast'import { i18n } from '@renderer/lib/i18n'+import { useOperatorSession } from '@renderer/lib/operator-auth'import { transport } from '@renderer/lib/transport'import {BridgeCommands,@@ -89,6 +91,75 @@ describe('browser extension installations', () => {})})+ it('claims the current account’s pending request inside settings and hides its code on account change', async () => {+ const original = useOperatorSession.getState()+ const status = {+ mode: 'synologyDsm' as const,+ authed: true,+ username: 'alice',+ canLogout: false,+ clientPairing: { cli: true, extension: true },+ }+ const id = 'nas-inbox-request'+ const request = {+ browser: 'chromium',+ extensionId: 'test-extension',+ pairingNonce: 'fixture-nonce',+ identity: 'official',+ accountName: 'alice',+ onDeny: vi.fn(),+ }+ const onClaim = vi.fn(() =>+ toast.update(id, {+ data: {+ pairRequest: { ...request, kind: 'extension', code: 'ABCD-EFGH' },+ },+ })+ )+ try {+ useOperatorSession.setState({ status, state: 'authenticated' })+ render(+ <Toaster>+ <Wrapper />+ </Toaster>+ )+ act(() => {+ toast.add({+ id,+ timeout: 0,+ priority: 'high',+ data: {+ pairRequest: {+ ...request,+ kind: 'extension-claim',+ claiming: false,+ onClaim,+ },+ },+ })+ })+ const inbox = within(+ await screen.findByRole('region', { name: 'Browser pairing requests' })+ )+ expect(inbox.getByText(/Current account: alice/)).toBeVisible()+ expect(inbox.queryByText('ABCD-EFGH')).toBeNull()+ fireEvent.click(+ inbox.getByRole('button', { name: 'Pair with current account' })+ )+ expect(onClaim).toHaveBeenCalledOnce()+ expect(await inbox.findByText('ABCD-EFGH')).toBeVisible()+ act(() =>+ useOperatorSession.setState({ status: { ...status, username: 'bob' } })+ )+ expect(inbox.queryByText('ABCD-EFGH')).toBeNull()+ } finally {+ act(() => {+ toast.close(id)+ useOperatorSession.setState(original)+ })+ }+ })+it('shows both profiles, refreshes disconnect status, and revokes the entire extension group', async () => {render(<Wrapper />)expect(await screen.findByText('Browser profile 1')).toBeVisible()diff --git a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsxindex 473c5128..438e6d83 100644--- a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx+++ b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx@@ -5,7 +5,12 @@ import {AlertTitle,} from '@renderer/components/ui/alert'import { Button } from '@renderer/components/ui/button'+import {+ ExtensionPairRequestContent,+ usePageExtensionPrompts,+} from '@renderer/components/ui/toast'import { browserDisplayName } from '@renderer/lib/browser-name'+import { useOperatorSession } from '@renderer/lib/operator-auth'import { cn } from '@renderer/lib/utils'import type { PairedClientInfo } from '@shared/protocol/bridge'import { useFormContext } from 'react-hook-form'@@ -23,11 +28,47 @@ const IDENTITY_LABEL_KEYS = {unverified: 'settings.integration.browser.pairToast.identityLabel.unverified',} as const+function NasPairingInbox({ accountName }: { accountName: string }) {+ const { t } = useTranslation()+ const requests = usePageExtensionPrompts(accountName)+ return (+ <section+ aria-label={t('settings.integration.browser.pendingTitle')}+ className="space-y-2"+ >+ <h3 className="text-xs font-medium">+ {t('settings.integration.browser.pendingTitle')} ({requests.length})+ </h3>+ {requests.length ? (+ requests.map(({ id, prompt }) => (+ <div+ key={id}+ className="rounded border border-border px-3 py-2 text-xs"+ >+ <ExtensionPairRequestContent pairRequest={prompt} inline />+ </div>+ ))+ ) : (+ <p className="text-xs text-muted-foreground">+ {t('settings.integration.browser.pendingEmpty')}+ </p>+ )}+ </section>+ )+}+export function BrowserExtensionsSection() {const { t } = useTranslation()const form = useFormContext<IntegrationFormValues>()const { items: paired, revoke } = usePairedExtensions()const status = useBridgeStatus()+ const accountName = useOperatorSession((session) =>+ session.state === 'authenticated' &&+ session.status?.mode === 'synologyDsm' &&+ session.status.clientPairing?.extension+ ? session.status.username+ : undefined+ )// This section lists browser extensions only; cli/agent clients (device-code// paired) are a separate principal kind.const pairedExtensions = paired.filter(@@ -41,6 +82,7 @@ export function BrowserExtensionsSection() {<ClientPairingSwitch browser /><BrowserExtensionInstalls />+ {enabled && accountName && <NasPairingInbox accountName={accountName} />}{status?.degraded && (<Alert className="border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] leading-4 text-amber-900 dark:text-amber-200">diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsxindex 47e704ed..15b20b64 100644--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx@@ -65,6 +65,9 @@ export function IntegrationDialog({}: SettingsCardDialogProps) {const { t } = useTranslation()const isWeb = transport.platform === 'web'+ const nasSettings = useOperatorSession(+ (session) => session.status?.nasCapabilities?.settings === true+ )const cliPairing = useOperatorSession((session) =>supportsClientPairing(session.status, 'cli'))@@ -173,6 +176,14 @@ export function IntegrationDialog({: 'settings.integration.clientPairingUnavailable')}</AlertDescription>+ {nasSettings && (+ <a+ className="mt-2 inline-block text-xs underline underline-offset-4"+ href="#/settings/nas"+ >+ {t('settings.nas.openSettings')}+ </a>+ )}</Alert>) : (<>diff --git a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsxindex 9262fcae..d15c7033 100644--- a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx+++ b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx@@ -143,11 +143,13 @@ describe('usePairRequestPrompts', () => {expiresAt: 120001,}const claimKey = pairRequestKey(claimRequest)- async function showClaim() {+ async function showClaim(+ mode: 'fnosGateway' | 'synologyDsm' = 'fnosGateway'+ ) {useOperatorSession.setState({epoch: 1,status: {- mode: 'fnosGateway',+ mode,authed: true,canLogout: false,username: 'alice',@@ -160,45 +162,96 @@ describe('usePairRequestPrompts', () => {return findAddCall(claimKey).data.pairRequest.onClaim as () => void}- it('reveals a NAS code only after claiming, then clears it at the server-provided lifetime', async () => {- vi.useFakeTimers()- const claim = await showClaim()- expect(invokeMock).toHaveBeenCalledTimes(1)+ it('refetches NAS requests when the administrator returns from the extension', async () => {+ useOperatorSession.setState({+ status: {+ mode: 'synologyDsm',+ authed: true,+ canLogout: false,+ username: 'alice',+ clientPairing: { cli: true, extension: true },+ },+ })+ invokeMock.mockResolvedValueOnce([])+ render(<Host />)+ await waitFor(() => expect(invokeMock).toHaveBeenCalledOnce())+ invokeMock.mockResolvedValueOnce([claimRequest])+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'))+ })+ expect(findAddCall(claimKey).data.pairRequest.kind).toBe('extension-claim')expect(findAddCall(claimKey).data.pairRequest).not.toHaveProperty('code')- expect(findAddCall(claimKey).data.pairRequest).not.toHaveProperty('onAllow')- expect(findAddCall(claimKey).data.pairRequest.accountName).toBe('alice')+ })++ it('drops a NAS code on disconnect and requires a new claim after reconnect', async () => {+ const claim = await showClaim('synologyDsm')invokeMock.mockResolvedValueOnce({ok: true,code: 'ABCD-EFGH',- expiresInMs: 500,+ expiresInMs: 120000,})await act(async () => claim())- expect(invokeMock).toHaveBeenLastCalledWith(- BridgeCommands.ClaimExtensionPair,- {- browser: claimRequest.browser,- extensionId: claimRequest.extensionId,- pairingNonce: claimRequest.pairingNonce,- expectedUsername: 'alice',- }- )- expect(toastUpdateMock).toHaveBeenLastCalledWith(claimKey, {- data: {- pairRequest: expect.objectContaining({- kind: 'extension',- accountName: 'alice',- code: 'ABCD-EFGH',- }),- },- })- toastCloseMock.mockImplementation((key: string) =>- findAddCall(key).onClose()- )- await act(async () => vi.advanceTimersByTime(500))+ const connection = onConnectionChangeMock.mock.calls[0][0]+ act(() => connection({ state: 'disconnected' }))expect(toastCloseMock).toHaveBeenCalledWith(claimKey)- expect(invokeMock).toHaveBeenCalledTimes(2)+ invokeMock.mockResolvedValueOnce([claimRequest])+ await act(async () => connection({ state: 'connected' }))+ const latest = toastAddMock.mock.calls.at(-1)?.[0] as ReturnType<+ typeof findAddCall+ >+ expect(latest.id).toBe(claimKey)+ expect(latest.data.pairRequest.kind).toBe('extension-claim')+ expect(latest.data.pairRequest).not.toHaveProperty('code')+ expect(invokeMock).not.toHaveBeenCalledWith(+ BridgeCommands.ResolvePair,+ expect.anything()+ )})+ it.each(['fnosGateway', 'synologyDsm'] as const)(+ 'reveals a %s code only after claiming, then clears it at the server-provided lifetime',+ async (mode) => {+ vi.useFakeTimers()+ const claim = await showClaim(mode)+ expect(invokeMock).toHaveBeenCalledTimes(1)+ expect(findAddCall(claimKey).data.pairRequest).not.toHaveProperty('code')+ expect(findAddCall(claimKey).data.pairRequest).not.toHaveProperty(+ 'onAllow'+ )+ expect(findAddCall(claimKey).data.pairRequest.accountName).toBe('alice')+ invokeMock.mockResolvedValueOnce({+ ok: true,+ code: 'ABCD-EFGH',+ expiresInMs: 500,+ })+ await act(async () => claim())+ expect(invokeMock).toHaveBeenLastCalledWith(+ BridgeCommands.ClaimExtensionPair,+ {+ browser: claimRequest.browser,+ extensionId: claimRequest.extensionId,+ pairingNonce: claimRequest.pairingNonce,+ expectedUsername: 'alice',+ }+ )+ expect(toastUpdateMock).toHaveBeenLastCalledWith(claimKey, {+ data: {+ pairRequest: expect.objectContaining({+ kind: 'extension',+ accountName: 'alice',+ code: 'ABCD-EFGH',+ }),+ },+ })+ toastCloseMock.mockImplementation((key: string) =>+ findAddCall(key).onClose()+ )+ await act(async () => vi.advanceTimersByTime(500))+ expect(toastCloseMock).toHaveBeenCalledWith(claimKey)+ expect(invokeMock).toHaveBeenCalledTimes(2)+ }+ )+it.each(['account-change', 'settled'] as const)('ignores a late claimed code after %s',async (reason) => {diff --git a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsx b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsxindex cbbde47f..606ffee6 100644--- a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsx+++ b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsx@@ -23,7 +23,10 @@ import type { CommandChannel } from '@shared/protocol/commands'import type { EventChannel } from '@shared/protocol/events'import type { QueryChannel } from '@shared/protocol/queries'import { claimExtensionPairResultSchema } from '@shared/schemas/extension-pairing'-import { supportsClientPairing } from '@shared/schemas/operator-auth'+import {+ isNasAuthMode,+ supportsClientPairing,+} from '@shared/schemas/operator-auth'import { useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'import { resolvePairWithFeedback } from './pair-resolve'@@ -89,7 +92,9 @@ function toPairRequestPayload(function operatorKey(session: ReturnType<typeof useOperatorSession.getState>): string | undefined {- return session.status?.mode === 'fnosGateway' && session.status.authed+ return session.status &&+ isNasAuthMode(session.status.mode) &&+ session.status.authed? `${session.epoch}:${session.status.username ?? ''}`: undefined}@@ -171,6 +176,7 @@ export function usePairRequestPrompts(): void {try {await resolvePairWithFeedback(params, tRef.current)} catch {+ if (cancelled || !sameOperator() || prompts.get(key) !== state) returnstate.settled = falseprompts.delete(key)toast.add({@@ -357,6 +363,7 @@ export function usePairRequestPrompts(): void {// so a later settle would fire the stale closure instead (spurious deny// + wrong "unavailable" toast).let cancelled = false+ let snapshotGeneration = 0// Reconciles `prompts`/the toast set against the backend's own// bookkeeping. Called once on mount, and again on every web-transport@@ -364,6 +371,8 @@ export function usePairRequestPrompts(): void {// guard makes repeat calls idempotent, so re-running this on reconnect// is safe even if nothing actually changed backend-side.const snapshot = async (): Promise<void> => {+ const generation = ++snapshotGeneration+ const known = new Map(prompts)let raw: unknowntry {raw = await transport.invoke(@@ -377,11 +386,16 @@ export function usePairRequestPrompts(): void {// use-notification-toasts.ts's mount-time engine-status check catch).return}- if (cancelled) return- // Defensive against a non-array reply (e.g. an unrelated stub that- // resolves every query to `{}`) — reload recovery degrades to "no- // prompts yet" rather than throwing.- const list = Array.isArray(raw) ? (raw as PendingPairRequestInfo[]) : []+ if (cancelled || generation !== snapshotGeneration || !Array.isArray(raw))+ return+ const list = raw as PendingPairRequestInfo[]+ if (operatorIdentity !== undefined) {+ const live = new Set(list.map(pairRequestKey))+ for (const [key, state] of known) {+ if (!state.settled && prompts.get(key) === state && !live.has(key))+ closeSilently(key)+ }+ }for (const info of list) {present(toPairRequestPayload(info))}@@ -398,10 +412,24 @@ export function usePairRequestPrompts(): void {// what covers its (much narrower) startup race instead.const stopConnectionSync = transport.onConnectionChange?.((event) => {if (event.state === 'connected') void snapshot()+ if (event.state === 'disconnected' && operatorIdentity !== undefined) {+ // A restarted package cannot honor a code from the old connection.+ // Forget local receipts without denying still-live requests on the host.+ snapshotGeneration+++ for (const key of prompts.keys()) closeSilently(key)+ prompts.clear()+ }})+ const refreshVisibleInbox = () => {+ if (!document.hidden) void snapshot()+ }+ if (operatorIdentity !== undefined)+ document.addEventListener('visibilitychange', refreshVisibleInbox)+return () => {cancelled = true+ document.removeEventListener('visibilitychange', refreshVisibleInbox)stopConnectionSync?.()transport.off(pairRequestedChannel, onPairRequested)transport.off(settledChannel, onSettled)diff --git a/src/renderer/routes/settings/cards/nas-dialog.test.tsx b/src/renderer/routes/settings/cards/nas-dialog.test.tsxnew file mode 100644index 00000000..2af32fc8--- /dev/null+++ b/src/renderer/routes/settings/cards/nas-dialog.test.tsx@@ -0,0 +1,175 @@+import '@test-utils/dom-animations'+import '@renderer/lib/i18n'+import '@testing-library/jest-dom/vitest'+import { NasStorageRecovery } from '@renderer/components/nas-storage-recovery'+import { i18n } from '@renderer/lib/i18n'+import { useOperatorSession } from '@renderer/lib/operator-auth'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import type { NasSettingsView } from '@shared/schemas/nas-settings'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { beforeEach, expect, it, vi } from 'vitest'+import { NasDialog } from './nas-dialog'++vi.mock('@renderer/lib/transport', () => ({+ transport: { platform: 'web', invoke: vi.fn(), onConnectionChange: vi.fn() },+}))+const settings = {+ roots: ['/volume1/motrix'],+ clientPort: 16802,+ extensionUrl: '',+ operatorUrl: 'https://nas.test:5001/motrix/',+ allowHttp: false,+}+let view: NasSettingsView,+ reconnect: ((event: { state: 'connected' }) => void) | undefined+beforeEach(async () => {+ await i18n.changeLanguage('en-US')+ vi.clearAllMocks()+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ useOperatorSession.setState({+ state: 'authenticated',+ status: {+ authed: true,+ mode: 'synologyDsm',+ canLogout: false,+ username: 'alice',+ },+ })+ view = {+ platform: 'synology',+ revision: 'a'.repeat(64),+ settings,+ active: settings,+ restartRequired: false,+ }+ const subscribe = transport.onConnectionChange+ if (!subscribe) throw new Error('Missing test transport subscription')+ vi.mocked(subscribe).mockImplementation((callback) => {+ reconnect = callback+ return () => {}+ })+ vi.mocked(transport.invoke).mockImplementation(async (channel, request) => {+ if (channel === Queries.GetNasSettings) return { ok: true, value: view }+ if (channel === Commands.SaveNasSettings) {+ const next = request as { settings: typeof settings }+ return {+ ok: true,+ value: {+ ...view,+ revision: 'b'.repeat(64),+ settings: next.settings,+ restartRequired: true,+ },+ }+ }+ throw new Error('Unexpected test request')+ })+})+function open() {+ render(+ <NasDialog+ open+ onClose={vi.fn()}+ labelKey="settings.cards.nas.title"+ descKey="settings.cards.nas.desc"+ />+ )+}+it('repairs an unavailable folder without changing saved client addresses or ports', async () => {+ const missing = '/volume2/missing'+ const applied = { ...settings, roots: [missing], operatorUrl: '' }+ view = { ...view, settings: applied, active: applied }+ useOperatorSession.setState({+ status: {+ ...useOperatorSession.getState().status!,+ nasUnavailableDownloadRoots: [missing],+ },+ })+ render(<NasStorageRecovery roots={[missing]} />)+ expect(screen.getByText(missing)).toBeVisible()+ fireEvent.click(+ screen.getByRole('button', { name: 'Authorized download folders' })+ )+ const folders = await screen.findByRole('textbox', {+ name: 'Authorized download folders',+ })+ await waitFor(() => expect(folders).toBeEnabled())+ expect(screen.queryByRole('spinbutton')).toBeNull()+ expect(screen.queryByText('CLI endpoint')).toBeNull()+ fireEvent.change(folders, { target: { value: '/volume1/motrix' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))+ await screen.findByText(i18n.t('settings.nas.restartRequired'))+ expect(transport.invoke).toHaveBeenCalledWith(Commands.SaveNasSettings, {+ revision: view.revision,+ settings: { ...applied, roots: ['/volume1/motrix'] },+ })+})++it('saves explicit package settings with a revision and shows the restart requirement', async () => {+ open()+ const port = await screen.findByRole('spinbutton', {+ name: 'Direct client port',+ })+ await waitFor(() => expect(port).toBeEnabled())+ fireEvent.change(port, { target: { value: '16812' } })+ fireEvent.click(+ screen.getByRole('switch', { name: 'Enable browser extension connections' })+ )+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))+ await screen.findByText(i18n.t('settings.nas.restartRequired'))+ expect(transport.invoke).toHaveBeenCalledWith(Commands.SaveNasSettings, {+ revision: 'a'.repeat(64),+ settings: {+ ...settings,+ clientPort: 16812,+ extensionUrl: 'wss://nas.test:5001/motrix/bridge',+ },+ })+ expect(screen.getByRole('textbox', { name: 'CLI endpoint' })).toHaveValue(+ 'https://nas.test:5001/motrix/client'+ )+})+it('preserves an unsaved draft across reconnects and rejects a changed baseline', async () => {+ open()+ const port = await screen.findByRole('spinbutton', {+ name: 'Direct client port',+ })+ await waitFor(() => expect(port).toBeEnabled())+ fireEvent.change(port, { target: { value: '16812' } })+ await act(async () => {+ reconnect?.({ state: 'connected' })+ })+ expect(port).toHaveValue(16812)+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()+ view = {+ ...view,+ revision: 'b'.repeat(64),+ settings: { ...settings, clientPort: 16815 },+ }+ await act(async () => {+ reconnect?.({ state: 'connected' })+ })+ await screen.findByText(/The saved configuration changed/)+ expect(port).toHaveValue(16812)+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))+ await waitFor(() => expect(port).toHaveValue(16815))+})+it('never enables saving before an authoritative baseline is available', async () => {+ vi.mocked(transport.invoke).mockResolvedValue({+ ok: false,+ error: { code: 'permissionDenied' },+ })+ open()+ await screen.findByRole('alert')+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()+})diff --git a/src/renderer/routes/settings/cards/nas-dialog.tsx b/src/renderer/routes/settings/cards/nas-dialog.tsxnew file mode 100644index 00000000..b98e2753--- /dev/null+++ b/src/renderer/routes/settings/cards/nas-dialog.tsx@@ -0,0 +1,556 @@+import { CopyButton } from '@renderer/components/desktop-kit/copy-button'+import {+ useSettingsForm,+ useSettingsSubmit,+} from '@renderer/components/settings-kit/use-settings-form'+import { SettingsLoadStatus } from '@renderer/components/settings-kit/use-settings-load'+import { Alert, AlertDescription } from '@renderer/components/ui/alert'+import { Button } from '@renderer/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/components/ui/dialog'+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@renderer/components/ui/form'+import { Input } from '@renderer/components/ui/input'+import {+ ScrollArea,+ ScrollAreaContent,+ ScrollAreaViewport,+ ScrollBar,+} from '@renderer/components/ui/scroll-area'+import { Separator } from '@renderer/components/ui/separator'+import { Switch } from '@renderer/components/ui/switch'+import { Textarea } from '@renderer/components/ui/textarea'+import { useOperatorSession } from '@renderer/lib/operator-auth'+import { transport } from '@renderer/lib/transport'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ type NasPackageSettings,+ type NasSettingsView,+ nasPackageSettingsSchema,+ nasSettingsResultSchema,+ synologyConnectionUrls,+} from '@shared/schemas/nas-settings'+import {+ Component,+ type ReactNode,+ useCallback,+ useEffect,+ useRef,+ useState,+} from 'react'+import { useTranslation } from 'react-i18next'+import type { SettingsCardDialogProps } from './card-types'++const DEFAULTS: NasPackageSettings = {+ roots: [''],+ clientPort: 16802,+ extensionUrl: '',+ operatorUrl: '',+ allowHttp: false,+}++export function NasDialog(props: SettingsCardDialogProps) {+ const { t } = useTranslation()+ return (+ <NasSettingsBoundary+ fallback={+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onClose()+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t(props.labelKey)}</DialogTitle>+ <DialogDescription>+ {t('settings.validation.loadFailed')}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button type="button" size="sm" onClick={props.onClose}>+ {t('common.close')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ }+ >+ <NasDialogForm {...props} />+ </NasSettingsBoundary>+ )+}++class NasSettingsBoundary extends Component<+ { children: ReactNode; fallback: ReactNode },+ { failed: boolean }+> {+ state = { failed: false }+ static getDerivedStateFromError() {+ return { failed: true }+ }+ render() {+ return this.state.failed ? this.props.fallback : this.props.children+ }+}++function NasDialogForm({ open, onClose, labelKey }: SettingsCardDialogProps) {+ const { t } = useTranslation()+ const foldersOnly = useOperatorSession((session) =>+ Boolean(session.status?.nasUnavailableDownloadRoots?.length)+ )+ const username = useOperatorSession(+ (session) => session.status?.username ?? ''+ )+ const form = useSettingsForm(nasPackageSettingsSchema, DEFAULTS)+ const [view, setView] = useState<NasSettingsView | null>(null)+ const [load, setLoad] = useState({ ready: false, error: false })+ const [error, setError] = useState<string | null>(null)+ const [rootsText, setRootsText] = useState('')+ const generation = useRef(0)+ const currentView = useRef<NasSettingsView | null>(null)+ const saving = useRef(false)+ const dirty = useRef(false)+ dirty.current = form.formState.isDirty+ const { reset } = form+ const refresh = useCallback(+ async (preserveDraft = false) => {+ if (saving.current) return+ const preserve = preserveDraft && dirty.current+ const current = ++generation.current+ if (!preserve) setLoad({ ready: false, error: false })+ try {+ const result = nasSettingsResultSchema.parse(+ await transport.invoke(Queries.GetNasSettings)+ )+ if (!result.ok) throw new Error('NAS configuration unavailable')+ if (current !== generation.current) return+ if (preserve) {+ setError(+ result.value.revision === currentView.current?.revision+ ? null+ : 'conflict'+ )+ return+ }+ currentView.current = result.value+ setView(result.value)+ setRootsText(result.value.settings.roots.join('\n'))+ reset({+ ...result.value.settings,+ operatorUrl: foldersOnly+ ? result.value.settings.operatorUrl+ : result.value.settings.operatorUrl ||+ synologyConnectionUrls(location.origin).operatorUrl,+ })+ setError(null)+ setLoad({ ready: true, error: false })+ } catch {+ if (current === generation.current) {+ if (preserve) setError('unavailable')+ else setLoad({ ready: false, error: true })+ }+ }+ },+ [reset, foldersOnly]+ )+ useEffect(() => {+ const unsubscribe = transport.onConnectionChange?.(({ state }) => {+ if (state !== 'connected') return+ void refresh(true)+ })+ void refresh()+ return () => {+ generation.current+++ unsubscribe?.()+ }+ }, [refresh])+ const extensionUrl = form.watch('extensionUrl')+ const busy = form.formState.isSubmitting+ const applyCurrentAddress = () => {+ const urls = synologyConnectionUrls(location.origin)+ form.setValue('operatorUrl', urls.operatorUrl, { shouldDirty: true })+ if (form.getValues('extensionUrl'))+ form.setValue('extensionUrl', urls.extensionUrl, { shouldDirty: true })+ }+ const submit = useSettingsSubmit(form, async (settings) => {+ if (!view || !load.ready) return+ const current = ++generation.current+ saving.current = true+ setError(null)+ // Package grants are host-owned configuration, not generic app preferences.+ try {+ const result = nasSettingsResultSchema.parse(+ await transport.invoke(Commands.SaveNasSettings, {+ revision: view.revision,+ settings,+ })+ )+ if (current !== generation.current) return+ if (!result.ok) {+ setError(result.error.code)+ return+ }+ currentView.current = result.value+ setView(result.value)+ form.reset(result.value.settings)+ setRootsText(result.value.settings.roots.join('\n'))+ } finally {+ saving.current = false+ }+ })+ const activeOperator =+ view?.active.operatorUrl ||+ synologyConnectionUrls(location.origin).operatorUrl+ let cliAddress = `${location.origin}/motrix/client`+ try {+ cliAddress = `${new URL(activeOperator).origin}/motrix/client`+ } catch {+ /* The form can repair an invalid legacy URL. */+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(value, details) => {+ if (!value) {+ if (busy) details.cancel()+ else onClose()+ }+ }}+ >+ <DialogContent+ className="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"+ initialFocus={false}+ >+ <DialogHeader className="shrink-0 px-6 pt-6">+ <DialogTitle>{t(labelKey)}</DialogTitle>+ <DialogDescription>{t('settings.nas.description')}</DialogDescription>+ </DialogHeader>+ <ScrollArea className="flex min-h-0 min-w-0 flex-1 flex-col">+ <ScrollAreaViewport+ tabIndex={-1}+ className="min-h-0 flex-1 overscroll-contain"+ >+ <ScrollAreaContent+ className="space-y-4 px-6 py-4"+ style={{ minWidth: '100%' }}+ >+ <SettingsLoadStatus {...load} retry={refresh} />+ <p className="text-xs text-muted-foreground">+ {t('settings.nas.account', { username })}+ </p>+ {view?.restartRequired && (+ <Alert>+ <AlertDescription>+ {t('settings.nas.restartRequired')}+ </AlertDescription>+ </Alert>+ )}+ <Form {...form}>+ <form noValidate onSubmit={submit}>+ <fieldset+ className="min-w-0 space-y-5"+ disabled={!load.ready || busy}+ inert={!load.ready || busy}+ >+ <section+ className="space-y-3"+ aria-label={t('settings.nas.roots')}+ >+ {!foldersOnly && (+ <h3 className="text-sm font-semibold">+ {t('settings.nas.roots')}+ </h3>+ )}+ <p className="text-xs text-muted-foreground">+ {t('settings.nas.rootsHint')}+ </p>+ <FormField+ control={form.control}+ name="roots"+ render={({ field }) => (+ <FormItem>+ <FormLabel className="sr-only">+ {t('settings.nas.roots')}+ </FormLabel>+ <FormControl>+ <Textarea+ ref={field.ref}+ name={field.name}+ onBlur={field.onBlur}+ rows={3}+ spellCheck={false}+ value={rootsText}+ placeholder="/volume1/motrix"+ onChange={(event) => {+ setRootsText(event.target.value)+ field.onChange(+ event.target.value+ .split(/\r?\n/)+ .map((value) =>+ value.trim().replace(/\/+$/, '')+ )+ .filter(Boolean)+ )+ }}+ />+ </FormControl>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ </section>+ {!foldersOnly && (+ <>+ <Separator />+ <FormField+ control={form.control}+ name="extensionUrl"+ render={({ field }) => (+ <FormItem className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.nas.extensionEnabled')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.nas.extensionHint')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={Boolean(field.value)}+ onCheckedChange={(enabled) => {+ if (!enabled) {+ field.onChange('')+ return+ }+ let urls: ReturnType<+ typeof synologyConnectionUrls+ >+ try {+ const origin = new URL(+ form.getValues('operatorUrl') ||+ location.origin+ ).origin+ urls = synologyConnectionUrls(origin)+ } catch {+ form.setError('operatorUrl', {+ message: t(+ 'settings.nas.errors.invalid'+ ),+ })+ return+ }+ if (!form.getValues('operatorUrl'))+ form.setValue(+ 'operatorUrl',+ urls.operatorUrl,+ { shouldDirty: true }+ )+ field.onChange(+ enabled ? urls.extensionUrl : ''+ )+ }}+ />+ </FormControl>+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="operatorUrl"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ {t('settings.nas.webAddress')}+ </FormLabel>+ <FormControl>+ <Input {...field} spellCheck={false} />+ </FormControl>+ <FormDescription className="text-xs">+ {t('settings.nas.webAddressHint')}+ </FormDescription>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={applyCurrentAddress}+ >+ {t('settings.nas.useCurrentAddress')}+ </Button>+ {extensionUrl && (+ <FormField+ control={form.control}+ name="extensionUrl"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ {t('settings.nas.extensionAddress')}+ </FormLabel>+ <FormControl>+ <Input {...field} spellCheck={false} />+ </FormControl>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ )}+ <FormField+ control={form.control}+ name="allowHttp"+ render={({ field }) => (+ <FormItem className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.nas.allowHttp')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.nas.allowHttpHint')}+ </FormDescription>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="clientPort"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ {t('settings.nas.clientPort')}+ </FormLabel>+ <FormControl>+ <Input+ type="number"+ min={1024}+ max={65535}+ {...field}+ onChange={(event) =>+ field.onChange(Number(event.target.value))+ }+ />+ </FormControl>+ <FormDescription className="text-xs">+ {t('settings.nas.clientPortHint')}+ </FormDescription>+ <FormMessage className="text-xs" />+ </FormItem>+ )}+ />+ </>+ )}+ </fieldset>+ </form>+ </Form>+ {view && !foldersOnly && (+ <section+ className="space-y-3 border-t pt-4"+ aria-label={t('settings.nas.activeConnections')}+ >+ <h3 className="text-sm font-semibold">+ {t('settings.nas.activeConnections')}+ </h3>+ <p className="text-xs text-muted-foreground">+ {t('settings.nas.sessionHint')}+ </p>+ <ConnectionAddress+ label={t('settings.nas.cliAddress')}+ value={cliAddress}+ />+ {view.active.extensionUrl && (+ <ConnectionAddress+ label={t('settings.nas.extensionAddress')}+ value={view.active.extensionUrl}+ />+ )}+ </section>+ )}+ {error && (+ <Alert variant="destructive">+ <AlertDescription>+ {t(`settings.nas.errors.${error}`)}+ </AlertDescription>+ {error === 'conflict' && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => void refresh()}+ >+ {t('common.retry')}+ </Button>+ )}+ </Alert>+ )}+ {form.formState.errors.root?.save && (+ <p role="alert" className="text-xs text-destructive">+ {form.formState.errors.root.save.message}+ </p>+ )}+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollBar />+ </ScrollArea>+ <DialogFooter className="shrink-0 border-t border-border px-6 py-4">+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={onClose}+ >+ {t('common.close')}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={!load.ready || busy || error === 'conflict'}+ onClick={submit}+ >+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++function ConnectionAddress({ label, value }: { label: string; value: string }) {+ const { t } = useTranslation()+ return (+ <div className="space-y-1">+ <p className="text-xs font-medium">{label}</p>+ <div className="flex gap-2">+ <Input aria-label={label} value={value} readOnly spellCheck={false} />+ <CopyButton content={value} size="sm" variant="outline">+ {t('settings.nas.copy')}+ </CopyButton>+ </div>+ </div>+ )+}diff --git a/src/renderer/routes/settings/settings-page.tsx b/src/renderer/routes/settings/settings-page.tsxindex 8581d4db..57d135e2 100644--- a/src/renderer/routes/settings/settings-page.tsx+++ b/src/renderer/routes/settings/settings-page.tsx@@ -1,9 +1,10 @@import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'+import { useOperatorSession } from '@renderer/lib/operator-auth'import { transport } from '@renderer/lib/transport'import { cn } from '@renderer/lib/utils'import { useTranslation } from 'react-i18next'import { useLocation, useNavigate, useParams } from 'react-router'-import { findCard, SETTINGS_CARDS } from './card-registry'+import { findCard, NAS_SETTINGS_CARD, SETTINGS_CARDS } from './card-registry'import { SettingsCard } from './cards/settings-card'export function SettingsPage() {@@ -12,9 +13,17 @@ export function SettingsPage() {const location = useLocation()const visible = /^\/settings(?:\/|$)/.test(location.pathname)const { cardId } = useParams<{ cardId: string }>()- const activeCard = findCard(cardId)+ const isSynology = useOperatorSession(+ (session) =>+ session.status?.mode === 'synologyDsm' &&+ session.status.nasCapabilities?.settings === true+ )+ const cards = isSynology+ ? [...SETTINGS_CARDS, NAS_SETTINGS_CARD]+ : SETTINGS_CARDS+ const activeCard = findCard(cardId, cards)const lastRowStart = (columns: number) =>- Math.floor((SETTINGS_CARDS.length - 1) / columns) * columns+ Math.floor((cards.length - 1) / columns) * columnsconst closeDialog = () => navigate('/settings')@@ -27,7 +36,7 @@ export function SettingsPage() {data-slot="settings-grid"className="grid min-h-0 flex-1 grid-cols-1 content-start items-stretch overflow-y-auto border-t-[0.5px] px-2 py-2 min-[914px]:content-stretch @min-[400px]/settings:grid-cols-2 @min-[400px]/settings:px-6 @min-[400px]/settings:py-4 @min-[600px]/settings:grid-cols-3">- {SETTINGS_CARDS.map((card, index) => (+ {cards.map((card, index) => (<SettingsCardkey={card.id}icon={card.icon}diff --git a/src/server/http/app.ts b/src/server/http/app.tsindex 522c7921..1b993f22 100644--- a/src/server/http/app.ts+++ b/src/server/http/app.ts@@ -46,6 +46,7 @@ import {isExtensionPairingCodeEvent,} from './extension-pairing-delivery'import { registerFnosAuth } from './fnos-auth'+import { type NasGatewayOptions, registerNasAuth } from './nas-auth'import { type OperatorAuthOptions, registerOperatorAuth } from './operator-auth'import { ServiceUnavailableError } from './service-unavailable-error'import {@@ -116,6 +117,7 @@ export interface AppOptions {clientPairing?: ClientPairingCapabilitiesbasePath?: stringfnosGateway?: FnosGatewayOptions+ nasGateway?: NasGatewayOptions/** Torrent-only RPC budget; defaults to 8 MiB, configurable from 2 to 64 MiB. */torrentBodyLimitBytes?: numbercommandHandlers?: CommandHandlerMap@@ -145,7 +147,10 @@ export interface AppOptions {export async function createApp(opts: AppOptions = {}): Promise<FastifyInstance> {- if (opts.fnosGateway && opts.operatorAuth)+ if (+ [opts.fnosGateway, opts.nasGateway, opts.operatorAuth].filter(Boolean)+ .length > 1+ )throw new Error('Authentication modes are mutually exclusive')const clientPairing =opts.clientPairing === undefined@@ -162,14 +167,17 @@ export async function createApp(// Register the deny-by-default operator gate FIRST so its onRequest hook runs// before every route (including /api/* added by the caller post-createApp and// the /rpc/events WS upgrade).- const operatorSessions = opts.fnosGateway- ? registerFnosAuth(app, opts.fnosGateway, clientPairing)- : opts.operatorAuth- ? registerOperatorAuth(app, {- ...opts.operatorAuth,- clientPairing: clientPairing ?? opts.operatorAuth.clientPairing,- })- : undefined+ const nasGateway = opts.nasGateway ?? opts.fnosGateway+ const operatorSessions = opts.nasGateway+ ? registerNasAuth(app, opts.nasGateway, clientPairing)+ : opts.fnosGateway+ ? registerFnosAuth(app, opts.fnosGateway, clientPairing)+ : opts.operatorAuth+ ? registerOperatorAuth(app, {+ ...opts.operatorAuth,+ clientPairing: clientPairing ?? opts.operatorAuth.clientPairing,+ })+ : undefinedif (!operatorSessions) {app.get('/rpc/auth/status', async () => ({authed: true,@@ -202,7 +210,7 @@ export async function createApp(if (!(principal &&- (opts.fnosGateway+ (nasGateway? canDeliverGatewayExtensionPairingCode(opts.remoteExtensionConfig,req.headers[WEB_ORIGIN_HEADER]@@ -260,7 +268,7 @@ export async function createApp(// An installation without a pairing surface has no pending requests.// Once configured, NAS hosts use the ordinary operator-gated inbox.if (- opts.fnosGateway &&+ nasGateway &&!clientPairing?.cli &&!clientPairing?.extension &&req.params.channel === BridgeQueries.ListPendingPairRequestsdiff --git a/src/server/http/fnos-auth.ts b/src/server/http/fnos-auth.tsindex c9267737..578bc7c5 100644--- a/src/server/http/fnos-auth.ts+++ b/src/server/http/fnos-auth.ts@@ -1,206 +1,41 @@-import { randomBytes } from 'node:crypto'-import { getLogger } from '@core/logger'-import {- type ClientPairingCapabilities,- FNOS_EVENT_PROTOCOL,- FNOS_EVENT_TICKET_PREFIX,- WEB_ORIGIN_HEADER,-} from '@shared/schemas/operator-auth'-import type { FastifyInstance, FastifyRequest } from 'fastify'+import type { ClientPairingCapabilities } from '@shared/schemas/operator-auth'+import type { FastifyInstance } from 'fastify'import {type FnosGatewayOptions,fnosIdentityDiagnostic,fnosPrincipal,isFnosListener,} from '../platform/fnos/identity'-import { runAsNasGatewayUser } from '../platform/nas/identity'-import type { OperatorSessionPolicy } from './operator-auth'--type Principal = NonNullable<ReturnType<typeof fnosPrincipal>>-interface EventTicket {- principal: Principal- origin: string- expiresAt: number- sessionExpiresAt: number-}--function browserOrigin(value: unknown): string | undefined {- if (typeof value !== 'string') return undefined- try {- const parsed = new URL(value)- if (- ['http:', 'https:'].includes(parsed.protocol) &&- parsed.origin === value- )- return value- } catch {- /* Reject malformed or opaque origins. */- }- return undefined-}--/** A cross-origin browser cannot supply this non-safelisted header without a- * CORS preflight. This listener never permits preflights or enables CORS.- * fnOS rewrites Host (including its port), so it cannot identify the browser- * origin. The marker must also match Origin when the browser supplies it. */-function requestOrigin(req: FastifyRequest): string | undefined {- const marker = browserOrigin(req.headers[WEB_ORIGIN_HEADER])- if (- !marker ||- (req.headers.origin !== undefined && req.headers.origin !== marker)- )- return undefined- const site = req.headers['sec-fetch-site']- if (site !== undefined && site !== 'same-origin' && site !== 'none')- return undefined- return marker-}+import { registerNasAuth } from './nas-auth'export function registerFnosAuth(app: FastifyInstance,opts: FnosGatewayOptions,- clientPairing: ClientPairingCapabilities = { cli: false, extension: false }-): OperatorSessionPolicy {- const log = getLogger('fnos:auth')- const now = opts.now ?? Date.now- let lastRejectionAt = -Infinity- const tickets = new Map<string, EventTicket>()- const identities = new WeakMap<FastifyRequest, Principal>()- const socketExpirations = new WeakMap<FastifyRequest, number>()- app.addHook('onClose', async () => {- tickets.clear()- })- app.addHook('onRequest', async (req, reply) => {- reply.header('cache-control', 'no-store')- const pathname = req.url.split('?')[0]- if (req.method === 'GET' && pathname === '/healthz') return- const upgrade = req.headers.upgrade?.toLowerCase() === 'websocket'- let principal = fnosPrincipal(req, opts)- let reason: string | undefined- if (!isFnosListener(req, opts)) reason = 'untrusted-listener'- else if (upgrade) {- const protocols = String(req.headers['sec-websocket-protocol'] ?? '')- .split(',')- .map((value) => value.trim())- const token =- protocols.length === 2 &&- protocols[0] === FNOS_EVENT_PROTOCOL &&- protocols[1].startsWith(FNOS_EVENT_TICKET_PREFIX)- ? protocols[1].slice(FNOS_EVENT_TICKET_PREFIX.length)- : ''- const ticket = tickets.get(token)- tickets.delete(token)- const hasIdentityHeaders = [- 'x-trim-userid',- 'x-trim-isadmin',- 'x-trim-username',- ].some((key) => req.headers[key] !== undefined)- if (!ticket || ticket.expiresAt <= now()) reason = 'event-ticket-required'- else if (req.headers.origin !== ticket.origin) reason = 'origin-mismatch'- else if (- hasIdentityHeaders &&- (!principal || principal.uid !== ticket.principal.uid)- )- reason = 'identity-rejected'- else {- // Some gateway versions omit X-Trim-* on upgrades. Only a one-use- // ticket from a freshly authenticated HTTP request can supply identity.- principal = ticket.principal- socketExpirations.set(req, ticket.sessionExpiresAt)- }- } else if (!principal) reason = 'identity-rejected'- else if (- req.method !== 'GET' &&- req.method !== 'HEAD' &&- !requestOrigin(req)- )- reason = 'origin-mismatch'- if (reason || !principal) {- const code = reason === 'origin-mismatch' ? 403 : 401- const diagnostic = fnosIdentityDiagnostic(req, opts)- if (now() - lastRejectionAt >= 60_000) {- lastRejectionAt = now()- log.warn({ reason, diagnostic }, 'fnOS gateway request rejected')- }- if (upgrade) {- reply.hijack()- req.raw.socket.end(- `HTTP/1.1 ${code} ${code === 403 ? 'Forbidden' : 'Unauthorized'}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`- )- return- }- return reply.code(code).send({- error: 'fnos administrator session required',- reason,- diagnostic,- })- }- identities.set(req, principal)- })- app.get('/rpc/auth/status', async (req) => ({- authed: true,- mode: 'fnosGateway',- canLogout: false,- username: identities.get(req)?.username,- clientPairing,- }))- app.post('/rpc/auth/event-ticket', async (req, reply) => {- const principal = identities.get(req)- const origin = requestOrigin(req)- if (!principal || !origin)- return reply.code(403).send({ error: 'unauthorized' })- for (const [key, ticket] of tickets)- if (ticket.expiresAt <= now()) tickets.delete(key)- if (tickets.size >= 256)- return reply- .code(429)- .send({ error: 'too many pending event connections' })- const token = randomBytes(24).toString('base64url')- tickets.set(token, {- principal,- origin,- expiresAt: now() + 30_000,- sessionExpiresAt: now() + 60_000,- })- return { ticket: token }- })- app.addHook('preHandler', (req, _reply, done) => {- const principal = identities.get(req)- if (!principal) done()- else- runAsNasGatewayUser(- {- platform: 'fnos',- userId: String(principal.uid),- username: principal.username,- administrator: true,- },- done- )- })- return {- principal(req) {- const user = identities.get(req)- return user ? { id: `fnos:${user.uid}`, eligible: () => true } : undefined+ clientPairing?: ClientPairingCapabilities+) {+ return registerNasAuth(+ app,+ {+ mode: 'fnosGateway',+ now: opts.now,+ isListener: (req) => isFnosListener(req, opts),+ authenticate(req) {+ const user = fnosPrincipal(req, opts)+ return user+ ? {+ platform: 'fnos',+ userId: String(user.uid),+ username: user.username,+ administrator: true,+ }+ : undefined+ },+ hasIdentity: (req) =>+ ['x-trim-userid', 'x-trim-isadmin', 'x-trim-username'].some(+ (key) => req.headers[key] !== undefined+ ),+ diagnostic: (req) => fnosIdentityDiagnostic(req, opts),},- bindSocket(req, socket) {- const expiration = socketExpirations.get(req) ?? now()- let eligible = identities.has(req) && expiration > now()- const timer = setTimeout(- () => {- eligible = false- socket.close(4401, 'Gateway reauthentication required')- },- Math.max(0, expiration - now())- )- timer.unref()- return {- eligible: () => eligible && expiration > now(),- dispose: () => {- clearTimeout(timer)- eligible = false- },- }- },- }+ clientPairing+ )}diff --git a/src/server/http/nas-auth.ts b/src/server/http/nas-auth.tsnew file mode 100644index 00000000..c77426e7--- /dev/null+++ b/src/server/http/nas-auth.ts@@ -0,0 +1,251 @@+import { randomBytes } from 'node:crypto'+import { getLogger } from '@core/logger'+import {+ type ClientPairingCapabilities,+ FNOS_EVENT_PROTOCOL,+ FNOS_EVENT_TICKET_PREFIX,+ type NasCapabilities,+ nasAuthDiagnosticSchema,+ WEB_ORIGIN_HEADER,+} from '@shared/schemas/operator-auth'+import { webEventRenewalSchema } from '@shared/schemas/web-event-stream'+import type { FastifyInstance, FastifyRequest } from 'fastify'+import type { NasIdentity } from '../platform/nas/identity'+import { runAsNasGatewayUser } from '../platform/nas/identity'+import { NAS_EVENT_AUTH_MS, NasEventSessions } from './nas-event-sessions'+import type { OperatorSessionPolicy } from './operator-auth'++type Principal = NasIdentity+export interface NasGatewayOptions {+ mode: 'fnosGateway' | 'synologyDsm'+ now?: () => number+ isListener(req: FastifyRequest): boolean+ authenticate(+ req: FastifyRequest+ ): Principal | undefined | Promise<Principal | undefined>+ hasIdentity(req: FastifyRequest): boolean+ diagnostic?(req: FastifyRequest): object | undefined+ publicShell?: boolean+ capabilities?: NasCapabilities+ unavailableDownloadRoots?: readonly string[]+}+interface EventTicket {+ principal: Principal+ origin: string+ expiresAt: number+ sessionExpiresAt: number+}++function browserOrigin(value: unknown): string | undefined {+ if (typeof value !== 'string') return undefined+ try {+ const parsed = new URL(value)+ if (+ ['http:', 'https:'].includes(parsed.protocol) &&+ parsed.origin === value+ )+ return value+ } catch {+ /* Reject malformed or opaque origins. */+ }+ return undefined+}++/** A cross-origin browser cannot supply this non-safelisted header without a+ * CORS preflight. This listener never permits preflights or enables CORS.+ * fnOS rewrites Host (including its port), so it cannot identify the browser+ * origin. The marker must also match Origin when the browser supplies it. */+function requestOrigin(req: FastifyRequest): string | undefined {+ const marker = browserOrigin(req.headers[WEB_ORIGIN_HEADER])+ if (+ !marker ||+ (req.headers.origin !== undefined && req.headers.origin !== marker)+ )+ return undefined+ const site = req.headers['sec-fetch-site']+ if (site !== undefined && site !== 'same-origin' && site !== 'none')+ return undefined+ return marker+}++export function registerNasAuth(+ app: FastifyInstance,+ opts: NasGatewayOptions,+ clientPairing: ClientPairingCapabilities = { cli: false, extension: false }+): OperatorSessionPolicy {+ const log = getLogger('nas:auth')+ const now = opts.now ?? Date.now+ const sessions = new NasEventSessions(now)+ let lastRejectionAt = -Infinity+ const tickets = new Map<string, EventTicket>()+ const identities = new WeakMap<FastifyRequest, Principal>()+ const socketExpirations = new WeakMap<FastifyRequest, number>()+ app.addHook('onClose', async () => {+ tickets.clear()+ })+ app.addHook('onRequest', async (req, reply) => {+ reply.header('cache-control', 'no-store')+ const pathname = req.url.split('?')[0]+ if (req.method === 'GET' && pathname === '/healthz') return+ const upgrade = req.headers.upgrade?.toLowerCase() === 'websocket'+ let principal = await opts.authenticate(req)+ let reason: string | undefined+ if (!opts.isListener(req)) reason = 'untrusted-listener'+ else if (upgrade) {+ const protocols = String(req.headers['sec-websocket-protocol'] ?? '')+ .split(',')+ .map((value) => value.trim())+ const token =+ protocols.length === 2 &&+ protocols[0] === FNOS_EVENT_PROTOCOL &&+ protocols[1].startsWith(FNOS_EVENT_TICKET_PREFIX)+ ? protocols[1].slice(FNOS_EVENT_TICKET_PREFIX.length)+ : ''+ const ticket = tickets.get(token)+ tickets.delete(token)+ const hasIdentityHeaders = opts.hasIdentity(req)+ if (!ticket || ticket.expiresAt <= now()) reason = 'event-ticket-required'+ else if (req.headers.origin !== ticket.origin) reason = 'origin-mismatch'+ else if (+ hasIdentityHeaders &&+ (!principal ||+ principal.userId !== ticket.principal.userId ||+ principal.username !== ticket.principal.username ||+ principal.accountRevision !== ticket.principal.accountRevision)+ )+ reason = 'identity-rejected'+ else {+ // Some gateway versions omit X-Trim-* on upgrades. Only a one-use+ // ticket from a freshly authenticated HTTP request can supply identity.+ principal = ticket.principal+ socketExpirations.set(req, ticket.sessionExpiresAt)+ }+ } else if (!principal) reason = 'identity-rejected'+ else if (+ req.method !== 'GET' &&+ req.method !== 'HEAD' &&+ !requestOrigin(req)+ )+ reason = 'origin-mismatch'+ if (reason || !principal) {+ // A rejected DSM session can only consume its own origin-bound renewal+ // challenge and close the stream. All data routes still require identity.+ if (+ opts.mode === 'synologyDsm' &&+ reason === 'identity-rejected' &&+ !upgrade &&+ req.method === 'POST' &&+ pathname === '/rpc/auth/event-renew' &&+ requestOrigin(req)+ )+ return+ // An unauthenticated browser may load the shell and its status message;+ // all data and command endpoints remain behind the same gate.+ if (+ opts.publicShell &&+ opts.isListener(req) &&+ !upgrade &&+ req.method === 'GET' &&+ (pathname === '/rpc/auth/status' ||+ pathname === '/' ||+ pathname === '/index.html' ||+ pathname.startsWith('/assets/'))+ )+ return+ const code = reason === 'origin-mismatch' ? 403 : 401+ const diagnostic = opts.diagnostic?.(req)+ if (now() - lastRejectionAt >= 60_000) {+ lastRejectionAt = now()+ log.warn({ reason, diagnostic }, 'NAS gateway request rejected')+ }+ if (upgrade) {+ reply.hijack()+ req.raw.socket.end(+ `HTTP/1.1 ${code} ${code === 403 ? 'Forbidden' : 'Unauthorized'}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`+ )+ return+ }+ return reply.code(code).send({+ error: 'NAS administrator session required',+ reason,+ diagnostic,+ })+ }+ identities.set(req, principal)+ })+ app.get('/rpc/auth/status', async (req) => {+ const diagnostic =+ opts.mode === 'synologyDsm' && !identities.has(req)+ ? nasAuthDiagnosticSchema.safeParse(opts.diagnostic?.(req))+ : undefined+ return {+ authed: identities.has(req),+ mode: opts.mode,+ canLogout: false,+ username: identities.get(req)?.username,+ clientPairing,+ ...(opts.capabilities ? { nasCapabilities: opts.capabilities } : {}),+ ...(identities.has(req) && opts.unavailableDownloadRoots?.length+ ? { nasUnavailableDownloadRoots: opts.unavailableDownloadRoots }+ : {}),+ ...(diagnostic?.success ? { nasAuthDiagnostic: diagnostic.data } : {}),+ }+ })+ app.post('/rpc/auth/event-ticket', async (req, reply) => {+ const principal = identities.get(req)+ const origin = requestOrigin(req)+ if (!principal || !origin)+ return reply.code(403).send({ error: 'unauthorized' })+ for (const [key, ticket] of tickets)+ if (ticket.expiresAt <= now()) tickets.delete(key)+ if (tickets.size >= 256)+ return reply+ .code(429)+ .send({ error: 'too many pending event connections' })+ const token = randomBytes(24).toString('base64url')+ tickets.set(token, {+ principal,+ origin,+ expiresAt: now() + 30_000,+ sessionExpiresAt: now() + NAS_EVENT_AUTH_MS,+ })+ return { ticket: token }+ })+ if (opts.mode === 'synologyDsm') {+ app.post('/rpc/auth/event-renew', { bodyLimit: 512 }, (req, reply) => {+ const owner = identities.get(req)+ const origin = requestOrigin(req)+ const frame = webEventRenewalSchema.safeParse(req.body)+ if (!frame.success)+ return reply.code(400).send({ error: 'Invalid event renewal' })+ if (!origin || !sessions.renew(frame.data.challenge, origin, owner))+ return reply+ .code(owner ? 403 : 401)+ .send({ error: 'Event renewal denied' })+ return reply.code(204).send()+ })+ }+ app.addHook('preHandler', (req, _reply, done) => {+ const principal = identities.get(req)+ if (!principal) done()+ else runAsNasGatewayUser(principal, done)+ })+ return {+ principal(req) {+ const user = identities.get(req)+ return user+ ? { id: `${user.platform}:${user.userId}`, eligible: () => true }+ : undefined+ },+ bindSocket(req, socket) {+ return sessions.bind(+ socket,+ socketExpirations.get(req) ?? now(),+ identities.get(req),+ opts.mode === 'synologyDsm'+ ? browserOrigin(req.headers.origin)+ : undefined+ )+ },+ }+}diff --git a/src/server/http/nas-event-sessions.test.ts b/src/server/http/nas-event-sessions.test.tsnew file mode 100644index 00000000..b5834645--- /dev/null+++ b/src/server/http/nas-event-sessions.test.ts@@ -0,0 +1,191 @@+import {+ FNOS_EVENT_PROTOCOL,+ FNOS_EVENT_TICKET_PREFIX,+ WEB_ORIGIN_HEADER,+} from '@shared/schemas/operator-auth'+import type { WebEventRenewal } from '@shared/schemas/web-event-stream'+import Fastify from 'fastify'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import type { NasIdentity } from '../platform/nas/identity'+import { registerNasAuth } from './nas-auth'+import { NAS_EVENT_AUTH_MS, NasEventSessions } from './nas-event-sessions'++const origin = 'https://nas.example:5001'+const owner: NasIdentity = {+ platform: 'synology',+ userId: '4',+ username: 'alice',+ administrator: true,+ accountRevision: 'epoch-a',+}+beforeEach(() =>+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })+)+afterEach(() => vi.useRealTimers())++function fixture(renewable = true) {+ const sessions = new NasEventSessions(Date.now)+ const frames: WebEventRenewal[] = []+ const socket = {+ send: vi.fn((data: string, done: (err?: Error) => void) => {+ frames.push(JSON.parse(data))+ done()+ }),+ close: vi.fn(),+ }+ const bound = sessions.bind(+ socket,+ Date.now() + NAS_EVENT_AUTH_MS,+ owner,+ renewable ? origin : undefined+ )+ return { sessions, socket, bound, frames }+}++it('renews the same socket repeatedly with single-use, origin-bound challenges', () => {+ const { sessions, socket, bound, frames } = fixture()+ for (let round = 0; round < 3; round++) {+ vi.advanceTimersByTime(45_000)+ const c = frames[round].challenge+ expect(sessions.renew(c, 'https://other.example', owner)).toBe(false)+ expect(sessions.renew(c, origin, owner)).toBe(true)+ expect(sessions.renew(c, origin, owner)).toBe(false)+ expect(bound.eligible()).toBe(true)+ }+ expect(new Set(frames.map((f) => f.challenge)).size).toBe(3)+ expect(socket.close).not.toHaveBeenCalled()+ bound.dispose()+})++it.each([+ { userId: '5' },+ { username: 'bob' },+ { accountRevision: 'epoch-b' },+ { administrator: false },+])('closes on a different DSM principal: %o', (changed) => {+ const { sessions, socket, bound, frames } = fixture()+ vi.advanceTimersByTime(45_000)+ expect(+ sessions.renew(frames[0].challenge, origin, { ...owner, ...changed })+ ).toBe(false)+ expect(bound.eligible()).toBe(false)+ expect(socket.close).toHaveBeenCalledWith(4401, expect.any(String))+})++it.each(['disposed', 'expired', 'delayed timer'] as const)(+ 'cannot renew a %s socket',+ (reason) => {+ const { sessions, socket, bound, frames } = fixture()+ vi.advanceTimersByTime(45_000)+ if (reason === 'disposed') bound.dispose()+ else if (reason === 'expired') vi.advanceTimersByTime(15_000)+ else vi.setSystemTime(Date.now() + 15_000)+ expect(bound.eligible()).toBe(false)+ expect(sessions.renew(frames[0].challenge, origin, owner)).toBe(false)+ expect(socket.close).toHaveBeenCalledTimes(reason === 'disposed' ? 0 : 1)+ }+)++it('leaves a gateway without renewal support on its original deadline', () => {+ const { socket, bound, frames } = fixture(false)+ vi.advanceTimersByTime(NAS_EVENT_AUTH_MS)+ expect(frames).toHaveLength(0)+ expect(bound.eligible()).toBe(false)+ expect(socket.close).toHaveBeenCalledTimes(1)+})++it('renewing one tab cannot extend the other tab’s deadline', () => {+ const { sessions, socket, bound, frames } = fixture()+ const other = { send: vi.fn(), close: vi.fn() }+ const second = sessions.bind(+ other,+ Date.now() + NAS_EVENT_AUTH_MS,+ owner,+ origin+ )+ vi.advanceTimersByTime(45_000)+ expect(sessions.renew(frames[0].challenge, origin, owner)).toBe(true)+ vi.advanceTimersByTime(15_000)+ expect(second.eligible()).toBe(false)+ expect(other.close).toHaveBeenCalledOnce()+ expect(bound.eligible()).toBe(true)+ expect(socket.close).not.toHaveBeenCalled()+ bound.dispose()+})++it('uses current HTTP credentials to renew and closes on logout or account switch', async () => {+ const app = Fastify()+ const policy = registerNasAuth(app, {+ mode: 'synologyDsm',+ isListener: () => true,+ hasIdentity: () => true,+ authenticate: (req) =>+ req.headers.cookie === 'valid'+ ? owner+ : req.headers.cookie === 'other'+ ? { ...owner, userId: '9', username: 'bob' }+ : undefined,+ })+ let frame: WebEventRenewal | undefined+ const socket = {+ close: vi.fn(),+ send: (s: string, done: (error?: Error) => void) => {+ frame = JSON.parse(s)+ done()+ },+ }+ let bound: ReturnType<typeof policy.bindSocket> | undefined+ app.get('/rpc/events', async (req) => {+ bound = policy.bindSocket(req, socket)+ return { ok: true }+ })+ const headers = { cookie: 'valid', origin, [WEB_ORIGIN_HEADER]: origin }+ const post = (cookie: string, pageOrigin = origin) =>+ app.inject({+ method: 'POST',+ url: '/rpc/auth/event-renew',+ headers: { cookie, origin: pageOrigin, [WEB_ORIGIN_HEADER]: pageOrigin },+ payload: frame,+ })+ try {+ for (const [cookie, deniedStatus] of [+ ['expired', 401],+ ['other', 403],+ ] as const) {+ const { ticket } = (+ await app.inject({+ method: 'POST',+ url: '/rpc/auth/event-ticket',+ headers,+ })+ ).json()+ expect(+ (+ await app.inject({+ url: '/rpc/events',+ headers: {+ ...headers,+ upgrade: 'websocket',+ 'sec-websocket-protocol': `${FNOS_EVENT_PROTOCOL}, ${FNOS_EVENT_TICKET_PREFIX}${ticket}`,+ },+ })+ ).statusCode+ ).toBe(200)+ vi.advanceTimersByTime(45_000)+ expect(+ (await post('valid', 'https://different.example')).statusCode+ ).toBe(403)+ expect((await post('valid')).statusCode).toBe(204)+ expect((await post('valid')).statusCode).toBe(403)+ vi.advanceTimersByTime(45_000)+ expect(bound?.eligible()).toBe(true)+ expect((await post(cookie)).statusCode).toBe(deniedStatus)+ expect(bound?.eligible()).toBe(false)+ expect(socket.close).toHaveBeenCalledWith(4401, expect.any(String))+ bound?.dispose()+ }+ } finally {+ bound?.dispose()+ await app.close()+ }+})diff --git a/src/server/http/nas-event-sessions.ts b/src/server/http/nas-event-sessions.tsnew file mode 100644index 00000000..df516bde--- /dev/null+++ b/src/server/http/nas-event-sessions.ts@@ -0,0 +1,104 @@+import { randomBytes } from 'node:crypto'+import type { WebEventRenewal } from '@shared/schemas/web-event-stream'+import { sameNasAccount } from '../platform/nas/client-authorization'+import type { NasIdentity } from '../platform/nas/identity'+import type { SessionSocket } from './operator-auth'++export const NAS_EVENT_AUTH_MS = 60_000+const RENEW_BEFORE_EXPIRY_MS = 15_000++interface Renewal {+ origin: string+ accept(principal: NasIdentity | undefined): boolean+}++export class NasEventSessions {+ private readonly pending = new Map<string, Renewal>()++ constructor(private readonly now: () => number) {}++ renew(+ challenge: string,+ origin: string,+ principal: NasIdentity | undefined+ ): boolean {+ const renewal = this.pending.get(challenge)+ if (!renewal || renewal.origin !== origin) return false+ this.pending.delete(challenge)+ return renewal.accept(principal)+ }++ bind(+ socket: SessionSocket,+ initialExpiry: number,+ owner: NasIdentity | undefined,+ renewalOrigin?: string+ ) {+ let expiresAt = initialExpiry+ let active = true+ let challenge: string | undefined+ let warning: NodeJS.Timeout | undefined+ let expiry: NodeJS.Timeout | undefined+ const eligible = () => active && !!owner && this.now() < expiresAt+ const disarm = () => {+ clearTimeout(warning)+ clearTimeout(expiry)+ if (challenge) this.pending.delete(challenge)+ challenge = undefined+ }+ const dispose = () => {+ active = false+ disarm()+ }+ const close = () => {+ if (!active) return+ dispose()+ socket.close(4401, 'Gateway reauthentication required')+ }+ const schedule = () => {+ disarm()+ const remaining = Math.max(0, expiresAt - this.now())+ expiry = setTimeout(close, remaining)+ expiry.unref()+ if (!renewalOrigin || !owner) return+ warning = setTimeout(+ () => {+ if (!eligible()) return close()+ challenge = randomBytes(24).toString('base64url')+ this.pending.set(challenge, {+ origin: renewalOrigin,+ accept: (principal) => {+ if (+ !eligible() ||+ !principal?.administrator ||+ !sameNasAccount(principal, owner)+ ) {+ close()+ return false+ }+ expiresAt = this.now() + NAS_EVENT_AUTH_MS+ schedule()+ return true+ },+ })+ const frame: WebEventRenewal = {+ type: 'session-renewal',+ version: 1,+ challenge,+ }+ try {+ socket.send(JSON.stringify(frame), (error) => {+ if (error) close()+ })+ } catch {+ close()+ }+ },+ Math.max(0, remaining - RENEW_BEFORE_EXPIRY_MS)+ )+ warning.unref()+ }+ schedule()+ return { eligible, dispose }+ }+}diff --git a/src/server/http/operator-auth.ts b/src/server/http/operator-auth.tsindex a4936034..3e31e025 100644--- a/src/server/http/operator-auth.ts+++ b/src/server/http/operator-auth.ts@@ -174,8 +174,9 @@ function isPublic(method: string, url: string): boolean {return false}-interface SessionSocket {+export interface SessionSocket {close(code: number, reason: string): void+ send(data: string, callback: (error?: Error) => void): void}export interface OperatorSessionPolicy {diff --git a/src/server/index.ts b/src/server/index.tsindex 97bacc54..3f40d32d 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -115,6 +115,7 @@ import {defaultRecoveryFs,TaskRecoveryServiceImpl,} from '@core/task/task-recovery-service'+import { taskRowToDownloadTask } from '@core/task/task-row-to-download-task'import { TaskUpdatePublisher } from '@core/task/task-update-publisher'import { TorrentMetaStoreImpl } from '@core/task/torrent-meta-store'import { MagnetSelectionTimeout } from '@core/torrent/magnet-selection-timeout'@@ -132,6 +133,7 @@ import { resolveSupportedLocale } from '@shared/constants/locales'import { Commands } from '@shared/protocol/commands'import { Events } from '@shared/protocol/events'import type { TaskCreateCommandResult } from '@shared/schemas/add-task'+import { synologyFileStationUrl } from '@shared/schemas/nas-files'import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'import { EngineState } from '@shared/types/engine'import { getHiddenNotificationKinds } from '@shared/types/notification'@@ -175,9 +177,24 @@ import { FnosAccountAuthority } from './platform/fnos/accounts'import { FnosFiles } from './platform/fnos/files'import { registerFnosRoutes } from './platform/fnos/routes'import { fnosRuntime, listenFnos } from './platform/fnos/runtime'+import { listenNasClientGateway } from './platform/nas/client-gateway'import { NasFileRemover } from './platform/nas/file-remover'+import { registerNasFileRoutes } from './platform/nas/file-routes'+import { NasRecoveryAccess } from './platform/nas/recovery-access'import { NasTaskAccess } from './platform/nas/task-access'import { createNodePlatformServices } from './platform/services'+import { SynologyAccounts } from './platform/synology/accounts'+import { probeDsmApi } from './platform/synology/api'+import { SynologyFiles } from './platform/synology/files'+import { synologyGateway } from './platform/synology/identity'+import {+ dsmDefaultSaveDir,+ dsmGatewayGroupId,+ listenSynology,+ synologyRuntime,+} from './platform/synology/runtime'+import { synologySettingsHandlers } from './platform/synology/settings'+import { SynologyTaskFiles } from './platform/synology/task-files'import { createServerCapabilityHost } from './plugin/capability-host'import {createServerCommunityPluginPolicy,@@ -209,9 +226,13 @@ let requestActiveServerExit: ((code: number) => Promise<void>) | null = nullasync function main() {const fnos = fnosRuntime()+ const synology = synologyRuntime()+ const nas = fnos ?? synology+ const dsmAccounts = synology ? new SynologyAccounts() : undefined// ─── Logger ───────────────────────────────────────────────────initLogger(pino({ level: process.env.LOG_LEVEL ?? 'info' }))const log = getLogger('server')+ const dsmAuthority = synology ? await probeDsmApi() : undefinedconst torrentBodyLimitBytes = parseTorrentBodyLimit(process.env.MOTRIX_TORRENT_BODY_LIMIT_MIB)@@ -299,6 +320,59 @@ async function main() {onListenerError: (channel, err) =>log.warn({ err, channel }, 'event listener threw'),})+ const serverDir = path.dirname(fileURLToPath(import.meta.url))+ const rendererDir =+ process.env.MOTRIX_RENDERER_DIR ??+ path.resolve(serverDir, '..', 'renderer-web')+ const nasSettings =+ synology && dsmAccounts+ ? await synologySettingsHandlers(synology.variable, dsmAccounts)+ : undefined+ if (synology && dsmAccounts && nasSettings) {+ const unavailable = nasSettings.unavailableRoots+ if (unavailable.length) {+ // Keep the task database, finalize journals and engine session untouched+ // until every grant can be checked. A fresh start applies any repairs.+ const recoveryApp = await createApp({+ basePath: process.env.MOTRIX_WEB_BASE_PATH,+ rendererDir,+ eventBus,+ nasGateway: {+ ...synologyGateway(synology.socketPath, dsmAccounts),+ capabilities: {+ settings: true,+ fileActions: false,+ torrentPicker: false,+ clientGateway: false,+ },+ unavailableDownloadRoots: unavailable,+ },+ clientPairing: { cli: false, extension: false },+ commandHandlers: nasSettings.commandHandlers,+ queryHandlers: nasSettings.queryHandlers,+ healthCheck: () => ({+ ok: shellAsyncWork.isAccepting(),+ status: 'storage-recovery',+ engine: { state: EngineState.Stopped },+ }),+ })+ shutdownActions.closeIngress = () => recoveryApp.close()+ if (!shellAsyncWork.isAccepting()) {+ await recoveryApp.close()+ return+ }+ await listenSynology(recoveryApp, synology.socketPath)+ if (!shellAsyncWork.isAccepting()) {+ await recoveryApp.close()+ return+ }+ log.warn(+ { count: unavailable.length },+ 'DSM download folders unavailable; settings are available'+ )+ return+ }+ }const taskManager = new TaskManager()// Coalesces the per-commit TaskUpdated fan-out (see// docs/superpowers/specs/2026-08-07-task-updated-emit-coalescing-design.md).@@ -412,24 +486,30 @@ async function main() {geoipManager = activeGeoipManagershutdownActions.stopGeoIP = () => activeGeoipManager.stop()const hasDefaultSaveDirOverride =- !fnos && Boolean(process.env.MOTRIX_DEFAULT_SAVE_DIR?.trim())+ !nas && Boolean(process.env.MOTRIX_DEFAULT_SAVE_DIR?.trim())const effectiveDefaultSaveDir = hasDefaultSaveDirOverride? configuredDefaultSaveDir- : settingsManager.getApp().defaultSaveDir- const fnosFiles = fnos- ? new FnosFiles(process.env, process.env.MOTRIX_FNOS_API_SOCKET)- : undefined- const downloadPathPolicy = fnosFiles- ? await fnosFiles.policy(effectiveDefaultSaveDir)+ : synology+ ? dsmDefaultSaveDir(+ settingsManager.getApp().defaultSaveDir,+ configuredDefaultSaveDir,+ process.env.MOTRIX_ALLOWED_SAVE_DIRS+ )+ : settingsManager.getApp().defaultSaveDir+ const nasFiles =+ synology && dsmAccounts+ ? new SynologyFiles(synology.configFile, dsmAccounts)+ : fnos+ ? new FnosFiles(process.env, process.env.MOTRIX_FNOS_API_SOCKET)+ : undefined+ const downloadPathPolicy = nasFiles+ ? await nasFiles.policy(effectiveDefaultSaveDir): await createServerDownloadPathPolicy({defaultSaveDir: effectiveDefaultSaveDir,allowedSaveDirsValue: process.env.MOTRIX_ALLOWED_SAVE_DIRS,})- const nasTaskAccess = fnosFiles- ? new NasTaskAccess(fnosFiles, downloadPathPolicy)- : undefinedif (- hasDefaultSaveDirOverride &&+ (hasDefaultSaveDirOverride || synology) &&settingsManager.getApp().defaultSaveDir !== effectiveDefaultSaveDir) {await settingsManager.update({@@ -517,6 +597,13 @@ async function main() {const db = new MotrixDatabase(path.join(platform.userDataDir, 'motrix.db'))shutdownActions.closeDatabase = () => db.close()db.init()+ const dsmTaskFiles = synology+ ? new SynologyTaskFiles(db, downloadPathPolicy)+ : undefined+ await dsmTaskFiles?.initialize()+ const nasTaskAccess = nasFiles+ ? new NasTaskAccess(nasFiles, downloadPathPolicy, dsmTaskFiles)+ : undefined// Delivers durably-persisted terminal/diagnosis occurrences to in-process// consumers (timeline, failure log); see the "occurrence consumer@@ -620,7 +707,6 @@ async function main() {}await localeCoordinator.reconcile()if (!shellAsyncWork.isAccepting()) return- const serverDir = path.dirname(fileURLToPath(import.meta.url))const detectServerFfmpeg = makeServerFfmpegDetect({settingsManager,userDataDir: platform.userDataDir,@@ -792,6 +878,34 @@ async function main() {supervisor.setSessionRecoveryStore(sessionManager.getEngineSessionRecoveryStore())+ const nasRecoveryAccess = nasTaskAccess+ ? new NasRecoveryAccess({+ access: nasTaskAccess,+ policy: downloadPathPolicy,+ tempDir: runtimeDirectories.tempDir,+ getTask: (gid) => {+ const owners = db+ .getAllTasks()+ .filter((pair) =>+ pair.instances.some((instance) => instance.gid === gid)+ )+ return owners.length === 1+ ? taskRowToDownloadTask(owners[0].task, owners[0].instances)+ : undefined+ },+ getEnginePaths: async (gid) => {+ const state = await rpcClient.tellStatus(gid, ['dir', 'files'])+ return {+ directory: state.dir,+ files: state.files.map((file) => file.path),+ }+ },+ })+ : undefined+ if (nasRecoveryAccess)+ sessionManager.setRecoveryWriteAuthorization(+ nasRecoveryAccess.authorizeWrite+ )supervisor.setStartupGuard(new CompletedTaskStartupGuard({completedGids: () => sessionManager.getCompletedDirectEngineTaskIds(),@@ -803,6 +917,7 @@ async function main() {),rpc: rpcClient,removeResult: (gid) => adapter.removeDownloadResult(gid),+ authorizeResume: nasRecoveryAccess?.authorizeResume,}))supervisor.setPreReadyMaintenance(() =>@@ -974,13 +1089,21 @@ async function main() {proxyBridge)+ const createParent = (+ task: DownloadTask,+ persist: () => void | Promise<void>+ ) =>+ taskInspectorActivityRuntime.parentTaskCreated(+ task,+ dsmTaskFiles ? () => dsmTaskFiles.create(task, persist) : persist+ )+const completedEngineTaskCleanup = new CompletedEngineTaskCleanup({taskManager,adapter,mintTaskId: newTaskId,persist: persistTaskWithOccurrence,- adopt: (task, persist) =>- taskInspectorActivityRuntime.parentTaskCreated(task, persist),+ adopt: (task, persist) => createParent(task, persist),publish: publishTaskUpdateNow,dispatch: (occurrence) => occurrenceDispatcher.dispatch(occurrence),runTaskMutation: (ids, operation) =>@@ -1056,10 +1179,7 @@ async function main() {const id = newTaskId()const discoveredTask: DownloadTask = { ...translated, id }try {- await taskInspectorActivityRuntime.parentTaskCreated(- discoveredTask,- () => persistTask(discoveredTask)- )+ await createParent(discoveredTask, () => persistTask(discoveredTask))} catch (err) {// Persistence rejected before publication. The next poll can retry// adoption without exposing a task whose Activity parent is absent.@@ -1124,9 +1244,9 @@ async function main() {await mediaMetaStore.pruneOrphans(db.getAllTasks().map(({ task }) => task.motrixId)).catch((err) => log.warn({ err }, 'Media metadata recovery failed'))- const nasFileRemover = fnosFiles+ const nasFileRemover = nasFiles? new NasFileRemover(- fnosFiles,+ nasFiles,downloadPathPolicy,finalizeFilesystemAdapter,path.join(platform.userDataDir, 'nas-removals')@@ -1138,6 +1258,16 @@ async function main() {else await fs.rm(absPath, { recursive: true, force: true })},})+ const fileCleanupForTask =+ dsmTaskFiles && nasFileRemover+ ? (task: DownloadTask) =>+ new FileCleanupServiceImpl({+ removePathRecursive: (file) =>+ nasFileRemover.remove(file, (selected) =>+ dsmTaskFiles.removalIdentity(task, file, selected)+ ),+ })+ : undefinedconst torrentParser = new TorrentParser()const magnetTracker = new MagnetTracker(rpcClient,@@ -1151,7 +1281,7 @@ async function main() {publishTaskUpdate,publishTaskUpdateNow,parentTaskCreated: (task, persistParent) =>- taskInspectorActivityRuntime.parentTaskCreated(task, persistParent),+ createParent(task, persistParent),recordTransition: (input) =>taskInspectorActivityRuntime.recordTransition(input),deleteParentTask: (taskId, deleteParent) =>@@ -1225,7 +1355,14 @@ async function main() {)// ─── HTTP App ─────────────────────────────────────────────────- const serverDirectoryService = new ServerDirectoryService(downloadPathPolicy)+ const serverDirectoryService = new ServerDirectoryService(+ downloadPathPolicy,+ undefined,+ undefined,+ nasFiles+ ? (file) => nasFiles.authorizeFile(file, downloadPathPolicy)+ : undefined+ )const updateService = new ServerUpdateService({eventBus,currentVersion: appVersion,@@ -1239,6 +1376,9 @@ async function main() {authorizeTaskWrite: nasTaskAccess?.authorizeWrite,authorizeTaskRemoval: nasTaskAccess?.authorizeRemoval,btStorageRuntime: durableFinalizeRuntime,+ authorizeRecheck: dsmTaskFiles?.checkDirectory.bind(dsmTaskFiles),+ prepareStorageBinding:+ dsmTaskFiles?.prepareStorageBinding.bind(dsmTaskFiles),persistBtStorage: (task, source, target) =>sessionManager.persistBtStorage(task, source, target),operationService: pluginRuntime.operations,@@ -1272,6 +1412,7 @@ async function main() {finalNamePicker,torrentMetaStore,taskManager,+ fileCleanupForTask,fileCleanupService,eventBus,proxyApplier,@@ -1304,7 +1445,7 @@ async function main() {runTaskMutation: (taskIds, operation) =>taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),parentTaskCreated: (task, persistParent) =>- taskInspectorActivityRuntime.parentTaskCreated(task, persistParent),+ createParent(task, persistParent),publishTaskUpdate,publishTaskUpdateNow,downloadPathPolicy,@@ -1359,10 +1500,6 @@ async function main() {environment: process.env,})- const rendererDir =- process.env.MOTRIX_RENDERER_DIR ??- path.resolve(serverDir, '..', 'renderer-web')-// Operator (control-plane) secret — provisioned INDEPENDENTLY of the// (non-fatal) MDXP bridge so a bridge bootstrap failure can never lock the web// UI behind an unrecoverable in-memory token (Spec 9 / F1). Distinct from the@@ -1377,32 +1514,41 @@ async function main() {)const remoteExtensionConfig = parseRemoteExtensionConfig(process.env, {- requireWebOperator: fnos !== undefined,+ requireWebOperator: nas !== undefined,})- const nasAccounts = fnos?.accountSocketPath- ? new FnosAccountAuthority(fnos.accountSocketPath)- : undefined+ const nasAccounts =+ dsmAccounts ??+ (fnos?.accountSocketPath+ ? new FnosAccountAuthority(fnos.accountSocketPath)+ : undefined)+ let nasClientGateway:+ | Awaited<ReturnType<typeof listenNasClientGateway>>+ | undefinedconst app = await createApp({getHiddenNotificationKinds: () =>getHiddenNotificationKinds(settingsManager.getApp()),clientPairing: {- cli: !fnos || nasAccounts !== undefined,+ cli: !nas || nasAccounts !== undefined,extension:- (!fnos || nasAccounts !== undefined) &&+ (!nas || nasAccounts !== undefined) &&remoteExtensionConfig.status === 'enabled',},basePath: process.env.MOTRIX_WEB_BASE_PATH,fnosGateway: fnos,+ nasGateway:+ synology && dsmAccounts+ ? synologyGateway(synology.socketPath, dsmAccounts)+ : undefined,remoteExtensionConfig,torrentBodyLimitBytes,- commandHandlers,- queryHandlers,+ commandHandlers: { ...commandHandlers, ...nasSettings?.commandHandlers },+ queryHandlers: { ...queryHandlers, ...nasSettings?.queryHandlers },bridgeCommandHandlers: bridgeManager.bridgeCommandHandlers,bridgeQueryHandlers: bridgeManager.bridgeQueryHandlers,eventBus,pluginLogSource: pluginCapHost,rendererDir,- operatorAuth: fnos+ operatorAuth: nas? undefined: {operatorToken: operator.token,@@ -1410,13 +1556,16 @@ async function main() {onEventSocketRejected: (detail) =>log.warn(detail, 'operator event connection rejected'),},- healthCheck: () =>- serverHealthSnapshot({+ healthCheck: () => ({+ ...serverHealthSnapshot({accepting: shellAsyncWork.isAccepting(),engine: supervisor.getStatus(),}),+ ...(dsmAuthority ? { nasAuthority: dsmAuthority } : {}),+ }),})shutdownActions.closeIngress = async () => {+ await nasClientGateway?.close()pluginUploadStore.dispose()await app.close()}@@ -1427,8 +1576,17 @@ async function main() {}registerPluginUploadRoute(app, pluginUploadStore)- if (fnosFiles)- registerFnosRoutes(app, fnosFiles, downloadPathPolicy, (id) =>+ if (synology && nasFiles)+ registerNasFileRoutes(app, {+ files: nasFiles,+ policy: downloadPathPolicy,+ getTask: (id) => taskManager.getById(id),+ webBasePath: '/motrix',+ fileManagerUrl: synologyFileStationUrl,+ outputIdentity: dsmTaskFiles?.outputIdentity.bind(dsmTaskFiles),+ })+ if (fnos && nasFiles)+ registerFnosRoutes(app, nasFiles, downloadPathPolicy, (id) =>taskManager.getById(id))registerServerDiagnosticsRoute(app, async () => ({@@ -1473,7 +1631,7 @@ async function main() {}))registerTasksBulkRoutes(app, {- resumeAll: fnosFiles+ resumeAll: nasFiles? async () => {await commandHandlers[Commands.ResumeAllTasks]?.()}@@ -1632,6 +1790,16 @@ async function main() {},},torrentMetaStore,+ authorizeDirectoryForTask:+ dsmTaskFiles?.checkDirectory.bind(dsmTaskFiles),+ recordInPlaceOutput: dsmTaskFiles?.recordOutput.bind(dsmTaskFiles),+ removeTaskOutput:+ dsmTaskFiles && nasFileRemover+ ? (task: DownloadTask, file: string) =>+ nasFileRemover.remove(file, (selected) =>+ dsmTaskFiles.removalIdentity(task, file, selected)+ )+ : undefined,settings: {get: () => {const engine = settingsManager.getEngine()@@ -1870,7 +2038,15 @@ async function main() {// can observe an empty/partial TaskManager or a false TaskNotFound.const port = parseServerPort(process.env.PORT, 'PORT', 8080)try {- if (fnos) await listenFnos(app, fnos.socketPath)+ if (synology) {+ await listenSynology(app, synology.socketPath)+ nasClientGateway = await listenNasClientGateway({+ socketPath: synology.clientSocketPath,+ groupId: await dsmGatewayGroupId(),+ currentPort: () => bridgeManager.current?.port,+ extensionEnabled: () => remoteExtensionConfig.status === 'enabled',+ })+ } else if (fnos) await listenFnos(app, fnos.socketPath)else await app.listen({ port, host: '0.0.0.0' })} catch (err) {if (!shellAsyncWork.isAccepting()) return@@ -1884,8 +2060,8 @@ async function main() {}return}- const serverUrl = fnos- ? `unix:${fnos.socketPath}`+ const serverUrl = nas+ ? `unix:${nas.socketPath}`: `http://localhost:${port}`log.info({ port, url: serverUrl }, `server listening at ${serverUrl}`)@@ -1894,11 +2070,11 @@ async function main() {| 'bridge-data-lock'| 'trusted-extension-registry' = 'process-ownership'bridgeOwnershipSetup = (async () => {- if (fnos) {+ if (nas) {const authority = await establishLinuxServerProcessOwnershipAuthority({userDataDir: platform.userDataDir,assertControlPlaneOwnership: () =>- app.server.listening && app.server.address() === fnos.socketPath,+ app.server.listening && app.server.address() === nas.socketPath,})bridgeDataDirLockRecoveryAuthority = authorityshutdownActions.releaseProcessOwnership = authority.release@@ -1956,7 +2132,7 @@ async function main() {if (!shellAsyncWork.isAccepting()) return// Older native packages have no protected account authority. Keep client// ingress closed until the lifecycle launcher supplies that endpoint.- if (fnos && !nasAccounts) return+ if (nas && !nasAccounts) return// ─── MDXP bridge (Spec 6) ─────────────────────────────────────// Agent-facing unary POST /mdxp + SSE GET /mdxp/events, on its OWN port@@ -1972,6 +2148,7 @@ async function main() {taskManager,adapter,log,+ fileCleanupForTask,fileCleanupService,mediaMetaStore,torrentMetaStore,@@ -2011,8 +2188,7 @@ async function main() {parentTaskCreated: (task: DownloadTask,persistParent: () => void | Promise<void>- ) =>- taskInspectorActivityRuntime.parentTaskCreated(task, persistParent),+ ) => createParent(task, persistParent),rollbackTaskCreation: (taskId: string) =>sessionManager.runExclusivePersistence(() =>taskInspectorActivityRuntime.deleteParentTask(taskId, () => {@@ -2079,7 +2255,7 @@ async function main() {? 16801: fixedPortconst mdxpHost =- process.env.MOTRIX_MDXP_HOST ?? (fnos ? '0.0.0.0' : '127.0.0.1')+ process.env.MOTRIX_MDXP_HOST ?? (nas ? '0.0.0.0' : '127.0.0.1')if (remoteExtensionConfig.status === 'invalid') {log.warn({@@ -2093,7 +2269,7 @@ async function main() {mdxpHost,publicUrl: process.env.MOTRIX_PUBLIC_URL,})- if (publicUrlWarning && !fnos) {+ if (publicUrlWarning && !nas) {log.warn({reason: publicUrlWarning.reason,@@ -2176,10 +2352,7 @@ async function main() {persistTaskWithOccurrence,occurrenceDispatcher,parentTaskCreated: (task, persistParent) =>- taskInspectorActivityRuntime.parentTaskCreated(- task,- persistParent- ),+ createParent(task, persistParent),recordTransition: (input) =>taskInspectorActivityRuntime.recordTransition(input),runTaskMutation: (taskIds, operation) =>@@ -2189,7 +2362,7 @@ async function main() {})),// The web approval UI is a separate (Fastify) service; the operator points// device-code clients at it via MOTRIX_PUBLIC_URL. Unset → no URL printed.- verificationUri: fnos+ verificationUri: nas? remoteExtensionConfig.status === 'enabled'? remoteExtensionConfig.publicOperatorBaseUrl: undefineddiff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.tsindex 503e77b2..b3cb9dbe 100644--- a/src/server/ipc/commands.ts+++ b/src/server/ipc/commands.ts@@ -127,6 +127,8 @@ export interface ServerCommandContext {authorizeTaskWrite?: (task: DownloadTask) => Promise<void>authorizeTaskRemoval?: (task: DownloadTask) => Promise<void>authorizeOutputWrite?: (output: string) => Promise<void>+ authorizeRecheck?: (task: DownloadTask) => Promise<void>+ prepareStorageBinding?: import('@core/task/bt-storage-service').BtStorageServiceDeps['prepareStorageBinding']btStorageRuntime?: Pick<DurableFinalizeRuntime,'commit' | 'withArtifactLease' | 'hasPendingFinalization'@@ -165,6 +167,7 @@ export interface ServerCommandContext {torrentMetaStore: TorrentMetaStoretaskManager: TaskManagerfileCleanupService: FileCleanupService+ fileCleanupForTask?: (task: DownloadTask) => FileCleanupServiceeventBus: EventBusproxyApplier: ReturnType<typeof createServerProxyApplier>appliedDownloadProxyPolicy: AppliedDownloadProxyPolicy@@ -381,6 +384,8 @@ export function buildServerCommandHandlers(ctx.btStorageRuntime && ctx.persistBtStorage? new BtStorageService({authorizeOutputWrite: ctx.authorizeOutputWrite,+ prepareStorageBinding: ctx.prepareStorageBinding,+ authorizeRecheck: ctx.authorizeRecheck,...reAddDeps,runtime: ctx.btStorageRuntime,persistStorage: ctx.persistBtStorage,@@ -416,6 +421,7 @@ export function buildServerCommandHandlers(bindTaskRetry?.((id) => reAddTask(id, reAddDeps))const removeDeps = {authorizeTaskRemoval: ctx.authorizeTaskRemoval,+ fileCleanupForTask: ctx.fileCleanupForTask,cancelMedia: ctx.cancelMedia,taskManager,adapter,diff --git a/src/server/platform/fnos/open-file.ts b/src/server/platform/fnos/open-file.tsindex f0051b6f..e4c8992b 100644--- a/src/server/platform/fnos/open-file.ts+++ b/src/server/platform/fnos/open-file.ts@@ -1,59 +1 @@-import { constants } from 'node:fs'-import { lstat, open, readlink } from 'node:fs/promises'--// Linux O_PATH allows traversal through execute-only NAS ancestors. Node does-// not expose this flag; fnOS runs on Linux and requires procfs for this reader.-const O_PATH = 0x200000--/** Anchor every component to an open parent; never follow replacement links. */-export async function openFnosFile(- canonical: string,- authorize: (path: string) => Promise<string>-) {- if (process.platform !== 'linux' || !canonical.startsWith('/'))- throw new Error('Descriptor-relative file access is unavailable')- const parts = canonical.slice(1).split('/')- if (parts.some((part) => !part || part === '.' || part === '..'))- throw new Error('Invalid canonical file path')- const directoryFlags = O_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW- let parent = await open('/', directoryFlags)- try {- for (const part of parts.slice(0, -1)) {- const next = await open(- `/proc/self/fd/${parent.fd}/${part}`,- directoryFlags- )- const previous = parent- parent = next- await previous.close()- }- const file = await open(- `/proc/self/fd/${parent.fd}/${parts.at(-1)}`,- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK- )- try {- const descriptor = `/proc/self/fd/${file.fd}`- // A held ancestor may have been renamed. Authorize the opened file's- // actual location and confirm that the checked name still denotes it.- if ((await readlink(descriptor)) !== canonical)- throw new Error('File moved while opening')- if ((await authorize(canonical)) !== canonical)- throw new Error('File authorization changed')- const named = await lstat(canonical, { bigint: true })- const opened = await file.stat({ bigint: true })- if (- !opened.isFile() ||- named.dev !== opened.dev ||- named.ino !== opened.ino ||- (await readlink(descriptor)) !== canonical- )- throw new Error('File changed during authorization')- return file- } catch (error) {- await file.close()- throw error- }- } finally {- await parent.close()- }-}+export { openNasFile as openFnosFile } from '../nas/open-file'diff --git a/src/server/platform/fnos/routes.ts b/src/server/platform/fnos/routes.tsindex c5e8df69..0a0b2d0f 100644--- a/src/server/platform/fnos/routes.ts+++ b/src/server/platform/fnos/routes.ts@@ -1,13 +1,12 @@import path from 'node:path'-import { MAX_TORRENT_FILE_SIZE } from '@shared/lib/torrent-meta'import type { DownloadTask } from '@shared/types/task'import { canOpenTaskFile } from '@shared/types/task-actions'import type { FastifyInstance } from 'fastify'import { z } from 'zod'import type { ServerDownloadPathPolicy } from '../../download-path-policy'+import { readNasTorrent } from '../nas/file-routes'import type { NasFiles } from '../nas/files'import { currentNasUser } from '../nas/identity'-import { openFnosFile } from './open-file'const pathSchema = z.object({ path: z.string().min(1).max(4096) }).strict()const taskSchema = z@@ -68,34 +67,8 @@ export function registerFnosRoutes()return reply.code(400).send({ error: 'invalid torrent path' })try {- const candidate = await files.authorizeFile(body.data.path, policy, user)- const handle = await openFnosFile(candidate, (opened) =>- files.authorizeFile(opened, policy, user)- )- try {- const info = await handle.stat()- if (!info.isFile() || info.size > MAX_TORRENT_FILE_SIZE)- throw new Error('Invalid torrent file')- // Bounded read also handles a file growing after stat.- const data = Buffer.alloc(info.size + 1)- let size = 0- while (size < data.length) {- const { bytesRead } = await handle.read(- data,- size,- data.length - size,- size- )- if (!bytesRead) break- size += bytesRead- }- if (size !== info.size) throw new Error('Torrent changed')- return reply- .type('application/x-bittorrent')- .send(data.subarray(0, size))- } finally {- await handle.close()- }+ const data = await readNasTorrent(body.data.path, files, policy, user)+ return reply.type('application/x-bittorrent').send(data)} catch {return reply.code(403).send({ error: 'torrent not authorized' })}diff --git a/src/server/platform/fnos/runtime.ts b/src/server/platform/fnos/runtime.tsindex 9b544e1a..85d7e3ea 100644--- a/src/server/platform/fnos/runtime.ts+++ b/src/server/platform/fnos/runtime.ts@@ -1,10 +1,13 @@-import { chmod, lstat, unlink } from 'node:fs/promises'-import { connect } from 'node:net'import path from 'node:path'-import type { FastifyInstance } from 'fastify'++export { listenNas as listenFnos } from '../nas/listener'export function fnosRuntime(env: NodeJS.ProcessEnv = process.env) {- if (env.MOTRIX_AUTH_MODE === undefined || env.MOTRIX_AUTH_MODE === 'operator')+ if (+ env.MOTRIX_AUTH_MODE === undefined ||+ env.MOTRIX_AUTH_MODE === 'operator' ||+ env.MOTRIX_AUTH_MODE === 'synologyDsm'+ )return undefinedif (env.MOTRIX_AUTH_MODE !== 'fnosGateway')throw new Error('Invalid MOTRIX_AUTH_MODE')@@ -21,41 +24,3 @@ export function fnosRuntime(env: NodeJS.ProcessEnv = process.env) {throw new Error('Invalid fnOS account authority socket')return { socketPath: path.join(target, 'app.sock'), accountSocketPath }}--export async function listenFnos(- app: FastifyInstance,- socketPath: string-): Promise<void> {- const before = await lstat(socketPath).catch(- (error: NodeJS.ErrnoException) => {- if (error.code === 'ENOENT') return undefined- throw error- }- )- if (before) {- if (!before.isSocket() || before.uid !== process.getuid?.())- throw new Error('Refusing to replace an unowned socket path')- await new Promise<void>((resolve, reject) => {- const probe = connect(socketPath)- probe.setTimeout(1_000, () => {- probe.destroy()- reject(new Error('Gateway socket is busy'))- })- probe.once('connect', () => {- probe.destroy()- reject(new Error('Gateway socket is already listening'))- })- probe.once('error', (error: NodeJS.ErrnoException) => {- if (error.code === 'ECONNREFUSED') resolve()- else reject(error)- })- })- const current = await lstat(socketPath)- if (before.dev !== current.dev || before.ino !== current.ino)- throw new Error('Gateway socket changed during startup')- await unlink(socketPath)- }- await app.listen({ path: socketPath })- // Only the package account and root gateway may submit identity headers.- await chmod(socketPath, 0o600)-}diff --git a/src/server/platform/nas/client-gateway.test.ts b/src/server/platform/nas/client-gateway.test.tsnew file mode 100644index 00000000..ca41f0a4--- /dev/null+++ b/src/server/platform/nas/client-gateway.test.ts@@ -0,0 +1,180 @@+import { once } from 'node:events'+import { mkdtemp, rm } from 'node:fs/promises'+import { createServer, request } from 'node:http'+import net from 'node:net'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { WebSocket, WebSocketServer } from 'ws'+import { listenNasClientGateway } from './client-gateway'++const cleanups: (() => Promise<unknown>)[] = []+afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup()+})+async function fixture() {+ const root = await mkdtemp('/tmp/mtx-nas-gateway-')+ cleanups.push(() => rm(root, { recursive: true, force: true }))+ const seen: {+ url: string | undefined+ cookie: string | undefined+ authorization: string | undefined+ identity: unknown+ }[] = []+ const upstream = createServer((req, res) => {+ seen.push({+ url: req.url,+ cookie: req.headers.cookie,+ authorization: req.headers.authorization,+ identity: req.headers['x-trim-userid'],+ })+ res.setHeader('set-cookie', 'must-not-forward')+ res.end('ok')+ })+ upstream.listen(0, '127.0.0.1')+ await once(upstream, 'listening')+ cleanups.push(+ () => new Promise<void>((resolve) => upstream.close(() => resolve()))+ )+ const address = upstream.address()+ if (!address || typeof address === 'string')+ throw new Error('Missing test listener')+ let currentPort: number | undefined = address.port,+ enabled = false+ const socketPath = path.join(root, 'client.sock')+ const gateway = await listenNasClientGateway({+ socketPath,+ currentPort: () => currentPort,+ extensionEnabled: () => enabled,+ })+ cleanups.push(() => gateway.close())+ const call = (url: string, method = 'POST') =>+ new Promise<{+ status: number | undefined+ cookie: unknown+ cache: unknown+ }>((resolve, reject) => {+ const req = request(+ {+ socketPath,+ path: url,+ method,+ headers: {+ host: 'nas.test:5001',+ cookie: 'id=private-test-cookie',+ authorization: 'Bearer test-credential',+ 'x-trim-userid': '1700',+ },+ },+ (res) => {+ res.resume()+ res.on('end', () =>+ resolve({+ status: res.statusCode,+ cookie: res.headers['set-cookie'],+ cache: res.headers['cache-control'],+ })+ )+ }+ )+ req.on('error', reject)+ req.end()+ })+ return {+ upstream,+ gateway,+ socketPath,+ seen,+ call,+ enable: () => {+ enabled = true+ },+ unavailable: () => {+ currentPort = undefined+ },+ }+}+describe.skipIf(process.platform === 'win32')(+ 'NAS client HTTPS gateway',+ () => {+ it('preserves CLI bearer auth and rewrites only known routes, stripping DSM identity and cookies', async () => {+ const f = await fixture()+ expect(await f.call('/motrix/client/mdxp')).toEqual({+ status: 200,+ cookie: undefined,+ cache: 'no-store',+ })+ expect(f.seen).toEqual([+ {+ url: '/mdxp',+ cookie: undefined,+ authorization: 'Bearer test-credential',+ identity: undefined,+ },+ ])+ for (const url of [+ '/motrix/client/mdxp?token=bad',+ '/motrix/client/../mdxp',+ '/motrix/client/mdxp/unknown',+ '/motrix/bridge/nonce',+ ])+ expect((await f.call(url)).status).toBe(404)+ expect(f.seen).toHaveLength(1)+ f.unavailable()+ expect((await f.call('/motrix/client/mdxp')).status).toBe(503)+ })+ it('keeps extension requests closed until enabled and retains the raw public prefix', async () => {+ const f = await fixture()+ f.enable()+ expect((await f.call('/motrix/bridge/nonce')).status).toBe(200)+ expect(f.seen[0]).toEqual({+ url: '/motrix/bridge/nonce',+ cookie: undefined,+ authorization: undefined,+ identity: undefined,+ })+ })+ it('rejects duplicate Host fields before any upstream request', async () => {+ const f = await fixture()+ f.enable()+ const response = await new Promise<string>((resolve, reject) => {+ const socket = net.connect(f.socketPath)+ let value = ''+ socket.on('connect', () =>+ socket.end(+ 'GET /motrix/bridge/discovery HTTP/1.1\r\nHost: nas.test:5001\r\nHost: other.test\r\nConnection: close\r\n\r\n'+ )+ )+ socket.on('data', (chunk) => {+ value += chunk+ })+ socket.on('end', () => resolve(value))+ socket.on('error', reject)+ })+ expect(response).toMatch(/^HTTP\/1.1 (400|404)/)+ expect(f.seen).toHaveLength(0)+ })+ it('forwards websocket bytes unchanged and closes the connection with the gateway', async () => {+ const f = await fixture()+ f.enable()+ const wss = new WebSocketServer({ noServer: true })+ f.upstream.on('upgrade', (req, socket, head) => {+ expect(req.url).toBe('/motrix/bridge/v1')+ expect(req.headers.cookie).toBeUndefined()+ wss.handleUpgrade(req, socket, head, (ws) =>+ ws.on('message', (data) => ws.send(data))+ )+ })+ const ws = new WebSocket(`ws+unix:${f.socketPath}:/motrix/bridge/v1`, {+ headers: { host: 'nas.test:5001', cookie: 'private' },+ })+ await once(ws, 'open')+ const message = once(ws, 'message')+ ws.send(Buffer.from([1, 2, 3]))+ expect((await message)[0]).toEqual(Buffer.from([1, 2, 3]))+ const closed = once(ws, 'close')+ await f.gateway.close()+ await closed+ wss.close()+ })+ }+)diff --git a/src/server/platform/nas/client-gateway.ts b/src/server/platform/nas/client-gateway.tsnew file mode 100644index 00000000..3da5a46b--- /dev/null+++ b/src/server/platform/nas/client-gateway.ts@@ -0,0 +1,182 @@+import { createServer, type IncomingMessage, request } from 'node:http'+import type { Duplex } from 'node:stream'+import { prepareNasSocket, secureNasSocket } from './listener'++const CLI_ROUTES = new Map([+ ['POST /motrix/client/mdxp', '/mdxp'],+ ['POST /motrix/client/mdxp/pair/request', '/mdxp/pair/request'],+ ['POST /motrix/client/mdxp/pair/poll', '/mdxp/pair/poll'],+ ['GET /motrix/client/mdxp/events', '/mdxp/events'],+])+const EXTENSION_PREFIX = '/motrix/bridge/'++/** Stable Unix upstream for DSM TLS termination. Only the running Motrix bridge+ * can be selected; DSM cookies and vendor identity headers never cross it. */+export async function listenNasClientGateway(options: {+ socketPath: string+ groupId?: number+ currentPort: () => number | undefined+ extensionEnabled: () => boolean+}) {+ const sockets = new Set<Duplex>()+ const select = (req: IncomingMessage, upgrade = false) => {+ if (upgrade && req.method !== 'GET') return undefined+ const url = req.url ?? ''+ const hostCount = req.rawHeaders.filter(+ (_value, index) =>+ index % 2 === 0 && req.rawHeaders[index].toLowerCase() === 'host'+ ).length+ if (url.length > 4096 || hostCount !== 1 || !req.headers.host)+ return undefined+ const cli = !upgrade && CLI_ROUTES.get(`${req.method} ${url}`)+ if (cli) return { path: cli, cli: true }+ if (options.extensionEnabled() && url.startsWith(EXTENSION_PREFIX))+ return { path: url, cli: false }+ return undefined+ }+ const headers = (req: IncomingMessage, cli: boolean) =>+ Object.fromEntries(+ Object.entries(req.headers).filter(+ ([key]) =>+ [+ 'host',+ 'origin',+ 'content-type',+ 'content-length',+ 'accept',+ 'connection',+ 'upgrade',+ 'sec-websocket-key',+ 'sec-websocket-version',+ 'sec-websocket-protocol',+ 'sec-websocket-extensions',+ 'x-motrix-bridge',+ ].includes(key) ||+ (cli && key === 'authorization')+ )+ )+ const port = () => {+ const value = options.currentPort()+ return value !== undefined &&+ Number.isInteger(value) &&+ value >= 1024 &&+ value <= 65535+ ? value+ : undefined+ }+ const server = createServer({ maxHeaderSize: 16 * 1024 }, (req, res) => {+ const route = select(req)+ const target = port()+ if (!route || target === undefined) {+ res.writeHead(route ? 503 : 404, { 'cache-control': 'no-store' })+ res.end()+ return+ }+ const upstream = request(+ {+ hostname: '127.0.0.1',+ port: target,+ path: route.path,+ method: req.method,+ headers: headers(req, route.cli),+ agent: false,+ },+ (response) => {+ const { 'set-cookie': _cookie, ...safeHeaders } = response.headers+ res.writeHead(response.statusCode ?? 502, {+ ...safeHeaders,+ 'cache-control': 'no-store',+ })+ response.pipe(res)+ response.on('error', () => res.destroy())+ }+ )+ upstream.setTimeout(75_000, () => upstream.destroy())+ upstream.on('error', () => {+ if (!res.headersSent) res.writeHead(502, { 'cache-control': 'no-store' })+ res.end()+ })+ req.on('aborted', () => upstream.destroy())+ res.on('close', () => upstream.destroy())+ req.pipe(upstream)+ })+ server.on('connection', (socket) => {+ if (sockets.size >= 128) {+ socket.destroy()+ return+ }+ sockets.add(socket)+ socket.on('close', () => sockets.delete(socket))+ })+ server.on('upgrade', (req, downstream, head) => {+ const route = select(req, true)+ const target = port()+ if (!route || target === undefined) {+ downstream.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n')+ return+ }+ const upstream = request({+ hostname: '127.0.0.1',+ port: target,+ path: route.path,+ method: 'GET',+ headers: headers(req, false),+ agent: false,+ })+ upstream.setTimeout(10_000, () => upstream.destroy())+ upstream.on('upgrade', (response, socket, upstreamHead) => {+ // The upstream handshake deadline ends when ownership passes to the WS.+ socket.setTimeout(0)+ if (downstream.destroyed) {+ socket.destroy()+ return+ }+ const values: string[] = []+ for (let index = 0; index < response.rawHeaders.length; index += 2) {+ if (response.rawHeaders[index].toLowerCase() !== 'set-cookie')+ values.push(+ `${response.rawHeaders[index]}: ${response.rawHeaders[index + 1]}`+ )+ }+ downstream.write(+ `HTTP/1.1 101 Switching Protocols\r\n${values.join('\r\n')}\r\n\r\n`+ )+ if (upstreamHead.length) downstream.write(upstreamHead)+ if (head.length) socket.write(head)+ socket.on('error', () => downstream.destroy())+ downstream.on('error', () => socket.destroy())+ socket.on('close', () => downstream.destroy())+ downstream.on('close', () => socket.destroy())+ downstream.pipe(socket).pipe(downstream)+ })+ upstream.on('response', (response) => {+ response.resume()+ downstream.end(+ `HTTP/1.1 ${response.statusCode ?? 502} Rejected\r\nConnection: close\r\n\r\n`+ )+ })+ upstream.on('error', () => downstream.destroy())+ downstream.on('close', () => upstream.destroy())+ upstream.end()+ })+ await prepareNasSocket(options.socketPath, options.groupId)+ try {+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(options.socketPath, () => {+ server.off('error', reject)+ resolve()+ })+ })+ await secureNasSocket(options.socketPath, options.groupId)+ } catch (error) {+ server.close()+ throw error+ }+ return {+ close: async () => {+ for (const socket of sockets) socket.destroy()+ await new Promise<void>((resolve) => server.close(() => resolve()))+ },+ }+}diff --git a/src/server/platform/nas/file-remover.ts b/src/server/platform/nas/file-remover.tsindex a9110fe9..7381413d 100644--- a/src/server/platform/nas/file-remover.ts+++ b/src/server/platform/nas/file-remover.ts@@ -39,12 +39,17 @@ export class NasFileRemover {private readonly intentsDirectory: string) {}- remove(candidate: string): Promise<void> {+ remove(+ candidate: string,+ expectedIdentity?: (selectedPath: string) => Promise<string | undefined>+ ): Promise<void> {if (!path.isAbsolute(candidate) || candidate.includes('\0'))return Promise.reject(new Error('Invalid NAS cleanup path'))const requested = path.resolve(candidate)const previous = this.pending.get(requested) ?? Promise.resolve()- const current = previous.catch(() => {}).then(() => this.perform(requested))+ const current = previous+ .catch(() => {})+ .then(() => this.perform(requested, expectedIdentity))this.pending.set(requested, current)void current.finally(() => {@@ -55,7 +60,10 @@ export class NasFileRemover {return current}- private async perform(requested: string): Promise<void> {+ private async perform(+ requested: string,+ expectedIdentity?: (selectedPath: string) => Promise<string | undefined>+ ): Promise<void> {if (!this.adapter.openRemoval)throw new Error('Held NAS cleanup is unavailable')const journal = path.join(@@ -88,6 +96,11 @@ export class NasFileRemover {path.resolve(intent.original) !== intent.original)throw new Error('Invalid NAS cleanup intent')+ const checkOwnership = async (selectedPath: string) => {+ const expected = await expectedIdentity?.(selectedPath)+ if (expected && expected !== intent.artifactIdentity)+ throw new Error('Task output changed')+ }const parentPath = path.dirname(intent.original)const quarantine = path.join(parentPath, intent.quarantine)const originalInfo = await inspect(intent.original)@@ -112,6 +125,7 @@ export class NasFileRemover {return}await this.files.authorizeRemoval(selectedPath, this.policy)+ await checkOwnership(selectedPath)const artifact = await this.adapter.openRemoval(root,path.basename(selectedPath),@@ -128,6 +142,7 @@ export class NasFileRemover {currentFile.isSymbolicLink())throw new Error('NAS cleanup path changed during authorization')+ await checkOwnership(selectedPath)await storage.write(`${JSON.stringify(intent)}\n`)await this.adapter.removeOpened(artifact,diff --git a/src/server/platform/nas/file-routes.integration.test.ts b/src/server/platform/nas/file-routes.integration.test.tsnew file mode 100644index 00000000..345e9d91--- /dev/null+++ b/src/server/platform/nas/file-routes.integration.test.ts@@ -0,0 +1,229 @@+import {+ mkdir,+ mkdtemp,+ readFile,+ rename,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import { request } from 'node:http'+import path from 'node:path'+import {+ makeDownloadTask,+ TaskKind,+ TaskStatus,+ TaskType,+} from '@shared/types/task'+import Fastify from 'fastify'+import { afterEach, describe, expect, it } from 'vitest'+import { registerNasFileRoutes } from './file-routes'+import { NasFiles } from './files'+import { runAsNasGatewayUser } from './identity'++const cleanups: (() => Promise<unknown>)[] = []+afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup()+})+async function fixture(size = 4096) {+ const root = await mkdtemp('/tmp/motrix-nas-read-')+ cleanups.push(() => rm(root, { recursive: true, force: true }))+ const downloads = path.join(root, 'downloads'),+ outside = path.join(root, 'outside')+ await mkdir(downloads)+ await mkdir(outside)+ const file = path.join(downloads, 'payload.bin'),+ payload = Buffer.alloc(size, 0x4d)+ await writeFile(file, payload)+ let allowed = true,+ beforeCheck: ((candidate: string) => Promise<void>) | undefined+ const files = new NasFiles({+ platform: 'synology',+ authorizedRoots: async () => [downloads],+ checkAccess: async (_user, candidate) => {+ await beforeCheck?.(candidate)+ return allowed+ },+ })+ const policy = await files.policy(downloads)+ const task = makeDownloadTask({+ id: 'test-task',+ name: 'payload.bin',+ kind: TaskKind.Direct,+ type: TaskType.Http,+ status: TaskStatus.Completed,+ saveDir: downloads,+ createdAt: 1,+ updatedAt: 1,+ filename: 'payload.bin',+ finalName: 'payload.bin',+ source: 'user',+ sourceMeta: null,+ instances: [],+ fileCount: 1,+ diskPath: file,+ finalPath: file,+ })+ const app = Fastify()+ app.addHook('preHandler', (req, _reply, done) => {+ if (req.headers.cookie === 'synthetic')+ runAsNasGatewayUser(+ {+ platform: 'synology',+ userId: '1700',+ username: 'alice',+ administrator: true,+ },+ done+ )+ else done()+ })+ registerNasFileRoutes(app, {+ files,+ policy,+ getTask: (id) => (id === task.id ? task : undefined),+ webBasePath: '',+ fileManagerUrl: (folder) => `/?folder=${encodeURIComponent(folder)}`,+ })+ cleanups.push(() => app.close())+ return {+ app,+ task,+ root,+ downloads,+ outside,+ file,+ payload,+ deny: () => {+ allowed = false+ },+ onCheck: (callback: typeof beforeCheck) => {+ beforeCheck = callback+ },+ }+}+describe.skipIf(process.platform !== 'linux')(+ 'NAS descriptor-backed file routes',+ () => {+ it('serves task-owned bytes and ranges with safe attachment headers, rejecting missing identity', async () => {+ const f = await fixture()+ const denied = await f.app.inject({+ method: 'GET',+ url: '/api/nas/tasks/test-task/file',+ })+ expect(denied.statusCode).toBe(403)+ const result = await f.app.inject({+ method: 'GET',+ url: '/api/nas/tasks/test-task/file',+ headers: { cookie: 'synthetic', range: 'bytes=10-39' },+ })+ expect(result.statusCode).toBe(206)+ expect(result.rawPayload).toEqual(f.payload.subarray(10, 40))+ expect(result.headers['content-range']).toBe('bytes 10-39/4096')+ expect(result.headers['content-disposition']).toContain('attachment;')+ expect(result.headers['x-content-type-options']).toBe('nosniff')+ const head = await f.app.inject({+ method: 'HEAD',+ url: '/api/nas/tasks/test-task/file',+ headers: { cookie: 'synthetic' },+ })+ expect(head.statusCode).toBe(200)+ expect(head.rawPayload.length).toBe(0)+ expect(head.headers['content-length']).toBe('4096')+ expect(+ (+ await f.app.inject({+ method: 'GET',+ url: '/api/nas/tasks/test-task/file',+ headers: { cookie: 'synthetic', range: 'bytes=99999-' },+ })+ ).statusCode+ ).toBe(416)+ })+ it('does not serve an outside symlink swapped in during authorization', async () => {+ const f = await fixture(),+ secret = path.join(f.outside, 'secret')+ await writeFile(secret, 'must not be returned')+ let changed = false+ f.onCheck(async (candidate) => {+ if (candidate !== f.file || changed) return+ changed = true+ await rename(f.file, `${f.file}.old`)+ await symlink(secret, f.file)+ })+ const result = await f.app.inject({+ method: 'GET',+ url: '/api/nas/tasks/test-task/file',+ headers: { cookie: 'synthetic' },+ })+ expect(result.statusCode).toBe(403)+ expect(result.body).not.toContain('must not be returned')+ })+ it('reads only authorized torrent files and rejects unrelated paths and cross-site downloads', async () => {+ const f = await fixture(),+ torrent = path.join(f.downloads, 'fixture.torrent')+ await writeFile(torrent, 'd4:infodee')+ const result = await f.app.inject({+ method: 'POST',+ url: '/api/nas/torrent',+ headers: { cookie: 'synthetic' },+ payload: { path: torrent },+ })+ expect(result.statusCode).toBe(200)+ expect(result.rawPayload).toEqual(await readFile(torrent))+ expect(+ (+ await f.app.inject({+ method: 'POST',+ url: '/api/nas/torrent',+ headers: { cookie: 'synthetic' },+ payload: { path: f.file },+ })+ ).statusCode+ ).toBe(403)+ expect(+ (+ await f.app.inject({+ method: 'GET',+ url: '/api/nas/tasks/test-task/file',+ headers: { cookie: 'synthetic', 'sec-fetch-site': 'cross-site' },+ })+ ).statusCode+ ).toBe(403)+ })+ it('cuts an in-progress response when file permission is withdrawn', async () => {+ const f = await fixture(8 * 1024 * 1024)+ await f.app.listen({ host: '127.0.0.1', port: 0 })+ const address = f.app.server.address()+ if (!address || typeof address === 'string')+ throw new Error('Missing test listener')+ const result = await new Promise<{ bytes: number; complete: boolean }>(+ (resolve, reject) => {+ const req = request(+ {+ hostname: '127.0.0.1',+ port: address.port,+ path: '/api/nas/tasks/test-task/file',+ headers: { cookie: 'synthetic' },+ },+ (res) => {+ let bytes = 0+ res.on('data', (data) => {+ bytes += data.length+ f.deny()+ })+ res.on('aborted', () => resolve({ bytes, complete: false }))+ res.on('error', () => resolve({ bytes, complete: false }))+ res.on('end', () => resolve({ bytes, complete: true }))+ }+ )+ req.on('error', reject)+ req.end()+ }+ )+ expect(result.bytes).toBeGreaterThan(0)+ expect(result.bytes).toBeLessThan(f.payload.length)+ expect(result.complete).toBe(false)+ })+ }+)diff --git a/src/server/platform/nas/file-routes.test.ts b/src/server/platform/nas/file-routes.test.tsnew file mode 100644index 00000000..4f381cd0--- /dev/null+++ b/src/server/platform/nas/file-routes.test.ts@@ -0,0 +1,21 @@+import { expect, it } from 'vitest'+import { nasFileRange } from './file-routes'++it('supports single explicit and suffix byte ranges without unsafe arithmetic', () => {+ expect(nasFileRange(undefined, 10)).toEqual({ start: 0, end: 9 })+ expect(nasFileRange('bytes=2-5', 10)).toEqual({ start: 2, end: 5 })+ expect(nasFileRange('bytes=2-', 10)).toEqual({ start: 2, end: 9 })+ expect(nasFileRange('bytes=-3', 10)).toEqual({ start: 7, end: 9 })+ expect(nasFileRange('bytes=-30', 10)).toEqual({ start: 0, end: 9 })+ for (const value of [+ 'bytes=-',+ 'bytes=-0',+ 'bytes=8-2',+ 'bytes=10-',+ 'bytes=0-1,4-6',+ 'bytes=99999999999999999999-',+ 'items=0-1',+ ])+ expect(nasFileRange(value, 10)).toBeNull()+ expect(nasFileRange('bytes=0-', 0)).toBeNull()+})diff --git a/src/server/platform/nas/file-routes.ts b/src/server/platform/nas/file-routes.tsnew file mode 100644index 00000000..c2dcc001--- /dev/null+++ b/src/server/platform/nas/file-routes.ts@@ -0,0 +1,319 @@+import { lstat } from 'node:fs/promises'+import path from 'node:path'+import { performance } from 'node:perf_hooks'+import { Readable } from 'node:stream'+import { MAX_TORRENT_FILE_SIZE } from '@shared/lib/torrent-meta'+import {+ NAS_FILE_API,+ nasTaskActionSchema,+ nasTorrentPathSchema,+} from '@shared/schemas/nas-files'+import type { DownloadTask } from '@shared/types/task'+import {+ canOpenTaskFile,+ canRevealTaskFolder,+} from '@shared/types/task-actions'+import type { FastifyInstance } from 'fastify'+import type { ServerDownloadPathPolicy } from '../../download-path-policy'+import type { NasFiles } from './files'+import { currentNasUser, type NasIdentity } from './identity'+import { openNasFile } from './open-file'++export function nasFileRange(+ header: string | undefined,+ size: number+): { start: number; end: number } | null {+ if (!Number.isSafeInteger(size) || size < 0) return null+ if (header === undefined) return { start: 0, end: size - 1 }+ const match = /^bytes=(\d*)-(\d*)$/.exec(header)+ if (!match || size === 0 || (!match[1] && !match[2])) return null+ const first = match[1] ? Number(match[1]) : undefined+ const last = match[2] ? Number(match[2]) : undefined+ if (+ [first, last].some(+ (value) =>+ value !== undefined && (!Number.isSafeInteger(value) || value < 0)+ )+ )+ return null+ if (first === undefined)+ return last && last > 0+ ? { start: Math.max(0, size - last), end: size - 1 }+ : null+ if (first >= size || (last !== undefined && last < first)) return null+ return { start: first, end: Math.min(last ?? size - 1, size - 1) }+}++export async function readNasTorrent(+ candidate: string,+ files: NasFiles,+ policy: ServerDownloadPathPolicy,+ user: NasIdentity+): Promise<Buffer> {+ if (!candidate.toLowerCase().endsWith('.torrent'))+ throw new Error('Not a torrent')+ const canonical = await files.authorizeFile(candidate, policy, user)+ const handle = await openNasFile(canonical, (opened) =>+ files.authorizeFile(opened, policy, user)+ )+ try {+ const info = await handle.stat({ bigint: true })+ if (!info.isFile() || info.size > BigInt(MAX_TORRENT_FILE_SIZE))+ throw new Error('Torrent too large')+ const data = Buffer.alloc(Number(info.size) + 1)+ let size = 0+ while (size < data.length) {+ const read = await handle.read(data, size, data.length - size, size)+ if (!read.bytesRead) break+ size += read.bytesRead+ }+ const after = await handle.stat({ bigint: true })+ if (+ BigInt(size) !== info.size ||+ after.size !== info.size ||+ after.mtimeNs !== info.mtimeNs ||+ after.ctimeNs !== info.ctimeNs+ )+ throw new Error('Torrent changed during read')+ await files.authorizeFile(canonical, policy, user)+ const named = await lstat(canonical, { bigint: true })+ if (+ named.dev !== info.dev ||+ named.ino !== info.ino ||+ named.size !== info.size ||+ named.mtimeNs !== info.mtimeNs ||+ named.ctimeNs !== info.ctimeNs+ )+ throw new Error('Torrent identity changed')+ return data.subarray(0, size)+ } finally {+ await handle.close()+ }+}++export function registerNasFileRoutes(+ app: FastifyInstance,+ options: {+ files: NasFiles+ policy: ServerDownloadPathPolicy+ getTask: (id: string) => DownloadTask | undefined+ webBasePath: string+ fileManagerUrl: (canonical: string) => string+ outputIdentity?: (+ task: DownloadTask,+ path: string+ ) => Promise<string | undefined>+ }+) {+ const { files, policy, getTask } = options+ const streams = new Set<Readable>()+ app.addHook('preClose', async () => {+ for (const stream of streams) stream.destroy()+ })+ const output = (id: string, action: 'open' | 'reveal') => {+ const task = getTask(id)+ if (+ !task ||+ !(action === 'open' ? canOpenTaskFile(task) : canRevealTaskFolder(task))+ )+ throw new Error('Task output unavailable')+ const stored = task.finalPath || task.diskPath+ if (!stored) throw new Error('Task output unavailable')+ return {+ task,+ stored,+ candidate: action === 'reveal' ? path.dirname(stored) : stored,+ }+ }+ const openTaskFile = async (+ task: DownloadTask,+ stored: string,+ canonical: string,+ user: NasIdentity+ ) => {+ const expected = await options.outputIdentity?.(task, stored)+ const handle = await openNasFile(canonical, (opened) =>+ files.authorizeFile(opened, policy, user)+ )+ try {+ const named = await handle.stat({ bigint: true })+ if (expected && expected !== `${named.dev}:${named.ino}`)+ throw Error('Task output changed')+ return handle+ } catch (error) {+ await handle.close()+ throw error+ }+ }+ app.post(`${NAS_FILE_API}/task-action`, async (req, reply) => {+ const parsed = nasTaskActionSchema.safeParse(req.body),+ user = currentNasUser()+ if (!parsed.success || !user)+ return reply.code(400).send({ error: 'Invalid task action' })+ try {+ const { taskId, action } = parsed.data+ const { task, stored, candidate } = output(taskId, action)+ const canonical =+ action === 'reveal'+ ? (await policy.authorizeDirectory(candidate)).canonicalPath+ : await files.authorizeFile(candidate, policy, user)+ await files.check(canonical, 'readable', user)+ if (output(taskId, action).stored !== stored)+ throw new Error('Task changed')+ if (action === 'reveal') {+ await options.outputIdentity?.(task, stored)+ return { kind: 'file-manager', url: options.fileManagerUrl(canonical) }+ }+ const handle = await openTaskFile(task, stored, canonical, user)+ await handle.close()+ return {+ kind: 'download',+ url: `${options.webBasePath}${NAS_FILE_API}/tasks/${encodeURIComponent(taskId)}/file`,+ }+ } catch {+ return reply.code(403).send({ error: 'Task output is not authorized' })+ }+ })+ app.post(`${NAS_FILE_API}/torrent`, async (req, reply) => {+ const parsed = nasTorrentPathSchema.safeParse(req.body),+ user = currentNasUser()+ if (!parsed.success || !user)+ return reply.code(400).send({ error: 'Invalid torrent path' })+ try {+ const data = await readNasTorrent(parsed.data.path, files, policy, user)+ return reply+ .type('application/x-bittorrent')+ .header('cache-control', 'no-store')+ .send(data)+ } catch {+ return reply.code(403).send({ error: 'Torrent is not authorized' })+ }+ })+ app.route<{ Params: { taskId: string } }>({+ method: ['GET', 'HEAD'],+ exposeHeadRoute: false,+ url: `${NAS_FILE_API}/tasks/:taskId/file`,+ handler: async (req, reply) => {+ const user = currentNasUser()+ const site = req.headers['sec-fetch-site']+ if (+ !user ||+ (site !== undefined && site !== 'same-origin' && site !== 'none')+ )+ return reply.code(403).send({ error: 'File is not authorized' })+ let handle: Awaited<ReturnType<typeof openNasFile>> | undefined+ try {+ const { task, stored, candidate } = output(req.params.taskId, 'open')+ const canonical = await files.authorizeFile(candidate, policy, user)+ handle = await openTaskFile(task, stored, canonical, user)+ const file = handle,+ original = await file.stat({ bigint: true })+ const range = nasFileRange(req.headers.range, Number(original.size))+ if (!range) {+ await file.close()+ return reply+ .code(416)+ .header('content-range', `bytes */${original.size}`)+ .send()+ }+ const recheck = async () => {+ if (+ output(req.params.taskId, 'open').stored !== stored ||+ (await files.authorizeFile(canonical, policy, user)) !== canonical+ )+ throw new Error('File authorization changed')+ const expected = await options.outputIdentity?.(task, stored)+ if (expected && expected !== `${original.dev}:${original.ino}`)+ throw Error('Task output changed')+ const current = await lstat(canonical, { bigint: true })+ if (+ current.dev !== original.dev ||+ current.ino !== original.ino ||+ current.size !== original.size ||+ current.mtimeNs !== original.mtimeNs ||+ current.ctimeNs !== original.ctimeNs+ )+ throw new Error('File identity changed')+ }+ await recheck()+ const stream = Readable.from(+ (async function* () {+ let position = range.start,+ lastCheck = performance.now(),+ sinceCheck = 0+ try {+ while (position <= range.end) {+ if (+ performance.now() - lastCheck >= 1000 ||+ sinceCheck >= 32 * 1024 * 1024+ ) {+ await recheck()+ lastCheck = performance.now()+ sinceCheck = 0+ }+ const chunk = Buffer.alloc(+ Math.min(64 * 1024, range.end - position + 1)+ )+ const { bytesRead } = await file.read(+ chunk,+ 0,+ chunk.length,+ position+ )+ if (!bytesRead) throw new Error('File truncated')+ position += bytesRead+ sinceCheck += bytesRead+ if (position > range.end) await recheck()+ yield chunk.subarray(0, bytesRead)+ }+ } finally {+ await file.close().catch(() => {})+ }+ })(),+ { objectMode: false }+ )+ stream.once('close', () => {+ streams.delete(stream)+ void file.close().catch(() => {})+ })+ streams.add(stream)+ reply.raw.once('close', () => stream.destroy())+ const filename = encodeURIComponent(path.basename(canonical)).replace(+ /[!'()*]/g,+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`+ )+ reply+ .header(+ 'content-disposition',+ `attachment; filename="download"; filename*=UTF-8''${filename}`+ )+ .header(+ 'content-length',+ String(Math.max(0, range.end - range.start + 1))+ )+ .header('accept-ranges', 'bytes')+ .header('cache-control', 'private, no-store')+ .header('x-content-type-options', 'nosniff')+ .header('referrer-policy', 'no-referrer')+ .header('content-security-policy', "sandbox; default-src 'none'")+ .type('application/octet-stream')+ if (req.headers.range !== undefined)+ reply+ .code(206)+ .header(+ 'content-range',+ `bytes ${range.start}-${range.end}/${original.size}`+ )+ if (req.method === 'HEAD') {+ stream.destroy()+ await file.close()+ return reply.send()+ }+ return reply.send(stream)+ } catch {+ await handle?.close().catch(() => {})+ return reply.code(403).send({ error: 'File is not authorized' })+ }+ },+ })+}diff --git a/src/server/platform/nas/listener.ts b/src/server/platform/nas/listener.tsnew file mode 100644index 00000000..7a08cabf--- /dev/null+++ b/src/server/platform/nas/listener.ts@@ -0,0 +1,66 @@+import { chmod, chown, lstat, unlink } from 'node:fs/promises'+import { connect } from 'node:net'+import type { FastifyInstance } from 'fastify'++export async function listenNas(+ app: FastifyInstance,+ socketPath: string,+ gatewayGroupId?: number+): Promise<void> {+ await prepareNasSocket(socketPath, gatewayGroupId)+ await app.listen({ path: socketPath })+ await secureNasSocket(socketPath, gatewayGroupId)+}++export async function prepareNasSocket(+ socketPath: string,+ gatewayGroupId?: number+): Promise<void> {+ if (+ gatewayGroupId !== undefined &&+ (!Number.isInteger(gatewayGroupId) ||+ gatewayGroupId <= 0 ||+ gatewayGroupId >= 0xffffffff ||+ !process.getgroups?.().includes(gatewayGroupId))+ )+ throw new Error('Gateway group is not available to the package account')+ const before = await lstat(socketPath).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code === 'ENOENT') return undefined+ throw error+ }+ )+ if (before) {+ if (!before.isSocket() || before.uid !== process.getuid?.())+ throw new Error('Refusing to replace an unowned socket path')+ await new Promise<void>((resolve, reject) => {+ const probe = connect(socketPath)+ probe.setTimeout(1_000, () => {+ probe.destroy()+ reject(new Error('Gateway socket is busy'))+ })+ probe.once('connect', () => {+ probe.destroy()+ reject(new Error('Gateway socket is already listening'))+ })+ probe.once('error', (error: NodeJS.ErrnoException) => {+ if (error.code === 'ECONNREFUSED') resolve()+ else reject(error)+ })+ })+ const current = await lstat(socketPath)+ if (before.dev !== current.dev || before.ino !== current.ino)+ throw new Error('Gateway socket changed during startup')+ await unlink(socketPath)+ }+}++export async function secureNasSocket(+ socketPath: string,+ gatewayGroupId?: number+): Promise<void> {+ // Grant only a declared supplementary gateway group. Application state keeps+ // its private owner/modes; membership is never an authenticated NAS identity.+ if (gatewayGroupId !== undefined) await chown(socketPath, -1, gatewayGroupId)+ await chmod(socketPath, gatewayGroupId === undefined ? 0o600 : 0o660)+}diff --git a/src/server/platform/nas/open-file.ts b/src/server/platform/nas/open-file.tsnew file mode 100644index 00000000..c721502a--- /dev/null+++ b/src/server/platform/nas/open-file.ts@@ -0,0 +1,59 @@+import { constants } from 'node:fs'+import { lstat, open, readlink } from 'node:fs/promises'++// Linux O_PATH allows traversal through execute-only NAS ancestors. Node does+// not expose this flag; NAS hosts run on Linux and requires procfs for this reader.+const O_PATH = 0x200000++/** Anchor every component to an open parent; never follow replacement links. */+export async function openNasFile(+ canonical: string,+ authorize: (path: string) => Promise<string>+) {+ if (process.platform !== 'linux' || !canonical.startsWith('/'))+ throw new Error('Descriptor-relative file access is unavailable')+ const parts = canonical.slice(1).split('/')+ if (parts.some((part) => !part || part === '.' || part === '..'))+ throw new Error('Invalid canonical file path')+ const directoryFlags = O_PATH | constants.O_DIRECTORY | constants.O_NOFOLLOW+ let parent = await open('/', directoryFlags)+ try {+ for (const part of parts.slice(0, -1)) {+ const next = await open(+ `/proc/self/fd/${parent.fd}/${part}`,+ directoryFlags+ )+ const previous = parent+ parent = next+ await previous.close()+ }+ const file = await open(+ `/proc/self/fd/${parent.fd}/${parts.at(-1)}`,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK+ )+ try {+ const descriptor = `/proc/self/fd/${file.fd}`+ // A held ancestor may have been renamed. Authorize the opened file's+ // actual location and confirm that the checked name still denotes it.+ if ((await readlink(descriptor)) !== canonical)+ throw new Error('File moved while opening')+ if ((await authorize(canonical)) !== canonical)+ throw new Error('File authorization changed')+ const named = await lstat(canonical, { bigint: true })+ const opened = await file.stat({ bigint: true })+ if (+ !opened.isFile() ||+ named.dev !== opened.dev ||+ named.ino !== opened.ino ||+ (await readlink(descriptor)) !== canonical+ )+ throw new Error('File changed during authorization')+ return file+ } catch (error) {+ await file.close()+ throw error+ }+ } finally {+ await parent.close()+ }+}diff --git a/src/server/platform/nas/recovery-access.test.ts b/src/server/platform/nas/recovery-access.test.tsnew file mode 100644index 00000000..447468e7--- /dev/null+++ b/src/server/platform/nas/recovery-access.test.ts@@ -0,0 +1,105 @@+import {+ mkdir,+ mkdtemp,+ realpath,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'+import path from 'node:path'+import { TaskInstancePhase } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'+import { afterEach, expect, it } from 'vitest'+import { NasFiles } from './files'+import { NasRecoveryAccess } from './recovery-access'+import { NasTaskAccess } from './task-access'++const cleanup: string[] = []+afterEach(async () => {+ for (const root of cleanup.splice(0))+ await rm(root, { recursive: true, force: true })+})++async function fixture() {+ const root = await realpath(await mkdtemp('/tmp/motrix-nas-recovery-'))+ cleanup.push(root)+ const downloads = path.join(root, 'downloads'),+ outside = path.join(root, 'outside')+ await mkdir(downloads)+ await mkdir(outside)+ const file = path.join(downloads, 'partial.bin')+ await writeFile(file, 'partial')+ let roots = [downloads]+ const files = new NasFiles({+ platform: 'synology',+ authorizedRoots: async () => roots,+ checkAccess: async () => true,+ })+ const policy = await files.policy(downloads)+ const task = makeDownloadTask({+ saveDir: downloads,+ finalPath: file,+ diskPath: file,+ })+ const actual = { directory: downloads, files: [file] }+ const recovery = new NasRecoveryAccess({+ access: new NasTaskAccess(files, policy),+ policy,+ tempDir: root,+ getTask: (gid) => (gid === 'owned' ? task : undefined),+ getEnginePaths: async () => actual,+ })+ return {+ root,+ downloads,+ outside,+ file,+ task,+ actual,+ recovery,+ revoke: () => {+ roots = []+ },+ }+}++it('holds unowned rows, revoked grants, and actual engine paths outside the task grant', async () => {+ const f = await fixture()+ expect(await f.recovery.authorizeResume('owned')).toBe(true)+ expect(await f.recovery.authorizeResume('unknown')).toBe(false)+ f.actual.files = [path.join(f.outside, 'injected.bin')]+ expect(await f.recovery.authorizeResume('owned')).toBe(false)+ f.actual.files = [f.file]+ f.revoke()+ expect(await f.recovery.authorizeResume('owned')).toBe(false)+ await expect(f.recovery.authorizeWrite(f.task)).rejects.toThrow()+})++it('rejects an output replaced by a symlink before restoring the engine', async () => {+ const f = await fixture()+ await writeFile(path.join(f.outside, 'private.bin'), 'private')+ await rm(f.file)+ await symlink(path.join(f.outside, 'private.bin'), f.file)+ expect(await f.recovery.authorizeResume('owned')).toBe(false)+})++it('allows protected metadata staging but rejects shared or symlinked metadata workspaces', async () => {+ const f = await fixture()+ const metadata = path.join(f.root, 'motrix-magnet-metadata-test')+ await mkdir(metadata, { mode: 0o700 })+ f.task.instances = [+ {+ phase: TaskInstancePhase.MagnetMetadataResolution,+ payload: { metadataDir: metadata },+ } as never,+ ]+ f.actual.directory = metadata+ f.actual.files = [path.join(metadata, 'metadata.torrent')]+ expect(await f.recovery.authorizeResume('owned')).toBe(true)+ f.task.instances[0].payload.metadataDir = f.downloads+ expect(await f.recovery.authorizeResume('owned')).toBe(false)+ f.task.instances[0].payload.metadataDir = metadata+ await rm(metadata, { recursive: true })+ await symlink(f.outside, metadata)+ expect(await f.recovery.authorizeResume('owned')).toBe(false)+})diff --git a/src/server/platform/nas/recovery-access.ts b/src/server/platform/nas/recovery-access.tsnew file mode 100644index 00000000..cd16c900--- /dev/null+++ b/src/server/platform/nas/recovery-access.ts@@ -0,0 +1,87 @@+import { lstat, realpath } from 'node:fs/promises'+import path from 'node:path'+import {+ type DownloadTask,+ TaskInstancePhase,+ TaskKind,+} from '@shared/types/task'+import type { ServerDownloadPathPolicy } from '../../download-path-policy'+import type { NasTaskAccess } from './task-access'++/** Recheck durable task ownership and actual engine paths before releasing a+ * paused boot. Unknown engine rows remain paused for explicit user review. */+export class NasRecoveryAccess {+ constructor(+ private readonly deps: {+ access: Pick<NasTaskAccess, 'authorizeWrite' | 'authorizeOutputWrite'>+ policy: Pick<ServerDownloadPathPolicy, 'authorizeDirectory'>+ tempDir: string+ getTask: (gid: string) => DownloadTask | undefined+ getEnginePaths: (+ gid: string+ ) => Promise<{ directory: string; files: string[] }>+ }+ ) {}++ private async metadataDirectory(+ task: DownloadTask+ ): Promise<string | undefined> {+ const instance = task.instances?.find(+ (item) => item.phase === TaskInstancePhase.MagnetMetadataResolution+ )+ if (!instance) return undefined+ const directory = instance.payload.metadataDir+ if (+ typeof directory !== 'string' ||+ path.dirname(directory) !== this.deps.tempDir ||+ !path.basename(directory).startsWith('motrix-magnet-metadata-') ||+ (await realpath(directory)) !== directory+ )+ throw new Error('Invalid metadata recovery directory')+ const info = await lstat(directory)+ if (+ !info.isDirectory() ||+ info.uid !== process.getuid?.() ||+ (info.mode & 0o022) !== 0+ )+ throw new Error('Untrusted metadata recovery directory')+ return directory+ }++ readonly authorizeWrite = async (task: DownloadTask): Promise<void> => {+ await this.deps.access.authorizeWrite(task)+ await this.metadataDirectory(task)+ }++ readonly authorizeResume = async (gid: string): Promise<boolean> => {+ try {+ const task = this.deps.getTask(gid)+ if (!task || task.kind === TaskKind.Hls || task.kind === TaskKind.Mux)+ return false+ await this.authorizeWrite(task)+ const actual = await this.deps.getEnginePaths(gid)+ const metadata = await this.metadataDirectory(task)+ if (metadata) {+ if (actual.directory !== metadata) return false+ for (const file of actual.files) {+ // Metadata output must be a direct child of the protected cache.+ if (path.dirname(file) !== metadata) return false+ const info = await lstat(file).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code === 'ENOENT') return undefined+ throw error+ }+ )+ if (info && (!info.isFile() || info.isSymbolicLink())) return false+ }+ } else {+ await this.deps.policy.authorizeDirectory(actual.directory)+ for (const file of actual.files)+ await this.deps.access.authorizeOutputWrite(file)+ }+ return true+ } catch {+ return false+ }+ }+}diff --git a/src/server/platform/nas/settings-store.test.ts b/src/server/platform/nas/settings-store.test.tsnew file mode 100644index 00000000..13ed3724--- /dev/null+++ b/src/server/platform/nas/settings-store.test.ts@@ -0,0 +1,193 @@+import {+ mkdtemp,+ readFile,+ rm,+ stat,+ symlink,+ writeFile,+} from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { NasSettingsStore } from './settings-store'++const cleanup: string[] = []+afterEach(async () => {+ for (const root of cleanup.splice(0))+ await rm(root, { recursive: true, force: true })+})+async function fixture() {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-nas-settings-'))+ cleanup.push(root)+ await writeFile(+ path.join(root, 'package-settings.json'),+ JSON.stringify({+ clientPort: 16802,+ extensionUrl: '',+ operatorUrl: '',+ allowHttp: false,+ }),+ { mode: 0o600 }+ )+ await writeFile(+ path.join(root, 'directories.json'),+ JSON.stringify({ roots: ['/volume1/motrix'] }),+ { mode: 0o600 }+ )+ return { root, store: new NasSettingsStore(root, 'synology') }+}+describe.skipIf(process.platform === 'win32')(+ 'NAS package configuration journal',+ () => {+ it('times out authority checks without blocking subsequent saves or accepting a late result', async () => {+ const { root } = await fixture()+ const store = new NasSettingsStore(root, 'synology', 20)+ const before = await store.view()+ let finish!: (value: boolean) => void+ let signal: AbortSignal | undefined+ const saved = await store.save(+ { revision: before.revision, settings: before.settings },+ async (_settings, current) => {+ signal = current+ return new Promise<boolean>((resolve) => {+ finish = resolve+ })+ }+ )+ expect(saved).toEqual({ ok: false, error: { code: 'unavailable' } })+ expect(signal?.aborted).toBe(true)+ finish(true)+ await expect(+ stat(path.join(root, 'pending-settings.json'))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ expect(+ (+ await store.save(+ { revision: before.revision, settings: before.settings },+ async () => true+ )+ ).ok+ ).toBe(true)+ })+ it('rejects a valid schema whose serialized configuration exceeds the journal bound', async () => {+ const { root, store } = await fixture(),+ before = await store.view()+ expect(+ await store.save(+ {+ revision: before.revision,+ settings: {+ ...before.settings,+ roots: Array.from(+ { length: 64 },+ (_, index) => `/volume1/${index}${'x'.repeat(600)}`+ ),+ },+ },+ async () => true+ )+ ).toEqual({ ok: false, error: { code: 'invalid' } })+ await expect(+ stat(path.join(root, 'pending-settings.json'))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ })+ it('queues validated settings without changing live grants or client settings', async () => {+ const { root, store } = await fixture(),+ before = await store.view()+ const settings = {+ ...before.settings,+ roots: ['/volume1/motrix', '/volume1/downloads'],+ clientPort: 16812,+ }+ const saved = await store.save(+ { revision: before.revision, settings },+ async () => true+ )+ expect(saved).toMatchObject({+ ok: true,+ value: { settings, restartRequired: true, active: before.settings },+ })+ expect(+ JSON.parse(await readFile(path.join(root, 'directories.json'), 'utf8'))+ ).toEqual({ roots: ['/volume1/motrix'] })+ expect(+ JSON.parse(+ await readFile(path.join(root, 'package-settings.json'), 'utf8')+ ).clientPort+ ).toBe(16802)+ expect(+ (await stat(path.join(root, 'pending-settings.json'))).mode & 0o777+ ).toBe(0o600)+ })+ it('rejects stale and concurrently changed snapshots without overwriting them', async () => {+ const { root, store } = await fixture(),+ before = await store.view()+ const first = {+ revision: before.revision,+ settings: { ...before.settings, clientPort: 16812 },+ }+ expect((await store.save(first, async () => true)).ok).toBe(true)+ expect(await store.save(first, async () => true)).toEqual({+ ok: false,+ error: { code: 'conflict' },+ })+ const current = await store.view()+ expect(+ await store.save(+ {+ revision: current.revision,+ settings: { ...current.settings, clientPort: 16813 },+ },+ async () => {+ await writeFile(+ path.join(root, 'directories.json'),+ JSON.stringify({ roots: ['/volume1/changed'] }),+ { mode: 0o600 }+ )+ return true+ }+ )+ ).toEqual({ ok: false, error: { code: 'conflict' } })+ expect(+ JSON.parse(+ await readFile(path.join(root, 'pending-settings.json'), 'utf8')+ ).clientPort+ ).toBe(16812)+ })+ it('does not create pending grants after authorization failure or malformed input', async () => {+ const { root, store } = await fixture(),+ before = await store.view()+ expect(+ await store.save(+ { revision: before.revision, settings: before.settings },+ async () => false+ )+ ).toEqual({ ok: false, error: { code: 'permissionDenied' } })+ expect(+ await store.save(+ {+ revision: before.revision,+ settings: { ...before.settings, clientPort: 65536 },+ },+ async () => true+ )+ ).toEqual({ ok: false, error: { code: 'invalid' } })+ await expect(+ stat(path.join(root, 'pending-settings.json'))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ })+ it('refuses symlinked and non-private state documents', async () => {+ const { root, store } = await fixture()+ await symlink(+ path.join(root, 'directories.json'),+ path.join(root, 'pending-settings.json')+ )+ await expect(store.view()).rejects.toThrow()+ await rm(path.join(root, 'pending-settings.json'))+ await writeFile(path.join(root, 'pending-settings.json'), '{}', {+ mode: 0o644,+ })+ await expect(store.view()).rejects.toThrow()+ })+ }+)diff --git a/src/server/platform/nas/settings-store.ts b/src/server/platform/nas/settings-store.tsnew file mode 100644index 00000000..6ed2abb8--- /dev/null+++ b/src/server/platform/nas/settings-store.ts@@ -0,0 +1,254 @@+import { createHash } from 'node:crypto'+import { constants } from 'node:fs'+import { lstat, open } from 'node:fs/promises'+import path from 'node:path'+import {+ type NasPackageSettings,+ type NasSettingsResult,+ type NasSettingsView,+ nasPackageSettingsSchema,+ saveNasSettingsSchema,+} from '@shared/schemas/nas-settings'+import writeFileAtomic from 'write-file-atomic'++const MAX_BYTES = 32 * 1024+// Up to 64 package-generated device/inode pairs may accompany the public settings.+const MAX_PRIVATE_BYTES = MAX_BYTES + 4 * 1024+type GrantValidation =+ | boolean+ | 'folderUnavailable'+ | { directoryIdentities: string[] }+export async function readNasConfigurationText(+ file: string,+ optional = false+): Promise<string | null> {+ const handle = await open(+ file,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK+ ).catch((error: NodeJS.ErrnoException) => {+ if (optional && error.code === 'ENOENT') return null+ throw error+ })+ if (!handle) return null+ try {+ const info = await handle.stat()+ if (+ !info.isFile() ||+ info.uid !== process.getuid?.() ||+ (info.mode & 0o077) !== 0 ||+ info.size > MAX_PRIVATE_BYTES+ )+ throw new Error('Untrusted NAS configuration')+ const buffer = Buffer.alloc(MAX_PRIVATE_BYTES + 1)+ let bytesRead = 0+ while (bytesRead < buffer.length) {+ const part = await handle.read(+ buffer,+ bytesRead,+ buffer.length - bytesRead,+ bytesRead+ )+ if (!part.bytesRead) break+ bytesRead += part.bytesRead+ }+ if (bytesRead > MAX_PRIVATE_BYTES)+ throw new Error('NAS configuration too large')+ return buffer.subarray(0, bytesRead).toString('utf8')+ } finally {+ await handle.close()+ }+}++/** A pending document is a restart journal: lifecycle applies it only after+ * the old server/engine have stopped. Active grants never change under open IO. */+export class NasSettingsStore {+ private transition: Promise<void> = Promise.resolve()+ private active?: NasPackageSettings+ constructor(+ private readonly directory: string,+ private readonly platform: NasSettingsView['platform'],+ private readonly validationTimeoutMs = 20_000+ ) {}++ private async snapshot() {+ const [packageText, rootsText, pendingText] = await Promise.all([+ readNasConfigurationText(+ path.join(this.directory, 'package-settings.json')+ ),+ readNasConfigurationText(path.join(this.directory, 'directories.json')),+ readNasConfigurationText(+ path.join(this.directory, 'pending-settings.json'),+ true+ ),+ ])+ // DSM's directory fingerprints are package-private and must never be+ // supplied by an operator's form or included in the public settings view.+ const unpack = (text: string) => {+ const raw = JSON.parse(text)+ if (this.platform !== 'synology')+ return { settings: raw, identities: undefined }+ const { directoryIdentities, ...settings } = raw+ return { settings, identities: directoryIdentities }+ }+ const grants = unpack(rootsText ?? '')+ const applied = nasPackageSettingsSchema.parse({+ ...JSON.parse(packageText ?? ''),+ ...grants.settings,+ })+ const pending = pendingText === null ? null : unpack(pendingText)+ const settings =+ pending === null+ ? applied+ : nasPackageSettingsSchema.parse(pending.settings)+ const pinnedRoots = new Map<string, string>()+ for (const entry of [grants, pending]) {+ if (!entry || entry.identities === undefined) continue+ if (+ !Array.isArray(entry.identities) ||+ entry.identities.length !== entry.settings.roots.length+ )+ throw new Error('Invalid NAS directory identities')+ for (const [i, root] of entry.settings.roots.entries()) {+ const id = entry.identities[i]+ if (+ typeof id !== 'string' ||+ !/^\d{1,20}:\d{1,20}$/.test(id) ||+ (pinnedRoots.has(root) && pinnedRoots.get(root) !== id)+ )+ throw new Error('Inconsistent NAS directory identities')+ pinnedRoots.set(root, id)+ }+ }+ const revision = createHash('sha256')+ .update(JSON.stringify([packageText, rootsText, pendingText]))+ .digest('hex')+ this.active ??= applied+ const grantChange =+ pending !== null &&+ JSON.stringify(pending.identities) !== JSON.stringify(grants.identities)+ return { applied, settings, revision, grantChange, pinnedRoots }+ }++ async view(): Promise<NasSettingsView> {+ const state = await this.snapshot()+ const active = this.active ?? state.applied+ return {+ platform: this.platform,+ revision: state.revision,+ settings: state.settings,+ active,+ restartRequired:+ state.grantChange ||+ JSON.stringify(state.settings) !== JSON.stringify(active),+ }+ }++ async save(+ raw: unknown,+ validate: (+ settings: NasPackageSettings,+ signal: AbortSignal+ ) => Promise<GrantValidation>+ ): Promise<NasSettingsResult> {+ const parsed = saveNasSettingsSchema.safeParse(raw)+ if (!parsed.success) return { ok: false, error: { code: 'invalid' } }+ if (Buffer.byteLength(JSON.stringify(parsed.data.settings)) + 1 > MAX_BYTES)+ return { ok: false, error: { code: 'invalid' } }+ let result: NasSettingsResult = {+ ok: false,+ error: { code: 'unavailable' },+ }+ const operation = async () => {+ try {+ const previous = await this.snapshot()+ if (previous.revision !== parsed.data.revision) {+ result = { ok: false, error: { code: 'conflict' } }+ return+ }+ const controller = new AbortController()+ let timedOut = false,+ timer: ReturnType<typeof setTimeout> | undefined+ let valid: GrantValidation+ try {+ valid = await Promise.race([+ validate(parsed.data.settings, controller.signal),+ new Promise<boolean>((resolve) => {+ timer = setTimeout(() => {+ timedOut = true+ controller.abort()+ resolve(false)+ }, this.validationTimeoutMs)+ }),+ ])+ } finally {+ clearTimeout(timer)+ controller.abort()+ }+ if (valid === false || valid === 'folderUnavailable') {+ result = {+ ok: false,+ error: {+ code: timedOut+ ? 'unavailable'+ : valid === 'folderUnavailable'+ ? valid+ : 'permissionDenied',+ },+ }+ return+ }+ if ((await this.snapshot()).revision !== parsed.data.revision) {+ result = { ok: false, error: { code: 'conflict' } }+ return+ }+ if (+ typeof valid === 'object' &&+ parsed.data.settings.roots.some((root, index) => {+ const pinned = previous.pinnedRoots.get(root)+ return (+ pinned !== undefined &&+ pinned !== valid.directoryIdentities[index]+ )+ })+ ) {+ result = { ok: false, error: { code: 'folderUnavailable' } }+ return+ }+ const parent = await lstat(this.directory)+ if (+ !parent.isDirectory() ||+ parent.uid !== process.getuid?.() ||+ (parent.mode & 0o022) !== 0+ )+ throw new Error('Untrusted NAS configuration directory')+ await writeFileAtomic(+ path.join(this.directory, 'pending-settings.json'),+ `${JSON.stringify({+ ...parsed.data.settings,+ ...(typeof valid === 'object' ? valid : {}),+ })}\n`,+ { mode: 0o600 }+ )+ const directory = await open(+ this.directory,+ constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW+ )+ try {+ await directory.sync()+ } finally {+ await directory.close()+ }+ result = { ok: true, value: await this.view() }+ } catch {+ result = { ok: false, error: { code: 'unavailable' } }+ }+ }+ const queued = this.transition.then(operation, operation)+ this.transition = queued.then(+ () => undefined,+ () => undefined+ )+ await queued+ return result+ }+}diff --git a/src/server/platform/nas/task-access.ts b/src/server/platform/nas/task-access.tsindex 2c224055..a20ac175 100644--- a/src/server/platform/nas/task-access.ts+++ b/src/server/platform/nas/task-access.ts@@ -38,13 +38,21 @@ export class NasTaskAccess {NasFiles,'authorizeFile' | 'authorizeRemoval' | 'check'>,- private readonly policy: ServerDownloadPathPolicy+ private readonly policy: ServerDownloadPathPolicy,+ private readonly ownership?: {+ checkDirectory(task: DownloadTask): Promise<void>+ checkRemoval(task: DownloadTask, path: string): Promise<void>+ checkOutput(task: DownloadTask, path: string): Promise<void>+ }) {}readonly authorizeWrite = async (task: DownloadTask): Promise<void> => {+ await this.ownership?.checkDirectory(task)await this.policy.prepareSaveDir(task.saveDir)- for (const output of outputPaths(task))+ for (const output of outputPaths(task)) {await this.authorizeOutputWrite(output)+ await this.ownership?.checkOutput(task, output)+ }}readonly authorizeOutputWrite = async (output: string): Promise<void> => {@@ -61,7 +69,10 @@ export class NasTaskAccess {}readonly authorizeRemoval = async (task: DownloadTask): Promise<void> => {- for (const output of outputPaths(task))+ await this.ownership?.checkDirectory(task)+ for (const output of outputPaths(task)) {await this.files.authorizeRemoval(output, this.policy)+ await this.ownership?.checkRemoval(task, output)+ }}}diff --git a/src/server/platform/synology/accounts.test.ts b/src/server/platform/synology/accounts.test.tsnew file mode 100644index 00000000..f04dd405--- /dev/null+++ b/src/server/platform/synology/accounts.test.ts@@ -0,0 +1,214 @@+import { describe, expect, it, vi } from 'vitest'+import { NasClientAuthorization } from '../nas/client-authorization'+import { currentNasUser } from '../nas/identity'+import { SynologyAccounts } from './accounts'+import type { DsmApi } from './api'++const context = {+ cookie: 'id=synthetic',+ remoteAddress: '127.0.0.1',+ serverAddress: '127.0.0.1',+ serverPort: 5001,+ scheme: 'https' as const,+}+function fixture() {+ const state = {+ expired: 'normal',+ admin: true,+ epoch: 'first',+ username: 'alice',+ uid: 1700,+ session: true,+ filePath: '/volume1/motrix/file',+ }+ const api: DsmApi = vi.fn(async (_context, request, token) => {+ if (!state.session) return { success: false, error: { code: 119 } }+ if (request.kind === 'bootstrap')+ return { success: true, SynoToken: 'synthetic-token' }+ expect(token).toBe('synthetic-token')+ if (request.kind === 'session')+ return { success: true, data: { username: state.username } }+ if (request.kind === 'account')+ return {+ success: true,+ data: {+ users: [+ { name: request.username, uid: state.uid, expired: state.expired },+ ],+ },+ }+ return {+ success: true,+ data: {+ files: [+ {+ path: request.path,+ isdir: false,+ additional: {+ real_path: state.filePath,+ perm: {+ acl: {+ read: true,+ write: true,+ append: true,+ exec: true,+ del: true,+ },+ },+ },+ },+ ],+ },+ }+ })+ const accounts = new SynologyAccounts(+ api,+ async () => state.epoch,+ async () => ({ uid: state.uid, administrator: state.admin })+ )+ return { state, api, accounts }+}+describe('DSM live account authorization', () => {+ it('requires live session, local active account and POSIX administrator membership', async () => {+ const { state, accounts } = fixture()+ const signal = AbortSignal.timeout(1000)+ expect(await accounts.lookup('alice', signal)).toBeNull()+ expect(await accounts.authenticate(context, signal)).toMatchObject({+ username: 'alice',+ userId: '1700',+ administrator: true,+ })+ for (const expired of ['now', '', 'false', '2030-01-01']) {+ state.expired = expired+ expect(await accounts.authenticate(context, signal)).toBeNull()+ }+ state.expired = 'normal'+ state.admin = false+ expect(await accounts.authenticate(context, signal)).toBeNull()+ })+ it('revalidates paired credentials and rejects disable, demotion, expiry, UID reuse and missing context', async () => {+ const { state, accounts } = fixture()+ const signal = AbortSignal.timeout(1000)+ const owner = await accounts.authenticate(context, signal)+ const authorization = new NasClientAuthorization(+ { ownerOf: () => owner ?? undefined },+ accounts+ )+ const client = {+ identity: { kind: 'cli' as const, id: 'test', name: 'test' },+ credential: { kind: 'paired-cli' as const, fingerprint: 'synthetic' },+ }+ const operation = vi.fn(async () => currentNasUser()?.username)+ expect(await authorization.run(client, operation)).toBe('alice')+ state.expired = 'now'+ await expect(authorization.run(client, operation)).rejects.toThrow()+ state.expired = 'normal'+ // Failed authority clears the in-memory context until this account returns.+ await expect(authorization.run(client, operation)).rejects.toThrow()+ await accounts.authenticate(context, signal)+ state.admin = false+ await expect(authorization.run(client, operation)).rejects.toThrow()+ state.admin = true+ await accounts.authenticate(context, signal)+ state.session = false+ await expect(authorization.run(client, operation)).rejects.toThrow()+ state.session = true+ await accounts.authenticate(context, signal)+ state.epoch = 'recreated'+ await expect(authorization.run(client, operation)).rejects.toThrow()+ state.epoch = 'first'+ state.uid = 1800+ await expect(authorization.run(client, operation)).rejects.toThrow()+ expect(operation).toHaveBeenCalledTimes(1)+ })+ it('does not authorize an old owner with another current session account', async () => {+ const { state, accounts } = fixture()+ await accounts.authenticate(context, AbortSignal.timeout(1000))+ state.username = 'bob'+ expect(await accounts.lookup('alice', AbortSignal.timeout(1000))).toBeNull()+ })+ it('rechecks DSM instead of expiring a valid account after browser inactivity', async () => {+ const { state, api, accounts } = fixture()+ const identity = await accounts.authenticate(+ context,+ AbortSignal.timeout(1000)+ )+ expect(JSON.stringify(identity)).not.toContain('synthetic')+ const before = vi.mocked(api).mock.calls.length+ const clock = vi+ .spyOn(Date, 'now')+ .mockReturnValue(Date.now() + 8 * 60 * 60_000)+ try {+ expect(+ await accounts.lookup('alice', AbortSignal.timeout(1000))+ ).toMatchObject({ userId: '1700' })+ expect(vi.mocked(api).mock.calls.length).toBeGreaterThan(before)+ state.session = false+ expect(+ await accounts.lookup('alice', AbortSignal.timeout(1000))+ ).toBeNull()+ } finally {+ clock.mockRestore()+ }+ })+ it('keeps concurrent client validation valid when the same browser renews its context', async () => {+ const { api, accounts } = fixture()+ await accounts.authenticate(context, AbortSignal.timeout(1000))+ const original = vi.mocked(api).getMockImplementation()+ if (!original) throw new Error('Fixture API missing')+ let release: () => void = () => {}+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ vi.mocked(api).mockImplementationOnce(async (...args) => {+ await gate+ return original(...args)+ })+ const pending = accounts.lookup('alice', AbortSignal.timeout(1000))+ await accounts.authenticate(context, AbortSignal.timeout(1000))+ release()+ expect(await pending).toMatchObject({ username: 'alice' })+ })+ it('requires exact File Station path mapping and complete permission metadata', async () => {+ const { state, accounts } = fixture()+ const identity = await accounts.authenticate(+ context,+ AbortSignal.timeout(1000)+ )+ if (!identity) throw new Error('Fixture identity missing')+ expect(+ await accounts.inspectFile(+ identity,+ '/volume1/motrix/file',+ AbortSignal.timeout(1000)+ )+ ).not.toBeNull()+ state.filePath = '/volume2/motrix/file'+ expect(+ await accounts.inspectFile(+ identity,+ '/volume1/motrix/file',+ AbortSignal.timeout(1000)+ )+ ).toBeNull()+ expect(+ await accounts.inspectFile(+ identity,+ '/etc/shadow',+ AbortSignal.timeout(1000)+ )+ ).toBeNull()+ })+ it('rejects account generation changes during an authority lookup', async () => {+ const { api } = fixture()+ let epoch = 0+ const accounts = new SynologyAccounts(+ api,+ async () => String(epoch++),+ async () => ({ uid: 1700, administrator: true })+ )+ expect(+ await accounts.authenticate(context, AbortSignal.timeout(1000))+ ).toBeNull()+ })+})diff --git a/src/server/platform/synology/accounts.ts b/src/server/platform/synology/accounts.tsnew file mode 100644index 00000000..d8c11422--- /dev/null+++ b/src/server/platform/synology/accounts.ts@@ -0,0 +1,178 @@+import { createHash } from 'node:crypto'+import { stat } from 'node:fs/promises'+import {+ type NasAccountAuthority,+ sameNasAccount,+} from '../nas/client-authorization'+import type { NasIdentity } from '../nas/identity'+import {+ type DsmApi,+ dsmAccountSchema,+ dsmApi,+ dsmBootstrapSchema,+ dsmFileSchema,+ dsmSessionSchema,+} from './api'+import { readDsmPosixAccount } from './commands'+import { type DsmContext, validDsmUsername } from './validation'++export { validDsmUsername } from './validation'++async function accountEpoch(): Promise<string> {+ const records = await Promise.all(+ ['/etc/passwd', '/etc/group'].map(async (file) => {+ const info = await stat(file, { bigint: true })+ if (!info.isFile() || info.uid !== 0n || (info.mode & 0o022n) !== 0n)+ throw new Error('Untrusted DSM account database')+ return [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(+ ':'+ )+ })+ )+ return records.join('|')+}++export class SynologyAccounts implements NasAccountAuthority {+ readonly platform = 'synology' as const+ // No cookie/token is written to disk or returned to a client. Reopening the+ // DSM app supplies a new context after restart/expiration; bindings persist.+ // Only DSM determines session validity: every operation rechecks it. A local+ // inactivity cutoff must not interrupt a still-authorized long download.+ private readonly sessions = new Map<string, { context: DsmContext }>()+ constructor(+ private readonly api: DsmApi = dsmApi,+ private readonly epoch = accountEpoch,+ private readonly posix = readDsmPosixAccount+ ) {}++ private async validate(context: DsmContext, signal: AbortSignal) {+ const bootstrap = dsmBootstrapSchema.safeParse(+ await this.api(context, { kind: 'bootstrap' }, undefined, signal)+ )+ if (!bootstrap.success) return null+ const token = bootstrap.data.SynoToken+ const session = dsmSessionSchema.safeParse(+ await this.api(context, { kind: 'session' }, token, signal)+ )+ if (!session.success) return null+ const username = session.data.data.username+ const before = await this.epoch()+ const result = dsmAccountSchema.safeParse(+ await this.api(context, { kind: 'account', username }, token, signal)+ )+ if (!result.success) return null+ const record = result.data.data.users[0]+ const unix = await this.posix(username, signal)+ const after = await this.epoch()+ if (+ record.name !== username ||+ record.uid !== unix.uid ||+ !unix.administrator ||+ before !== after+ )+ return null+ return {+ token,+ identity: {+ platform: this.platform,+ userId: String(record.uid),+ username,+ administrator: true,+ accountRevision: createHash('sha256')+ .update(`${after}|${record.uid}|${username}`)+ .digest('hex'),+ },+ }+ }++ async authenticate(+ context: DsmContext,+ signal: AbortSignal+ ): Promise<NasIdentity | null> {+ const result = await this.validate(context, signal)+ if (!result) return null+ if (+ !this.sessions.has(result.identity.username) &&+ this.sessions.size >= 64+ ) {+ const oldest = this.sessions.keys().next().value+ if (oldest !== undefined) this.sessions.delete(oldest)+ }+ const existing = this.sessions.get(result.identity.username)+ const entry =+ existing && JSON.stringify(existing.context) === JSON.stringify(context)+ ? existing+ : { context: { ...context } }+ this.sessions.delete(result.identity.username)+ this.sessions.set(result.identity.username, entry)+ return result.identity+ }++ private async current(username: string, signal: AbortSignal) {+ if (!validDsmUsername(username)) return null+ const entry = this.sessions.get(username)+ if (!entry) return null+ const forget = () => {+ if (this.sessions.get(username) === entry) this.sessions.delete(username)+ }+ try {+ const result = await this.validate(entry.context, signal)+ if (!result || result.identity.username !== username) {+ forget()+ return null+ }+ if (this.sessions.get(username) !== entry) return null+ this.sessions.delete(username)+ this.sessions.set(username, entry)+ return { ...result, context: entry.context }+ } catch (error) {+ forget()+ throw error+ }+ }++ async lookup(+ username: string,+ signal: AbortSignal+ ): Promise<NasIdentity | null> {+ return (await this.current(username, signal))?.identity ?? null+ }+ async resolve(+ identity: NasIdentity,+ signal: AbortSignal+ ): Promise<NasIdentity | null> {+ if (identity.platform !== this.platform) return null+ const current = await this.lookup(identity.username, signal)+ return current?.userId === identity.userId ? current : null+ }+ async inspectFile(+ identity: NasIdentity,+ candidate: string,+ signal: AbortSignal+ ) {+ if (+ !/^\/volume[1-9]\d*\/[^/]+(?:\/.*)?$/.test(candidate) ||+ candidate+ .split('/')+ .slice(1)+ .some((p) => !p || p === '.' || p === '..')+ )+ return null+ const current = await this.current(identity.username, signal)+ if (!current || !sameNasAccount(current.identity, identity)) return null+ const virtual = candidate.replace(/^\/volume[1-9]\d*/, '')+ const result = dsmFileSchema.safeParse(+ await this.api(+ current.context,+ { kind: 'file', path: virtual },+ current.token,+ signal+ )+ )+ if (!result.success) return null+ const file = result.data.data.files[0]+ if (file.path !== virtual || file.additional.real_path !== candidate)+ return null+ return file+ }+}diff --git a/src/server/platform/synology/api.test.ts b/src/server/platform/synology/api.test.tsnew file mode 100644index 00000000..fff5f0d1--- /dev/null+++ b/src/server/platform/synology/api.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from 'vitest'+import { dsmScgiRequest, parseDsmScgiResponse } from './api'++const context = {+ cookie: 'id=synthetic',+ remoteAddress: '192.0.2.2',+ serverAddress: '192.0.2.1',+ serverPort: 5001,+ scheme: 'https' as const,+}+function decode(buffer: Buffer) {+ const colon = buffer.indexOf(':')+ const length = Number(buffer.subarray(0, colon).toString())+ const parts = buffer+ .subarray(colon + 1, colon + 1 + length)+ .toString()+ .split('\0')+ .slice(0, -1)+ return {+ env: Object.fromEntries(+ Array.from({ length: parts.length / 2 }, (_, i) =>+ parts.slice(i * 2, i * 2 + 2)+ )+ ),+ body: buffer.subarray(colon + length + 2).toString(),+ }+}+describe('fixed DSM SCGI bridge', () => {+ it('uses only the vendor bootstrap and read APIs, with secrets outside URI/argv', () => {+ const boot = decode(dsmScgiRequest(context, { kind: 'bootstrap' }))+ expect(boot.env.SCRIPT_FILENAME).toBe('/usr/syno/synoman/webman/login.cgi')+ expect(boot.body).toBe('')+ const req = decode(+ dsmScgiRequest(+ context,+ { kind: 'account', username: 'alice' },+ 'synthetic-token'+ )+ )+ expect(req.env).toMatchObject({+ REMOTE_ADDR: '192.0.2.2',+ SERVER_PORT: '5001',+ HTTPS: 'on',+ HTTP_X_SYNO_TOKEN: 'synthetic-token',+ QUERY_STRING: '',+ REQUEST_URI: '/webapi/entry.cgi',+ })+ expect(new URLSearchParams(req.body).get('additional')).toBe('["expired"]')+ const file = decode(+ dsmScgiRequest(+ context,+ { kind: 'file', path: '/motrix/a,b' },+ 'synthetic-token'+ )+ )+ expect(+ JSON.parse(new URLSearchParams(file.body).get('path') ?? '')+ ).toEqual(['/motrix/a,b'])+ expect(() =>+ dsmScgiRequest(+ { ...context, cookie: 'id=x\0REMOTE_USER\0root' },+ { kind: 'bootstrap' }+ )+ ).toThrow()+ expect(() =>+ dsmScgiRequest(+ context,+ { kind: 'file', path: '/motrix/../private' },+ 'token'+ )+ ).toThrow()+ expect(() =>+ dsmScgiRequest(context, { kind: 'account', username: '--help' }, 'token')+ ).toThrow()+ })+ it('rejects truncated, ambiguous and non-JSON responses without retaining their content', () => {+ expect(+ parseDsmScgiResponse(+ Buffer.from('Content-Type: application/json\r\n\r\n{"success":false}')+ )+ ).toEqual({ success: false })+ for (const text of [+ 'private-token',+ 'Status: 302 Found\r\n\r\n{}',+ 'Status: 200\r\nStatus: 500\r\n\r\n{}',+ 'Content-Length: 99\r\n\r\n{}',+ 'Content-Type: text/html\r\n\r\nprivate-token',+ ]) {+ let error: unknown+ try {+ parseDsmScgiResponse(Buffer.from(text))+ } catch (e) {+ error = e+ }+ expect(error).toBeInstanceOf(Error)+ expect(JSON.stringify(error)).not.toContain('private')+ }+ })+})diff --git a/src/server/platform/synology/api.ts b/src/server/platform/synology/api.tsnew file mode 100644index 00000000..f73fc771--- /dev/null+++ b/src/server/platform/synology/api.ts@@ -0,0 +1,252 @@+import { lstat } from 'node:fs/promises'+import { createConnection } from 'node:net'+import { z } from 'zod'+import { DsmCommandError } from './commands'+import {+ type DsmContext,+ dsmContextSchema,+ dsmText,+ dsmUsername,+} from './validation'++type DsmRequest =+ | { kind: 'bootstrap' }+ | { kind: 'session' }+ | { kind: 'account'; username: string }+ | { kind: 'file'; path: string }+export type DsmApi = (+ context: DsmContext,+ request: DsmRequest,+ token?: string,+ signal?: AbortSignal+) => Promise<unknown>++const socketPath = '/run/synoscgi.sock'+export async function probeDsmApi() {+ try {+ const [socket, parent] = await Promise.all([+ lstat(socketPath),+ lstat('/run'),+ ])+ if (+ !socket.isSocket() ||+ ![0, 1023].includes(socket.uid) ||+ (socket.mode & 0o007) !== 0 ||+ parent.uid !== 0 ||+ (parent.mode & 0o022) !== 0+ )+ throw new Error('Untrusted DSM endpoint')+ return { webApiSocketProbe: 'passed' as const }+ } catch {+ return { webApiSocketProbe: 'failed' as const }+ }+}++/** Only fixed, read-only vendor routes. Credentials stay in memory on the NAS.+ * No HTTP redirect, remote host, executable, arbitrary API or environment input. */+export function dsmScgiRequest(+ context: DsmContext,+ request: DsmRequest,+ token?: string+): Buffer {+ const c = dsmContextSchema.parse(context)+ const bootstrap = request.kind === 'bootstrap'+ const script = bootstrap ? '/webman/login.cgi' : '/webapi/entry.cgi'+ let params: Record<string, string>+ switch (request.kind) {+ case 'bootstrap':+ params = {}+ break+ case 'session':+ params = { api: 'SYNO.Core.NormalUser', version: '1', method: 'get' }+ break+ case 'account':+ params = {+ api: 'SYNO.Core.User',+ version: '1',+ method: 'get',+ name: dsmUsername.parse(request.username),+ type: 'local',+ additional: '["expired"]',+ }+ break+ case 'file': {+ const file = dsmText(4096)+ .regex(/^\/[^/]+(?:\/.*)?$/)+ .parse(request.path)+ if (+ file+ .split('/')+ .slice(1)+ .some((p) => !p || p === '.' || p === '..')+ )+ throw new Error('Invalid DSM path')+ params = {+ api: 'SYNO.FileStation.List',+ version: '2',+ method: 'getinfo',+ path: JSON.stringify([file]),+ additional: '["real_path","perm"]',+ }+ break+ }+ default:+ throw new Error('Unsupported DSM operation')+ }+ const csrf = bootstrap ? undefined : dsmText(4096).min(1).parse(token)+ const body = Buffer.from(new URLSearchParams(params).toString())+ const env = {+ CONTENT_LENGTH: String(body.length),+ SCGI: '1',+ REQUEST_METHOD: bootstrap ? 'GET' : 'POST',+ SCRIPT_FILENAME: `/usr/syno/synoman${script}`,+ SCRIPT_NAME: script,+ REQUEST_URI: script,+ DOCUMENT_URI: script,+ DOCUMENT_ROOT: '/usr/syno/synoman',+ QUERY_STRING: '',+ CONTENT_TYPE: 'application/x-www-form-urlencoded',+ SERVER_PROTOCOL: 'HTTP/1.1',+ GATEWAY_INTERFACE: 'CGI/1.1',+ REQUEST_SCHEME: c.scheme,+ HTTPS: c.scheme === 'https' ? 'on' : '',+ REMOTE_ADDR: c.remoteAddress,+ REMOTE_PORT: '0',+ SERVER_ADDR: c.serverAddress,+ SERVER_PORT: String(c.serverPort),+ HTTP_HOST: c.host ?? c.serverAddress,+ HTTP_COOKIE: c.cookie,+ HTTP_USER_AGENT: c.userAgent ?? '',+ ...(csrf === undefined ? {} : { HTTP_X_SYNO_TOKEN: csrf }),+ }+ const header = Buffer.from(`${Object.entries(env).flat().join('\0')}\0`)+ return Buffer.concat([+ Buffer.from(`${header.length}:`),+ header,+ Buffer.from(','),+ body,+ ])+}++export function parseDsmScgiResponse(bytes: Buffer): unknown {+ const offset = bytes.indexOf('\r\n\r\n')+ if (offset < 0 || offset > 16384) throw new DsmCommandError({})+ const headers = bytes.subarray(0, offset).toString('utf8')+ const statuses = [+ ...headers.matchAll(/^Status:\s*(\d{3})(?:\s[^\r\n]*)?\r?$/gim),+ ]+ if (+ statuses.length > 1 ||+ (statuses.length === 1 && statuses[0][1] !== '200') ||+ /^Transfer-Encoding:/im.test(headers)+ )+ throw new DsmCommandError({})+ const body = bytes.subarray(offset + 4)+ const lengths = [...headers.matchAll(/^Content-Length:\s*(\d+)\s*$/gim)]+ if (+ lengths.length > 1 ||+ (lengths.length === 1 && Number(lengths[0][1]) !== body.length)+ )+ throw new DsmCommandError({})+ try {+ return JSON.parse(body.toString('utf8'))+ } catch {+ throw new DsmCommandError({})+ }+}++export const dsmApi: DsmApi = async (context, request, token, signal) => {+ if (signal?.aborted || (await probeDsmApi()).webApiSocketProbe !== 'passed')+ throw new DsmCommandError({})+ let payload: Buffer+ try {+ payload = dsmScgiRequest(context, request, token)+ } catch {+ throw new DsmCommandError({})+ }+ return new Promise((resolve, reject) => {+ const socket = createConnection(socketPath)+ const chunks: Buffer[] = []+ let size = 0,+ settled = false+ const finish = (error?: unknown) => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ signal?.removeEventListener('abort', abort)+ socket.destroy()+ if (error) reject(new DsmCommandError(error))+ else {+ try {+ resolve(parseDsmScgiResponse(Buffer.concat(chunks)))+ } catch {+ reject(new DsmCommandError({}))+ }+ }+ }+ const abort = () => finish({ killed: true })+ const timer = setTimeout(abort, 2500)+ signal?.addEventListener('abort', abort, { once: true })+ if (signal?.aborted) abort()+ socket.on('connect', () => socket.write(payload))+ socket.on('data', (chunk: Buffer) => {+ size += chunk.length+ if (size > 128 * 1024)+ finish({ code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' })+ else chunks.push(chunk)+ })+ socket.on('error', finish)+ socket.on('end', () => finish())+ socket.on('close', () => {+ if (!settled) finish({})+ })+ })+}++export const dsmBootstrapSchema = z.object({+ success: z.literal(true),+ SynoToken: dsmText(4096).min(1),+})+export const dsmSessionSchema = z.object({+ success: z.literal(true),+ data: z.object({ username: dsmUsername }),+})+export const dsmAccountSchema = z.object({+ success: z.literal(true),+ data: z.object({+ users: z+ .array(+ z.object({+ name: dsmUsername,+ uid: z.number().int().positive().max(0xfffffffe),+ expired: z.literal('normal'),+ })+ )+ .length(1),+ }),+})+export const dsmFileSchema = z.object({+ success: z.literal(true),+ data: z.object({+ files: z+ .array(+ z.object({+ path: z.string(),+ isdir: z.boolean(),+ additional: z.object({+ real_path: z.string(),+ perm: z.object({+ acl: z.object({+ read: z.boolean(),+ write: z.boolean(),+ append: z.boolean(),+ exec: z.boolean(),+ del: z.boolean(),+ }),+ }),+ }),+ })+ )+ .length(1),+ }),+})diff --git a/src/server/platform/synology/commands.test.ts b/src/server/platform/synology/commands.test.tsnew file mode 100644index 00000000..750a804f--- /dev/null+++ b/src/server/platform/synology/commands.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest'+import { DsmCommandError } from './commands'++describe('DSM command failure metadata', () => {+ it.each([+ [{ code: 'EACCES' }, 'accessDenied', undefined],+ [{ code: 'ENOENT' }, 'notFound', undefined],+ [{ killed: true }, 'timeout', undefined],+ [{ code: 5 }, 'exit', 5],+ [{ code: 'untrusted-session-text' }, 'unavailable', undefined],+ ])(+ 'retains only a bounded failure category from %o',+ (cause, failure, exitCode) => {+ const error = new DsmCommandError({+ ...cause,+ message: 'id=private-cookie',+ stdout: 'private-account',+ stderr: 'private-output',+ env: { HTTP_COOKIE: 'id=private-cookie' },+ })+ expect(error.failure).toBe(failure)+ expect(error.exitCode).toBe(exitCode)+ expect(JSON.stringify(error)).not.toContain('private')+ expect(error.message).toBe('DSM authority unavailable')+ expect(error.cause).toBeUndefined()+ }+ )+})diff --git a/src/server/platform/synology/commands.ts b/src/server/platform/synology/commands.tsnew file mode 100644index 00000000..69a1cf99--- /dev/null+++ b/src/server/platform/synology/commands.ts@@ -0,0 +1,72 @@+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import type { NasAuthDiagnostic } from '@shared/schemas/operator-auth'+import { validDsmUsername } from './validation'++const execute = promisify(execFile)+export class DsmCommandError extends Error {+ readonly failure: NonNullable<NasAuthDiagnostic['failure']>+ readonly exitCode?: number+ constructor(error: unknown) {+ super('DSM authority unavailable')+ const code =+ typeof error === 'object' && error !== null && 'code' in error+ ? error.code+ : undefined+ const killed =+ typeof error === 'object' &&+ error !== null &&+ 'killed' in error &&+ error.killed === true+ this.failure =+ code === 'EACCES' || code === 'EPERM'+ ? 'accessDenied'+ : code === 'ENOENT'+ ? 'notFound'+ : killed+ ? 'timeout'+ : code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'+ ? 'outputLimit'+ : typeof code === 'number' &&+ Number.isInteger(code) &&+ code >= 0 &&+ code <= 255+ ? 'exit'+ : 'unavailable'+ if (this.failure === 'exit') this.exitCode = code as number+ }+}++/** POSIX identity only. Account activity is checked separately by DSM Web API. */+export async function readDsmPosixAccount(+ username: string,+ signal: AbortSignal+) {+ if (!validDsmUsername(username)) throw new DsmCommandError({})+ try {+ const options = {+ env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C' },+ cwd: '/',+ timeout: 1500,+ maxBuffer: 8192,+ signal,+ encoding: 'utf8' as const,+ }+ const [uidResult, groupsResult] = await Promise.all([+ execute('/usr/bin/id', ['-u', '--', username], options),+ execute('/usr/bin/id', ['-G', '--', username], options),+ ])+ const uid = uidResult.stdout.trim()+ const groups = groupsResult.stdout.trim().split(/\s+/)+ if (+ !/^[1-9]\d*$/.test(uid) ||+ Number(uid) >= 0xffffffff ||+ groups.length > 1024 ||+ groups.some((g) => !/^\d+$/.test(g))+ )+ throw new Error('Invalid POSIX account')+ return { uid: Number(uid), administrator: groups.includes('101') }+ } catch (error) {+ throw new DsmCommandError(error)+ }+}diff --git a/src/server/platform/synology/files.test.ts b/src/server/platform/synology/files.test.tsnew file mode 100644index 00000000..477fc03f--- /dev/null+++ b/src/server/platform/synology/files.test.ts@@ -0,0 +1,63 @@+import { mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import { SynologyAccounts } from './accounts'+import { dsmDirectoryConfig, dsmPermission, SynologyFileAccess } from './files'++describe('DSM filesystem authority responses', () => {+ it.skipIf(process.platform === 'win32')(+ 'refuses a replaced live grants document before checking any share',+ async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'motrix-synology-grants-'))+ try {+ const grants = path.join(dir, 'directories.json'),+ target = path.join(dir, 'fixture')+ await writeFile(+ target,+ JSON.stringify({ roots: ['/volume1/motrix'] }),+ { mode: 0o600 }+ )+ await symlink(target, grants)+ const files = new SynologyFileAccess(grants, new SynologyAccounts())+ await expect(files.authorizedRoots()).rejects.toMatchObject({+ code: 'ELOOP',+ })+ await rm(grants)+ await writeFile(grants, 'private-test-content', { mode: 0o600 })+ await expect(files.authorizedRoots()).rejects.toThrow(+ /^Invalid DSM directory configuration$/+ )+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+ }+ )+ it('requires directory traversal and append rights, and a separate delete grant', () => {+ const acl = { read: true, write: true, exec: true, append: true, del: true }+ expect(dsmPermission(acl, 'writable', true)).toBe(true)+ expect(dsmPermission({ ...acl, exec: false }, 'writable', true)).toBe(false)+ expect(dsmPermission({ ...acl, append: false }, 'writable', true)).toBe(+ false+ )+ expect(dsmPermission({ ...acl, del: false }, 'deletable', false)).toBe(+ false+ )+ expect(dsmPermission({ ...acl, exec: false }, 'readable', true)).toBe(false)+ })+ it('does not treat empty grants, system paths, or a malformed volume as an unrestricted root', () => {+ for (const roots of [+ [],+ ['/'],+ ['/tmp/downloads'],+ ['/volume0/downloads'],+ ['/volume1'],+ ['/volume1/motrix/../other'],+ ['/volume1/motrix:/volume2/other'],+ ])+ expect(dsmDirectoryConfig.safeParse({ roots }).success).toBe(false)+ expect(+ dsmDirectoryConfig.safeParse({ roots: ['/volume1/downloads'] }).success+ ).toBe(true)+ })+})diff --git a/src/server/platform/synology/files.ts b/src/server/platform/synology/files.tsnew file mode 100644index 00000000..1ab8a0b5--- /dev/null+++ b/src/server/platform/synology/files.ts@@ -0,0 +1,268 @@+import { constants } from 'node:fs'+import {+ access,+ lstat,+ mkdir,+ open,+ readFile,+ realpath,+} from 'node:fs/promises'+import path from 'node:path'+import { nasRootPathSchema } from '@shared/schemas/nas-settings'+import writeFileAtomic from 'write-file-atomic'+import { z } from 'zod'+import type { ServerDownloadPathPolicy } from '../../download-path-policy'+import {+ type NasFileAccess,+ type NasFilePermission,+ NasFiles,+} from '../nas/files'+import type { NasIdentity } from '../nas/identity'+import { readNasConfigurationText } from '../nas/settings-store'+import type { SynologyAccounts } from './accounts'++export const dsmDirectoryConfig = z+ .object({+ roots: z+ .array(+ nasRootPathSchema.refine((root) =>+ /^\/volume[1-9]\d*\/[^/]+(?:\/.*)?$/.test(root)+ )+ )+ .min(1)+ .max(64),+ directoryIdentities: z+ .array(z.string().regex(/^\d{1,20}:\d{1,20}$/))+ .optional(),+ })+ .strict()+ .refine(+ (value) =>+ !value.directoryIdentities ||+ value.directoryIdentities.length === value.roots.length+ )++/** Capture only canonical directories on mounted DSM volumes. A failed lookup+ * cannot establish a new grant or satisfy a previously recorded identity. */+export async function inspectDsmRoots(roots: string[]) {+ dsmDirectoryConfig.parse({ roots })+ const mounts = new Set(+ (await readFile('/proc/self/mountinfo', 'utf8'))+ .split('\n')+ .map((line) => line.split(' ')[4])+ )+ return Promise.all(+ roots.map(async (root) => {+ if (!mounts.has(root.split('/').slice(0, 2).join('/'))) return null+ try {+ const directory = await open(+ root,+ constants.O_RDONLY |+ constants.O_DIRECTORY |+ constants.O_NOFOLLOW |+ constants.O_NONBLOCK+ )+ try {+ const held = await directory.stat({ bigint: true })+ if ((await realpath(root)) !== root) return null+ await access(root, constants.R_OK | constants.W_OK | constants.X_OK)+ const named = await lstat(root, { bigint: true })+ return held.dev === named.dev && held.ino === named.ino+ ? `${held.dev}:${held.ino}`+ : null+ } finally {+ await directory.close()+ }+ } catch {+ return null+ }+ })+ )+}++export async function readDsmDirectoryGrants(+ configFile: string,+ initializeLegacy = false+) {+ const text = await readNasConfigurationText(configFile)+ let document: unknown+ try {+ document = JSON.parse(text ?? '')+ } catch {+ throw new Error('Invalid DSM directory configuration')+ }+ const config = dsmDirectoryConfig.parse(document)+ const current = await inspectDsmRoots(config.roots)+ // Only the serialized lifecycle's initial server startup may migrate a+ // path-only configuration. Later requests never adopt a new directory.+ if (+ initializeLegacy &&+ !config.directoryIdentities &&+ current.every((id): id is string => id !== null)+ ) {+ config.directoryIdentities = current+ await writeFileAtomic(configFile, `${JSON.stringify(config)}\n`, {+ mode: 0o600,+ })+ const parent = await open(+ path.dirname(configFile),+ constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW+ )+ try {+ await parent.sync()+ } finally {+ await parent.close()+ }+ }+ const unavailable = config.roots.filter(+ (_, i) =>+ current[i] === null ||+ (config.directoryIdentities+ ? current[i] !== config.directoryIdentities[i]+ : !initializeLegacy)+ )+ return { ...config, unavailable }+}++export function dsmPermission(+ acl: {+ read: boolean+ write: boolean+ append: boolean+ exec: boolean+ del: boolean+ },+ permission: NasFilePermission,+ directory: boolean+): boolean {+ return permission === 'deletable'+ ? acl.del+ : permission === 'writable'+ ? acl.write && (!directory || (acl.exec && acl.append))+ : acl.read && (!directory || acl.exec)+}++export class SynologyFileAccess implements NasFileAccess {+ readonly platform = 'synology' as const+ constructor(+ private readonly configFile: string,+ private readonly accounts: SynologyAccounts+ ) {}++ async authorizedRoots(): Promise<string[]> {+ const config = await readDsmDirectoryGrants(this.configFile)+ if (config.unavailable.length) throw new Error('DSM share unavailable')+ return config.roots+ }++ async checkAccess(+ user: NasIdentity,+ candidate: string,+ permission: NasFilePermission+ ): Promise<boolean> {+ if (user.platform !== this.platform) return false+ try {+ const roots = await this.authorizedRoots()+ if (+ !roots.some(+ (root) => candidate === root || candidate.startsWith(`${root}/`)+ )+ )+ return false+ const info = await lstat(candidate)+ if (info.isSymbolicLink()) return false+ await access(+ permission === 'deletable' ? path.dirname(candidate) : candidate,+ permission === 'readable' ? constants.R_OK : constants.W_OK+ )+ const file = await this.accounts.inspectFile(+ user,+ candidate,+ AbortSignal.timeout(5000)+ )+ return (+ file !== null &&+ file.isdir === info.isDirectory() &&+ dsmPermission(file.additional.perm.acl, permission, file.isdir)+ )+ } catch {+ return false+ }+ }+}++export class SynologyFiles extends NasFiles {+ constructor(configFile: string, accounts: SynologyAccounts) {+ super(new SynologyFileAccess(configFile, accounts))+ }++ override async policy(+ defaultSaveDir: string+ ): Promise<ServerDownloadPathPolicy> {+ const base = await super.policy(defaultSaveDir)+ return {+ get allowedSaveDirs() {+ return base.allowedSaveDirs+ },+ authorizeDirectory: base.authorizeDirectory,+ prepareSaveDir: async (requested) => {+ const candidate = requested || defaultSaveDir+ if (+ !path.isAbsolute(candidate) ||+ path.resolve(candidate) !== candidate ||+ candidate.includes('\0')+ )+ throw Error('Invalid DSM save path')+ const root = (await this.roots())+ .filter((dir) => candidate === dir || candidate.startsWith(`${dir}/`))+ .sort((a, b) => b.length - a.length)[0]+ if (!root) throw Error('DSM directory is outside authorized shares')+ const flags =+ constants.O_RDONLY |+ constants.O_DIRECTORY |+ constants.O_NOFOLLOW |+ constants.O_NONBLOCK+ let name = root+ let held = await open(root, flags)+ try {+ for (const part of [+ ...path.relative(root, candidate).split(path.sep).filter(Boolean),+ null,+ ]) {+ if ((await base.authorizeDirectory(name)).canonicalPath !== name)+ throw Error('DSM directory changed')+ const opened = await held.stat({ bigint: true }),+ named = await lstat(name, { bigint: true })+ if (named.dev !== opened.dev || named.ino !== opened.ino)+ throw Error('DSM directory changed')+ const fd = `/proc/self/fd/${held.fd}`+ if (!part) {+ await this.check(name, 'writable')+ await access(fd, constants.W_OK | constants.X_OK)+ return name+ }+ const child = path.join(fd, part)+ let next: typeof held+ try {+ next = await open(child, flags)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')+ throw error+ await this.check(name, 'writable')+ await mkdir(child).catch((cause: NodeJS.ErrnoException) => {+ if (cause.code !== 'EEXIST') throw cause+ })+ next = await open(child, flags)+ }+ await held.close()+ held = next+ name = path.join(name, part)+ }+ throw Error('Invalid DSM save path')+ } finally {+ await held.close()+ }+ },+ }+ }+}diff --git a/src/server/platform/synology/identity.test.ts b/src/server/platform/synology/identity.test.tsnew file mode 100644index 00000000..c4a738b6--- /dev/null+++ b/src/server/platform/synology/identity.test.ts@@ -0,0 +1,70 @@+import type { FastifyRequest } from 'fastify'+import { expect, it, vi } from 'vitest'+import { SynologyAccounts } from './accounts'+import { DsmCommandError } from './commands'+import { synologyGateway } from './identity'++function request(headers: Record<string, string>, peer?: string) {+ return {+ headers,+ server: { server: { address: () => '/var/test.sock' } },+ raw: { socket: { remoteAddress: peer } },+ } as unknown as FastifyRequest+}+const headers = {+ cookie: 'id=private-cookie',+ 'x-motrix-dsm-remote-addr': '192.0.2.2',+ 'x-motrix-dsm-server-addr': '192.0.2.1',+ 'x-motrix-dsm-server-port': '5001',+ 'x-motrix-dsm-scheme': 'https',+}+it('uses live DSM APIs only through the trusted Unix listener and ignores identity headers', async () => {+ const accounts = new SynologyAccounts()+ const authenticate = vi.spyOn(accounts, 'authenticate').mockResolvedValue({+ platform: 'synology',+ userId: '1700',+ username: 'alice',+ administrator: true,+ })+ const adapter = synologyGateway('/var/test.sock', accounts)+ expect(await adapter.authenticate(request(headers))).toMatchObject({+ username: 'alice',+ administrator: true,+ })+ expect(authenticate).toHaveBeenCalledWith(+ expect.objectContaining({+ cookie: 'id=private-cookie',+ remoteAddress: '192.0.2.2',+ scheme: 'https',+ serverPort: 5001,+ }),+ expect.any(AbortSignal)+ )+ authenticate.mockClear()+ for (const req of [+ request(headers, '127.0.0.1'),+ request({ 'x-trim-userid': '1700', 'x-trim-isadmin': 'true' }),+ request({ ...headers, 'x-motrix-dsm-remote-addr': 'spoofed' }),+ ])+ expect(await adapter.authenticate(req)).toBeUndefined()+ expect(authenticate).not.toHaveBeenCalled()+})+it('fails closed and returns only bounded diagnostics, never session or account data', async () => {+ const accounts = new SynologyAccounts()+ const authenticate = vi+ .spyOn(accounts, 'authenticate')+ .mockResolvedValue(null)+ const adapter = synologyGateway('/var/test.sock', accounts)+ const req = request(headers)+ expect(await adapter.authenticate(req)).toBeUndefined()+ authenticate.mockRejectedValue(+ new DsmCommandError({ code: 'EACCES', stderr: 'private-output' })+ )+ expect(await adapter.authenticate(req)).toBeUndefined()+ expect(adapter.diagnostic?.(req)).toEqual({+ stage: 'account',+ code: 'commandFailed',+ failure: 'accessDenied',+ })+ expect(JSON.stringify(adapter.diagnostic?.(req))).not.toContain('private')+})diff --git a/src/server/platform/synology/identity.ts b/src/server/platform/synology/identity.tsnew file mode 100644index 00000000..0f169dfe--- /dev/null+++ b/src/server/platform/synology/identity.ts@@ -0,0 +1,74 @@+import type { NasAuthDiagnostic } from '@shared/schemas/operator-auth'+import type { FastifyRequest } from 'fastify'+import type { NasGatewayOptions } from '../../http/nas-auth'+import type { SynologyAccounts } from './accounts'+import { DsmCommandError } from './commands'+import { dsmContextSchema } from './validation'++export function synologyGateway(+ socketPath: string,+ accounts: SynologyAccounts+): NasGatewayOptions {+ const isListener = (req: FastifyRequest) =>+ req.server.server.address() === socketPath &&+ req.raw.socket.remoteAddress === undefined+ const diagnostics = new WeakMap<FastifyRequest, NasAuthDiagnostic>()+ return {+ mode: 'synologyDsm',+ publicShell: true,+ capabilities: {+ settings: true,+ fileActions: true,+ torrentPicker: true,+ clientGateway: true,+ },+ isListener,+ // DSM authenticates upgrades as well; tickets cannot extend a disabled account.+ hasIdentity: () => true,+ diagnostic: (req) => diagnostics.get(req),+ async authenticate(req) {+ const deny = (value: NasAuthDiagnostic) => {+ diagnostics.set(req, value)+ return undefined+ }+ if (!isListener(req))+ return deny({ stage: 'gateway', code: 'untrustedListener' })+ if (!req.headers.cookie)+ return deny({ stage: 'session', code: 'missingCookie' })+ const parsed = dsmContextSchema.safeParse({+ cookie: req.headers.cookie,+ remoteAddress: req.headers['x-motrix-dsm-remote-addr'],+ serverAddress: req.headers['x-motrix-dsm-server-addr'],+ serverPort: req.headers['x-motrix-dsm-server-port'],+ scheme: req.headers['x-motrix-dsm-scheme'],+ host: req.headers.host,+ userAgent: req.headers['user-agent'],+ })+ if (!parsed.success)+ return deny({ stage: 'gateway', code: 'invalidContext' })+ const stage = 'account'+ try {+ const account = await accounts.authenticate(+ parsed.data,+ AbortSignal.timeout(5000)+ )+ if (!account) return deny({ stage, code: 'rejected' })+ diagnostics.delete(req)+ return account+ } catch (error) {+ return deny(+ error instanceof DsmCommandError+ ? {+ stage,+ code: 'commandFailed',+ failure: error.failure,+ ...(error.exitCode !== undefined+ ? { exitCode: error.exitCode }+ : {}),+ }+ : { stage, code: 'unavailable' }+ )+ }+ },+ }+}diff --git a/src/server/platform/synology/runtime.test.ts b/src/server/platform/synology/runtime.test.tsnew file mode 100644index 00000000..4c6ba773--- /dev/null+++ b/src/server/platform/synology/runtime.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest'+import { dsmGatewayGroup } from './runtime'++describe('DSM gateway group resolution', () => {+ it('uses the system-assigned group only when it is an actual supplementary group', () => {+ expect(+ dsmGatewayGroup('motrix:x:4500:\nhttp:x:1023:motrix\n', [4500, 1023])+ ).toBe(1023)+ // Text membership alone cannot authorize changing socket access.+ expect(() => dsmGatewayGroup('http:x:1023:motrix\n', [4500])).toThrow()+ })+ it('rejects missing, ambiguous, root and invalid groups', () => {+ for (const contents of [+ '',+ 'http:x:0:motrix',+ 'http:x:1023:\nhttp:x:1024:',+ 'http:x:4294967295:',+ 'http:x:-1:',+ 'http:x:1023:extra:field',+ ]) {+ expect(() =>+ dsmGatewayGroup(contents, [0, 1023, 1024, 4294967295, -1])+ ).toThrow()+ }+ })+})diff --git a/src/server/platform/synology/runtime.ts b/src/server/platform/synology/runtime.tsnew file mode 100644index 00000000..d96a3633--- /dev/null+++ b/src/server/platform/synology/runtime.ts@@ -0,0 +1,72 @@+import { readFile, stat } from 'node:fs/promises'+import path from 'node:path'+import type { FastifyInstance } from 'fastify'+import { listenNas } from '../nas/listener'++export function dsmDefaultSaveDir(+ current: string,+ configured: string,+ rootsValue: string | undefined+): string {+ const roots = rootsValue?.split(':').filter(Boolean) ?? []+ const normalized = path.posix.resolve(current)+ return roots.length > 0 &&+ !roots.some(+ (root) => normalized === root || normalized.startsWith(`${root}/`)+ )+ ? configured+ : current+}++export function synologyRuntime(env: NodeJS.ProcessEnv = process.env) {+ if (env.MOTRIX_AUTH_MODE !== 'synologyDsm') return undefined+ const variable = env.SYNOPKG_PKGVAR+ if (+ !variable ||+ !path.isAbsolute(variable) ||+ env.MOTRIX_WEB_BASE_PATH !== '/motrix'+ )+ throw new Error('Invalid DSM runtime configuration')+ if (process.getuid?.() === 0)+ throw new Error('DSM Server must run as the package account')+ return {+ socketPath: path.join(variable, 'web.sock'),+ clientSocketPath: path.join(variable, 'client.sock'),+ variable,+ configFile: path.join(variable, 'directories.json'),+ }+}++/** DSM provisions the supplementary http group through conf/privilege.+ * Read the system-assigned GID instead of assuming a numeric value. */+export function dsmGatewayGroup(contents: string, groups: number[]): number {+ const entries = contents+ .split('\n')+ .filter((line) => line.startsWith('http:'))+ if (entries.length !== 1) throw new Error('DSM http group is unavailable')+ const fields = entries[0].split(':')+ const gid = Number(fields[2])+ if (+ fields.length !== 4 ||+ !/^[1-9]\d*$/.test(fields[2]) ||+ !Number.isSafeInteger(gid) ||+ gid >= 0xffffffff ||+ !groups.includes(gid)+ )+ throw new Error('DSM http group is not assigned to the package account')+ return gid+}++export async function dsmGatewayGroupId() {+ const info = await stat('/etc/group')+ if (!info.isFile() || info.uid !== 0 || (info.mode & 0o022) !== 0)+ throw new Error('Untrusted DSM group database')+ return dsmGatewayGroup(+ await readFile('/etc/group', 'utf8'),+ process.getgroups?.() ?? []+ )+}++export async function listenSynology(app: FastifyInstance, socketPath: string) {+ await listenNas(app, socketPath, await dsmGatewayGroupId())+}diff --git a/src/server/platform/synology/settings.ts b/src/server/platform/synology/settings.tsnew file mode 100644index 00000000..a3bef639--- /dev/null+++ b/src/server/platform/synology/settings.ts@@ -0,0 +1,128 @@+import path from 'node:path'+import { Commands } from '@shared/protocol/commands'+import { Queries } from '@shared/protocol/queries'+import {+ type NasPackageSettings,+ type NasSettingsResult,+ saveNasSettingsSchema,+} from '@shared/schemas/nas-settings'+import { parseRemoteExtensionConfig } from '../../bridge/remote-extension-config'+import {+ resolveNasAdministrator,+ sameNasAccount,+} from '../nas/client-authorization'+import { currentNasUser } from '../nas/identity'+import { NasSettingsStore } from '../nas/settings-store'+import type { SynologyAccounts } from './accounts'+import {+ dsmDirectoryConfig,+ inspectDsmRoots,+ readDsmDirectoryGrants,+} from './files'++function validConnections(value: NasPackageSettings): boolean {+ if (!value.operatorUrl && !value.extensionUrl) return true+ try {+ const url = new URL(value.operatorUrl)+ if (+ !['http:', 'https:'].includes(url.protocol) ||+ url.username ||+ url.password ||+ url.search ||+ url.hash ||+ url.pathname.replace(/\/$/, '') !== '/motrix'+ )+ return false+ } catch {+ return false+ }+ return (+ parseRemoteExtensionConfig(+ {+ MOTRIX_REMOTE_EXTENSION_ENABLED: value.extensionUrl ? 'true' : 'false',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: value.extensionUrl,+ MOTRIX_PUBLIC_URL: value.operatorUrl,+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: String(value.allowHttp),+ },+ { requireWebOperator: true }+ ).status !== 'invalid'+ )+}++export async function synologySettingsHandlers(+ directory: string,+ accounts: SynologyAccounts+) {+ const store = new NasSettingsStore(directory, 'synology')+ const active = await readDsmDirectoryGrants(+ path.join(directory, 'directories.json'),+ true+ )+ await store.view()+ const denied = (): NasSettingsResult => ({+ ok: false,+ error: { code: 'permissionDenied' },+ })+ const identity = async () => {+ const user = currentNasUser()+ if (user?.platform !== 'synology')+ throw new Error('DSM administrator required')+ return resolveNasAdministrator(accounts, user)+ }+ return {+ unavailableRoots: active.unavailable,+ queryHandlers: {+ [Queries.GetNasSettings]: async (): Promise<NasSettingsResult> => {+ try {+ await identity()+ return { ok: true, value: await store.view() }+ } catch {+ return denied()+ }+ },+ },+ commandHandlers: {+ [Commands.SaveNasSettings]: async (+ raw: unknown+ ): Promise<NasSettingsResult> => {+ const request = saveNasSettingsSchema.safeParse(raw)+ if (+ !request.success ||+ !validConnections(request.data.settings) ||+ !dsmDirectoryConfig.safeParse({ roots: request.data.settings.roots })+ .success+ )+ return { ok: false, error: { code: 'invalid' } }+ try {+ const user = await identity()+ return store.save(raw, async (settings, signal) => {+ const before = await inspectDsmRoots(settings.roots)+ if (!before.every((id): id is string => id !== null))+ return 'folderUnavailable'+ for (const root of settings.roots) {+ signal.throwIfAborted()+ const info = await accounts.inspectFile(user, root, signal)+ const acl = info?.additional.perm.acl+ if (+ !info?.isdir ||+ !acl?.read ||+ !acl.write ||+ !acl.append ||+ !acl.exec+ )+ return false+ }+ const current = await accounts.resolve(user, signal)+ if (current === null || !sameNasAccount(user, current)) return false+ const after = await inspectDsmRoots(settings.roots)+ if (!after.every((id, index) => id === before[index]))+ return 'folderUnavailable'+ return { directoryIdentities: before }+ })+ } catch {+ return denied()+ }+ },+ },+ }+}diff --git a/src/server/platform/synology/task-files.test.ts b/src/server/platform/synology/task-files.test.tsnew file mode 100644index 00000000..d9f089ab--- /dev/null+++ b/src/server/platform/synology/task-files.test.ts@@ -0,0 +1,134 @@+import {+ lstat,+ mkdir,+ mkdtemp,+ realpath,+ rename,+ rm,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { readArtifactIdentity } from '@core/plugin/finalize/artifact-identity'+import { TaskStatus } from '@shared/types/task'+import { makeDownloadTask } from '@test-utils/task'+import Database from 'better-sqlite3'+import { afterEach, beforeEach, expect, it } from 'vitest'+import { createServerDownloadPathPolicy } from '../../download-path-policy'+import { SynologyTaskFiles } from './task-files'++let database: Database.Database+let root: string+let guard: SynologyTaskFiles+let task: ReturnType<typeof makeDownloadTask>+beforeEach(async () => {+ root = await realpath(+ await mkdtemp(path.join(tmpdir(), 'motrix-dsm-claims-'))+ )+ database = new Database(':memory:')+ database.exec(`CREATE TABLE tasks(motrix_id TEXT PRIMARY KEY);+ CREATE TABLE plugin_finalize_journals(plan_id TEXT, task_id TEXT, phase TEXT,+ plan_json TEXT,target_identity_json TEXT)`)+ guard = new SynologyTaskFiles(+ { database, getAllTasks: () => [] },+ await createServerDownloadPathPolicy({+ defaultSaveDir: root,+ allowedSaveDirs: [root],+ initialize: false,+ })+ )+ await guard.initialize()+ const target = path.join(root, 'output')+ task = makeDownloadTask({+ saveDir: root,+ finalPath: target,+ diskPath: target,+ status: TaskStatus.Completed,+ })+ await guard.create(task, () => {+ database.prepare('INSERT INTO tasks VALUES(?)').run(task.id)+ })+})+afterEach(async () => {+ database.close()+ await rm(root, { recursive: true, force: true })+})++it('requires the historical publisher, matching bytes and the physical save directory', async () => {+ await writeFile(task.finalPath, 'original')+ await expect(guard.outputIdentity(task, task.finalPath)).rejects.toThrow(+ /No verified identity/+ )+ const original = await readArtifactIdentity(task.finalPath)+ database+ .prepare('INSERT INTO plugin_finalize_journals VALUES(?,?,?,?,?)')+ .run(+ 'old-plan',+ task.id,+ 'cleaned',+ JSON.stringify({ plan: { targetPath: task.finalPath } }),+ JSON.stringify(original)+ )+ await expect(guard.outputIdentity(task, task.finalPath)).resolves.toBe(+ original.platformFileId+ )+ const other = { ...task, id: 'other' }+ await guard.create(other, () => {+ database.prepare('INSERT INTO tasks VALUES(?)').run(other.id)+ })+ await expect(guard.checkRemoval(other, task.finalPath)).rejects.toThrow(+ /No verified identity/+ )+ await writeFile(task.finalPath, 'modified')+ await expect(guard.checkRemoval(task, task.finalPath)).rejects.toThrow(+ /changed/+ )+ await writeFile(task.finalPath, 'original')+ const parked = `${root}-parked`+ await rename(root, parked)+ try {+ await mkdir(root)+ await expect(guard.checkDirectory(task)).rejects.toThrow(/changed/)+ } finally {+ await rm(root, { recursive: true, force: true })+ await rename(parked, root)+ }+ await expect(+ guard.checkRemoval(task, task.finalPath)+ ).resolves.toBeUndefined()+})++it('refuses unrelated files during recursive deletion and changes during torrent verification', async () => {+ await mkdir(task.finalPath)+ const member = path.join(task.finalPath, 'member')+ await writeFile(member, 'content')+ const before = await guard.prepareStorageBinding(task, 'locate', [member])+ await rename(member, `${member}.parked`)+ await writeFile(member, 'another')+ await expect(before.bindVerified()).rejects.toThrow(/changed/)+ await rm(member)+ await rename(`${member}.parked`, member)+ await (+ await guard.prepareStorageBinding(task, 'locate', [member])+ ).bindVerified()+ await expect(+ guard.checkRemoval(task, task.finalPath)+ ).resolves.toBeUndefined()+ const unknown = path.join(task.finalPath, 'unrelated')+ await writeFile(unknown, 'preserve')+ await expect(guard.checkRemoval(task, task.finalPath)).rejects.toThrow(+ /Untracked/+ )+ await expect(guard.checkRemoval(task, unknown)).rejects.toThrow(/changed/)+ expect((await lstat(unknown)).isFile()).toBe(true)+})++it('rejects an unproven partial file without adopting it during deletion', async () => {+ task.status = TaskStatus.Paused+ await writeFile(task.diskPath, 'not owned')+ await expect(guard.checkRemoval(task, task.diskPath)).rejects.toThrow(+ /changed/+ )+ await rm(task.diskPath)+ await expect(guard.checkRemoval(task, task.diskPath)).resolves.toBeUndefined()+})diff --git a/src/server/platform/synology/task-files.ts b/src/server/platform/synology/task-files.tsnew file mode 100644index 00000000..73e759de--- /dev/null+++ b/src/server/platform/synology/task-files.ts@@ -0,0 +1,401 @@+import { lstat, readdir, realpath } from 'node:fs/promises'+import path from 'node:path'+import {+ type ArtifactIdentity,+ ArtifactIdentityCache,+ artifactIdentityEquals,+ readArtifactIdentity,+} from '@core/plugin/finalize/artifact-identity'+import type { MotrixDatabase } from '@core/session/motrix-database'+import { verifyBtFiles } from '@core/task/bt-file-verifier'+import {+ getBtDirectStorageLayout,+ parseBtFileLayout,+} from '@core/task/bt-storage-layout'+import { isTempPath } from '@core/task/paths'+import { restoreTaskSaveDirectory } from '@core/task/task-save-directory'+import { type DownloadTask, TaskStatus, TaskType } from '@shared/types/task'+import type { ServerDownloadPathPolicy } from '../../download-path-policy'++const fileStamp = (info: {+ dev: bigint+ ino: bigint+ birthtimeNs: bigint+ size: bigint+ mtimeNs: bigint+ isDirectory(): boolean+}) =>+ info.isDirectory()+ ? `${fileId(info)}:${info.birthtimeNs}`+ : `${fileId(info)}:${info.birthtimeNs}:${info.size}:${info.mtimeNs}`+const fileId = (info: { dev: bigint; ino: bigint }) => `${info.dev}:${info.ino}`+type PathClaim = {+ identity: string+ stamp: string+ tree: string | null+ journal: string | null+}+type Published = { journal: string; artifact: string | null }+type Tree = Record<string, string>++async function existing(file: string) {+ return lstat(file, { bigint: true }).catch((error: NodeJS.ErrnoException) => {+ if (error.code === 'ENOENT') return null+ throw error+ })+}++function inside(root: string, candidate: string) {+ const relative = path.relative(root, candidate)+ return relative &&+ relative !== '..' &&+ !relative.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relative)+ ? relative+ : null+}++// Only inspect the torrent's own paths. A neighbour can add unrelated files+// to a shared directory at any time.+async function snapshotMembers(root: string, paths: readonly string[]) {+ const entries: Tree = Object.create(null)+ const names = new Set<string>()+ for (const candidate of paths) {+ let relative = inside(root, candidate)+ while (relative && relative !== '.') {+ names.add(relative)+ relative = path.dirname(relative)+ }+ }+ for (const name of [...names].sort()) {+ const file = path.join(root, name)+ const info = await existing(file)+ if (!info) continue+ if (+ (!info.isFile() && !info.isDirectory()) ||+ (await realpath(file)) !== file+ )+ throw Error('Unsafe entry in task directory')+ entries[name] = fileStamp(info)+ }+ return entries+}++async function verifyMembers(root: string, allowed: Tree, relative = '') {+ for (const name of await readdir(path.join(root, relative))) {+ const child = path.join(relative, name)+ if (!Object.hasOwn(allowed, child))+ throw Error('Untracked file in task directory')+ const file = path.join(root, child)+ const info = await lstat(file, { bigint: true })+ if (+ (!info.isFile() && !info.isDirectory()) ||+ fileStamp(info) !== allowed[child] ||+ (await realpath(file)) !== file+ )+ throw Error('Task directory contains a different file')+ if (info.isDirectory()) await verifyMembers(root, allowed, child)+ }+}++/** Path grants cover the share. These private claims tie a task to the+ * directory it was admitted into and to the artifact actually published. */+export class SynologyTaskFiles {+ private readonly digests = new ArtifactIdentityCache()+ constructor(+ private readonly db: Pick<MotrixDatabase, 'database' | 'getAllTasks'>,+ private readonly policy: ServerDownloadPathPolicy+ ) {}++ async initialize() {+ const sql = this.db.database+ if (+ sql+ .prepare(+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='synology_task_paths'"+ )+ .get()+ )+ return+ // An old task has no historical directory identity. Bind only available,+ // authorized locations once. Never adopt a file during read or deletion.+ const legacy: [string, string, string][] = []+ const directories = new Map<string, string | null>()+ for (const { task, instances } of this.db.getAllTasks()) {+ const dir = restoreTaskSaveDirectory(task, instances)+ if (!directories.has(dir))+ directories.set(dir, await this.directoryId(dir).catch(() => null))+ const id = directories.get(dir)+ if (id) legacy.push([task.motrixId, dir, id])+ }+ sql.transaction(() => {+ sql.exec(`CREATE TABLE synology_task_paths (+ task_id TEXT NOT NULL REFERENCES tasks(motrix_id) ON DELETE CASCADE,+ role TEXT NOT NULL CHECK(role IN ('directory','output')),+ path TEXT NOT NULL, identity TEXT NOT NULL, stamp TEXT, tree TEXT, journal TEXT,+ PRIMARY KEY(task_id,role,path))`)+ const insert = sql.prepare(+ "INSERT INTO synology_task_paths(task_id,role,path,identity) VALUES (?,'directory',?,?)"+ )+ for (const row of legacy) insert.run(...row)+ })()+ }++ private async directoryId(directory: string) {+ if (+ !path.isAbsolute(directory) ||+ (await this.policy.authorizeDirectory(directory)).canonicalPath !==+ directory+ )+ throw Error('Untrusted task directory')+ const info = await lstat(directory, { bigint: true })+ if (!info.isDirectory() || (await realpath(directory)) !== directory)+ throw Error('Task directory changed')+ return fileStamp(info)+ }++ private row(id: string, role: 'directory' | 'output', candidate: string) {+ return this.db.database+ .prepare(+ 'SELECT identity,stamp,tree,journal FROM synology_task_paths WHERE task_id=? AND role=? AND path=?'+ )+ .get(id, role, candidate) as PathClaim | undefined+ }++ async create(task: DownloadTask, persist: () => void | Promise<void>) {+ const id = await this.directoryId(task.saveDir)+ await persist()+ this.db.database+ .prepare(+ "INSERT INTO synology_task_paths(task_id,role,path,identity) VALUES (?,'directory',?,?) ON CONFLICT DO NOTHING"+ )+ .run(task.id, task.saveDir, id)+ await this.checkDirectory(task)+ }++ async checkDirectory(task: DownloadTask) {+ const claim = this.row(task.id, 'directory', task.saveDir)+ if (!claim || (await this.directoryId(task.saveDir)) !== claim.identity)+ throw Error('Task download directory changed')+ }++ private published(id: string, candidate: string) {+ return this.db.database+ .prepare(`SELECT plan_id AS journal,target_identity_json AS artifact+ FROM plugin_finalize_journals WHERE task_id=? AND phase IN ('db_committed','cleaned')+ AND json_extract(plan_json,'$.plan.targetPath')=?`)+ .get(id, candidate) as Published | undefined+ }++ private async capture(task: DownloadTask, members: readonly string[]) {+ const target = task.finalPath || task.diskPath+ const info = await lstat(target, { bigint: true })+ if (+ (!info.isFile() && !info.isDirectory()) ||+ (await realpath(target)) !== target+ )+ throw Error('Invalid task output')+ // Certify only tracked torrent members and their ancestors. A file added+ // by another share user must never become part of a recursive removal.+ const tree = info.isDirectory()+ ? await snapshotMembers(target, members)+ : null+ return { target, identity: fileId(info), stamp: fileStamp(info), tree }+ }++ private writeOutput(+ task: DownloadTask,+ proof: Awaited<ReturnType<SynologyTaskFiles['capture']>>+ ) {+ const journal = this.published(task.id, proof.target)?.journal ?? null+ this.db.database+ .prepare(`INSERT INTO synology_task_paths VALUES (?,'output',?,?,?,?,?)+ ON CONFLICT(task_id,role,path) DO UPDATE SET identity=excluded.identity,stamp=excluded.stamp,tree=excluded.tree,journal=excluded.journal`)+ .run(+ task.id,+ proof.target,+ proof.identity,+ proof.stamp,+ proof.tree ? JSON.stringify(proof.tree) : null,+ journal+ )+ }++ async recordOutput(task: DownloadTask, metadata: Uint8Array) {+ await this.checkDirectory(task)+ const layout = await parseBtFileLayout(metadata)+ if (task.infoHash && layout.infoHash !== task.infoHash.toLowerCase())+ throw Error('Torrent identity changed')+ const target = task.finalPath || task.diskPath+ const selected = task.bt?.selectedFiles+ const members = layout.files+ .filter((f) => !selected?.length || selected.includes(f.fileIndex))+ .map((f) =>+ f.pathInsideRoot ? path.join(target, f.pathInsideRoot) : target+ )+ const before = await this.capture(task, members)+ const old = this.row(task.id, 'output', target)+ if (old && old.identity !== before.identity)+ throw Error('Task output changed')+ const result = await verifyBtFiles({+ metadata,+ payloadPath: target,+ selectedFiles: selected,+ })+ // Partial torrents may no longer have boundary pieces from unselected files.+ // Keep the download; only verifiable payloads can acquire a destructive claim.+ if (!result.complete) return+ const after = await this.capture(task, members)+ await this.checkDirectory(task)+ if (!this.sameOutput(before, after))+ throw Error('Task output changed during verification')+ this.writeOutput(task, after)+ }++ private sameOutput(+ first: Awaited<ReturnType<SynologyTaskFiles['capture']>>,+ second: Awaited<ReturnType<SynologyTaskFiles['capture']>>+ ) {+ return (+ first.identity === second.identity &&+ first.stamp === second.stamp &&+ JSON.stringify(first.tree) === JSON.stringify(second.tree)+ )+ }++ async outputIdentity(+ task: DownloadTask,+ candidate: string,+ selected = candidate+ ) {+ await this.checkDirectory(task)+ const journal = this.published(task.id, candidate),+ record = this.row(task.id, 'output', candidate)+ // A verified locate supersedes an older journal for this task and path.+ if (record && record.journal === (journal?.journal ?? null)) {+ const info = await existing(selected)+ if (info && fileStamp(info) !== record.stamp)+ throw Error('Task output changed')+ return record.identity+ }+ if (journal?.artifact) {+ const original = JSON.parse(journal.artifact) as ArtifactIdentity+ const info = await existing(selected)+ if (info) {+ if (fileId(info) !== original.platformFileId)+ throw Error('Task output changed')+ if (+ original.kind === 'file' &&+ (!info.isFile() ||+ !artifactIdentityEquals(+ original,+ await readArtifactIdentity(selected, { cache: this.digests })+ ))+ )+ throw Error('Task output changed')+ }+ return original.platformFileId+ }+ const root = task.finalPath || task.diskPath+ const relative = root && inside(root, candidate)+ if (relative) {+ const parent = this.row(task.id, 'output', root)+ if (parent?.tree) {+ const allowed: Tree = JSON.parse(parent.tree)+ if (Object.hasOwn(allowed, relative)) {+ const info = await existing(selected)+ if (!info || fileStamp(info) !== allowed[relative])+ throw Error('Task output changed')+ return fileId(info)+ }+ }+ }+ if (+ candidate === (task.finalPath || task.diskPath) &&+ (task.status === TaskStatus.Completed ||+ task.status === TaskStatus.Seeding)+ )+ throw Error('No verified identity for this task output')+ return undefined+ }++ async checkOutput(task: DownloadTask, candidate: string) {+ const expected = await this.outputIdentity(task, candidate)+ if (!expected) return+ const info = await existing(candidate)+ if (info && fileId(info) !== expected) throw Error('Task output changed')+ }++ async checkRemoval(task: DownloadTask, candidate: string) {+ await this.removalIdentity(task, candidate, candidate)+ if (+ candidate === task.diskPath &&+ (getBtDirectStorageLayout(task)?.multiFile === false ||+ ((task.type === TaskType.Http || task.type === TaskType.Ftp) &&+ isTempPath(candidate)))+ ) {+ const sidecar = `${candidate}.aria2`+ await this.removalIdentity(task, sidecar, sidecar)+ }+ }++ async removalIdentity(+ task: DownloadTask,+ candidate: string,+ selected: string+ ) {+ await this.checkDirectory(task)+ const info = await existing(selected)+ if (!info) return undefined+ const expected = await this.outputIdentity(task, candidate, selected)+ if (!expected || fileId(info) !== expected)+ throw Error('Task output changed')+ if (info.isDirectory()) {+ const recorded = this.row(task.id, 'output', candidate)+ if (!expected || !recorded?.tree || recorded.identity !== expected)+ throw Error('No verified task directory manifest')+ await verifyMembers(selected, JSON.parse(recorded.tree) as Tree)+ }+ return expected+ }++ /** Move publishes a new durable journal. Locate/recheck must bind the inode+ * that was verified, not whichever file is present afterwards. Other paths+ * keep their original claims if persistence fails or an operation is retried. */+ async prepareStorageBinding(+ task: DownloadTask,+ mode: 'locate' | 'recheck' | 'move',+ members: readonly string[]+ ) {+ const directory = await this.directoryId(task.saveDir)+ const before = mode === 'move' ? null : await this.capture(task, members)+ const bindVerified = async () => {+ if ((await this.directoryId(task.saveDir)) !== directory)+ throw Error('BT storage directory changed')+ const after = before && (await this.capture(task, members))+ if (before && after && !this.sameOutput(before, after))+ throw Error('BT output changed during verification')+ this.db.database.transaction(() => {+ this.db.database+ .prepare(`INSERT INTO synology_task_paths(task_id,role,path,identity) VALUES (?,'directory',?,?)+ ON CONFLICT(task_id,role,path) DO UPDATE SET identity=excluded.identity`)+ .run(task.id, task.saveDir, directory)+ if (after) this.writeOutput(task, after)+ })()+ }+ const bindMoved = async () => {+ const original = this.published(task.id, task.finalPath)?.artifact+ if (!original) throw Error('Missing committed BT storage journal')+ const proof = await this.capture(task, members)+ if (proof.tree) await verifyMembers(proof.target, proof.tree)+ const current = await readArtifactIdentity(proof.target, {+ cache: this.digests,+ })+ if (!artifactIdentityEquals(JSON.parse(original), current))+ throw Error('Moved task output changed')+ await this.checkDirectory(task)+ this.writeOutput(task, proof)+ }+ return { bindVerified, bindMoved }+ }+}diff --git a/src/server/platform/synology/validation.ts b/src/server/platform/synology/validation.tsnew file mode 100644index 00000000..4ef63c87--- /dev/null+++ b/src/server/platform/synology/validation.ts@@ -0,0 +1,23 @@+import { isIP } from 'node:net'+import { z } from 'zod'++export const dsmText = (max: number) =>+ z+ .string()+ .max(max)+ .regex(/^\P{Cc}*$/u)+export const dsmUsername = dsmText(128)+ .min(1)+ .regex(/^(?!-)(?!.*[\s:[\]\\/]).+$/u)+export const validDsmUsername = (name: string): boolean =>+ dsmUsername.safeParse(name).success+export const dsmContextSchema = z.object({+ cookie: dsmText(8192).min(1),+ remoteAddress: z.string().refine((s) => isIP(s) !== 0),+ serverAddress: z.string().refine((s) => isIP(s) !== 0),+ serverPort: z.coerce.number().int().min(1).max(65535),+ scheme: z.enum(['http', 'https']),+ host: dsmText(512).optional(),+ userAgent: dsmText(2048).optional(),+})+export type DsmContext = z.infer<typeof dsmContextSchema>diff --git a/src/server/server-directory-service.ts b/src/server/server-directory-service.tsindex e1831191..9153c132 100644--- a/src/server/server-directory-service.ts+++ b/src/server/server-directory-service.ts@@ -102,7 +102,8 @@ export class ServerDirectoryService {constructor(private readonly policy: ServerDownloadPathPolicy,private readonly fs: typeof filesystem = filesystem,- private readonly homeDirectory: () => string = homedir+ private readonly homeDirectory: () => string = homedir,+ private readonly authorizeFile?: (path: string) => Promise<unknown>) {}async resolvePreferenceDirectory(value: string): Promise<string> {@@ -212,6 +213,7 @@ export class ServerDirectoryService {const logicalPath = path.join(parent.path, path.basename(value))const canonical = await realpath(logicalPath)await this.policy.authorizeDirectory(path.dirname(canonical))+ await this.authorizeFile?.(canonical)const info = await stat(canonical)if (!info.isFile())throw new DirectoryAuthorizationError('notFile', 'Not a regular file')diff --git a/src/server/shutdown.test.ts b/src/server/shutdown.test.tsindex 02ba8c06..a52bc3aa 100644--- a/src/server/shutdown.test.ts+++ b/src/server/shutdown.test.ts@@ -380,8 +380,16 @@ describe('server lifecycle production wiring', () => {'const discoveredTask: DownloadTask =',handler)- const parentBarrier = source.indexOf(+ const createParent = source.indexOf('const createParent =')+ const activityBarrier = source.indexOf('taskInspectorActivityRuntime.parentTaskCreated(',+ createParent+ )+ expect(createParent).toBeGreaterThan(-1)+ expect(activityBarrier).toBeGreaterThan(createParent)+ expect(activityBarrier).toBeLessThan(handler)+ const parentBarrier = source.indexOf(+ 'await createParent(discoveredTask',discoveredTask)const persistParent = source.indexOf(@@ -435,6 +443,11 @@ describe('server lifecycle production wiring', () => {)const shutdown = source.indexOf('const shutdown = createServerShutdown(')const signalOwner = source.indexOf('requestActiveServerExit = requestExit')+ const recovery = source.indexOf('const recoveryApp = await createApp(')+ const recoveryClose = source.indexOf(+ 'shutdownActions.closeIngress = () => recoveryApp.close()'+ )+ const recoveryListen = source.indexOf('await listenSynology(recoveryApp,')const database = source.indexOf('db.init()')const app = source.indexOf('const app = await createApp(')const producers = source.indexOf("runShellAsyncWork('tracker manager init'")@@ -442,7 +455,10 @@ describe('server lifecycle production wiring', () => {expect(shutdown).toBeGreaterThan(-1)expect(signalOwner).toBeGreaterThan(shutdown)- expect(database).toBeGreaterThan(signalOwner)+ expect(recovery).toBeGreaterThan(signalOwner)+ expect(recoveryClose).toBeGreaterThan(recovery)+ expect(recoveryListen).toBeGreaterThan(recoveryClose)+ expect(database).toBeGreaterThan(recoveryListen)expect(app).toBeGreaterThan(database)expect(producers).toBeGreaterThan(shutdown)expect(listen).toBeGreaterThan(producers)diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 16c0e2e0..6c2afa58 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -405,7 +405,8 @@"placeholder": "رمز المشغّل","submit": "فتح القفل","title": "فتح قفل Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "تعذر التحقق من جلسة مسؤول NAS. افتح Motrix من سطح مكتب NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -435,7 +436,7 @@"more": "أكثر","rangeSummary": "نشاط التنزيل من {{start}} إلى {{end}}؛ عدد الأسابيع: {{weeks}}","retry": "إعادة المحاولة",- "stale": "قد تكون بيانات النشاط قديمة",+ "refreshFailed": "تعذّر التحديث","title": "النشاط","tooltip": {"completed": "المكتمل: {{count}}",@@ -918,7 +919,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "إعادة محاولة التنزيل","retryDialogDescription": "عدّل معلمات طلب {{name}} لبدء تنزيل جديد. ستُحفظ المهمة الفاشلة وملفها الجزئي.",- "retryDialogProgress": "التنزيل {{current}} من {{total}}"+ "retryDialogProgress": "التنزيل {{current}} من {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "الاتصالات",@@ -2118,6 +2123,10 @@"network": {"desc": "الوكيل وDNS وNAT/UPnP","title": "الشبكة"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2490,6 +2499,8 @@"connected": "متصل","disconnected": "غير متصل","revokeAll": "قطع اتصال الكل",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "الامتدادات المتصلة","pairingStateDegraded": {"description": "تعذّر على Motrix تحديث سجلات الامتدادات المقترنة بأمان. أُغلقت جلسات الامتدادات الحالية وحُظر الوصول الجديد خلال هذا التشغيل. أعد تشغيل Motrix لإعادة محاولة الإصلاح؛ لا تعتمد على القائمة أدناه حتى تختفي هذه الرسالة.",@@ -2849,6 +2860,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2967,7 +3009,8 @@"urlsLabel": "عناوين URL","urlsWithInvalid": "الصالح: {{valid}}، غير الصالح: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "الصالح: {{count}}"+ "validUrlCount": "الصالح: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "الأقران: {{count}}",diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 6acae19f..5735425c 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -401,7 +401,8 @@"placeholder": "Операторски токен","submit": "Отключване","title": "Отключване на Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Сесията на администратора на NAS не може да бъде проверена. Отворете Motrix от работния плот на NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -431,7 +432,7 @@"more": "Повече","rangeSummary": "{{weeks}} седмици активност по изтеглянията, от {{start}} до {{end}}","retry": "Повторен опит",- "stale": "Данните за активността може да не са актуални",+ "refreshFailed": "Неуспешно опресняване","title": "Активност","tooltip": {"completed": "Завършени: {{count}}",@@ -906,7 +907,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Повторен опит за изтегляне","retryDialogDescription": "Редактирайте параметрите на заявката за {{name}}, за да започнете ново изтегляне. Неуспешната задача и частичният ѝ файл ще бъдат запазени.",- "retryDialogProgress": "Изтегляне {{current}} от {{total}}"+ "retryDialogProgress": "Изтегляне {{current}} от {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Връзки",@@ -2042,6 +2047,10 @@"network": {"desc": "Прокси, DNS и NAT/UPnP","title": "Мрежа"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2414,6 +2423,8 @@"connected": "Свързан","disconnected": "Няма връзка","revokeAll": "Прекъсване на всички",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Свързани разширения","pairingStateDegraded": {"description": "Motrix не успя безопасно да обнови записите за сдвоени разширения. Съществуващите сесии на разширенията са затворени, а новият достъп е блокиран за това стартиране. Рестартирайте Motrix, за да опитате поправката отново; не разчитайте на списъка по-долу, докато това съобщение не изчезне.",@@ -2769,6 +2780,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2883,7 +2925,8 @@"urlsLabel": "URL адреси","urlsWithInvalid": "Валидни: {{valid}}, невалидни: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Валидни: {{count}}"+ "validUrlCount": "Валидни: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Участници: {{count}}",diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex c9b85137..e4cc4005 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -402,7 +402,8 @@"placeholder": "Testimoni d'operador","submit": "Desbloquejar","title": "Desbloquejar el Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "No es pot verificar la sessió d’administrador del NAS. Obriu Motrix des de l’escriptori del NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -432,7 +433,7 @@"more": "Més","rangeSummary": "{{weeks}} setmanes d'activitat de baixades, del {{start}} al {{end}}","retry": "Tornar-ho a provar",- "stale": "L'activitat podria estar desactualitzada",+ "refreshFailed": "No s’ha pogut actualitzar","title": "Activitat","tooltip": {"completed": "Completades: {{count}}",@@ -909,7 +910,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Torna a provar la baixada","retryDialogDescription": "Edita els paràmetres de la sol·licitud de {{name}} per iniciar una baixada nova. Es conservaran la tasca fallida i el fitxer parcial.",- "retryDialogProgress": "Baixada {{current}} de {{total}}"+ "retryDialogProgress": "Baixada {{current}} de {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Connexions",@@ -2061,6 +2066,10 @@"network": {"desc": "Servidor intermediari, DNS i NAT/UPnP","title": "Xarxa"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2433,6 +2442,8 @@"connected": "Connectat","disconnected": "No connectat","revokeAll": "Desconnecta’ls tots",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Extensions connectades","pairingStateDegraded": {"description": "El Motrix no ha pogut actualitzar de manera segura els registres d'extensions aparellades. S'han tancat les sessions d'extensions existents i s'ha bloquejat l'accés nou durant aquesta execució. Reinicieu el Motrix per tornar a provar la reparació; no us refieu de la llista següent fins que desaparegui aquest missatge.",@@ -2789,6 +2800,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2904,7 +2946,8 @@"urlsLabel": "URL","urlsWithInvalid": "Vàlids: {{valid}}, no vàlids: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Vàlids: {{count}}"+ "validUrlCount": "Vàlids: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Parells: {{count}}",diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex 6714a855..f24f329f 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -5,7 +5,8 @@"placeholder": "Betreiber-Token","error": "Ungültiges Betreiber-Token. Prüfen Sie MOTRIX_OPERATOR_TOKEN oder <dataDir>/operator-token auf dem Host und versuchen Sie es erneut.","submit": "Entsperren",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Die NAS-Administratorsitzung konnte nicht bestätigt werden. Öffne Motrix über den NAS-Desktop.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Verwendung:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nDer Befehl kommuniziert ausschließlich über die Loopback-Schnittstelle des Containers mit dem laufenden Motrix-Server.",@@ -332,7 +333,7 @@"loading": "Aktivität wird geladen","unavailable": "Aktivität nicht verfügbar","retry": "Erneut versuchen",- "stale": "Die Aktivitätsdaten sind möglicherweise veraltet",+ "refreshFailed": "Aktualisierung fehlgeschlagen","coverageDegraded": "Die Aktivitätsdaten sind seit {{time}} möglicherweise unvollständig","rangeSummary": "Download-Aktivität über {{weeks}} Wochen, von {{start}} bis {{end}}","completedIntensity": "Die Farbintensität zeigt die Anzahl abgeschlossener Downloads",@@ -945,7 +946,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Download erneut versuchen","retryDialogDescription": "Bearbeite die Anfrageparameter für {{name}}, um einen neuen Download zu starten. Der fehlgeschlagene Auftrag und seine Teildatei bleiben erhalten.",- "retryDialogProgress": "Download {{current}} von {{total}}"+ "retryDialogProgress": "Download {{current}} von {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}} angezeigt · {{total}} insgesamt","type": {@@ -1135,7 +1140,8 @@"failed": "{{name}} konnte nicht automatisch gestartet werden. Öffnen Sie die Aufgabendetails, um Dateien auszuwählen, und versuchen Sie es erneut."},"undoCorrection": "URL-Korrektur rückgängig machen",- "submissionUnconfirmed": "Das Ergebnis ist nicht bestätigt. Ein erneuter Versuch prüft die ursprüngliche Anfrage, bevor eine weitere Aufgabe erstellt wird."+ "submissionUnconfirmed": "Das Ergebnis ist nicht bestätigt. Ein erneuter Versuch prüft die ursprüngliche Anfrage, bevor eine weitere Aufgabe erstellt wird.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Peers: {{count}}",@@ -1291,6 +1297,10 @@"integration": {"title": "Integration","desc": "Browsererweiterungen, CLI, Systemintegration"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1939,6 +1949,8 @@"store": "Installieren","development": "Entwicklung"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Verbundene Erweiterungen","pairedEmpty": "Noch keine Erweiterungen verbunden.","profile": "Browserprofil {{number}}",@@ -2266,6 +2278,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex addeeb98..2763b244 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -401,7 +401,8 @@"placeholder": "Διακριτικό χειριστή","submit": "Ξεκλείδωμα","title": "Ξεκλείδωμα του Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Δεν ήταν δυνατή η επαλήθευση της συνεδρίας διαχειριστή NAS. Ανοίξτε το Motrix από την επιφάνεια εργασίας του NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -431,7 +432,7 @@"more": "Περισσότερες","rangeSummary": "{{weeks}} εβδομάδες δραστηριότητας λήψεων, από {{start}} έως {{end}}","retry": "Επανάληψη",- "stale": "Η δραστηριότητα ενδέχεται να μην είναι ενημερωμένη",+ "refreshFailed": "Η ανανέωση απέτυχε","title": "Δραστηριότητα","tooltip": {"completed": "Ολοκληρωμένες: {{count}}",@@ -906,7 +907,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Επανάληψη λήψης","retryDialogDescription": "Επεξεργαστείτε τις παραμέτρους αιτήματος για το {{name}} για να ξεκινήσετε νέα λήψη. Η αποτυχημένη εργασία και το μερικό αρχείο της θα διατηρηθούν.",- "retryDialogProgress": "Λήψη {{current}} από {{total}}"+ "retryDialogProgress": "Λήψη {{current}} από {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Συνδέσεις",@@ -2042,6 +2047,10 @@"network": {"desc": "Διακομιστής μεσολάβησης, DNS και NAT/UPnP","title": "Δίκτυο"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2414,6 +2423,8 @@"connected": "Συνδεδεμένο","disconnected": "Μη συνδεδεμένο","revokeAll": "Αποσύνδεση όλων",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Συνδεδεμένες επεκτάσεις","pairingStateDegraded": {"description": "Το Motrix δεν μπόρεσε να ενημερώσει με ασφάλεια τις εγγραφές συζευγμένων επεκτάσεων. Οι υπάρχουσες συνεδρίες επεκτάσεων έχουν κλείσει και η νέα πρόσβαση έχει αποκλειστεί για αυτή την εκτέλεση. Επανεκκινήστε το Motrix για νέα προσπάθεια επιδιόρθωσης· μη βασίζεστε στην παρακάτω λίστα μέχρι να εξαφανιστεί αυτό το μήνυμα.",@@ -2769,6 +2780,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2883,7 +2925,8 @@"urlsLabel": "URL","urlsWithInvalid": "Έγκυρα: {{valid}}, μη έγκυρα: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Έγκυρα: {{count}}"+ "validUrlCount": "Έγκυρα: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Ομότιμοι: {{count}}",diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex a0dd8065..48767f7d 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -5,7 +5,8 @@"placeholder": "Operator token","error": "Invalid operator token. Check MOTRIX_OPERATOR_TOKEN or <dataDir>/operator-token on the host and try again.","submit": "Unlock",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Unable to verify your NAS administrator session. Open Motrix from the NAS desktop.",+ "openDsm": "Open DSM to sign in"},"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 motrix-admin extension pair\n\nThe command talks only to the running Motrix server over container loopback.",@@ -332,7 +333,7 @@"loading": "Loading activity","unavailable": "Activity unavailable","retry": "Retry",- "stale": "Activity may be out of date",+ "refreshFailed": "Refresh failed","coverageDegraded": "Activity may be incomplete since {{time}}","rangeSummary": "{{weeks}} weeks of download activity, {{start}} to {{end}}","completedIntensity": "Color intensity shows completed downloads",@@ -945,7 +946,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Retry download","retryDialogDescription": "Edit the request parameters for {{name}} to start a new download. The failed task and its partial file will be kept.",- "retryDialogProgress": "Download {{current}} of {{total}}"+ "retryDialogProgress": "Download {{current}} of {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}} shown · {{total}} total","type": {@@ -1135,7 +1140,8 @@"failed": "Could not start {{name}} automatically. Open task details to select files and retry."},"undoCorrection": "Undo URL correction",- "submissionUnconfirmed": "The result is unconfirmed. Retry will check the original request before creating another task."+ "submissionUnconfirmed": "The result is unconfirmed. Retry will check the original request before creating another task.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Peers: {{count}}",@@ -1291,6 +1297,10 @@"integration": {"title": "Integration","desc": "Browser extensions, CLI, system integrations"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1939,6 +1949,8 @@"store": "Install","development": "Development"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Connected extensions","pairedEmpty": "No extensions connected yet.","profile": "Browser profile {{number}}",@@ -2266,6 +2278,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex 48ef5a68..5659c344 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -5,7 +5,8 @@"placeholder": "Token del operador","error": "El token del operador no es válido. Comprueba MOTRIX_OPERATOR_TOKEN o <dataDir>/operator-token en el host y vuelve a intentarlo.","submit": "Desbloquear",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "No se puede verificar la sesión de administrador del NAS. Abre Motrix desde el escritorio del NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Uso:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nEl comando solo se comunica con el servidor Motrix en ejecución a través de la interfaz de bucle local del contenedor.",@@ -333,7 +334,7 @@"loading": "Cargando actividad","unavailable": "Actividad no disponible","retry": "Reintentar",- "stale": "La actividad podría estar desactualizada",+ "refreshFailed": "No se pudo actualizar","coverageDegraded": "La actividad podría estar incompleta desde {{time}}","rangeSummary": "{{weeks}} semanas de actividad de descargas, de {{start}} a {{end}}","completedIntensity": "La intensidad del color indica las descargas completadas",@@ -957,7 +958,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Reintentar descarga","retryDialogDescription": "Edita los parámetros de la solicitud de {{name}} para iniciar una nueva descarga. Se conservarán la tarea fallida y su archivo parcial.",- "retryDialogProgress": "Descarga {{current}} de {{total}}"+ "retryDialogProgress": "Descarga {{current}} de {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "Mostradas: {{shown}} · total: {{total}}","type": {@@ -1148,7 +1153,8 @@},"undoCorrection": "Deshacer corrección de URL","submissionUnconfirmed": "El resultado no está confirmado. Al reintentar, se comprobará la solicitud original antes de crear otra tarea.",- "urlsCount_many": "{{count}} URL"+ "urlsCount_many": "{{count}} URL",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Pares: {{count}}",@@ -1305,6 +1311,10 @@"integration": {"title": "Integración","desc": "Extensiones del navegador, CLI e integración con el sistema"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1953,6 +1963,8 @@"store": "Instalar","development": "Desarrollo"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Extensiones conectadas","pairedEmpty": "Todavía no hay extensiones conectadas.","profile": "Perfil del navegador {{number}}",@@ -2281,6 +2293,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex 8ff061b2..45e1d248 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -401,7 +401,8 @@"placeholder": "توکن اپراتور","submit": "باز کردن قفل","title": "باز کردن قفل Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "تأیید نشست مدیر NAS ممکن نیست. Motrix را از دسکتاپ NAS باز کنید.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -431,7 +432,7 @@"more": "بیشتر","rangeSummary": "{{weeks}} هفته فعالیت دانلود، از {{start}} تا {{end}}","retry": "تلاش دوباره",- "stale": "ممکن است فعالیت بهروز نباشد",+ "refreshFailed": "تازهسازی ناموفق بود","title": "فعالیت","tooltip": {"completed": "{{count}} تکمیلشده",@@ -906,7 +907,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "تلاش دوباره برای دانلود","retryDialogDescription": "پارامترهای درخواست {{name}} را برای شروع دانلود جدید ویرایش کنید. کار ناموفق و فایل ناقص آن حفظ میشوند.",- "retryDialogProgress": "دانلود {{current}} از {{total}}"+ "retryDialogProgress": "دانلود {{current}} از {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "اتصالها",@@ -2042,6 +2047,10 @@"network": {"desc": "پروکسی، DNS و NAT/UPnP","title": "شبکه"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2414,6 +2423,8 @@"connected": "متصل","disconnected": "متصل نیست","revokeAll": "قطع اتصال همه",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "افزونههای متصل","pairingStateDegraded": {"description": "Motrix نتوانست سوابق افزونههای جفتشده را ایمن بهروز کند. نشستهای فعلی افزونهها بسته شدهاند و دسترسی جدید در این اجرای برنامه مسدود است. برای تلاش دوباره جهت ترمیم، Motrix را دوباره راهاندازی کنید؛ تا رفع این پیام به فهرست زیر اتکا نکنید.",@@ -2769,6 +2780,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2883,7 +2925,8 @@"urlsLabel": "نشانیها","urlsWithInvalid": "{{valid}} معتبر، {{invalid}} نامعتبر","userAgent": "User-Agent",- "validUrlCount": "{{count}} معتبر"+ "validUrlCount": "{{count}} معتبر",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "همتاها: {{count}}",diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex 8af3dd52..d1432d0e 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -402,7 +402,8 @@"placeholder": "Jeton d’administration","submit": "Déverrouiller","title": "Déverrouiller Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Impossible de vérifier votre session administrateur NAS. Ouvrez Motrix depuis le bureau du NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -432,7 +433,7 @@"more": "Plus","rangeSummary": "{{weeks}} semaines d’activité de téléchargement, du {{start}} au {{end}}","retry": "Réessayer",- "stale": "Les données d’activité peuvent être obsolètes",+ "refreshFailed": "Échec de l’actualisation","title": "Activité","tooltip": {"completed": "Terminés : {{count}}",@@ -909,7 +910,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Réessayer le téléchargement","retryDialogDescription": "Modifiez les paramètres de la requête pour {{name}} afin de lancer un nouveau téléchargement. La tâche en échec et son fichier partiel seront conservés.",- "retryDialogProgress": "Téléchargement {{current}} sur {{total}}"+ "retryDialogProgress": "Téléchargement {{current}} sur {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Connexions",@@ -2061,6 +2066,10 @@"network": {"desc": "Proxy, DNS et NAT/UPnP","title": "Réseau"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2433,6 +2442,8 @@"connected": "Connecté","disconnected": "Non connecté","revokeAll": "Tout déconnecter",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Extensions connectées","pairingStateDegraded": {"description": "Motrix n’a pas pu mettre à jour en toute sécurité les enregistrements des extensions associées. Les sessions existantes sont fermées et les nouveaux accès sont bloqués pour cette exécution. Redémarrez Motrix pour retenter la réparation ; ne vous fiez pas à la liste ci-dessous tant que ce message est présent.",@@ -2789,6 +2800,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2904,7 +2946,8 @@"urlsLabel": "URL","urlsWithInvalid": "Valides : {{valid}}, invalides : {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Valides : {{count}}"+ "validUrlCount": "Valides : {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Pairs : {{count}}",diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex 87e6b500..7879d0d1 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -5,7 +5,8 @@"placeholder": "Üzemeltetői token","error": "Érvénytelen üzemeltetői token. Ellenőrizd a MOTRIX_OPERATOR_TOKEN értékét vagy a <dataDir>/operator-token fájlt a szervert futtató gépen, majd próbáld újra.","submit": "Feloldás",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "A NAS rendszergazdai munkamenete nem ellenőrizhető. Nyissa meg a Motrixot a NAS asztaláról.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Használat:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nA parancs kizárólag a futó Motrix szerverrel kommunikál a konténer loopback kapcsolatán keresztül.",@@ -332,7 +333,7 @@"loading": "Aktivitási adatok betöltése","unavailable": "Az aktivitási adatok nem érhetők el","retry": "Újrapróbálás",- "stale": "Az aktivitási adatok elavultak lehetnek",+ "refreshFailed": "A frissítés sikertelen","coverageDegraded": "Az aktivitási adatok {{time}} óta hiányosak lehetnek","rangeSummary": "{{weeks}} hét letöltési aktivitása, {{start}} – {{end}}","completedIntensity": "A szín intenzitása a befejezett letöltések számát jelzi",@@ -945,7 +946,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Letöltés újrapróbálása","retryDialogDescription": "Új letöltés indításához módosítsa a(z) {{name}} kérési paramétereit. A sikertelen feladat és a részleges fájl megmarad.",- "retryDialogProgress": "{{current}}. letöltés, összesen {{total}}"+ "retryDialogProgress": "{{current}}. letöltés, összesen {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}} megjelenítve · összesen {{total}}","type": {@@ -1135,7 +1140,8 @@"failed": "A(z) {{name}} automatikus indítása sikertelen. Nyisd meg a feladat részleteit, válaszd ki a fájlokat, majd próbáld újra."},"undoCorrection": "URL-javítás visszavonása",- "submissionUnconfirmed": "Az eredmény nincs megerősítve. Újrapróbáláskor a rendszer ellenőrzi az eredeti kérést, mielőtt újabb feladatot hozna létre."+ "submissionUnconfirmed": "Az eredmény nincs megerősítve. Újrapróbáláskor a rendszer ellenőrzi az eredeti kérést, mielőtt újabb feladatot hozna létre.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Partnerek: {{count}}",@@ -1291,6 +1297,10 @@"integration": {"title": "Integráció","desc": "Böngészőbővítmények, CLI és rendszerintegrációk"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1939,6 +1949,8 @@"store": "Telepítés","development": "Fejlesztői"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Csatlakoztatott bővítmények","pairedEmpty": "Még nincs csatlakoztatott bővítmény.","profile": "Böngészőprofil {{number}}",@@ -2266,6 +2278,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex 8846e220..a211bcee 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -5,7 +5,8 @@"placeholder": "Token operator","error": "Token operator tidak valid. Periksa MOTRIX_OPERATOR_TOKEN atau <dataDir>/operator-token pada host dan coba lagi.","submit": "Buka akses",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Sesi administrator NAS tidak dapat diverifikasi. Buka Motrix dari desktop NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Penggunaan:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nPerintah ini hanya berkomunikasi dengan server Motrix yang berjalan melalui loopback kontainer.",@@ -331,7 +332,7 @@"loading": "Memuat aktivitas","unavailable": "Aktivitas tidak tersedia","retry": "Coba lagi",- "stale": "Aktivitas mungkin belum diperbarui",+ "refreshFailed": "Gagal memuat ulang","coverageDegraded": "Data aktivitas mungkin tidak lengkap sejak {{time}}","rangeSummary": "{{weeks}} minggu aktivitas unduhan, {{start}} hingga {{end}}","completedIntensity": "Intensitas warna menunjukkan unduhan selesai",@@ -933,7 +934,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Coba unduh lagi","retryDialogDescription": "Edit parameter permintaan untuk {{name}} guna memulai unduhan baru. Tugas yang gagal dan file parsialnya akan disimpan.",- "retryDialogProgress": "Unduhan {{current}} dari {{total}}"+ "retryDialogProgress": "Unduhan {{current}} dari {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}} ditampilkan · {{total}} total","type": {@@ -1122,7 +1127,8 @@"failed": "{{name}} tidak dapat dimulai secara otomatis. Buka detail tugas untuk memilih berkas dan mencoba lagi."},"undoCorrection": "Urungkan koreksi URL",- "submissionUnconfirmed": "Hasilnya belum terkonfirmasi. Saat dicoba lagi, permintaan awal akan diperiksa sebelum membuat tugas lain."+ "submissionUnconfirmed": "Hasilnya belum terkonfirmasi. Saat dicoba lagi, permintaan awal akan diperiksa sebelum membuat tugas lain.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Peer: {{count}}",@@ -1277,6 +1283,10 @@"integration": {"title": "Integrasi","desc": "Ekstensi browser, CLI, integrasi sistem"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1925,6 +1935,8 @@"store": "Pasang","development": "Pengembangan"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Ekstensi terhubung","pairedEmpty": "Belum ada ekstensi yang terhubung.","profile": "Profil browser {{number}}",@@ -2251,6 +2263,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex ac1f069e..3243efd6 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -5,7 +5,8 @@"placeholder": "Token operatore","error": "Token operatore non valido. Controlla MOTRIX_OPERATOR_TOKEN o <dataDir>/operator-token sull’host e riprova.","submit": "Sblocca",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Impossibile verificare la sessione di amministratore NAS. Apri Motrix dal desktop del NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Utilizzo:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nIl comando comunica esclusivamente con il server Motrix in esecuzione tramite l’interfaccia di loopback del container.",@@ -333,7 +334,7 @@"loading": "Caricamento delle attività","unavailable": "Dati sulle attività non disponibili","retry": "Riprova",- "stale": "I dati sulle attività potrebbero non essere aggiornati",+ "refreshFailed": "Aggiornamento non riuscito","coverageDegraded": "I dati sulle attività potrebbero essere incompleti da {{time}}","rangeSummary": "{{weeks}} settimane di attività di download, da {{start}} a {{end}}","completedIntensity": "L’intensità del colore indica i download completati",@@ -957,7 +958,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Riprova il download","retryDialogDescription": "Modifica i parametri della richiesta per {{name}} per avviare un nuovo download. L’attività non riuscita e il suo file parziale verranno conservati.",- "retryDialogProgress": "Download {{current}} di {{total}}"+ "retryDialogProgress": "Download {{current}} di {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "Visualizzati: {{shown}} · Totale: {{total}}","type": {@@ -1148,7 +1153,8 @@"failed": "Impossibile avviare {{name}} automaticamente. Apri i dettagli dell’attività per selezionare i file e riprovare."},"undoCorrection": "Annulla correzione URL",- "submissionUnconfirmed": "L’esito non è confermato. Un nuovo tentativo verificherà la richiesta originale prima di creare un’altra attività."+ "submissionUnconfirmed": "L’esito non è confermato. Un nuovo tentativo verificherà la richiesta originale prima di creare un’altra attività.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Peer: {{count}}",@@ -1305,6 +1311,10 @@"integration": {"title": "Integrazione","desc": "Estensioni del browser, CLI, integrazione con il sistema"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1953,6 +1963,8 @@"store": "Installa","development": "Sviluppo"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Estensioni collegate","pairedEmpty": "Nessuna estensione collegata.","profile": "Profilo del browser {{number}}",@@ -2281,6 +2293,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex 5d1b56ae..dfae6506 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -5,7 +5,8 @@"placeholder": "管理者トークン","error": "管理者トークンが無効です。ホスト上の MOTRIX_OPERATOR_TOKEN または <dataDir>/operator-token を確認して、もう一度お試しください。","submit": "ロックを解除",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "NAS 管理者セッションを確認できません。NAS デスクトップから Motrix を開いてください。",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "使い方:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nこのコマンドは、コンテナーのループバック経由で、実行中の Motrix サーバーとのみ通信します。",@@ -331,7 +332,7 @@"loading": "アクティビティを読み込み中","unavailable": "アクティビティを取得できません","retry": "再試行",- "stale": "アクティビティが古い可能性があります",+ "refreshFailed": "更新できませんでした","coverageDegraded": "{{time}} 以降のアクティビティに欠落がある可能性があります","rangeSummary": "{{start}} から {{end}} までの {{weeks}} 週間のダウンロードアクティビティ","completedIntensity": "色の濃さは完了したダウンロード数を表します",@@ -933,7 +934,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "ダウンロードを再試行","retryDialogDescription": "{{name}} のリクエストパラメーターを編集して、新しいダウンロードを開始します。失敗したタスクと未完了ファイルは保持されます。",- "retryDialogProgress": "{{total}} 件中 {{current}} 件目"+ "retryDialogProgress": "{{total}} 件中 {{current}} 件目",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}} 件表示 · 全 {{total}} 件","type": {@@ -1122,7 +1127,8 @@"failed": "{{name}} を自動で開始できませんでした。タスクの詳細を開き、ファイルを選択して再試行してください。"},"undoCorrection": "URL の修正を取り消す",- "submissionUnconfirmed": "結果を確認できていません。再試行時は、別のタスクを作成する前に元のリクエストを確認します。"+ "submissionUnconfirmed": "結果を確認できていません。再試行時は、別のタスクを作成する前に元のリクエストを確認します。",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "ピア: {{count}}",@@ -1277,6 +1283,10 @@"integration": {"title": "連携","desc": "ブラウザー拡張機能、CLI、システム連携"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1925,6 +1935,8 @@"store": "インストール","development": "開発"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "接続済みの拡張機能","pairedEmpty": "接続済みの拡張機能はまだありません。","profile": "ブラウザープロファイル {{number}}",@@ -2251,6 +2263,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex b70a6ccb..ec43ca16 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -5,7 +5,8 @@"placeholder": "관리자 토큰","error": "관리자 토큰이 올바르지 않습니다. 호스트의 MOTRIX_OPERATOR_TOKEN 또는 <dataDir>/operator-token을 확인하고 다시 시도하세요.","submit": "잠금 해제",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "NAS 관리자 세션을 확인할 수 없습니다. NAS 바탕 화면에서 Motrix를 여세요.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "사용법:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\n이 명령은 컨테이너 루프백을 통해 실행 중인 Motrix 서버와만 통신합니다.",@@ -331,7 +332,7 @@"loading": "활동을 불러오는 중","unavailable": "활동을 사용할 수 없음","retry": "다시 시도",- "stale": "최신 활동 정보가 아닐 수 있습니다",+ "refreshFailed": "새로고침 실패","coverageDegraded": "{{time}} 이후의 활동 기록이 불완전할 수 있습니다","rangeSummary": "{{start}}~{{end}}, {{weeks}}주간의 다운로드 활동","completedIntensity": "색상의 진하기는 완료된 다운로드 수를 나타냅니다",@@ -933,7 +934,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "다운로드 재시도","retryDialogDescription": "{{name}}의 요청 매개변수를 편집하여 새 다운로드를 시작하세요. 실패한 작업과 부분 파일은 유지됩니다.",- "retryDialogProgress": "{{total}}개 중 {{current}}번째 다운로드"+ "retryDialogProgress": "{{total}}개 중 {{current}}번째 다운로드",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}}개 표시 · 전체 {{total}}개","type": {@@ -1122,7 +1127,8 @@"failed": "{{name}} 작업을 자동으로 시작하지 못했습니다. 작업 상세 정보에서 파일을 선택하고 다시 시도하세요."},"undoCorrection": "URL 수정 실행 취소",- "submissionUnconfirmed": "결과가 확인되지 않았습니다. 다시 시도하면 새 작업을 만들기 전에 원래 요청의 처리 결과를 확인합니다."+ "submissionUnconfirmed": "결과가 확인되지 않았습니다. 다시 시도하면 새 작업을 만들기 전에 원래 요청의 처리 결과를 확인합니다.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "피어: {{count}}",@@ -1277,6 +1283,10 @@"integration": {"title": "연동","desc": "브라우저 확장 프로그램, CLI, 시스템 연동"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1925,6 +1935,8 @@"store": "설치","development": "개발"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "연결된 확장 프로그램","pairedEmpty": "아직 연결된 확장 프로그램이 없습니다.","profile": "브라우저 프로필 {{number}}",@@ -2251,6 +2263,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex e3602c7a..e642ffaf 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -401,7 +401,8 @@"placeholder": "Operatørtoken","submit": "Lås opp","title": "Lås opp Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Kan ikke bekrefte NAS-administratorøkten. Åpne Motrix fra NAS-skrivebordet.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -431,7 +432,7 @@"more": "Flere","rangeSummary": "{{weeks}} uker med nedlastingsaktivitet, fra {{start}} til {{end}}","retry": "Prøv igjen",- "stale": "Aktiviteten kan være utdatert",+ "refreshFailed": "Oppdateringen mislyktes","title": "Aktivitet","tooltip": {"completed": "Fullført: {{count}}",@@ -906,7 +907,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Prøv nedlastingen på nytt","retryDialogDescription": "Rediger forespørselsparametrene for {{name}} for å starte en ny nedlasting. Den mislykkede oppgaven og den delvise filen beholdes.",- "retryDialogProgress": "Nedlasting {{current}} av {{total}}"+ "retryDialogProgress": "Nedlasting {{current}} av {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Tilkoblinger",@@ -2042,6 +2047,10 @@"network": {"desc": "Mellomtjener, DNS og NAT/UPnP","title": "Nettverk"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2414,6 +2423,8 @@"connected": "Tilkoblet","disconnected": "Ikke tilkoblet","revokeAll": "Koble fra alle",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Tilkoblede utvidelser","pairingStateDegraded": {"description": "Motrix kunne ikke oppdatere registreringene for sammenkoblede utvidelser trygt. Eksisterende utvidelsesøkter er lukket, og ny tilgang er blokkert for denne kjøringen. Start Motrix på nytt for å prøve reparasjonen igjen; ikke stol på listen nedenfor før denne meldingen forsvinner.",@@ -2769,6 +2780,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2883,7 +2925,8 @@"urlsLabel": "URL-er","urlsWithInvalid": "Gyldige: {{valid}}, ugyldige: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Gyldige: {{count}}"+ "validUrlCount": "Gyldige: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Noder: {{count}}",diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 5298f7f2..da60b5e5 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -401,7 +401,8 @@"placeholder": "Operatortoken","submit": "Ontgrendelen","title": "Motrix ontgrendelen",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "De NAS-beheerderssessie kan niet worden geverifieerd. Open Motrix vanaf het NAS-bureaublad.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -431,7 +432,7 @@"more": "Meer","rangeSummary": "{{weeks}} weken downloadactiviteit, van {{start}} tot {{end}}","retry": "Opnieuw proberen",- "stale": "Activiteit is mogelijk verouderd",+ "refreshFailed": "Vernieuwen mislukt","title": "Activiteit","tooltip": {"completed": "{{count}} voltooid",@@ -906,7 +907,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Download opnieuw proberen","retryDialogDescription": "Bewerk de aanvraagparameters voor {{name}} om een nieuwe download te starten. De mislukte taak en het gedeeltelijke bestand blijven behouden.",- "retryDialogProgress": "Download {{current}} van {{total}}"+ "retryDialogProgress": "Download {{current}} van {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Verbindingen",@@ -2042,6 +2047,10 @@"network": {"desc": "Proxy, DNS en NAT/UPnP","title": "Netwerk"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2414,6 +2423,8 @@"connected": "Verbonden","disconnected": "Niet verbonden","revokeAll": "Alles ontkoppelen",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Verbonden extensies","pairingStateDegraded": {"description": "Motrix kon de gegevens van gekoppelde extensies niet veilig bijwerken. Bestaande extensiesessies zijn gesloten en nieuwe toegang is voor deze uitvoering geblokkeerd. Herstart Motrix om het herstel opnieuw te proberen; vertrouw niet op de onderstaande lijst totdat dit bericht verdwenen is.",@@ -2769,6 +2780,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2883,7 +2925,8 @@"urlsLabel": "URL's","urlsWithInvalid": "{{valid}} geldig, {{invalid}} ongeldig","userAgent": "User-Agent",- "validUrlCount": "{{count}} geldig"+ "validUrlCount": "{{count}} geldig",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Peers: {{count}}",diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex 89a9ee7e..50df33d9 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -5,7 +5,8 @@"placeholder": "Token operatora","error": "Nieprawidłowy token operatora. Sprawdź MOTRIX_OPERATOR_TOKEN lub <dataDir>/operator-token na hoście i spróbuj ponownie.","submit": "Odblokuj",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Nie można zweryfikować sesji administratora NAS. Otwórz Motrix z pulpitu NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Użycie:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nPolecenie łączy się wyłącznie z działającym serwerem Motrix przez interfejs pętli zwrotnej kontenera.",@@ -334,7 +335,7 @@"loading": "Wczytywanie aktywności","unavailable": "Aktywność niedostępna","retry": "Spróbuj ponownie",- "stale": "Aktywność może być nieaktualna",+ "refreshFailed": "Odświeżenie nie powiodło się","coverageDegraded": "Aktywność może być niekompletna od {{time}}","rangeSummary": "Aktywność pobierania od {{start}} do {{end}} (tygodnie: {{weeks}})","completedIntensity": "Intensywność koloru oznacza liczbę ukończonych pobrań",@@ -969,7 +970,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Ponów pobieranie","retryDialogDescription": "Edytuj parametry żądania dla {{name}}, aby rozpocząć nowe pobieranie. Nieudane zadanie i jego częściowy plik zostaną zachowane.",- "retryDialogProgress": "Pobieranie {{current}} z {{total}}"+ "retryDialogProgress": "Pobieranie {{current}} z {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "Wyświetlane: {{shown}} · Łącznie: {{total}}","type": {@@ -1161,7 +1166,8 @@"failed": "Nie udało się automatycznie rozpocząć {{name}}. Otwórz szczegóły zadania, wybierz pliki i spróbuj ponownie."},"undoCorrection": "Cofnij poprawkę adresu URL",- "submissionUnconfirmed": "Wynik nie został potwierdzony. Ponowna próba sprawdzi pierwotne żądanie przed utworzeniem kolejnego zadania."+ "submissionUnconfirmed": "Wynik nie został potwierdzony. Ponowna próba sprawdzi pierwotne żądanie przed utworzeniem kolejnego zadania.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Peery: {{count}}",@@ -1319,6 +1325,10 @@"integration": {"title": "Integracja","desc": "Rozszerzenia przeglądarki, CLI, integracja z systemem"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1967,6 +1977,8 @@"store": "Zainstaluj","development": "Deweloperskie"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Połączone rozszerzenia","pairedEmpty": "Nie połączono jeszcze żadnych rozszerzeń.","profile": "Profil przeglądarki {{number}}",@@ -2296,6 +2308,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex ccb853e8..cee47bb3 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -5,7 +5,8 @@"placeholder": "Token do operador","error": "Token do operador inválido. Verifique MOTRIX_OPERATOR_TOKEN ou <dataDir>/operator-token no host e tente novamente.","submit": "Desbloquear",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Não foi possível verificar sua sessão de administrador do NAS. Abra o Motrix pela área de trabalho do NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Uso:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nO comando se comunica apenas com o servidor Motrix em execução, pela interface de loopback do contêiner.",@@ -333,7 +334,7 @@"loading": "Carregando atividade","unavailable": "Atividade indisponível","retry": "Tentar novamente",- "stale": "A atividade pode estar desatualizada",+ "refreshFailed": "Falha ao atualizar","coverageDegraded": "Os dados de atividade podem estar incompletos desde {{time}}","rangeSummary": "{{weeks}} semanas de atividade de downloads, de {{start}} a {{end}}","completedIntensity": "A intensidade da cor indica os downloads concluídos",@@ -957,7 +958,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Tentar baixar novamente","retryDialogDescription": "Edite os parâmetros da solicitação de {{name}} para iniciar um novo download. A tarefa com falha e seu arquivo parcial serão mantidos.",- "retryDialogProgress": "Download {{current}} de {{total}}"+ "retryDialogProgress": "Download {{current}} de {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "Exibidos: {{shown}} · total: {{total}}","type": {@@ -1148,7 +1153,8 @@"failed": "Não foi possível iniciar {{name}} automaticamente. Abra os detalhes da tarefa para selecionar arquivos e tentar novamente."},"undoCorrection": "Desfazer correção do URL",- "submissionUnconfirmed": "O resultado não foi confirmado. Ao tentar novamente, a solicitação original será verificada antes de criar outra tarefa."+ "submissionUnconfirmed": "O resultado não foi confirmado. Ao tentar novamente, a solicitação original será verificada antes de criar outra tarefa.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Pares: {{count}}",@@ -1305,6 +1311,10 @@"integration": {"title": "Integração","desc": "Extensões de navegador, CLI, integrações com o sistema"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1953,6 +1963,8 @@"store": "Instalar","development": "Desenvolvimento"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Extensões conectadas","pairedEmpty": "Nenhuma extensão conectada ainda.","profile": "Perfil do navegador {{number}}",@@ -2281,6 +2293,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex 21456693..2c246159 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -402,7 +402,8 @@"placeholder": "Token operator","submit": "Deblochează","title": "Deblochează Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Sesiunea de administrator NAS nu poate fi verificată. Deschideți Motrix de pe desktopul NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -432,7 +433,7 @@"more": "Mai multe","rangeSummary": "Activitate de descărcare de la {{start}} la {{end}}; număr de săptămâni: {{weeks}}","retry": "Încearcă din nou",- "stale": "Activitatea poate fi învechită",+ "refreshFailed": "Reîmprospătarea a eșuat","title": "Activitate","tooltip": {"completed": "Finalizate: {{count}}",@@ -909,7 +910,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Reîncearcă descărcarea","retryDialogDescription": "Editează parametrii cererii pentru {{name}} pentru a începe o descărcare nouă. Sarcina eșuată și fișierul parțial vor fi păstrate.",- "retryDialogProgress": "Descărcarea {{current}} din {{total}}"+ "retryDialogProgress": "Descărcarea {{current}} din {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "Conexiuni",@@ -2061,6 +2066,10 @@"network": {"desc": "Proxy, DNS și NAT/UPnP","title": "Rețea"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2433,6 +2442,8 @@"connected": "Conectat","disconnected": "Neconectat","revokeAll": "Deconectează toate",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Extensii conectate","pairingStateDegraded": {"description": "Motrix nu a putut actualiza în siguranță înregistrările extensiilor asociate. Sesiunile existente ale extensiilor sunt închise, iar accesul nou este blocat pentru această rulare. Repornește Motrix pentru a reîncerca repararea; nu te baza pe lista de mai jos până când dispare acest mesaj.",@@ -2789,6 +2800,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2904,7 +2946,8 @@"urlsLabel": "URL-uri","urlsWithInvalid": "Valide: {{valid}}, nevalide: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Valide: {{count}}"+ "validUrlCount": "Valide: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Parteneri: {{count}}",diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex 9caeab8d..3350b6ed 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -5,7 +5,8 @@"placeholder": "Токен оператора","error": "Неверный токен оператора. Проверьте MOTRIX_OPERATOR_TOKEN или <dataDir>/operator-token на хосте и повторите попытку.","submit": "Разблокировать",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Не удалось проверить сеанс администратора NAS. Откройте Motrix с рабочего стола NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Использование:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nКоманда взаимодействует только с запущенным сервером Motrix через интерфейс обратной петли контейнера.",@@ -334,7 +335,7 @@"loading": "Загрузка активности","unavailable": "Активность недоступна","retry": "Повторить",- "stale": "Данные об активности могут быть устаревшими",+ "refreshFailed": "Не удалось обновить","coverageDegraded": "Данные об активности могут быть неполными с {{time}}","rangeSummary": "Активность загрузок с {{start}} по {{end}} (недель: {{weeks}})","completedIntensity": "Интенсивность цвета показывает количество завершённых загрузок",@@ -969,7 +970,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Повторить загрузку","retryDialogDescription": "Измените параметры запроса для {{name}}, чтобы начать новую загрузку. Неудачная задача и её частичный файл будут сохранены.",- "retryDialogProgress": "Загрузка {{current}} из {{total}}"+ "retryDialogProgress": "Загрузка {{current}} из {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "Показано: {{shown}} · Всего: {{total}}","type": {@@ -1161,7 +1166,8 @@"failed": "Не удалось автоматически запустить {{name}}. Откройте сведения о задаче, выберите файлы и повторите попытку."},"undoCorrection": "Отменить исправление URL",- "submissionUnconfirmed": "Результат не подтверждён. При повторной попытке исходный запрос будет проверен перед созданием новой задачи."+ "submissionUnconfirmed": "Результат не подтверждён. При повторной попытке исходный запрос будет проверен перед созданием новой задачи.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Пиры: {{count}}",@@ -1319,6 +1325,10 @@"integration": {"title": "Интеграция","desc": "Расширения браузера, CLI, интеграция с системой"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1967,6 +1977,8 @@"store": "Установить","development": "Разработка"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Подключённые расширения","pairedEmpty": "Расширения ещё не подключены.","profile": "Профиль браузера {{number}}",@@ -2296,6 +2308,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex 588f1edc..1d298c9e 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -400,7 +400,8 @@"placeholder": "โทเค็นผู้ดูแล","submit": "ปลดล็อก","title": "ปลดล็อก Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "ไม่สามารถตรวจสอบเซสชันผู้ดูแลระบบ NAS ได้ โปรดเปิด Motrix จากเดสก์ท็อป NAS",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -430,7 +431,7 @@"more": "มาก","rangeSummary": "กิจกรรมการดาวน์โหลด {{weeks}} สัปดาห์ ตั้งแต่ {{start}} ถึง {{end}}","retry": "ลองอีกครั้ง",- "stale": "กิจกรรมอาจไม่เป็นปัจจุบัน",+ "refreshFailed": "รีเฟรชไม่สำเร็จ","title": "กิจกรรม","tooltip": {"completed": "เสร็จสิ้น {{count}} รายการ",@@ -903,7 +904,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "ลองดาวน์โหลดอีกครั้ง","retryDialogDescription": "แก้ไขพารามิเตอร์คำขอสำหรับ {{name}} เพื่อเริ่มการดาวน์โหลดใหม่ งานที่ล้มเหลวและไฟล์ที่ดาวน์โหลดบางส่วนจะยังคงอยู่",- "retryDialogProgress": "การดาวน์โหลด {{current}} จาก {{total}}"+ "retryDialogProgress": "การดาวน์โหลด {{current}} จาก {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "การเชื่อมต่อ",@@ -2023,6 +2028,10 @@"network": {"desc": "พร็อกซี DNS และ NAT/UPnP","title": "เครือข่าย"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2395,6 +2404,8 @@"connected": "เชื่อมต่อแล้ว","disconnected": "ไม่ได้เชื่อมต่อ","revokeAll": "ยกเลิกการเชื่อมต่อทั้งหมด",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "ส่วนขยายที่เชื่อมต่อ","pairingStateDegraded": {"description": "Motrix ไม่สามารถอัปเดตระเบียนส่วนขยายที่จับคู่แล้วได้อย่างปลอดภัย เซสชันส่วนขยายที่มีอยู่ถูกปิด และการเข้าถึงใหม่ถูกบล็อกสำหรับการเปิดแอปครั้งนี้ เริ่ม Motrix ใหม่เพื่อลองซ่อมอีกครั้ง อย่าอ้างอิงรายการด้านล่างจนกว่าข้อความนี้จะหายไป",@@ -2749,6 +2760,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2862,7 +2904,8 @@"urlsLabel": "URL","urlsWithInvalid": "ใช้ได้ {{valid}} รายการ ใช้ไม่ได้ {{invalid}} รายการ","userAgent": "User-Agent",- "validUrlCount": "ใช้ได้ {{count}} รายการ"+ "validUrlCount": "ใช้ได้ {{count}} รายการ",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "เพียร์: {{count}}",diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex 299260f6..bca0e45b 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -5,7 +5,8 @@"placeholder": "Operatör belirteci","error": "Operatör belirteci geçersiz. Sunucu makinesindeki MOTRIX_OPERATOR_TOKEN değişkenini veya <dataDir>/operator-token dosyasını kontrol edip tekrar deneyin.","submit": "Kilidi aç",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "NAS yönetici oturumu doğrulanamadı. Motrix’i NAS masaüstünden açın.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Kullanım:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nKomut yalnızca çalışan Motrix sunucusuyla, kapsayıcının geri döngü bağlantısı üzerinden iletişim kurar.",@@ -332,7 +333,7 @@"loading": "Etkinlik yükleniyor","unavailable": "Etkinlik kullanılamıyor","retry": "Yeniden dene",- "stale": "Etkinlik güncel olmayabilir",+ "refreshFailed": "Yenileme başarısız","coverageDegraded": "{{time}} itibarıyla etkinlik eksik olabilir","rangeSummary": "{{start}} ile {{end}} arasında {{weeks}} haftalık indirme etkinliği","completedIntensity": "Renk yoğunluğu tamamlanan indirmeleri gösterir",@@ -945,7 +946,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "İndirmeyi yeniden dene","retryDialogDescription": "Yeni bir indirme başlatmak için {{name}} isteğinin parametrelerini düzenleyin. Başarısız görev ve kısmi dosyası korunacaktır.",- "retryDialogProgress": "{{total}} indirmeden {{current}}. indirme"+ "retryDialogProgress": "{{total}} indirmeden {{current}}. indirme",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "{{shown}} gösteriliyor · toplam {{total}}","type": {@@ -1135,7 +1140,8 @@"failed": "{{name}} otomatik olarak başlatılamadı. Dosyaları seçip tekrar denemek için görev ayrıntılarını açın."},"undoCorrection": "URL düzeltmesini geri al",- "submissionUnconfirmed": "Sonuç doğrulanmadı. Yeniden denediğinizde, başka bir görev oluşturulmadan önce ilk isteğin sonucu kontrol edilir."+ "submissionUnconfirmed": "Sonuç doğrulanmadı. Yeniden denediğinizde, başka bir görev oluşturulmadan önce ilk isteğin sonucu kontrol edilir.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Eş: {{count}}",@@ -1291,6 +1297,10 @@"integration": {"title": "Entegrasyon","desc": "Tarayıcı uzantıları, CLI, sistem entegrasyonları"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1939,6 +1949,8 @@"store": "Yükle","development": "Geliştirme"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Bağlı uzantılar","pairedEmpty": "Henüz bağlı uzantı yok.","profile": "Tarayıcı profili {{number}}",@@ -2266,6 +2278,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex dbaa23b6..973bdbb6 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -403,7 +403,8 @@"placeholder": "Токен оператора","submit": "Розблокувати","title": "Розблокувати Motrix",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Не вдалося перевірити сеанс адміністратора NAS. Відкрийте Motrix із робочого столу NAS.",+ "openDsm": "Open DSM to sign in"},"panel": {"completed": {@@ -433,7 +434,7 @@"more": "Більше","rangeSummary": "Активність завантажень за період із {{start}} до {{end}}; тижнів: {{weeks}}","retry": "Спробувати ще раз",- "stale": "Дані активності можуть бути застарілими",+ "refreshFailed": "Не вдалося оновити","title": "Активність","tooltip": {"completed": "Завершено: {{count}}",@@ -912,7 +913,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Повторити завантаження","retryDialogDescription": "Змініть параметри запиту для {{name}}, щоб почати нове завантаження. Невдале завдання та його частковий файл буде збережено.",- "retryDialogProgress": "Завантаження {{current}} з {{total}}"+ "retryDialogProgress": "Завантаження {{current}} з {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"column": {"connections": "З’єднання",@@ -2080,6 +2085,10 @@"network": {"desc": "Проксі, DNS і NAT/UPnP","title": "Мережа"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"common": {@@ -2452,6 +2461,8 @@"connected": "Підключено","disconnected": "Не підключено","revokeAll": "Від’єднати всі",+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Підключені розширення","pairingStateDegraded": {"description": "Motrix не вдалося безпечно оновити записи про сполучені розширення. Поточні сеанси розширень закрито, а новий доступ заблоковано до завершення цього запуску. Перезапустіть Motrix, щоб повторити відновлення; не покладайтеся на список нижче, доки це повідомлення не зникне.",@@ -2809,6 +2820,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"task": {@@ -2925,7 +2967,8 @@"urlsLabel": "URL","urlsWithInvalid": "Коректні: {{valid}}, некоректні: {{invalid}}","userAgent": "User-Agent",- "validUrlCount": "Коректні: {{count}}"+ "validUrlCount": "Коректні: {{count}}",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Піри: {{count}}",diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex 12146d27..56dd2aff 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -5,7 +5,8 @@"placeholder": "Token quản trị","error": "Token quản trị không hợp lệ. Hãy kiểm tra MOTRIX_OPERATOR_TOKEN hoặc <dataDir>/operator-token trên máy chủ rồi thử lại.","submit": "Mở khóa",- "fnosSessionExpired": "Your fnOS administrator session has ended. Open Motrix again from the fnOS desktop."+ "nasSessionExpired": "Không thể xác minh phiên quản trị viên NAS. Hãy mở Motrix từ màn hình NAS.",+ "openDsm": "Open DSM to sign in"},"operatorAdmin": {"help": "Cách dùng:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\nLệnh chỉ giao tiếp với máy chủ Motrix đang chạy qua địa chỉ loopback của container.",@@ -331,7 +332,7 @@"loading": "Đang tải dữ liệu hoạt động","unavailable": "Không thể tải dữ liệu hoạt động","retry": "Thử lại",- "stale": "Dữ liệu hoạt động có thể đã cũ",+ "refreshFailed": "Không thể làm mới","coverageDegraded": "Dữ liệu hoạt động có thể không đầy đủ từ {{time}}","rangeSummary": "{{weeks}} tuần hoạt động tải xuống, từ {{start}} đến {{end}}","completedIntensity": "Độ đậm của màu thể hiện số lượt tải xuống hoàn tất",@@ -933,7 +934,11 @@"redownloadStarted": "Re-download started","retryDialogTitle": "Thử tải xuống lại","retryDialogDescription": "Chỉnh sửa tham số yêu cầu cho {{name}} để bắt đầu lượt tải xuống mới. Tác vụ thất bại và tệp tải xuống một phần sẽ được giữ lại.",- "retryDialogProgress": "Lượt tải {{current}} trên {{total}}"+ "retryDialogProgress": "Lượt tải {{current}} trên {{total}}",+ "downloadToDevice": "Download to this device",+ "revealInFileStation": "Show in File Station",+ "nasFileUnavailable": "File access could not be authorized. Check the account and folder permissions.",+ "fileStationWindowBlocked": "The browser blocked the File Station window. Allow popups for this site and try again."},"titleCount": "Đang hiện {{shown}} · Tổng cộng {{total}}","type": {@@ -1122,7 +1127,8 @@"failed": "Không thể tự động bắt đầu {{name}}. Hãy mở chi tiết tác vụ để chọn tệp rồi thử lại."},"undoCorrection": "Hoàn tác sửa URL",- "submissionUnconfirmed": "Chưa xác nhận được kết quả. Khi thử lại, yêu cầu ban đầu sẽ được kiểm tra trước khi tạo tác vụ khác."+ "submissionUnconfirmed": "Chưa xác nhận được kết quả. Khi thử lại, yêu cầu ban đầu sẽ được kiểm tra trước khi tạo tác vụ khác.",+ "selectNasTorrent": "Choose a torrent from the NAS"},"detail": {"peers": "Máy ngang hàng: {{count}}",@@ -1277,6 +1283,10 @@"integration": {"title": "Tích hợp","desc": "Tiện ích mở rộng trình duyệt, CLI, tích hợp hệ thống"+ },+ "nas": {+ "title": "Synology NAS",+ "desc": "Download folders and client connections"}},"general": {@@ -1925,6 +1935,8 @@"store": "Cài đặt","development": "Phát triển"},+ "pendingTitle": "Browser pairing requests",+ "pendingEmpty": "Start pairing in your extension.","pairedTitle": "Tiện ích mở rộng đã kết nối","pairedEmpty": "Chưa có tiện ích mở rộng nào kết nối.","profile": "Hồ sơ trình duyệt {{number}}",@@ -2251,6 +2263,37 @@"updateDescription": "Download the Windows ZIP, exit Motrix, and move the entire data folder to the new version. Portable mode never runs the installer.","recoveryError": "Portable data could not be recovered safely. Keep the data folder and check the logs and directory permissions before retrying. Motrix has stopped without using the system profile.","enginePathDescription": "Portable mode manages engine state inside the data folder for the current application location."+ },+ "nas": {+ "description": "Shared by all DSM administrators. Restart Motrix in Package Center to apply changes.",+ "account": "Current DSM account: {{username}}",+ "restartRequired": "Settings saved. Restart Motrix in Package Center to apply them.",+ "storageUnavailable": "Download folders unavailable",+ "storageRecoveryHint": "Downloads are paused. Restore the original folders or authorize a different path, then restart Motrix in Package Center.",+ "roots": "Authorized download folders",+ "rootsHint": "One existing folder per line. Both your account and the system user motrix need read/write access. Removing the default makes the first folder the new default.",+ "extensionEnabled": "Enable browser extension connections",+ "extensionHint": "Use a DSM certificate hostname that resolves to the NAS LAN address.",+ "webAddress": "Motrix Web address",+ "webAddressHint": "Use the address you normally open, including /motrix/. You can fill it from this browser.",+ "useCurrentAddress": "Use this DSM address",+ "extensionAddress": "Extension connection address",+ "allowHttp": "Allow pairing codes over HTTP",+ "allowHttpHint": "Enable only on a trusted network. HTTPS does not require this option.",+ "clientPort": "Direct client port",+ "clientPortHint": "Direct clients use this port (1024–65535). DSM HTTPS addresses use the DSM port.",+ "activeConnections": "Current connection addresses",+ "cliAddress": "CLI endpoint",+ "sessionHint": "Clients use their paired DSM account’s current permissions. After DSM logout, session expiration or a package restart, reopen Motrix with that account; pairing again is not required.",+ "copy": "Copy address",+ "openSettings": "Configure NAS connections",+ "errors": {+ "invalid": "Check the folder paths, port and connection addresses. HTTP code delivery requires explicit permission.",+ "folderUnavailable": "Check that each folder is on a mounted volume and writable by the internal system user motrix.",+ "permissionDenied": "The account or folder cannot be authorized. Check DSM shared-folder permissions for your account and the internal system user motrix.",+ "unavailable": "Package settings are unavailable. Try again after the service has recovered.",+ "conflict": "The saved configuration changed. Reload before editing again; your unsaved changes will be replaced."+ }}},"errors": {diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 6b838541..6dcccbdd 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -5,7 +5,8 @@"placeholder": "管理员令牌","error": "管理员令牌无效。请核对主机上的 MOTRIX_OPERATOR_TOKEN 或 <dataDir>/operator-token 后重试。","submit": "解锁",- "fnosSessionExpired": "飞牛管理员会话已失效,请从飞牛桌面重新打开 Motrix。"+ "nasSessionExpired": "无法验证 NAS 管理员会话,请从 NAS 桌面重新打开 Motrix。",+ "openDsm": "打开 DSM 登录"},"operatorAdmin": {"help": "用法:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <配对码> [--json]\n motrix-admin pairing deny <配对码> [--json]\n motrix-admin extension pair\n\n此命令仅通过容器内的本机回环地址与正在运行的 Motrix 服务器通信。",@@ -331,7 +332,7 @@"loading": "正在加载活动数据","unavailable": "无法获取活动数据","retry": "重试",- "stale": "活动数据可能已过期",+ "refreshFailed": "刷新失败","coverageDegraded": "自 {{time}} 起活动记录可能不完整","rangeSummary": "{{weeks}} 周下载活动,{{start}} 至 {{end}}","completedIntensity": "颜色深度表示已完成的下载任务数",@@ -933,7 +934,11 @@"redownloadStarted": "已重新发起下载","retryDialogTitle": "重试下载","retryDialogDescription": "修改 {{name}} 的请求参数以开始新下载。原失败任务和部分文件将保留。",- "retryDialogProgress": "第 {{current}} 项,共 {{total}} 项"+ "retryDialogProgress": "第 {{current}} 项,共 {{total}} 项",+ "downloadToDevice": "下载到本机",+ "revealInFileStation": "在 File Station 中显示",+ "nasFileUnavailable": "无法授权访问文件,请检查当前账号和目录权限。",+ "fileStationWindowBlocked": "浏览器阻止了 File Station 窗口,请允许此站点打开弹窗后重试。"},"titleCount": "{{shown}} 项 · 共 {{total}}","type": {@@ -1122,7 +1127,8 @@"failed": "无法自动开始下载 {{name}},请打开任务详情,选择文件后重试。"},"undoCorrection": "撤销 URL 修正",- "submissionUnconfirmed": "结果尚未确认。再次提交时会先核对原请求,避免重复创建任务。"+ "submissionUnconfirmed": "结果尚未确认。再次提交时会先核对原请求,避免重复创建任务。",+ "selectNasTorrent": "从 NAS 选择种子文件"},"detail": {"peers": "节点:{{count}}",@@ -1277,6 +1283,10 @@"integration": {"title": "集成","desc": "浏览器扩展、命令行工具、操作系统集成"+ },+ "nas": {+ "title": "群晖套件",+ "desc": "授权目录与客户端连接"}},"general": {@@ -1925,6 +1935,8 @@"store": "安装扩展","development": "开发版"},+ "pendingTitle": "浏览器扩展配对请求",+ "pendingEmpty": "在扩展中点击“配对”,请求将显示在这里。","pairedTitle": "已连接的扩展","pairedEmpty": "还没有扩展连接到 Motrix。","profile": "浏览器配置 {{number}}",@@ -2251,6 +2263,37 @@"updateDescription": "请下载 Windows ZIP,退出 Motrix 后将完整的 data 文件夹移到新版本目录。便携模式不会运行安装程序。","recoveryError": "无法安全恢复便携数据。请保留 data 文件夹,检查日志和目录权限后重试。Motrix 已停止启动,未使用系统用户数据目录。","enginePathDescription": "便携模式将引擎状态保存在 data 文件夹内,随应用位置自动管理。"+ },+ "nas": {+ "description": "所有 DSM 管理员共用这些设置。请在套件中心重启 Motrix 以应用更改。",+ "account": "当前 DSM 账号:{{username}}",+ "restartRequired": "设置已保存。请在套件中心停止并重新启动 Motrix。",+ "storageUnavailable": "下载目录不可用",+ "storageRecoveryHint": "下载已暂停。请恢复原目录,或改为授权其他路径,然后在套件中心重新启动 Motrix。",+ "roots": "授权下载目录",+ "rootsHint": "每行一个已有目录。当前账号和系统内部用户 motrix 均需读写权限。移除默认目录后,第一个目录成为新默认目录。",+ "extensionEnabled": "启用浏览器扩展连接",+ "extensionHint": "使用 DSM HTTPS 证书覆盖的域名,并将它解析到 NAS 内网地址。",+ "webAddress": "Motrix Web 地址",+ "webAddressHint": "填写平时打开的地址,包含 /motrix/。可直接使用当前浏览器的地址。",+ "useCurrentAddress": "使用当前 DSM 地址",+ "extensionAddress": "扩展连接地址",+ "allowHttp": "允许通过 HTTP 显示配对码",+ "allowHttpHint": "仅在可信网络中启用。使用 HTTPS 时无需开启此选项。",+ "clientPort": "客户端直连端口",+ "clientPortHint": "直连客户端使用此端口(1024–65535)。DSM HTTPS 地址使用 DSM 端口。",+ "activeConnections": "当前连接地址",+ "cliAddress": "CLI 连接地址",+ "sessionHint": "客户端沿用配对账号的当前权限。退出 DSM、会话过期或套件重启后,请用对应账号重新打开 Motrix,无需重新配对。",+ "copy": "复制地址",+ "openSettings": "配置 NAS 连接",+ "errors": {+ "invalid": "请检查目录、端口和连接地址。通过 HTTP 显示配对码需要明确许可。",+ "folderUnavailable": "请确认目录位于已挂载的存储卷,并允许内部系统用户 motrix 读写。",+ "permissionDenied": "无法授权当前账号或目录。请在 DSM 共享文件夹权限中检查当前账号及内部系统用户 motrix 的权限。",+ "unavailable": "暂时无法读取或保存套件设置,请在服务恢复后重试。",+ "conflict": "已保存的配置发生变化,请重新加载后再编辑。重新加载会替换尚未保存的修改。"+ }}},"menu": {diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 5ebe5473..0c5b8823 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -5,7 +5,8 @@"placeholder": "Operator Token","error": "Operator Token 無效。請確認主機上的 MOTRIX_OPERATOR_TOKEN 或 <dataDir>/operator-token,然後再試一次。","submit": "解鎖",- "fnosSessionExpired": "飛牛管理員工作階段已失效,請從飛牛桌面重新開啟 Motrix。"+ "nasSessionExpired": "無法驗證 NAS 管理員工作階段,請從 NAS 桌面重新開啟 Motrix。",+ "openDsm": "開啟 DSM 登入"},"operatorAdmin": {"help": "用法:\n motrix-admin pairing pending [--json]\n motrix-admin pairing approve <user-code> [--json]\n motrix-admin pairing deny <user-code> [--json]\n motrix-admin extension pair\n\n此命令只會透過容器 loopback 與正在執行的 Motrix 伺服器通訊。",@@ -331,7 +332,7 @@"loading": "正在載入活動資料","unavailable": "無法取得活動資料","retry": "重試",- "stale": "活動資料可能不是最新的",+ "refreshFailed": "重新整理失敗","coverageDegraded": "自 {{time}} 起的活動資料可能不完整","rangeSummary": "{{start}} 至 {{end}} 的 {{weeks}} 週下載活動","completedIntensity": "色彩深淺表示已完成的下載數量",@@ -933,7 +934,11 @@"redownloadStarted": "已重新發起下載","retryDialogTitle": "重試下載","retryDialogDescription": "修改 {{name}} 的請求參數以開始新下載。原失敗任務和部分檔案將保留。",- "retryDialogProgress": "第 {{current}} 項,共 {{total}} 項"+ "retryDialogProgress": "第 {{current}} 項,共 {{total}} 項",+ "downloadToDevice": "下載到此裝置",+ "revealInFileStation": "在 File Station 中顯示",+ "nasFileUnavailable": "無法授權存取檔案,請檢查目前帳號和目錄權限。",+ "fileStationWindowBlocked": "瀏覽器封鎖了 File Station 視窗,請允許此網站開啟彈出式視窗後重試。"},"titleCount": "顯示 {{shown}} 項 · 共 {{total}} 項","type": {@@ -1122,7 +1127,8 @@"failed": "無法自動開始下載 {{name}},請開啟任務詳細資料,選擇檔案後重試。"},"undoCorrection": "復原 URL 修正",- "submissionUnconfirmed": "結果尚未確認。再次提交時會先核對原請求,避免重複建立任務。"+ "submissionUnconfirmed": "結果尚未確認。再次提交時會先核對原請求,避免重複建立任務。",+ "selectNasTorrent": "從 NAS 選擇種子檔案"},"detail": {"peers": "對等節點:{{count}}",@@ -1277,6 +1283,10 @@"integration": {"title": "整合","desc": "瀏覽器擴充功能、CLI、系統整合"+ },+ "nas": {+ "title": "群暉套件",+ "desc": "授權目錄與用戶端連線"}},"general": {@@ -1925,6 +1935,8 @@"store": "安裝擴充功能","development": "開發版"},+ "pendingTitle": "瀏覽器擴充功能配對請求",+ "pendingEmpty": "在擴充功能中點選「配對」,請求就會顯示在這裡。","pairedTitle": "已連線的擴充功能","pairedEmpty": "尚未連線任何擴充功能。","profile": "瀏覽器設定檔 {{number}}",@@ -2251,6 +2263,37 @@"updateDescription": "請下載 Windows ZIP,結束 Motrix 後將完整的 data 資料夾移至新版本目錄。可攜模式不會執行安裝程式。","recoveryError": "無法安全復原可攜資料。請保留 data 資料夾,檢查記錄和目錄權限後重試。Motrix 已停止啟動,未使用系統使用者資料目錄。","enginePathDescription": "可攜模式將引擎狀態儲存於 data 資料夾內,隨應用程式位置自動管理。"+ },+ "nas": {+ "description": "所有 DSM 管理員共用這些設定。請在套件中心重新啟動 Motrix 以套用變更。",+ "account": "目前 DSM 帳號:{{username}}",+ "restartRequired": "設定已儲存。請在套件中心停止並重新啟動 Motrix。",+ "storageUnavailable": "下載資料夾無法使用",+ "storageRecoveryHint": "下載已暫停。請還原原本的資料夾,或改為授權其他路徑,然後在套件中心重新啟動 Motrix。",+ "roots": "授權下載目錄",+ "rootsHint": "每行一個現有資料夾。必須允許目前帳號及內部系統使用者 motrix 讀寫。移除預設資料夾後,第一個資料夾會成為新預設。",+ "extensionEnabled": "啟用瀏覽器擴充功能連線",+ "extensionHint": "使用 DSM HTTPS 憑證涵蓋的網域名稱,並將它解析到 NAS 內部位址。",+ "webAddress": "Motrix Web 位址",+ "webAddressHint": "填寫平時開啟的位址,包含 /motrix/。可直接使用目前瀏覽器的位址。",+ "useCurrentAddress": "使用目前 DSM 位址",+ "extensionAddress": "擴充功能連線位址",+ "allowHttp": "允許透過 HTTP 顯示配對碼",+ "allowHttpHint": "僅在可信任網路中啟用。使用 HTTPS 時無需開啟此選項。",+ "clientPort": "用戶端直連連接埠",+ "clientPortHint": "直連用戶端使用此連接埠(1024–65535)。DSM HTTPS 位址使用 DSM 連接埠。",+ "activeConnections": "目前連線位址",+ "cliAddress": "CLI 連線位址",+ "sessionHint": "用戶端沿用配對帳號的目前權限。登出 DSM、工作階段過期或套件重新啟動後,請用對應帳號重新開啟 Motrix,無需重新配對。",+ "copy": "複製位址",+ "openSettings": "設定 NAS 連線",+ "errors": {+ "invalid": "請檢查目錄、連接埠和連線位址。透過 HTTP 顯示配對碼需要明確許可。",+ "folderUnavailable": "請確認資料夾位於已掛載的儲存空間,並允許內部系統使用者 motrix 讀寫。",+ "permissionDenied": "無法授權目前帳號或目錄。請在 DSM 共用資料夾權限中檢查目前帳號及內部系統使用者 motrix 的權限。",+ "unavailable": "暫時無法讀取或儲存套件設定,請在服務恢復後重試。",+ "conflict": "已儲存的設定發生變更,請重新載入後再編輯。重新載入會取代尚未儲存的修改。"+ }}},"errors": {diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex 8481fe42..5b0a9f7d 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -1,4 +1,5 @@export const Commands = {+ SaveNasSettings: 'command:saveNasSettings',AcknowledgeGraphicsRecoveryNotice:'command:acknowledgeGraphicsRecoveryNotice',ExecuteRendererSubmission: 'command:executeRendererSubmission',diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.tsindex fa930cff..d86a9b73 100644--- a/src/shared/protocol/queries.ts+++ b/src/shared/protocol/queries.ts@@ -1,4 +1,5 @@export const Queries = {+ GetNasSettings: 'query:getNasSettings',GetPortableMode: 'query:getPortableMode',GetGraphicsRecoveryNotice: 'query:getGraphicsRecoveryNotice',GetRendererSession: 'query:getRendererSession',diff --git a/src/shared/schemas/nas-files.test.ts b/src/shared/schemas/nas-files.test.tsnew file mode 100644index 00000000..823f8981--- /dev/null+++ b/src/shared/schemas/nas-files.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest'+import { synologyFileStationUrl } from './nas-files'+import {+ nasPackageSettingsSchema,+ synologyConnectionUrls,+} from './nas-settings'++describe('NAS host navigation and settings contracts', () => {+ it('roundtrips Unicode and URL punctuation without introducing another host or query field', () => {+ const path = '/volume1/motrix/中文 & #+% folder'+ const url = new URL(synologyFileStationUrl(path), 'https://nas.test:5001')+ expect(url.origin).toBe('https://nas.test:5001')+ expect([...url.searchParams.keys()]).toEqual(['launchApp', 'launchParam'])+ expect(url.searchParams.get('launchApp')).toBe(+ 'SYNO.SDS.App.FileStation3.Instance'+ )+ expect(+ new URLSearchParams(url.searchParams.get('launchParam') ?? '').get(+ 'openfile'+ )+ ).toBe('/motrix/中文 & #+% folder/')+ for (const path of [+ '/etc',+ '//evil.test/share',+ '/volume1/motrix/../private',+ '/volume1/motrix\n',+ ])+ expect(() => synologyFileStationUrl(path)).toThrow()+ })+ it('derives fixed same-origin endpoints and rejects credentials or non-origin inputs', () => {+ expect(synologyConnectionUrls('https://nas.test:5001')).toEqual({+ operatorUrl: 'https://nas.test:5001/motrix/',+ extensionUrl: 'wss://nas.test:5001/motrix/bridge',+ })+ for (const origin of [+ 'https://user:[email protected]',+ 'https://nas.test/path',+ 'javascript:alert(1)',+ ])+ expect(() => synologyConnectionUrls(origin)).toThrow()+ })+ it('rejects ambiguous folder grants and invalid ports before persistence', () => {+ const settings = {+ roots: ['/volume1/motrix'],+ clientPort: 16802,+ extensionUrl: '',+ operatorUrl: '',+ allowHttp: false,+ }+ for (const roots of [+ [],+ ['/'],+ ['relative'],+ ['/volume1/motrix/..'],+ ['/volume1/motrix', '/volume1/motrix'],+ ['/volume1/motrix\0'],+ ])+ expect(+ nasPackageSettingsSchema.safeParse({ ...settings, roots }).success+ ).toBe(false)+ expect(+ nasPackageSettingsSchema.safeParse({ ...settings, clientPort: 65536 })+ .success+ ).toBe(false)+ })+})diff --git a/src/shared/schemas/nas-files.ts b/src/shared/schemas/nas-files.tsnew file mode 100644index 00000000..2deef5d0--- /dev/null+++ b/src/shared/schemas/nas-files.ts@@ -0,0 +1,34 @@+import { z } from 'zod'++export const nasTaskActionSchema = z+ .object({+ taskId: z.string().min(1).max(128),+ action: z.enum(['open', 'reveal']),+ })+ .strict()+export const nasFileActionResultSchema = z+ .object({+ kind: z.enum(['download', 'file-manager']),+ url: z.string().min(1).max(16384).startsWith('/'),+ })+ .strict()+export const nasTorrentPathSchema = z+ .object({ path: z.string().min(1).max(4096) })+ .strict()+export const NAS_FILE_API = '/api/nas'++/** DSM's launchParam is a nested form-encoded string, not JSON. No SynoToken+ * is embedded: the DSM desktop authenticates with its own existing cookie. */+export function synologyFileStationUrl(canonical: string): string {+ if (+ !/^\/volume[1-9]\d*\/[^/]+(?:\/.*)?$/.test(canonical) ||+ /\p{Cc}/u.test(canonical) ||+ canonical+ .split('/')+ .slice(1)+ .some((part) => !part || part === '.' || part === '..')+ )+ throw new Error('Invalid DSM output path')+ const virtual = canonical.replace(/^\/volume[1-9]\d*/, '')+ return `/?${new URLSearchParams({ launchApp: 'SYNO.SDS.App.FileStation3.Instance', launchParam: `openfile=${encodeURIComponent(`${virtual}/`)}` })}`+}diff --git a/src/shared/schemas/nas-settings.ts b/src/shared/schemas/nas-settings.tsnew file mode 100644index 00000000..54aae121--- /dev/null+++ b/src/shared/schemas/nas-settings.ts@@ -0,0 +1,80 @@+import { z } from 'zod'++export const nasRootPathSchema = z+ .string()+ .min(1)+ .max(4096)+ .regex(/^\/[^:]+$/)+ .regex(/^\P{Cc}+$/u)+ .refine((value) =>+ value+ .split('/')+ .slice(1)+ .every((part) => part !== '' && part !== '.' && part !== '..')+ )++/** Host-owned package settings, separate from ordinary application preferences. */+export const nasPackageSettingsSchema = z+ .object({+ roots: z+ .array(nasRootPathSchema)+ .min(1)+ .max(64)+ .refine((values) => new Set(values).size === values.length),+ clientPort: z.number().int().min(1024).max(65535),+ extensionUrl: z.string().max(2048),+ operatorUrl: z.string().max(2048),+ allowHttp: z.boolean(),+ })+ .strict()+export type NasPackageSettings = z.infer<typeof nasPackageSettingsSchema>++export const nasSettingsViewSchema = z+ .object({+ platform: z.enum(['synology', 'fnos']),+ revision: z.string().regex(/^[a-f0-9]{64}$/),+ settings: nasPackageSettingsSchema,+ active: nasPackageSettingsSchema,+ restartRequired: z.boolean(),+ })+ .strict()+export type NasSettingsView = z.infer<typeof nasSettingsViewSchema>++export const saveNasSettingsSchema = z+ .object({+ revision: z.string().regex(/^[a-f0-9]{64}$/),+ settings: nasPackageSettingsSchema,+ })+ .strict()+export const nasSettingsErrorSchema = z.enum([+ 'invalid',+ 'folderUnavailable',+ 'permissionDenied',+ 'unavailable',+ 'conflict',+])+export const nasSettingsResultSchema = z.discriminatedUnion('ok', [+ z.object({ ok: z.literal(true), value: nasSettingsViewSchema }).strict(),+ z+ .object({+ ok: z.literal(false),+ error: z.object({ code: nasSettingsErrorSchema }).strict(),+ })+ .strict(),+])+export type NasSettingsResult = z.infer<typeof nasSettingsResultSchema>++export function synologyConnectionUrls(origin: string) {+ const url = new URL(origin)+ if (+ !['http:', 'https:'].includes(url.protocol) ||+ url.username ||+ url.password ||+ url.origin !== origin+ )+ throw new Error('Invalid DSM origin')+ return {+ operatorUrl: `${origin}/motrix/`,+ extensionUrl: `${origin.replace(/^http/, 'ws')}/motrix/bridge`,+ }+}diff --git a/src/shared/schemas/operator-auth.ts b/src/shared/schemas/operator-auth.tsindex 929d63e7..7e5c40f7 100644--- a/src/shared/schemas/operator-auth.ts+++ b/src/shared/schemas/operator-auth.ts@@ -1,4 +1,5 @@import { z } from 'zod'+import { nasRootPathSchema } from './nas-settings'export const WEB_ORIGIN_HEADER = 'x-motrix-web-origin'export const FNOS_EVENT_PROTOCOL = 'motrix.fnos.events'@@ -17,6 +18,44 @@ export type ClientPairingCapabilities = z.infer<typeof clientPairingCapabilitiesSchema>+export const nasCapabilitiesSchema = z+ .object({+ settings: z.boolean(),+ fileActions: z.boolean(),+ torrentPicker: z.boolean(),+ clientGateway: z.boolean(),+ })+ .readonly()+export type NasCapabilities = z.infer<typeof nasCapabilitiesSchema>++/** Safe support metadata only: no session, account name, command output or path. */+export const nasAuthDiagnosticSchema = z+ .object({+ stage: z.enum(['gateway', 'session', 'account']),+ code: z.enum([+ 'untrustedListener',+ 'missingCookie',+ 'invalidContext',+ 'rejected',+ 'commandFailed',+ 'unavailable',+ ]),+ failure: z+ .enum([+ 'accessDenied',+ 'notFound',+ 'timeout',+ 'outputLimit',+ 'exit',+ 'unavailable',+ ])+ .optional(),+ exitCode: z.number().int().min(0).max(255).optional(),+ })+ .strict()+ .readonly()+export type NasAuthDiagnostic = z.infer<typeof nasAuthDiagnosticSchema>+export const operatorStatusSchema = z.object({authed: z.boolean(),mode: z.enum([@@ -25,13 +64,25 @@ export const operatorStatusSchema = z.object({'unrestricted','unauthenticated','fnosGateway',+ 'synologyDsm',]),username: z.string().optional(),canLogout: z.boolean(),eventOriginMatches: z.boolean().optional(),clientPairing: clientPairingCapabilitiesSchema.optional(),+ nasAuthDiagnostic: nasAuthDiagnosticSchema.optional(),+ nasCapabilities: nasCapabilitiesSchema.optional(),+ nasUnavailableDownloadRoots: z+ .array(nasRootPathSchema)+ .min(1)+ .max(64)+ .optional(),})+export function isNasAuthMode(mode: string | undefined): boolean {+ return mode === 'fnosGateway' || mode === 'synologyDsm'+}+export type OperatorStatus = z.infer<typeof operatorStatusSchema>/** Older ordinary Server and Electron hosts predate capability reporting. */@@ -40,5 +91,5 @@ export function supportsClientPairing(kind: keyof ClientPairingCapabilities): boolean {if (status && !status.authed) return false- return status?.clientPairing?.[kind] ?? status?.mode !== 'fnosGateway'+ return status?.clientPairing?.[kind] ?? !isNasAuthMode(status?.mode)}diff --git a/src/shared/schemas/web-event-stream.ts b/src/shared/schemas/web-event-stream.tsindex 57a6dfb1..5773cfab 100644--- a/src/shared/schemas/web-event-stream.ts+++ b/src/shared/schemas/web-event-stream.ts@@ -14,6 +14,16 @@ export const WEB_EVENT_HEARTBEAT = webEventHeartbeatSchema.parse({type: 'heartbeat',version: 1,})+// The server sends this control frame only to the socket being renewed.+// The browser returns it via authenticated same-origin HTTP with its current cookie.+export const webEventRenewalSchema = z+ .object({+ type: z.literal('session-renewal'),+ version: z.literal(1),+ challenge: z.string().regex(/^[A-Za-z0-9_-]{32}$/),+ })+ .strict()+export type WebEventRenewal = z.infer<typeof webEventRenewalSchema>export const webEventFrameSchema = z.object({channel: z.string(),args: z.array(z.unknown()),diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.tsindex c2eaa4ca..5c4ea325 100644--- a/src/shared/types/task-actions.ts+++ b/src/shared/types/task-actions.ts@@ -90,6 +90,14 @@ export function canOpenTaskFile(t: DownloadTask): boolean {)}+export function canRevealTaskFolder(task: DownloadTask): boolean {+ if (task.status === TaskStatus.FetchingMetadata) return false+ const diskPath = task.diskPath.trim()+ if (!diskPath) return false+ const normalized = diskPath.replace(/[\\/]+$/, '')+ return normalized !== '' && !/^[A-Za-z]:$/.test(normalized)+}+/** Live multi-file downloads that accept a changed file selection. */export function canSelectTaskFiles(t: DownloadTask): boolean {return (diff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.tsindex 34dd7317..de1b2d1a 100644--- a/tests/scripts/production-build.test.ts+++ b/tests/scripts/production-build.test.ts@@ -9,10 +9,11 @@ const TARGETS = [{ name: 'main', initial: 2 * MIB, total: 5.5 * MIB + 12 * 1024 },{ name: 'preload', initial: 80 * 1024, total: 80 * 1024 },{ name: 'worker', initial: 48 * 1024, total: 48 * 1024 },- { name: 'renderer', initial: 2.75 * MIB, total: 8 * MIB },- // NAS integration and code claims bring total Web JS to ~8.009 MiB.- // Keep the startup ceiling unchanged and bound the added UI/locales to 12 KiB.- { name: 'renderer.web', initial: 2.75 * MIB, total: 8 * MIB + 12 * 1024 },+ // Native NAS strings in all 26 catalogs add ~60 KiB; the Web-only settings+ // dialog stays lazy and is excluded from Electron. Startup ceilings are unchanged.+ { name: 'renderer', initial: 2.75 * MIB, total: 8 * MIB + 64 * 1024 },+ // The lazy DSM storage recovery page and its localized controls add 9 KiB.+ { name: 'renderer.web', initial: 2.75 * MIB, total: 8 * MIB + 108 * 1024 },// The shared operation runtime brings total server JS to ~5.01 MiB.{ name: 'server', initial: 2 * MIB, total: 5.25 * MIB },]diff --git a/tests/scripts/synology-package.test.ts b/tests/scripts/synology-package.test.tsnew file mode 100644index 00000000..cf6066d9--- /dev/null+++ b/tests/scripts/synology-package.test.ts@@ -0,0 +1,202 @@+import { execFileSync } from 'node:child_process'+import { mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { expect, it } from 'vitest'+import {+ applyPendingSettings,+ configure,+ runtimeEnvironment,+} from '../../packaging/synology/app/lifecycle.mjs'+import { payloadInventory } from '../../scripts/verify-synology-package.mjs'++it.skipIf(process.platform === 'win32')(+ 'rejects unsafe package settings before starting either runtime',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-config-'))+ try {+ const env = { SYNOPKG_PKGDEST: root, SYNOPKG_PKGVAR: root }+ await configure(env)+ const config = path.join(root, 'directories.json'),+ target = path.join(root, 'fixture')+ await writeFile(target, JSON.stringify({ roots: ['/volume1/motrix'] }), {+ mode: 0o600,+ })+ await symlink(target, config)+ await expect(runtimeEnvironment(env)).rejects.toMatchObject({+ code: 'ELOOP',+ })+ await rm(config)+ await writeFile(config, 'private-test-content', { mode: 0o600 })+ await expect(runtimeEnvironment(env)).rejects.toThrow(+ 'Invalid DSM package configuration'+ )+ await writeFile(config, Buffer.alloc(36 * 1024 + 1))+ await expect(runtimeEnvironment(env)).rejects.toThrow(+ 'Untrusted DSM package configuration'+ )+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ }+)++it+ .skipIf(process.platform === 'win32')+ .each([{}, { directoryIdentities: ['12:257', '12:258'] }])(+ 'replays pending settings after an interrupted apply and preserves the grant metadata %j',+ async (grant) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-pending-'))+ try {+ const value = {+ ...grant,+ roots: ['/volume1/motrix', '/volume1/downloads'],+ clientPort: 16812,+ extensionUrl: 'wss://nas.test:5001/motrix/bridge',+ operatorUrl: 'https://nas.test:5001/motrix/',+ allowHttp: false,+ }+ await writeFile(+ path.join(root, 'pending-settings.json'),+ JSON.stringify(value),+ { mode: 0o600 }+ )+ const { mkdir } = await import('node:fs/promises')+ await mkdir(path.join(root, 'directories.json'))+ await expect(+ applyPendingSettings({ SYNOPKG_PKGVAR: root })+ ).rejects.toThrow()+ expect(+ JSON.parse(+ await readFile(path.join(root, 'pending-settings.json'), 'utf8')+ )+ ).toEqual(value)+ await rm(path.join(root, 'directories.json'), { recursive: true })+ await applyPendingSettings({ SYNOPKG_PKGVAR: root })+ expect(+ JSON.parse(+ await readFile(path.join(root, 'package-settings.json'), 'utf8')+ )+ ).toMatchObject({ clientPort: 16812, extensionUrl: value.extensionUrl })+ expect(+ JSON.parse(await readFile(path.join(root, 'directories.json'), 'utf8'))+ ).toEqual({ roots: value.roots, ...grant })+ await expect(+ readFile(path.join(root, 'pending-settings.json'))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ await applyPendingSettings({ SYNOPKG_PKGVAR: root })+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ }+)++it.skipIf(process.platform === 'win32')(+ 'keeps existing directory identities when replaying a path-only journal',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-replay-'))+ try {+ const grant = {+ roots: ['/volume1/motrix'],+ directoryIdentities: ['7:256'],+ }+ const file = path.join(root, 'directories.json')+ await writeFile(file, JSON.stringify(grant), { mode: 0o600 })+ const pending = path.join(root, 'pending-settings.json')+ const settings = {+ roots: grant.roots,+ clientPort: 16802,+ allowHttp: false,+ operatorUrl: '',+ extensionUrl: '',+ }+ await writeFile(pending, JSON.stringify(settings), { mode: 0o600 })+ await applyPendingSettings({ SYNOPKG_PKGVAR: root })+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(grant)+ const invalid = { ...settings, directoryIdentities: [] }+ await writeFile(pending, JSON.stringify(invalid), { mode: 0o600 })+ await expect(+ applyPendingSettings({ SYNOPKG_PKGVAR: root })+ ).rejects.toThrow('Invalid pending directory identities')+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(grant)+ expect(JSON.parse(await readFile(pending, 'utf8'))).toEqual(invalid)+ } finally {+ await rm(root, { recursive: true, force: true })+ }+ }+)++it('preserves package settings on upgrade and rejects invalid client ports before writing', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-config-'))+ try {+ const env = { SYNOPKG_PKGVAR: root, wizard_client_port: '65536' }+ await expect(configure(env)).rejects.toThrow()+ await configure({ ...env, wizard_client_port: '16812' })+ const before = await readFile(+ path.join(root, 'package-settings.json'),+ 'utf8'+ )+ await configure({+ ...env,+ wizard_client_port: '16820',+ wizard_allow_operator_http: 'true',+ })+ expect(+ await readFile(path.join(root, 'package-settings.json'), 'utf8')+ ).toBe(before)+ expect(JSON.parse(before)).toMatchObject({+ clientPort: 16812,+ allowHttp: false,+ extensionUrl: '',+ })+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})++it('detects changed and additional payload bytes, including executable permissions', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-hash-'))+ try {+ await writeFile(path.join(root, 'file'), 'original', { mode: 0o644 })+ const before = await payloadInventory(root)+ await writeFile(path.join(root, 'file'), 'tampered')+ expect(await payloadInventory(root)).not.toEqual(before)+ await writeFile(path.join(root, 'extra'), 'extra')+ expect(Object.keys(await payloadInventory(root))).toEqual(['extra', 'file'])+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})++it('refuses traversal, symlinks, macOS metadata and duplicate names in an SPK', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-spk-archive-'))+ try {+ for (const kind of ['traversal', 'link', 'metadata', 'duplicate']) {+ const archive = path.join(root, `${kind}.tar`)+ execFileSync('python3', [+ '-c',+ `import tarfile,sys\nt=tarfile.open(sys.argv[1],'w')\nk=sys.argv[2]\na=tarfile.TarInfo('../outside' if k=='traversal' else '._file' if k=='metadata' else 'file')\nif k=='link': a.type=tarfile.SYMTYPE; a.linkname='/tmp'\nt.addfile(a)\nif k=='duplicate': t.addfile(a)\nt.close()`,+ archive,+ kind,+ ])+ expect(() =>+ execFileSync(+ 'python3',+ ['scripts/spk_archive.py', archive, path.join(root, kind)],+ { stdio: 'pipe' }+ )+ ).toThrow()+ }+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})++it.skipIf(process.platform === 'win32')(+ 'verifies release architecture, source and payload before publication',+ () => {+ execFileSync('python3', ['tests/scripts/test_synology_publication.py'], {+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1' },+ })+ }+)diff --git a/tests/scripts/test_fnos_publication.py b/tests/scripts/test_fnos_publication.pyindex b4fbd023..4717710c 100644--- a/tests/scripts/test_fnos_publication.py+++ b/tests/scripts/test_fnos_publication.py@@ -1,6 +1,6 @@import copyimport hashlib-import importlib.util+import sysimport ioimport jsonfrom pathlib import Path@@ -9,9 +9,10 @@ import tempfileimport unittestfrom unittest.mock import patch-spec = importlib.util.spec_from_file_location('fnos_publication', Path(__file__).resolve().parents[2] / 'scripts/fnos_publication.py')-pub = importlib.util.module_from_spec(spec)-spec.loader.exec_module(pub)+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts'))+import fnos_publication as pub+import nas_release+VERSION = '2.3.0'TAG = 'v' + VERSIONSHA = 'a' * 40@@ -135,19 +136,19 @@ class PublicationTests(unittest.TestCase):def test_existing_different_asset_never_overwritten(self):existing = assets(self.root)existing[0]['digest'] = 'sha256:' + '0' * 64- with patch.object(pub, 'source', return_value=SOURCE), patch.object(pub, 'api', return_value={'assets': existing}), patch.object(pub.subprocess, 'run') as mutation:+ with patch.object(pub, 'source', return_value=SOURCE), patch.object(nas_release, 'api', return_value={'assets': existing}), patch.object(pub.subprocess, 'run') as mutation:with self.assertRaisesRegex(ValueError, 'immutable'):pub.publish(self.root, TAG, SHA, '123')mutation.assert_not_called()def test_retry_reuses_identical_assets(self):- with patch.object(pub, 'source', return_value=SOURCE), patch.object(pub, 'api', return_value={'assets': assets(self.root)}), patch.object(pub.subprocess, 'run') as mutation:+ with patch.object(pub, 'source', return_value=SOURCE), patch.object(nas_release, 'api', return_value={'assets': assets(self.root)}), patch.object(pub.subprocess, 'run') as mutation:pub.publish(self.root, TAG, SHA, '123')mutation.assert_not_called()def test_publish_adds_only_missing_verified_assets(self):existing = assets(self.root)- with patch.object(pub, 'source', return_value=SOURCE), patch.object(pub, 'api', side_effect=[{'assets': existing[:1]}, {'assets': existing}]), patch.object(pub.subprocess, 'run') as mutation:+ with patch.object(pub, 'source', return_value=SOURCE), patch.object(nas_release, 'api', side_effect=[{'assets': existing[:1]}, {'assets': existing}]), patch.object(pub.subprocess, 'run') as mutation:pub.publish(self.root, TAG, SHA, '123')command = mutation.call_args.args[0]self.assertNotIn('--clobber', command)diff --git a/tests/scripts/test_synology_publication.py b/tests/scripts/test_synology_publication.pynew file mode 100644index 00000000..d8b5e5bb--- /dev/null+++ b/tests/scripts/test_synology_publication.py@@ -0,0 +1,144 @@+"""Exercise release verification without writing to GitHub."""+import hashlib+import io+import json+from pathlib import Path+import sys+import tarfile+import tempfile+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'scripts'))+import synology_publication as pub++LOCK = json.loads((ROOT / 'scripts/synology-runtime.lock.json').read_text())+NODE = json.loads((ROOT / 'scripts/fnos-runtime.lock.json').read_text())+SHA = pub.run('git', 'rev-parse', 'HEAD')+TEMPLATES = pub.package_templates(SHA)+VERSION = '2.3.0'+ENGINES = {'assets': {}}+for arch, target in LOCK['targets'].items():+ header = bytearray(20)+ header[:6] = b'\x7fELF\x02\x01'+ header[18:20] = target['machine'].to_bytes(2, 'little')+ digest = hashlib.sha256(header).hexdigest()+ NODE['node'][arch]['binarySha256'] = digest+ ENGINES['assets'][f'linux-{arch}'] = {'binarySha256': digest}+++def tar(files, mode, executable=()):+ out = io.BytesIO()+ with tarfile.open(fileobj=out, mode=mode) as archive:+ for name, content in files.items():+ entry = tarfile.TarInfo(name)+ entry.mode = 0o755 if name in executable else 0o644+ entry.size = len(content)+ archive.addfile(entry, io.BytesIO(content))+ return out.getvalue()+++def fixture(directory, arch, *, replace_payload=False, source=SHA, outer_changes=None, wrong_machine=False, foreign_node=False):+ target = LOCK['targets'][arch]+ profiles = target['platforms']+ rev = LOCK['revision']+ name = f'Motrix-{VERSION}-{rev}-dsm-{arch}.spk'+ receipt = dict(schemaVersion=2, architecture=arch, revision=rev, version=VERSION, sourceCommit=source,+ sourceDirty=False, minimumDsm=LOCK['dsmVersion'], nodeArchiveSha256=NODE['node'][arch]['sha256'],+ platforms=list(profiles), toolchainDigests={k: v['toolchain']['sha256'] for k, v in profiles.items()})+ header = bytearray(20)+ header[:6] = b'\x7fELF\x02\x01'+ header[18:20] = (0 if wrong_machine else target['machine']).to_bytes(2, 'little')+ files = {f: bytes(header) for f in ['runtime/bin/node', 'server/bin/aria2c', 'server/bin/motrix-finalize-fs', 'server/sqlite.node']}+ if foreign_node:+ files['runtime/bin/node'] += b'untrusted executable'+ elf = [{'file': f, 'sha256': hashlib.sha256(b).hexdigest()} for f, b in files.items()]+ app_exec = set(files) - {'server/sqlite.node'}+ for k,(blob,is_exec) in TEMPLATES.items():+ if k.startswith('app/'):+ name_in_app = k.removeprefix('app/')+ files[name_in_app] = blob+ if is_exec:+ app_exec.add(name_in_app)+ files['synology-build.json'] = json.dumps(receipt).encode()+ files['payload-sha256.json'] = json.dumps(+ {f: {'sha256': hashlib.sha256(b).hexdigest(), 'executable': f in app_exec} for f, b in files.items()}).encode()+ if replace_payload:+ files['runtime/bin/node'] += b'fixture changed after validation'+ payload = tar(files, 'w:gz', app_exec)+ outer = {k: v[0] for k,v in TEMPLATES.items() if not k.startswith('app/')}+ outer['INFO'] = pub.render_info(outer['INFO'],VERSION,rev,target.get('infoArch',' '.join(profiles)),payload)+ outer['package.tgz'] = payload+ outer.update(outer_changes or {})+ package = tar(outer,'w',{k for k,v in TEMPLATES.items() if v[1]})+ digest = hashlib.sha256(package).hexdigest()+ (directory / name).write_bytes(package)+ (directory / (name+'.sha256')).write_text(f'{digest} {name}\n')+ reports = {k: dict(architecture=arch, platform=k, cpuEmulation=target.get('cpu'), toolchainSha256=v['toolchain']['sha256'],+ loaded=dict(arch=arch, glibc=LOCK['glibc'], node='v'+NODE['nodeVersion'], sqlite='read-write-ok'), elf=elf)+ for k, v in profiles.items()}+ abi = directory / (name+'.abi.json')+ abi.write_text(json.dumps(dict(schemaVersion=3, architecture=arch, spkSha256=digest, platforms=reports)))+ return abi+++class PublicationTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ fixture(self.root, 'x64')+ self.arm = fixture(self.root, 'arm64')+ patcher = patch.object(pub, 'run', side_effect=lambda *args: json.dumps(LOCK if 'synology' in args[-1] else ENGINES if 'engine.lock' in args[-1] else NODE))+ patcher.start()+ self.addCleanup(patcher.stop)++ def verify(self):+ return pub.verify_bundle(self.root, VERSION, SHA)++ def test_self_consistent_foreign_node(self):+ fixture(self.root, 'arm64', foreign_node=True)+ with self.assertRaisesRegex(ValueError, 'binary differs'):+ self.verify()++ def test_exact_set(self):+ self.assertEqual([r['arch'] for r in self.verify()], ['x64', 'arm64'])++ def test_incomplete_platform_proof(self):+ doc = json.loads(self.arm.read_text())+ del doc['platforms']['armada37xx']+ self.arm.write_text(json.dumps(doc))+ with self.assertRaisesRegex(ValueError, 'ABI report'):+ self.verify()++ def test_wrong_source(self):+ fixture(self.root, 'arm64', source='b'*40)+ with self.assertRaisesRegex(ValueError, 'source'):+ self.verify()++ def test_modified_payload_with_new_outer_checksums(self):+ fixture(self.root, 'arm64', replace_payload=True)+ with self.assertRaisesRegex(ValueError, 'inventory'):+ self.verify()++ def test_modified_install_code_and_privilege_denied_with_consistent_digests(self):+ for name, data in [('scripts/postinst',b'#!/bin/sh\nexit 0'),('conf/privilege',b'{"defaults":{"run-as":"root"}}'),('unexpected',b'extra')]:+ with self.subTest(member=name):+ fixture(self.root, 'arm64', outer_changes={name:data})+ with self.assertRaisesRegex(ValueError, 'template|Unexpected'):+ self.verify()++ def test_wrong_elf_machine_denied_with_consistent_metadata(self):+ fixture(self.root, 'arm64', wrong_machine=True)+ with self.assertRaisesRegex(ValueError, 'Foreign ELF'):+ self.verify()++ def test_missing_architecture(self):+ self.arm.unlink()+ with self.assertRaisesRegex(ValueError, 'Both complete'):+ self.verify()+++if __name__ == '__main__':+ unittest.main()