A full-featured download manager.
chore(release): prepare 2.0.0-beta.29 (#2043)
Dr_rOot46c887749de4
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.ymlindex 0caeb02b..f804bd76 100644--- a/.github/workflows/flatpak.yml+++ b/.github/workflows/flatpak.yml@@ -303,7 +303,7 @@ jobs:-path "*/native-messaging-hosts/*" \\) -print -quit)"output="$("$aria2c" --version)"- printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.11"+ printf "%s\n" "$output" | grep -qF "aria2 version 1.37.0-motrix.12"printf "%s\n" "$output" | grep -qF "Async DNS"printf "%s\n" "$output" | grep -qF "BitTorrent"printf "%s\n" "$output" | grep -qF "HTTPS"@@ -427,7 +427,7 @@ jobs:native_host_hex="$(printf '\025\000\000\000%s' '{"allowLaunch":false}' |"$installed_companion" \- 'chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/' |+ 'chrome-extension://lggbokfckofcgjndaboioakcmincinpo/' |od -An -tx1 -v |tr -d ' \n')"diff --git a/README.md b/README.mdindex eb828343..1f9054f9 100644--- a/README.md+++ b/README.md@@ -22,8 +22,8 @@ The same core powers two ways to run Motrix:## 🧪 Beta testingMotrix Turbo v2 is currently in beta. After its remaining release gates pass,-download [v2.0.0-beta.28 from GitHub Releases](https://github.com/agalwood/Motrix/releases/tag/v2.0.0-beta.28)-and read the [full release notes](./docs/release-notes/2.0.0-beta.28.md) before+download [v2.0.0-beta.29 from GitHub Releases](https://github.com/agalwood/Motrix/releases/tag/v2.0.0-beta.29)+and read the [full release notes](./docs/release-notes/2.0.0-beta.29.md) beforeinstalling it.Back up your existing Motrix data and downloads before testing. Migration from@@ -68,7 +68,7 @@ account, machine, or Docker data directory.- 📊 Customizable Dashboard with transfer stats, live activity, and task tiles- 🔔 System notifications when downloads finish, plus an in-app notification center- 🧩 QuickJS-based plugin sandboxing, fine-grained permissions, and an in-app marketplace-- 🌐 Chrome and Firefox extensions that hand browser downloads off to Motrix in one click+- 🌐 [Motrix Extension](https://github.com/motrixapp/motrix-extension) for Chrome and Firefox hands browser downloads off to Motrix in one click- ⌨️ Official `@motrix/cli` client for everyday shell use and AI agents- 🐳 Docker-ready headless server with secure device-code pairing for remote CLI and agent clients- 🎬 Extensible URL Resolver plugins for extracting media from supported sites@@ -84,7 +84,7 @@ Motrix extends beyond the desktop app with a shared protocol library, command-li|---------|--------------|--------------|| [`@motrix/mdxp`](https://github.com/motrixapp/mdxp) | npm package | Defines the shared JSON-RPC 2.0 wire schemas and Zod types for MDXP, with helpers for bidirectional connections || [`@motrix/cli`](https://github.com/motrixapp/cli) | npm package | Provides the `motrix` command, automatically discovers a local desktop app, and pairs with remote instances |-| Motrix Browser Extension | Browser extension | Intercepts downloads in Chrome and Firefox (Manifest V3), hands them off to Motrix, and pairs securely with the desktop app over native messaging |+| [Motrix Extension](https://github.com/motrixapp/motrix-extension) | Browser extension | Intercepts downloads in Chrome and Firefox (Manifest V3), hands them off to Motrix, and pairs securely with the desktop app over native messaging || [Motrix Plugin SDK](https://github.com/motrixapp/plugin-sdk) | Four npm packages | Includes `@motrix/plugin-manifest-schema`, `@motrix/plugin-api`, `@motrix/plugin-cli`, and `create-motrix-plugin` for developing, testing, and packaging plugins || [Builtin Plugins](https://github.com/motrixapp/builtin-plugins) | Signed `.moext` packages | Includes three official plugins: **Filename Template** for renaming files from a template before they are saved, **Page Scraper** for extracting direct file links from HTML pages, and **URL Resolver** as the foundation for site-specific media resolution || Plugin Registry | Public JSON feed | Publishes plugin listings and install metadata at `dl.motrix.app/registry/plugins.json` for both the website and the in-app marketplace |@@ -165,7 +165,7 @@ downloaded resources:```bashmkdir -p motrix-data downloadssudo chown 1000:1000 motrix-data downloads-export MOTRIX_IMAGE='docker.io/motrixapp/motrix-server:2.0.0-beta.28'+export MOTRIX_IMAGE='docker.io/motrixapp/motrix-server:2.0.0-beta.29'export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'docker compose pull serverdocker compose up -d --waitdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex c7d5445c..488cfcc1 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -22,8 +22,8 @@ Motrix 是一款界面简洁、功能丰富的桌面下载管理器,可处理## 🧪 Beta 测试Motrix Turbo v2 目前仍处于 beta 阶段。剩余发布门禁通过后,请从 GitHub Releases-下载 [v2.0.0-beta.28](https://github.com/agalwood/Motrix/releases/tag/v2.0.0-beta.28),-并在安装前阅读[完整发布说明](./docs/release-notes/2.0.0-beta.28.zh-CN.md)。+下载 [v2.0.0-beta.29](https://github.com/agalwood/Motrix/releases/tag/v2.0.0-beta.29),+并在安装前阅读[完整发布说明](./docs/release-notes/2.0.0-beta.29.zh-CN.md)。测试前请备份现有 Motrix 数据和下载文件。Motrix v1 数据的迁移路径尚未经过验证,请勿让本 beta 使用您唯一一份 v1 数据。条件允许时,建议通过独立的系统@@ -66,7 +66,7 @@ Motrix Turbo v2 目前仍处于 beta 阶段。剩余发布门禁通过后,请- 📊 Dashboard 支持自定义布局,可展示传输统计、实时活动和任务磁贴- 🔔 下载完成时发送系统通知,应用内也可集中查看通知- 🧩 插件采用 QuickJS 沙箱隔离和细粒度能力授权,并可直接从应用内插件市场安装-- 🌐 Chrome 和 Firefox 扩展可一键将浏览器下载任务交给 Motrix+- 🌐 Chrome 和 Firefox 上的 [Motrix Extension](https://github.com/motrixapp/motrix-extension) 可一键将浏览器下载任务交给 Motrix- ⌨️ 官方命令行客户端 `@motrix/cli` 既适合日常操作,也可供 AI agent 调用- 🐳 Headless server 可通过 Docker 部署,远程 CLI 和 agent 可使用 device-code 安全配对- 🎬 URL Resolver 插件可解析站点媒体页面,并可扩展对更多站点的支持@@ -82,7 +82,7 @@ Motrix Turbo v2 目前仍处于 beta 阶段。剩余发布门禁通过后,请|------|------|------|| [`@motrix/mdxp`](https://github.com/motrixapp/mdxp) | npm 包 | 集中定义 MDXP 的 JSON-RPC 2.0 wire schema 和 Zod 类型,并提供双向连接工具,让通信两端使用同一套协议 || [`@motrix/cli`](https://github.com/motrixapp/cli) | npm 包 | 命令行客户端,可执行命令为 `motrix`。它能自动发现并控制本地桌面应用,也能与远程实例配对 |-| Motrix Browser Extension | 浏览器扩展 | 面向 Chrome 和 Firefox 的 MV3 扩展,可接管浏览器下载任务,并通过 native messaging 与桌面应用安全配对 |+| [Motrix Extension](https://github.com/motrixapp/motrix-extension) | 浏览器扩展 | 面向 Chrome 和 Firefox 的 MV3 扩展,可接管浏览器下载任务,并通过 native messaging 与桌面应用安全配对 || [Motrix Plugin SDK](https://github.com/motrixapp/plugin-sdk) | 4 个 npm 包 | 包括 `@motrix/plugin-manifest-schema`、`@motrix/plugin-api`、`@motrix/plugin-cli` 和 `create-motrix-plugin`,提供插件开发、调试和打包所需的工具 || [Builtin Plugins](https://github.com/motrixapp/builtin-plugins) | 已签名的 `.moext` | 官方提供三个内置插件:**Filename Template**(保存文件时按模板自动重命名)、**Page Scraper**(从 HTML 页面提取实际文件链接)和 **URL Resolver**(为站点媒体解析提供基础能力) || Plugin Registry | 公共数据源 | 维护插件列表和安装信息,并生成 `dl.motrix.app/registry/plugins.json`,供官网插件目录和应用内插件市场使用 |@@ -156,7 +156,7 @@ Beta 只发布不可变的版本 tag,不会更新 `latest`;仓库的 `compos```bashmkdir -p motrix-data downloadssudo chown 1000:1000 motrix-data downloads-export MOTRIX_IMAGE='docker.io/motrixapp/motrix-server:2.0.0-beta.28'+export MOTRIX_IMAGE='docker.io/motrixapp/motrix-server:2.0.0-beta.29'export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'docker compose pull serverdocker compose up -d --waitdiff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 6e12062f..9292431d 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -83,8 +83,8 @@ must obtain permission or replace the font before distributing the build.Desktop builds bundle an `aria2c` executable pinned by`scripts/engine.lock.json`:-- **Version:** 1.37.0-motrix.11-- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.11>+- **Version:** 1.37.0-motrix.12+- **Source:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.12>- **License:** GNU General Public License v2.0 or later (`GPL-2.0-or-later`)- **Full license text:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL exception / notice:**diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.mdindex 62a52cd5..0250bc54 100644--- a/THIRD_PARTY_NOTICES.zh-CN.md+++ b/THIRD_PARTY_NOTICES.zh-CN.md@@ -71,8 +71,8 @@ src/renderer/routes/settings/icons/[email protected]桌面版随应用打包 `aria2c` 可执行文件,版本由 `scripts/engine.lock.json` 固定:-- **版本:** 1.37.0-motrix.11-- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.11>+- **版本:** 1.37.0-motrix.12+- **对应源码:** <https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.12>- **许可证:** GNU General Public License v2.0 or later(`GPL-2.0-or-later`)- **完整许可证文本:** `THIRD_PARTY_LICENSES/aria2-COPYING`- **OpenSSL 例外条款 / 声明:**diff --git a/docs/bridge-pairing-protocol-vectors.json b/docs/bridge-pairing-protocol-vectors.jsonindex d25dc5ff..1a45d26f 100644--- a/docs/bridge-pairing-protocol-vectors.json+++ b/docs/bridge-pairing-protocol-vectors.json@@ -12,8 +12,8 @@"codeNormalized": "MTX7K2Q9","pairNonce": "vec-nonce-8f3a1c5e7b2d4a90","browser": "chromium",- "verifiedOrigin": "chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi",- "claimedExtensionId": "ibpkjhgpbidfmbmomagmldcdlpbmchgi",+ "verifiedOrigin": "chrome-extension://lggbokfckofcgjndaboioakcmincinpo",+ "claimedExtensionId": "lggbokfckofcgjndaboioakcmincinpo","clientInstallationId": "5f0b6f9e-8a3d-4c5e-9b2a-7d1e4f6a8c0b","instanceId": "0d9c2b7a-4e6f-4a1b-8c3d-2e5f7a9b1c4d","x": "0338620bd18bc1b03c41f70e111cc55da580e334813857a12a27217e1f268561",@@ -23,26 +23,26 @@"intermediate": {"scryptOutput": "fc4d0c833ae57e13e602333e0c7e3bc5aece387ef1ed853edccbf8059d334fa5bd11e785efe4a7456a91143c40ec9947b6a4387dc007af234179d41dd69e0f7b","w": "030955c2809b06563fa6991f9657d84ca270df221d810fdeab4a02e386f3a7d6",- "aId": "09000000000000004d4250312f412f763108000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6962706b6a686770626964666d626d6f6d61676d6c6463646c70626d6368676920000000000000006962706b6a686770626964666d626d6f6d61676d6c6463646c70626d63686769240000000000000035663062366639652d386133642d346335652d396232612d376431653466366138633062",+ "aId": "09000000000000004d4250312f412f763108000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f20000000000000006c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f240000000000000035663062366639652d386133642d346335652d396232612d376431653466366138633062","bId": "09000000000000004d4250312f422f76310d000000000000006d6f747269782d627269646765240000000000000030643963326237612d346536662d346131622d386333642d326535663761396231633464","bindingPub": "fd64b13bcbdd3fcaaac3953f6212c769495003162d404066e119f5fcc1551173",- "ticketDigest": "6cbcc5cad1addb2dd6ebb6b7390fefd289a8979b684d7fee97bd003ecc8a11dd",- "aad": "000000011a000000000000007665632d6e6f6e63652d386633613163356537623264346139302000000000000000fd64b13bcbdd3fcaaac3953f6212c769495003162d404066e119f5fcc155117320000000000000006cbcc5cad1addb2dd6ebb6b7390fefd289a8979b684d7fee97bd003ecc8a11dd"+ "ticketDigest": "25a6ab235704ff9d5d707e9d6d52b5fa16c062596c828e654747b2c8b310ff0b",+ "aad": "000000011a000000000000007665632d6e6f6e63652d386633613163356537623264346139302000000000000000fd64b13bcbdd3fcaaac3953f6212c769495003162d404066e119f5fcc1551173200000000000000025a6ab235704ff9d5d707e9d6d52b5fa16c062596c828e654747b2c8b310ff0b"},"expected": {"pA": "4376c5f717876c87d7c8699e41da8e91a08a31834489d537e299649415b0d272","pB": "138d71989e96d8871d8e9dcfdf0d8d0bc540b77c301c5b9753b65b2fb69588f7","K": "6b35b41137942fafeb209fb808786b24f8c952b9c1a69754b5df3ac2038b42b4",- "TT": "b00000000000000009000000000000004d4250312f412f763108000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6962706b6a686770626964666d626d6f6d61676d6c6463646c70626d6368676920000000000000006962706b6a686770626964666d626d6f6d61676d6c6463646c70626d63686769240000000000000035663062366639652d386133642d346335652d396232612d376431653466366138633062520000000000000009000000000000004d4250312f422f76310d000000000000006d6f747269782d627269646765240000000000000030643963326237612d346536662d346131622d386333642d32653566376139623163346420000000000000004376c5f717876c87d7c8699e41da8e91a08a31834489d537e299649415b0d2722000000000000000138d71989e96d8871d8e9dcfdf0d8d0bc540b77c301c5b9753b65b2fb69588f720000000000000006b35b41137942fafeb209fb808786b24f8c952b9c1a69754b5df3ac2038b42b42000000000000000030955c2809b06563fa6991f9657d84ca270df221d810fdeab4a02e386f3a7d6",- "Ke": "34b8bb82b3afda9adb6a4a6aa562e181",- "Ka": "2aa9c8b9003fd06f54906f2287378107",- "KcA": "a7c63c598c280187336f7c6e2d1b54c9",- "KcB": "bcc1377e655fe466690e0960e297a211",- "cA": "66e8d23114d6717d08e48fc4d1fd1dd93186a82e31512f39bf07d41782b9182d",- "cB": "2261cb6da620f4982cf66cac8d38049dcfaff7d127fa255482830d9e6b73546c",- "ticketProof": "2d232ce6318a9bff5654dbf760d0091b20a78cfac56c6ca24178a197805d5ea658f1ca4a0a04cac8037a14d846a723a3f881d0212c560d03c2f888d3973f3502",- "trafficC2S": "248ff17bacfa39ebe2bbb851d552f9185924303c42a41da3f1ebbbfec70be692",- "trafficS2C": "b595581934dfe69513ed1b0814de366512bbb819d762d2a0338cc80683c361a2"+ "TT": "b00000000000000009000000000000004d4250312f412f763108000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f20000000000000006c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f240000000000000035663062366639652d386133642d346335652d396232612d376431653466366138633062520000000000000009000000000000004d4250312f422f76310d000000000000006d6f747269782d627269646765240000000000000030643963326237612d346536662d346131622d386333642d32653566376139623163346420000000000000004376c5f717876c87d7c8699e41da8e91a08a31834489d537e299649415b0d2722000000000000000138d71989e96d8871d8e9dcfdf0d8d0bc540b77c301c5b9753b65b2fb69588f720000000000000006b35b41137942fafeb209fb808786b24f8c952b9c1a69754b5df3ac2038b42b42000000000000000030955c2809b06563fa6991f9657d84ca270df221d810fdeab4a02e386f3a7d6",+ "Ke": "f5bf4860d9ca8e129551e85b20b1b6fa",+ "Ka": "e11ae0f14bfc92f607247448498fa604",+ "KcA": "e3cffbce15b8d35a7e043fb604484ee5",+ "KcB": "bd2bb250da98733afd060d0eb656ca3c",+ "cA": "03c1f81430af1bf4766d81a1f6a8fed50f28b26d295c5f76f68665918e099151",+ "cB": "ba6e95f658469131fc0c65458a1c09da7df482677604e49a5843d1760d90362f",+ "ticketProof": "07852b5a6fa3883de8e00c57abb1a92d20b97fcb143baadb9d4e9c590d74af0191388d4ac2e67f1c8cd820b6380e9ca05ffdf20dd3d035891432e631c6c2a00c",+ "trafficC2S": "ca806459e7b94b411bc9ff7c9a08b71de92f63aac552b2ef6039bba00d9d046f",+ "trafficS2C": "4f5ab45bec9db3a3459ca90d7302bc649ed8f0e0926c6e129c63a4904bb8e3dd"}},{@@ -54,11 +54,11 @@"aad": "000000011a000000000000007665632d6e6f6e63652d3866336131633565376232643461393000000000000000000000000000000000"},"expected": {- "TT": "b00000000000000009000000000000004d4250312f412f763108000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6962706b6a686770626964666d626d6f6d61676d6c6463646c70626d6368676920000000000000006962706b6a686770626964666d626d6f6d61676d6c6463646c70626d63686769240000000000000035663062366639652d386133642d346335652d396232612d376431653466366138633062520000000000000009000000000000004d4250312f422f76310d000000000000006d6f747269782d627269646765240000000000000030643963326237612d346536662d346131622d386333642d32653566376139623163346420000000000000004376c5f717876c87d7c8699e41da8e91a08a31834489d537e299649415b0d2722000000000000000138d71989e96d8871d8e9dcfdf0d8d0bc540b77c301c5b9753b65b2fb69588f720000000000000006b35b41137942fafeb209fb808786b24f8c952b9c1a69754b5df3ac2038b42b42000000000000000030955c2809b06563fa6991f9657d84ca270df221d810fdeab4a02e386f3a7d6",- "KcA": "de6f99e25fc759c6450ffa20c68b9b09",- "KcB": "f4818bdb1c193105a143792e3afe2dd8",- "cA": "4f5b21aa75a995359c18c9ccfff2f73e376fc01a5a181b5ae8f493051bf47e25",- "cB": "46bcc0ed7aaa4c12dcd58ef27bd78b03287fdb89cb2d2dc0f22afbbe1ba8e985"+ "TT": "b00000000000000009000000000000004d4250312f412f763108000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f20000000000000006c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f240000000000000035663062366639652d386133642d346335652d396232612d376431653466366138633062520000000000000009000000000000004d4250312f422f76310d000000000000006d6f747269782d627269646765240000000000000030643963326237612d346536662d346131622d386333642d32653566376139623163346420000000000000004376c5f717876c87d7c8699e41da8e91a08a31834489d537e299649415b0d2722000000000000000138d71989e96d8871d8e9dcfdf0d8d0bc540b77c301c5b9753b65b2fb69588f720000000000000006b35b41137942fafeb209fb808786b24f8c952b9c1a69754b5df3ac2038b42b42000000000000000030955c2809b06563fa6991f9657d84ca270df221d810fdeab4a02e386f3a7d6",+ "KcA": "8da95d959cbd9f70d5cb401be8d435ba",+ "KcB": "8f55db73a54dda0196a14c244d2132a3",+ "cA": "86f9c83872be0408eca9269519f91587ccf534d51659da3ba717eb1540fa48d6",+ "cB": "62081f9b9dcd1048c952cfb1fca710a734815a93692b1d59d658e26f68811127"}}],@@ -83,15 +83,15 @@"mutualKey": "a3b1c5d7e9f0a2b4c6d8e0f1a3b5c7d9e1f0a2c4b6d8e0f2a4b6c8d0e2f4a6b8","credentialId": "9e8d7c6b-5a49-4838-a2b1-c0d9e8f7a6b5","browser": "chromium",- "verifiedOrigin": "chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi",+ "verifiedOrigin": "chrome-extension://lggbokfckofcgjndaboioakcmincinpo","instanceId": "0d9c2b7a-4e6f-4a1b-8c3d-2e5f7a9b1c4d","S": "5a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9","C": "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"},"expected": {- "RT": "11000000000000004d4250312f7265636f6e6e6563742f763100000001240000000000000039653864376336622d356134392d343833382d613262312d63306439653866376136623508000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6962706b6a686770626964666d626d6f6d61676d6c6463646c70626d63686769240000000000000030643963326237612d346536662d346131622d386333642d326535663761396231633464",- "macClient": "411e75c3111b2b01a7b2026483c8eca60b5774ff865c9e1710abb4cd2092223f",- "macServer": "cb9e88d0c47c78383ebbc298440f4d7e22b27ba745815c793b6c213eca49e410",+ "RT": "11000000000000004d4250312f7265636f6e6e6563742f763100000001240000000000000039653864376336622d356134392d343833382d613262312d63306439653866376136623508000000000000006368726f6d69756d33000000000000006368726f6d652d657874656e73696f6e3a2f2f6c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f240000000000000030643963326237612d346536662d346131622d386333642d326535663761396231633464",+ "macClient": "2020552f9e52a0ebd6d731d0c10240401f30b33ce94b6e968550a064a6ff4f62",+ "macServer": "09ce136486b73b92ac1789e9f44507e6552390b74db4ab1dd614c5a606484a06","trafficC2S": "e9869b90256c460b6aa4db4db38c9f9943c3de7ff3be4ff44e8b818c3b42155b","trafficS2C": "efd391ff3b3078d3b066bfd4dd816d6f17b90b8c04e9605474e82f52c427e057"}@@ -102,15 +102,15 @@"localToken": "vector-local-token-0123456789abcdef","serverGeneration": "3c2b1a09-8f7e-4d6c-b5a4-93827160f0e1","browser": "chromium",- "callerId": "ibpkjhgpbidfmbmomagmldcdlpbmchgi",+ "callerId": "lggbokfckofcgjndaboioakcmincinpo","exp": 1755600000,"bindingPub": "fd64b13bcbdd3fcaaac3953f6212c769495003162d404066e119f5fcc1551173"},"expected": {"ticketKey": "9238e0993a8d4f79617696cbb627e23b26e3ab0c84a7258cf2b7d0e8889f2169",- "canonical": "10000000000000006d6270312d6174746573746174696f6e0000000100000001240000000000000033633262316130392d386637652d346436632d623561342d39333832373136306630653108000000000000006368726f6d69756d20000000000000006962706b6a686770626964666d626d6f6d61676d6c6463646c70626d636867690000000068a454802000000000000000fd64b13bcbdd3fcaaac3953f6212c769495003162d404066e119f5fcc1551173",- "mac": "df162b79b6b77417d2ffbace670fb5f36d91cac485e982a575c1ff0698355f6d",- "ticketDigest": "6cbcc5cad1addb2dd6ebb6b7390fefd289a8979b684d7fee97bd003ecc8a11dd"+ "canonical": "10000000000000006d6270312d6174746573746174696f6e0000000100000001240000000000000033633262316130392d386637652d346436632d623561342d39333832373136306630653108000000000000006368726f6d69756d20000000000000006c6767626f6b66636b6f6663676a6e6461626f696f616b636d696e63696e706f0000000068a454802000000000000000fd64b13bcbdd3fcaaac3953f6212c769495003162d404066e119f5fcc1551173",+ "mac": "20078e145d32415fe0ae070cd0d8d860f067c4989ba166bf3a18acdc9b0cf328",+ "ticketDigest": "25a6ab235704ff9d5d707e9d6d52b5fa16c062596c828e654747b2c8b310ff0b"},"mustReject": [{@@ -140,7 +140,7 @@},{"case": "ticketProof with S >= ell (S malleated by + ell)",- "signature": "2d232ce6318a9bff5654dbf760d0091b20a78cfac56c6ca24178a197805d5ea645c5c0a72467dc20da160c7b25a102b8f881d0212c560d03c2f888d3973f3512",+ "signature": "07852b5a6fa3883de8e00c57abb1a92d20b97fcb143baadb9d4e9c590d74af017e0c83a7dc4992746275185917087bb55ffdf20dd3d035891432e631c6c2a01c","reason": "RFC 8032 strict (zip215:false) rejects S >= ell"},{@@ -157,16 +157,16 @@},"envelope": {"inputs": {- "keyC2S": "248ff17bacfa39ebe2bbb851d552f9185924303c42a41da3f1ebbbfec70be692",- "keyS2C": "b595581934dfe69513ed1b0814de366512bbb819d762d2a0338cc80683c361a2",+ "keyC2S": "ca806459e7b94b411bc9ff7c9a08b71de92f63aac552b2ef6039bba00d9d046f",+ "keyS2C": "4f5ab45bec9db3a3459ca90d7302bc649ed8f0e0926c6e129c63a4904bb8e3dd","aad": "MBP1/env/v1","plaintext0": "7b226a736f6e727063223a22322e30222c226964223a312c226d6574686f64223a226d6f747269782f696e697469616c697a65222c22706172616d73223a7b7d7d","plaintext1": "7b226a736f6e727063223a22322e30222c226964223a312c22726573756c74223a7b226f6b223a747275657d7d"},"expected": {- "frameC2S_seq0": "00000000000000003daa0ef6eebb730232c61a0e08a00e91b026e6dec7af011db8119962c7d928fdb78c5565c8c0e906868397da672a656826cd18aacd5e75dd768ac33387c6dd7ce5fea94332db95d7b5ceb265acedec4199",- "frameS2C_seq0": "0000000000000000191f552f87bb4ac78b464c2f07663454296bbed573e0e5c3d4fb22fb7f9a66a80033ac7966ed1a8f726e27c61c807f991ec6f85fb2b0e5f82d6e0c8879",- "frameC2S_seq1": "0000000000000001555f45a1e8cbdab1eb483bac32c47d48002b13be2c9f10d2c0b7a1a39896b932ff180a3acc5696d9461e9451e9253d611caa0d21dbe3d4b86ad01d7b82"+ "frameC2S_seq0": "000000000000000071346e360b7bee7ebb7143a1304ada0daf05ed2f20bb74fda401f4d62b8cc184845fe915fcafbae373e032338c1a794d0a38c482bf7fd29786c87db443b3db094c6cee3202f954e9f2c13d1a39b822b7ad",+ "frameS2C_seq0": "00000000000000006084668772e97be7bfbd479a52e2f4132b90d4c74ef913166aac704ad8b1ae7442ba284d88057bff1b7d5c1313f230019b7de4306505b318d8a300dbe1",+ "frameC2S_seq1": "00000000000000013547d035761556229385117521feeff8f3784fa5a298d744591bb7152470f70ee1f68766cfdb87e4939fffbfd394fe71197adfc00e00d76989f55fef1d"},"mustReject": [{diff --git a/docs/release-notes/2.0.0-beta.29.md b/docs/release-notes/2.0.0-beta.29.mdnew file mode 100644index 00000000..558f8970--- /dev/null+++ b/docs/release-notes/2.0.0-beta.29.md@@ -0,0 +1,125 @@+# Motrix 2.0.0-beta.29++English | [简体中文](https://github.com/agalwood/Motrix/blob/v2.0.0-beta.29/docs/release-notes/2.0.0-beta.29.zh-CN.md)++Motrix 2.0.0-beta.29 introduces the secure Motrix Extension control plane,+brings the Desktop and Server application APIs to parity, adds a durable plugin+hook runtime, and updates the bundled aria2 engine. It is intended for public+distribution only after every protected release gate passes.++## Highlights++- [Motrix Extension](https://github.com/motrixapp/motrix-extension) can pair+ with the desktop app through Native Messaging and MBP1. The reviewed protocol+ uses a short pairing code, encrypted WebSocket envelopes, durable credentials,+ bounded retries, and explicit revocation. The official Chrome, Edge, and+ Firefox identities are aligned across manifests, test vectors, and runtime+ policy. Development builds also keep their Native Messaging host attached to+ the isolated development profile+ ([#2021](https://github.com/agalwood/Motrix/pull/2021)).+- Headless Server deployments can explicitly enable Motrix Extension pairing+ over a configured WS/WSS address. Admission, origin, route, process-ownership,+ and TLS policies keep the remote surface disabled unless the operator opts in;+ the release path includes compatibility, threat-evidence, integration, and+ soak checks+ ([#2033](https://github.com/agalwood/Motrix/pull/2033)).+- Desktop and Server now share host-neutral application command and query+ implementations. The browser UI gains multi-torrent parsing and queues, while+ bridge, plugin, file-selection, proxy, and task-management behavior is aligned+ across both hosts. Server operators can also opt into authenticated external+ aria2 RPC access while loopback remains the default+ ([#2008](https://github.com/agalwood/Motrix/pull/2008),+ [#2037](https://github.com/agalwood/Motrix/pull/2037)).+- Plugins can run typed pre- and post-download hooks with staged effects,+ durable post-delivery work, startup recovery, and crash-safe finalization.+ Desktop and Server use the same runtime, and the cross-platform finalization+ helper preserves the required filesystem ordering on Windows and Unix+ ([#2038](https://github.com/agalwood/Motrix/pull/2038)).+- Bundled aria2 is updated to `1.37.0-motrix.12`, with every supported archive+ and binary pinned by SHA-256. WebSocket RPC startup and parallel-response+ contracts are covered end to end, sparse native RPC diagnostics are promoted+ into the application log, and trust-store handling is more defensive+ ([#2032](https://github.com/agalwood/Motrix/pull/2032)).+- Native Messaging and Flatpak integration is hardened with owner-only+ development metadata, stricter caller and filesystem validation, bounded+ broker processes, atomic companion installation, and safer cleanup. The+ Flatpak companion remains the only host-side process and continues to reach+ the sandboxed bridge through its broker boundary.+- Redirected downloads preserve their intended filename through proxies,+ tracker synchronization follows the selected proxy, system proxy discovery+ runs in an isolated session, global connection options reach newly created+ tasks, and FFmpeg is resolved immediately before media muxing+ ([#2006](https://github.com/agalwood/Motrix/pull/2006),+ [#2013](https://github.com/agalwood/Motrix/pull/2013),+ [#2019](https://github.com/agalwood/Motrix/pull/2019),+ [#2022](https://github.com/agalwood/Motrix/pull/2022)).+- Desktop fixes cover stale default save directories, unavailable Downloads+ folders, Windows shortcut and maximized-window restoration, marquee selection,+ clearer pairing prompts, consistent Settings terminology, a wider peer-address+ column, and cleanup of ephemeral media-segment tasks after completion or failure+ ([#2014](https://github.com/agalwood/Motrix/pull/2014),+ [#2016](https://github.com/agalwood/Motrix/pull/2016),+ [#2023](https://github.com/agalwood/Motrix/pull/2023),+ [#2030](https://github.com/agalwood/Motrix/pull/2030),+ [#2036](https://github.com/agalwood/Motrix/pull/2036),+ [#2039](https://github.com/agalwood/Motrix/issues/2039),+ [#2041](https://github.com/agalwood/Motrix/pull/2041)).++## Before testing++This is prerelease software. Back up existing Motrix application data and+downloads before installing it. Migration from Motrix v1 data has not yet been+validated, so do not use your only copy of v1 data with this beta.++When practical, test v2 in parallel using a separate OS account, machine, or+Docker data directory. Pay particular attention to first-time and reconnecting+Motrix Extension pairing, remote Extension pairing behind your TLS reverse+proxy, plugin hooks across restart or interrupted finalization, browser-based+torrent creation, concurrent aria2 RPC traffic, proxied redirects, and Native+Messaging registration on your platform.++After the protected release completes, Snap testers can install the strictly+confined build with `sudo snap install motrix --edge`. Existing installations+tracking `latest/edge` should upgrade to the same beta.29 revision set.++## Planned downloads after release gates pass++| Distribution | Architectures | Planned output |+|--------------|---------------|----------------|+| macOS 12 or later | `arm64` (Apple Silicon), `x64` (Intel) | DMG and ZIP |+| Windows | `x64` | Unsigned NSIS installer (`.exe`) and ZIP |+| Linux | `x64`, `arm64` | AppImage, DEB, and RPM |+| Flatpak Native Host companion | `linux/x64`, `linux/arm64` | `Motrix-Native-Host-2.0.0-beta.29-linux-<arch>.tar.gz` |+| Docker Hub / GHCR | `linux/amd64`, `linux/arm64` | Immutable `2.0.0-beta.29` tag in both registries |+| Snap Store | `amd64`, `arm64` | Verified build set on `latest/edge` |++After every container gate passes, the versioned image references will be+`docker.io/motrixapp/motrix-server:2.0.0-beta.29` and+`ghcr.io/agalwood/motrix-server:2.0.0-beta.29`. See the+[Docker Server deployment guide](https://github.com/agalwood/Motrix/blob/v2.0.0-beta.29/docs/docker-server.md)+for storage, networking, remote Extension pairing, and upgrade guidance.++## Distribution notes++- AppImage desktop integration is opt-in and confined to the current user's+ XDG data directory. Browser-extension hand-off is not yet available from the+ AppImage package because its Native Messaging host does not have a stable+ path outside the mounted image.+- Flatpak is validated separately and is not published by the release tag; the+ GitHub prerelease includes its Native Host companion archives.+- Windows `arm64` and all 32-bit packages are not available.+- Windows packages are unsigned and may trigger a Windows SmartScreen warning.+ Download them only from the official GitHub prerelease after it is published.+- Beta container tags are immutable and do not update `latest`, `stable`, or+ other stable floating tags.+- The Snap package is strictly confined. Its approved `personal-files`+ interface is limited to registering Native Messaging host manifests for+ supported browsers. Beta publication updates `latest/edge` only; it does not+ promote the build to `candidate` or `stable`.++## Feedback++Please report reproducible problems through+[GitHub Issues](https://github.com/agalwood/Motrix/issues). Include your+operating system, architecture, package type, and the steps needed to reproduce+the issue.diff --git a/docs/release-notes/2.0.0-beta.29.zh-CN.md b/docs/release-notes/2.0.0-beta.29.zh-CN.mdnew file mode 100644index 00000000..6306f8a5--- /dev/null+++ b/docs/release-notes/2.0.0-beta.29.zh-CN.md@@ -0,0 +1,108 @@+# Motrix 2.0.0-beta.29++[English](https://github.com/agalwood/Motrix/blob/v2.0.0-beta.29/docs/release-notes/2.0.0-beta.29.md) | 简体中文++Motrix 2.0.0-beta.29 引入了安全的 Motrix Extension 控制平面,补齐了+Desktop 与 Server 的应用 API,加入可持久化的插件 hook runtime,并更新+内置 aria2 引擎。只有在所有受保护发布门禁通过后,本版本才适合+公开分发。++## 主要改进++- [Motrix Extension](https://github.com/motrixapp/motrix-extension) 现可通过+ Native Messaging 和 MBP1 与桌面应用配对。经过审查的协议使用短配对码、+ 加密 WebSocket envelope、可持久化凭据、有界重试与显式撤销。Chrome、+ Edge 和 Firefox 的官方身份已在 manifest、测试向量与 runtime 策略中+ 对齐;开发构建的 Native Messaging host 也会跟随独立的开发数据目录+ ([#2021](https://github.com/agalwood/Motrix/pull/2021))。+- Headless Server 可显式开启 Motrix Extension,并通过配置的 WS/WSS 地址+ 完成配对。远程入口在 operator 主动开启前保持关闭,并由接入、origin、+ route、进程所有权与 TLS 策略共同约束;发布流程还包含兼容性、威胁证据、+ 集成与 soak 检查+ ([#2033](https://github.com/agalwood/Motrix/pull/2033))。+- Desktop 与 Server 现共用 host-neutral 的应用 command 和 query 实现。浏览器+ UI 新增多 torrent 解析与队列,bridge、插件、文件选择、代理和任务管理+ 在两个 host 间保持一致。Server operator 还可选择开启带认证的对外 aria2+ RPC,loopback 仍是默认选项+ ([#2008](https://github.com/agalwood/Motrix/pull/2008)、+ [#2037](https://github.com/agalwood/Motrix/pull/2037))。+- 插件现可运行强类型的下载前置与后置 hook,支持 staged effect、可持久化+ 后处理、启动恢复和抗崩溃收尾。Desktop 与 Server 使用同一套 runtime,+ 跨平台收尾工具则在 Windows 和 Unix 上保持必要的文件系统操作顺序+ ([#2038](https://github.com/agalwood/Motrix/pull/2038))。+- 内置 aria2 升级到 `1.37.0-motrix.12`,全部受支持 archive 与 binary 均按+ SHA-256 锁定。WebSocket RPC 启动与并发响应契约现有端到端测试覆盖,+ 少量原生 RPC 诊断会进入应用日志,trust store 处理也更稳健+ ([#2032](https://github.com/agalwood/Motrix/pull/2032))。+- Native Messaging 与 Flatpak 集成进一步加固:开发配置限于 owner 读写,+ caller 和文件系统验证更严格,broker 进程受到时限约束,companion 使用+ 原子安装与更安全的清理。Flatpak companion 仍是唯一的 host-side 进程,+ 并继续通过 broker 边界访问沙箱中的 bridge。+- 代理下的重定向下载现会保留预期文件名,Tracker 同步遵循当前代理,+ 系统代理探测在隔离 session 中运行,全局连接选项会传给新建任务,FFmpeg+ 在 media mux 前即时解析+ ([#2006](https://github.com/agalwood/Motrix/pull/2006)、+ [#2013](https://github.com/agalwood/Motrix/pull/2013)、+ [#2019](https://github.com/agalwood/Motrix/pull/2019)、+ [#2022](https://github.com/agalwood/Motrix/pull/2022))。+- 桌面端修复包括过期的默认保存目录、不可用的 Downloads 路径、Windows 快捷方式与+ 最大化窗口恢复、框选稳定性、更清晰的配对提示、统一的“设置”文案、更宽的+ peer 地址列,以及完成或失败后对临时 media segment 任务的清理+ ([#2014](https://github.com/agalwood/Motrix/pull/2014)、+ [#2016](https://github.com/agalwood/Motrix/pull/2016)、+ [#2023](https://github.com/agalwood/Motrix/pull/2023)、+ [#2030](https://github.com/agalwood/Motrix/pull/2030)、+ [#2036](https://github.com/agalwood/Motrix/pull/2036)、+ [#2039](https://github.com/agalwood/Motrix/issues/2039)、+ [#2041](https://github.com/agalwood/Motrix/pull/2041))。++## 测试前须知++这是预发布软件。安装前请备份现有 Motrix 应用数据和下载文件。Motrix v1 数据的+迁移路径尚未经过验证,请勿让本 beta 使用您唯一的一份 v1 数据。++条件允许时,请使用独立的操作系统账号、设备或 Docker 数据目录并行测试 v2。+请重点检查 Motrix Extension 首次配对与重连、TLS 反向代理后的远程扩展配对、+重启或收尾中断前后的插件 hook、浏览器端 torrent 新建、并发 aria2 RPC 流量、+代理重定向,以及对应平台的 Native Messaging 注册。++受保护发布完成后,Snap 测试者可使用+`sudo snap install motrix --edge` 安装严格限制的构建。已跟踪+`latest/edge` 的安装应升级到同一组 beta.29 revision。++## 发布门禁通过后计划提供的下载++| 分发方式 | 架构 | 计划产物 |+|---------|------|---------|+| macOS 12 或更高版本 | `arm64`(Apple Silicon)、`x64`(Intel) | DMG 和 ZIP |+| Windows | `x64` | 未签名 NSIS 安装程序(`.exe`)和 ZIP |+| Linux | `x64`、`arm64` | AppImage、DEB 和 RPM |+| Flatpak Native Host companion | `linux/x64`、`linux/arm64` | `Motrix-Native-Host-2.0.0-beta.29-linux-<arch>.tar.gz` |+| Docker Hub / GHCR | `linux/amd64`、`linux/arm64` | 两个仓库中的不可变 `2.0.0-beta.29` 标签 |+| Snap Store | `amd64`、`arm64` | `latest/edge` 上的已验证构建集 |++所有容器门禁通过后,可使用以下带版本镜像:+`docker.io/motrixapp/motrix-server:2.0.0-beta.29` 和+`ghcr.io/agalwood/motrix-server:2.0.0-beta.29`。存储、网络、远程 Extension 配对与升级说明+请参阅 [Docker Server 部署指南](https://github.com/agalwood/Motrix/blob/v2.0.0-beta.29/docs/docker-server.zh-CN.md)。++## 分发说明++- AppImage 桌面集成需要用户主动启用,且只会写入当前用户的 XDG 数据目录。由于+ Native Messaging host 在挂载镜像之外没有稳定路径,浏览器扩展暂时无法向+ AppImage 安装包转交下载任务。+- Flatpak 单独验证,不由 release tag 发布;GitHub 预发布版会包含它的+ Native Host companion 压缩包。+- 不提供 Windows `arm64` 和所有 32 位安装包。+- Windows 安装包未签名,可能触发 Windows SmartScreen 警告。请仅从已发布的+ 官方 GitHub 预发布版下载。+- Beta 容器标签不可变,也不会更新 `latest`、`stable` 或其他稳定通道+ 浮动标签。+- Snap 安装包使用严格限制。已批准的 `personal-files` interface 仅用于为支持的+ 浏览器注册 Native Messaging host manifest。Beta 发布只会更新+ `latest/edge`,不会把构建晋级到 `candidate` 或 `stable`。++## 反馈++如遇到可复现问题,请通过 [GitHub Issues](https://github.com/agalwood/Motrix/issues)+反馈,并附上操作系统、架构、安装包类型和复现步骤。diff --git a/e2e/bridge/remote-extension-compatibility.json b/e2e/bridge/remote-extension-compatibility.jsonindex 6a447fdd..1068aca3 100644--- a/e2e/bridge/remote-extension-compatibility.json+++ b/e2e/bridge/remote-extension-compatibility.json@@ -7,7 +7,7 @@},"motrix": {"repository": "motrix-app",- "commit": "45fd67e35c27396ae1fb091970852880d8cc9102"+ "commit": "1b51c8fc1d24305d6075ea501274585343bbb269"},"e2e": {"browserCases": 5,diff --git a/flatpak/app.motrix.native.metainfo.xml b/flatpak/app.motrix.native.metainfo.xmlindex af5e1279..587510a7 100644--- a/flatpak/app.motrix.native.metainfo.xml+++ b/flatpak/app.motrix.native.metainfo.xml@@ -76,6 +76,16 @@<releases><!-- Update this list on every release; Flathub linter requires the mostrecent version listed here to match the manifest's source tag. -->+ <release version="2.0.0-beta.29" date="2026-09-02">+ <description>+ <p>+ Adds secure local and remote Motrix Extension pairing, completes+ Desktop and Server RPC parity, and introduces durable plugin hook+ execution and crash-safe finalization. This release also updates the+ bundled aria2 engine and hardens Native Messaging integration.+ </p>+ </description>+ </release><release version="2.0.0-beta.28" date="2026-08-28"><description><p>diff --git a/flatpak/app.motrix.native.yml b/flatpak/app.motrix.native.ymlindex 0fb7475b..fc3b59bd 100644--- a/flatpak/app.motrix.native.yml+++ b/flatpak/app.motrix.native.yml@@ -101,7 +101,7 @@ modules:set -eoutput="$(src/aria2c --version)"printf '%s\n' "$output"- printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.11'+ printf '%s\n' "$output" | grep -qF 'aria2 version 1.37.0-motrix.12'for feature in \'Async DNS' \'BitTorrent' \@@ -123,8 +123,8 @@ modules:sources:- type: giturl: https://github.com/motrixapp/aria2.git- tag: v1.37.0-motrix.11- commit: ab003d49360bac776ada3e967821410f527c00a6+ tag: v1.37.0-motrix.12+ commit: c9143bbf9c16f8c8563e41e7da2a23face4d5a8cx-checker-data:type: gittag-pattern: ^v([\d.]+-motrix\.\d+)$@@ -136,9 +136,9 @@ modules:commands:- |sed -i -E \- 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.11]/' \+ 's/AC_INIT\(\[aria2\],\[[^]]+\]/AC_INIT([aria2],[1.37.0-motrix.12]/' \configure.ac- grep -qF 'AC_INIT([aria2],[1.37.0-motrix.11]' configure.ac+ grep -qF 'AC_INIT([aria2],[1.37.0-motrix.12]' configure.ac- type: scriptdest-filename: autogen.shcommands:diff --git a/package.json b/package.jsonindex c0620745..fbb4a2a2 100644--- a/package.json+++ b/package.json@@ -3,7 +3,7 @@"type": "module","productName": "Motrix","homepage": "https://motrix.app",- "version": "2.0.0-beta.28",+ "version": "2.0.0-beta.29","packageManager": "[email protected]+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621","description": "A full-featured download manager","keywords": [],diff --git a/packages/native-host/src/caller.rs b/packages/native-host/src/caller.rsindex ede81549..5eb06838 100644--- a/packages/native-host/src/caller.rs+++ b/packages/native-host/src/caller.rs@@ -84,15 +84,15 @@ mod tests {#[test]fn chromium_origin_arg_yields_32_char_id() {let id = extract_caller_identity(vec![- "chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/".into(),+ "chrome-extension://lggbokfckofcgjndaboioakcmincinpo/".into(),]).expect("identity");assert_eq!(id.browser, "chromium");- assert_eq!(id.caller_id, "ibpkjhgpbidfmbmomagmldcdlpbmchgi");+ assert_eq!(id.caller_id, "lggbokfckofcgjndaboioakcmincinpo");// Windows: --parent-window may accompany the originassert!(extract_caller_identity(vec![- "chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/".into(),+ "chrome-extension://lggbokfckofcgjndaboioakcmincinpo/".into(),"--parent-window=42".into(),]).is_some()diff --git a/packages/native-host/src/endpoint.rs b/packages/native-host/src/endpoint.rsindex 01639a92..958448f4 100644--- a/packages/native-host/src/endpoint.rs+++ b/packages/native-host/src/endpoint.rs@@ -29,7 +29,7 @@ fn effective_user_id() -> u32 {/// root. Reads metadata from the already-open handle, avoiding a TOCTOU/// window between checking the file and reading its contents.#[cfg(unix)]-fn is_owner_only(file: &File) -> bool {+pub(crate) fn is_owner_only(file: &File) -> bool {use std::os::unix::fs::{MetadataExt, PermissionsExt};let Ok(metadata) = file.metadata() else {@@ -69,7 +69,7 @@ fn is_owner_only(file: &File) -> bool {/// Reads from the already-open handle, like the Unix path, so there is no/// TOCTOU window between the check and the read.#[cfg(windows)]-fn is_owner_only(file: &File) -> bool {+pub(crate) fn is_owner_only(file: &File) -> bool {use std::os::windows::io::AsRawHandle;use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE, LocalFree};diff --git a/packages/native-host/src/flatpak_companion.rs b/packages/native-host/src/flatpak_companion.rsindex 6fda249a..555427a7 100644--- a/packages/native-host/src/flatpak_companion.rs+++ b/packages/native-host/src/flatpak_companion.rs@@ -1,40 +1,36 @@-use std::ffi::{OsStr, OsString};use std::fmt;-use std::fs::{self, File, OpenOptions};-use std::io::{Read, Write};-use std::path::{Component, Path, PathBuf};-use std::process::{Command, ExitStatus, Stdio};-use std::sync::mpsc;-use std::thread;-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};--use serde::{Deserialize, Serialize};+use std::path::Path;++mod allowlist;+mod command;+mod installation;+mod manifest;+mod paths;+mod runtime;+mod secure_fs;+#[cfg(test)]+mod tests;pub use crate::MOTRIX_FLATPAK_ID;-use crate::broker_protocol::{- BROKER_HEADER_BYTES, BrokerOperation, BrokerRequest, MAX_BROKER_MESSAGE_BYTES,- decode_broker_response, write_broker_message,+pub use allowlist::{NativeMessagingAllowlist, embedded_allowlist};+pub use command::{+ BrowserCaller, CompanionCommand, parse_companion_command, validate_browser_caller,+};+pub use installation::{+ CompanionConfig, CompanionStatus, companion_status, install_companion, load_companion_config,+ uninstall_companion,};-use crate::resolve::{ResolveError, ResolveResult};+pub use paths::{+ CompanionPaths, ManifestFamily, ManifestTarget, current_companion_paths,+ resolve_companion_paths,+};+pub use runtime::{FlatpakProcessRuntime, FlatpakRuntime, resolve_flatpak_request};pub const FLATPAK_BROKER_COMMAND: &str = "motrix-native-host-broker";pub const FLATPAK_COMPANION_BINARY: &str = "motrix-flatpak-native-host";pub const NATIVE_MESSAGING_HOST_NAME: &str = "app.motrix.bridge";pub const DEFAULT_FLATPAK_BIN: &str = "/usr/bin/flatpak";-const CONFIG_SCHEMA_VERSION: u32 = 1;-const MANIFEST_FILE_NAME: &str = "app.motrix.bridge.json";-const MANIFEST_DESCRIPTION: &str = "Motrix browser download bridge";-const PROBE_PROCESS_TIMEOUT: Duration = Duration::from_secs(10);-// The broker's endpoint polling deadline is independently fixed at 15s. Give-// Flatpak process startup enough headroom without extending that security-// boundary on slower hosts.-const WAIT_PROCESS_TIMEOUT: Duration = Duration::from_secs(30);-const OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);-const CHILD_POLL_INTERVAL: Duration = Duration::from_millis(10);-const EMBEDDED_ALLOWLIST: &str =- include_str!("../../../src/shared/config/native-messaging-extensions.json");-#[derive(Debug)]pub struct CompanionError {message: String,@@ -60,1995 +56,7 @@ impl fmt::Display for CompanionError {impl std::error::Error for CompanionError {}-#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]-#[serde(deny_unknown_fields)]-pub struct NativeMessagingAllowlist {- pub chromium: Vec<String>,- pub firefox: Vec<String>,-}--pub fn embedded_allowlist() -> Result<NativeMessagingAllowlist, CompanionError> {- let allowlist: NativeMessagingAllowlist = serde_json::from_str(EMBEDDED_ALLOWLIST)- .map_err(|error| CompanionError::new(format!("invalid embedded allowlist: {error}")))?;- if allowlist.chromium.is_empty() || allowlist.firefox.is_empty() {- return Err(CompanionError::new("embedded allowlist must not be empty"));- }- for id in &allowlist.chromium {- if !is_chromium_extension_id(id) {- return Err(CompanionError::new(format!(- "invalid embedded Chromium extension ID: {id}"- )));- }- }- for id in &allowlist.firefox {- if !is_firefox_extension_id(id) {- return Err(CompanionError::new(format!(- "invalid embedded Firefox extension ID: {id}"- )));- }- }- Ok(allowlist)-}--fn is_chromium_extension_id(id: &str) -> bool {- id.len() == 32 && id.bytes().all(|byte| (b'a'..=b'p').contains(&byte))-}--fn is_firefox_extension_id(id: &str) -> bool {- let mut parts = id.split('@');- matches!(- (parts.next(), parts.next(), parts.next()),- (Some(left), Some(right), None) if !left.is_empty() && !right.is_empty()- && !id.bytes().any(|byte| byte.is_ascii_whitespace())- ) || (id.starts_with('{')- && id.ends_with('}')- && id.len() == 38- && id[1..id.len() - 1]- .bytes()- .all(|byte| byte.is_ascii_hexdigit() || byte == b'-'))-}--#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub enum ManifestFamily {- Chromium,- Firefox,-}--#[derive(Clone, Debug, Eq, PartialEq)]-pub struct ManifestTarget {- pub family: ManifestFamily,- pub path: PathBuf,-}--#[derive(Clone, Debug, Eq, PartialEq)]-pub struct CompanionPaths {- pub home_root: PathBuf,- pub data_root: PathBuf,- pub config_root: PathBuf,- pub binary: PathBuf,- pub config: PathBuf,- pub manifests: Vec<ManifestTarget>,-}--fn absolute_root(value: &OsStr, label: &str) -> Result<PathBuf, CompanionError> {- let text = value- .to_str()- .ok_or_else(|| CompanionError::new(format!("{label} must be valid UTF-8")))?;- if text.is_empty() || text.trim() != text {- return Err(CompanionError::new(format!(- "{label} must not be empty or padded"- )));- }- let path = PathBuf::from(value);- if !path.is_absolute()- || path.parent().is_none()- || path- .components()- .any(|component| matches!(component, Component::CurDir | Component::ParentDir))- {- return Err(CompanionError::new(format!(- "{label} must be a canonical absolute path"- )));- }- Ok(path)-}--pub fn resolve_companion_paths(- home: &Path,- xdg_data_home: Option<&OsStr>,- xdg_config_home: Option<&OsStr>,-) -> Result<CompanionPaths, CompanionError> {- let home = absolute_root(home.as_os_str(), "home")?;- let data_home = match xdg_data_home {- Some(value) if !value.is_empty() => absolute_root(value, "XDG_DATA_HOME")?,- Some(_) | None => home.join(".local").join("share"),- };- let config_home = match xdg_config_home {- Some(value) if !value.is_empty() => absolute_root(value, "XDG_CONFIG_HOME")?,- Some(_) | None => home.join(".config"),- };- let binary = data_home- .join("motrix")- .join("native-messaging")- .join(FLATPAK_COMPANION_BINARY);- let config = config_home- .join("motrix")- .join("native-messaging")- .join("flatpak-companion.json");- let manifests = vec![- ManifestTarget {- family: ManifestFamily::Chromium,- path: config_home- .join("google-chrome")- .join("NativeMessagingHosts")- .join(MANIFEST_FILE_NAME),- },- ManifestTarget {- family: ManifestFamily::Chromium,- path: config_home- .join("chromium")- .join("NativeMessagingHosts")- .join(MANIFEST_FILE_NAME),- },- ManifestTarget {- family: ManifestFamily::Chromium,- path: config_home- .join("microsoft-edge")- .join("NativeMessagingHosts")- .join(MANIFEST_FILE_NAME),- },- ManifestTarget {- family: ManifestFamily::Firefox,- path: home- .join(".mozilla")- .join("native-messaging-hosts")- .join(MANIFEST_FILE_NAME),- },- ];- Ok(CompanionPaths {- home_root: home,- data_root: data_home,- config_root: config_home,- binary,- config,- manifests,- })-}--pub fn current_companion_paths() -> Result<CompanionPaths, CompanionError> {- let home = home::home_dir().ok_or_else(|| CompanionError::new("home directory unavailable"))?;- resolve_companion_paths(- &home,- std::env::var_os("XDG_DATA_HOME").as_deref(),- std::env::var_os("XDG_CONFIG_HOME").as_deref(),- )-}--#[derive(Clone, Debug, Eq, PartialEq)]-pub enum CompanionCommand {- Browser,- Install { flatpak_bin: PathBuf, force: bool },- Status,- Uninstall,- Help,- Version,-}--pub fn parse_companion_command(args: &[OsString]) -> Result<CompanionCommand, CompanionError> {- let Some(first) = args.first().and_then(|value| value.to_str()) else {- return Ok(CompanionCommand::Browser);- };- match first {- "install" => {- let mut flatpak_bin = None;- let mut force = false;- let mut index = 1;- while index < args.len() {- let flag = args[index]- .to_str()- .ok_or_else(|| CompanionError::new("install arguments must be UTF-8"))?;- match flag {- "--force" if !force => force = true,- "--force" => return Err(CompanionError::new("--force provided twice")),- "--flatpak-bin" if flatpak_bin.is_none() => {- index += 1;- let value = args- .get(index)- .ok_or_else(|| CompanionError::new("--flatpak-bin requires a value"))?;- flatpak_bin = Some(absolute_root(value, "--flatpak-bin")?);- }- "--flatpak-bin" => {- return Err(CompanionError::new("--flatpak-bin provided twice"));- }- _ => {- return Err(CompanionError::new(format!(- "unknown install argument: {flag}"- )));- }- }- index += 1;- }- Ok(CompanionCommand::Install {- flatpak_bin: flatpak_bin.unwrap_or_else(|| PathBuf::from(DEFAULT_FLATPAK_BIN)),- force,- })- }- "status" if args.len() == 1 => Ok(CompanionCommand::Status),- "uninstall" if args.len() == 1 => Ok(CompanionCommand::Uninstall),- "--help" if args.len() == 1 => Ok(CompanionCommand::Help),- "--version" if args.len() == 1 => Ok(CompanionCommand::Version),- "status" | "uninstall" | "--help" | "--version" => {- Err(CompanionError::new(format!("{first} takes no arguments")))- }- _ => Ok(CompanionCommand::Browser),- }-}--#[derive(Clone, Debug, Eq, PartialEq)]-pub enum BrowserCaller {- Chromium { extension_id: String },- Firefox { extension_id: String },-}--pub fn validate_browser_caller(- args: &[OsString],- allowlist: &NativeMessagingAllowlist,- paths: &CompanionPaths,-) -> Result<BrowserCaller, CompanionError> {- if args.len() == 1 {- let origin = args[0]- .to_str()- .ok_or_else(|| CompanionError::new("Chromium caller origin must be UTF-8"))?;- let extension_id = origin- .strip_prefix("chrome-extension://")- .map(|value| value.strip_suffix('/').unwrap_or(value))- .filter(|value| !value.contains('/'))- .ok_or_else(|| CompanionError::new("invalid Chromium caller origin"))?;- if !allowlist- .chromium- .iter()- .any(|allowed| allowed == extension_id)- {- return Err(CompanionError::new("Chromium caller is not allowlisted"));- }- return Ok(BrowserCaller::Chromium {- extension_id: extension_id.into(),- });- }-- if args.len() == 2 {- let manifest_path = PathBuf::from(&args[0]);- let expected_manifest = paths- .manifests- .iter()- .find(|target| target.family == ManifestFamily::Firefox)- .map(|target| &target.path);- if !manifest_path.is_absolute() || Some(&manifest_path) != expected_manifest {- return Err(CompanionError::new("unexpected Firefox manifest path"));- }- let extension_id = args[1]- .to_str()- .ok_or_else(|| CompanionError::new("Firefox caller ID must be UTF-8"))?;- if !allowlist- .firefox- .iter()- .any(|allowed| allowed == extension_id)- {- return Err(CompanionError::new("Firefox caller is not allowlisted"));- }- return Ok(BrowserCaller::Firefox {- extension_id: extension_id.into(),- });- }-- Err(CompanionError::new("missing or malformed browser caller"))-}--#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct CompanionConfig {- schema_version: u32,- flatpak_bin: PathBuf,- installed_binary: PathBuf,-}--impl CompanionConfig {- fn new(flatpak_bin: PathBuf, installed_binary: PathBuf) -> Self {- Self {- schema_version: CONFIG_SCHEMA_VERSION,- flatpak_bin,- installed_binary,- }- }-- pub fn flatpak_bin(&self) -> &Path {- &self.flatpak_bin- }-}--#[derive(Serialize)]-struct ChromiumManifest<'a> {- name: &'static str,- description: &'static str,- path: &'a Path,- r#type: &'static str,- allowed_origins: Vec<String>,-}--#[derive(Serialize)]-struct FirefoxManifest<'a> {- name: &'static str,- description: &'static str,- path: &'a Path,- r#type: &'static str,- allowed_extensions: &'a [String],-}--fn manifest_bytes(- target: &ManifestTarget,- binary: &Path,- allowlist: &NativeMessagingAllowlist,-) -> Result<Vec<u8>, CompanionError> {- let value = match target.family {- ManifestFamily::Chromium => serde_json::to_value(ChromiumManifest {- name: NATIVE_MESSAGING_HOST_NAME,- description: MANIFEST_DESCRIPTION,- path: binary,- r#type: "stdio",- allowed_origins: allowlist- .chromium- .iter()- .map(|id| format!("chrome-extension://{id}/"))- .collect(),- }),- ManifestFamily::Firefox => serde_json::to_value(FirefoxManifest {- name: NATIVE_MESSAGING_HOST_NAME,- description: MANIFEST_DESCRIPTION,- path: binary,- r#type: "stdio",- allowed_extensions: &allowlist.firefox,- }),- }- .map_err(|error| CompanionError::new(format!("serialize manifest: {error}")))?;- let mut bytes = serde_json::to_vec_pretty(&value)- .map_err(|error| CompanionError::new(format!("serialize manifest: {error}")))?;- bytes.push(b'\n');- Ok(bytes)-}--#[derive(Deserialize)]-struct ManifestOwnership {- name: String,- path: PathBuf,-}--fn read_limited(path: &Path, maximum: u64) -> Result<Vec<u8>, CompanionError> {- let file = File::open(path).map_err(|error| CompanionError::io("open", path, error))?;- let mut bytes = Vec::new();- file.take(maximum + 1)- .read_to_end(&mut bytes)- .map_err(|error| CompanionError::io("read", path, error))?;- if bytes.len() as u64 > maximum {- return Err(CompanionError::new(format!(- "{} exceeds {maximum} bytes",- path.display()- )));- }- Ok(bytes)-}--fn manifest_points_to(path: &Path, binary: &Path) -> bool {- let Ok(bytes) = read_limited(path, MAX_BROKER_MESSAGE_BYTES as u64) else {- return false;- };- serde_json::from_slice::<ManifestOwnership>(&bytes).is_ok_and(|manifest| {- manifest.name == NATIVE_MESSAGING_HOST_NAME && manifest.path == binary- })-}--fn path_entry_exists(path: &Path) -> bool {- match fs::symlink_metadata(path) {- Ok(_) => true,- Err(error) => error.kind() != std::io::ErrorKind::NotFound,- }-}--fn path_entry_is_symlink(path: &Path) -> bool {- fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())-}--#[derive(Clone, Copy)]-enum OwnerRequirement {- Current,- CurrentOrRoot,-}--#[cfg(unix)]-fn effective_user_id() -> u32 {- unsafe extern "C" {- fn geteuid() -> u32;- }-- // SAFETY: geteuid has no preconditions and does not dereference pointers.- unsafe { geteuid() }-}--fn entry_metadata(path: &Path) -> Result<Option<fs::Metadata>, CompanionError> {- match fs::symlink_metadata(path) {- Ok(metadata) => Ok(Some(metadata)),- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),- Err(error) => Err(CompanionError::io("inspect", path, error)),- }-}--fn validate_owner(- path: &Path,- metadata: &fs::Metadata,- requirement: OwnerRequirement,-) -> Result<(), CompanionError> {- #[cfg(unix)]- {- use std::os::unix::fs::MetadataExt;-- let owner = metadata.uid();- let current = effective_user_id();- let accepted = owner == current- || matches!(requirement, OwnerRequirement::CurrentOrRoot) && owner == 0;- if !accepted {- return Err(CompanionError::new(format!(- "{} is not owned by the current user{}",- path.display(),- if matches!(requirement, OwnerRequirement::CurrentOrRoot) {- " or root"- } else {- ""- }- )));- }- }- #[cfg(not(unix))]- let _ = (path, metadata, requirement);- Ok(())-}--fn validate_directory(- path: &Path,- requirement: OwnerRequirement,- allow_shared_sticky: bool,-) -> Result<(), CompanionError> {- let metadata = fs::symlink_metadata(path)- .map_err(|error| CompanionError::io("inspect directory", path, error))?;- if metadata.file_type().is_symlink() || !metadata.is_dir() {- return Err(CompanionError::new(format!(- "{} is not a real directory",- path.display()- )));- }- validate_owner(path, &metadata, requirement)?;- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;-- let mode = metadata.permissions().mode();- if mode & 0o022 != 0 && !(allow_shared_sticky && mode & 0o1000 != 0) {- return Err(CompanionError::new(format!(- "{} is writable by another user",- path.display()- )));- }- }- #[cfg(not(unix))]- let _ = allow_shared_sticky;- Ok(())-}--fn create_private_directory(path: &Path) -> Result<(), CompanionError> {- #[cfg(unix)]- let mut builder = fs::DirBuilder::new();- #[cfg(unix)]- {- use std::os::unix::fs::DirBuilderExt;- builder.mode(0o700);- }- #[cfg(not(unix))]- let builder = fs::DirBuilder::new();- let created = match builder.create(path) {- Ok(()) => true,- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,- Err(error) => return Err(CompanionError::io("create directory", path, error)),- };- if !created {- return validate_directory(path, OwnerRequirement::Current, false);- }- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- fs::set_permissions(path, fs::Permissions::from_mode(0o700))- .map_err(|error| CompanionError::io("set directory permissions", path, error))?;- }- validate_directory(path, OwnerRequirement::Current, false)-}--fn prepare_private_root(root: &Path, create: bool) -> Result<(), CompanionError> {- match entry_metadata(root)? {- Some(_) => {- validate_executable_parent_chain(root)?;- return validate_directory(root, OwnerRequirement::Current, false);- }- None if !create => {- return Err(CompanionError::new(format!(- "private root is missing: {}",- root.display()- )));- }- None => {}- }-- let mut missing = vec![root.to_path_buf()];- let mut cursor = root- .parent()- .ok_or_else(|| CompanionError::new(format!("{} has no parent", root.display())))?;- loop {- match entry_metadata(cursor)? {- Some(_) => {- if cursor.parent().is_some() {- validate_executable_parent_chain(cursor)?;- }- validate_directory(cursor, OwnerRequirement::CurrentOrRoot, true)?;- break;- }- None => missing.push(cursor.to_path_buf()),- }- cursor = cursor.parent().ok_or_else(|| {- CompanionError::new(format!("no existing ancestor for {}", root.display()))- })?;- }-- for directory in missing.iter().rev() {- create_private_directory(directory)?;- }- validate_directory(root, OwnerRequirement::Current, false)-}--fn validate_private_parent(root: &Path, path: &Path, create: bool) -> Result<(), CompanionError> {- let parent = path- .parent()- .ok_or_else(|| CompanionError::new(format!("{} has no parent", path.display())))?;- let relative = parent.strip_prefix(root).map_err(|_| {- CompanionError::new(format!(- "{} escapes private root {}",- path.display(),- root.display()- ))- })?;- prepare_private_root(root, create)?;-- let mut directory = root.to_path_buf();- for component in relative.components() {- let Component::Normal(name) = component else {- return Err(CompanionError::new(format!(- "{} has a non-canonical component",- path.display()- )));- };- directory.push(name);- match entry_metadata(&directory)? {- Some(_) => validate_directory(&directory, OwnerRequirement::Current, false)?,- None if create => create_private_directory(&directory)?,- None => {- return Err(CompanionError::new(format!(- "private directory is missing: {}",- directory.display()- )));- }- }- }- Ok(())-}--fn validate_existing_private_parent_prefix(root: &Path, path: &Path) -> Result<(), CompanionError> {- let parent = path- .parent()- .ok_or_else(|| CompanionError::new(format!("{} has no parent", path.display())))?;- let relative = parent.strip_prefix(root).map_err(|_| {- CompanionError::new(format!(- "{} escapes private root {}",- path.display(),- root.display()- ))- })?;- if entry_metadata(root)?.is_none() {- return Ok(());- }- validate_directory(root, OwnerRequirement::Current, false)?;-- let mut directory = root.to_path_buf();- for component in relative.components() {- let Component::Normal(name) = component else {- return Err(CompanionError::new(format!(- "{} has a non-canonical component",- path.display()- )));- };- directory.push(name);- if entry_metadata(&directory)?.is_none() {- return Ok(());- }- validate_directory(&directory, OwnerRequirement::Current, false)?;- }- Ok(())-}--fn destination_root<'a>(- paths: &'a CompanionPaths,- destination: &Path,-) -> Result<&'a Path, CompanionError> {- if destination == paths.binary {- return Ok(&paths.data_root);- }- if destination == paths.config {- return Ok(&paths.config_root);- }- if let Some(target) = paths- .manifests- .iter()- .find(|target| target.path == destination)- {- return Ok(match target.family {- ManifestFamily::Chromium => &paths.config_root,- ManifestFamily::Firefox => &paths.home_root,- });- }- Err(CompanionError::new(format!(- "unknown companion destination: {}",- destination.display()- )))-}--fn validate_regular_file(- path: &Path,- requirement: OwnerRequirement,- exact_mode: Option<u32>,- executable: bool,-) -> Result<(), CompanionError> {- let metadata = fs::symlink_metadata(path)- .map_err(|error| CompanionError::io("inspect file", path, error))?;- if metadata.file_type().is_symlink() || !metadata.is_file() {- return Err(CompanionError::new(format!(- "{} is not a real regular file",- path.display()- )));- }- validate_owner(path, &metadata, requirement)?;- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;-- let mode = metadata.permissions().mode();- if let Some(expected) = exact_mode {- if mode & 0o7777 != expected {- return Err(CompanionError::new(format!(- "{} has mode {:04o}; expected {expected:04o}",- path.display(),- mode & 0o7777- )));- }- } else if mode & 0o022 != 0 {- return Err(CompanionError::new(format!(- "{} is writable by another user",- path.display()- )));- }- if executable && mode & 0o111 == 0 {- return Err(CompanionError::new(format!(- "{} is not executable",- path.display()- )));- }- }- #[cfg(not(unix))]- let _ = (exact_mode, executable);- Ok(())-}--fn validate_private_file(- paths: &CompanionPaths,- path: &Path,- expected_mode: u32,-) -> Result<(), CompanionError> {- validate_private_parent(destination_root(paths, path)?, path, false)?;- validate_regular_file(- path,- OwnerRequirement::Current,- Some(expected_mode),- expected_mode == 0o700,- )-}--fn validate_executable_parent_chain(path: &Path) -> Result<(), CompanionError> {- let parent = path- .parent()- .ok_or_else(|| CompanionError::new(format!("{} has no parent", path.display())))?;- let mut ancestors = parent.ancestors().collect::<Vec<_>>();- ancestors.reverse();- for directory in ancestors {- validate_directory(directory, OwnerRequirement::CurrentOrRoot, true)?;- }- Ok(())-}--fn validate_source_executable(path: &Path) -> Result<PathBuf, CompanionError> {- absolute_root(path.as_os_str(), "companion executable")?;- validate_regular_file(path, OwnerRequirement::Current, None, true)?;- let canonical = fs::canonicalize(path)- .map_err(|error| CompanionError::io("resolve companion executable", path, error))?;- validate_executable_parent_chain(&canonical)?;- Ok(canonical)-}--fn temporary_path(destination: &Path, attempt: u32) -> Result<PathBuf, CompanionError> {- let parent = destination- .parent()- .ok_or_else(|| CompanionError::new("destination has no parent"))?;- let name = destination- .file_name()- .and_then(OsStr::to_str)- .ok_or_else(|| CompanionError::new("destination name must be UTF-8"))?;- let timestamp = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- Ok(parent.join(format!(- ".{name}.{}.{}.{}.tmp",- std::process::id(),- timestamp,- attempt- )))-}--fn rename_replace(source: &Path, destination: &Path) -> Result<(), CompanionError> {- #[cfg(windows)]- if destination.exists() {- fs::remove_file(destination)- .map_err(|error| CompanionError::io("remove old file", destination, error))?;- }- fs::rename(source, destination)- .map_err(|error| CompanionError::io("replace file", destination, error))-}--fn atomic_write(- root: &Path,- destination: &Path,- bytes: &[u8],- executable: bool,-) -> Result<(), CompanionError> {- #[cfg(not(unix))]- let _ = executable;- validate_private_parent(root, destination, true)?;- for attempt in 0..16 {- let temporary = temporary_path(destination, attempt)?;- let mut options = OpenOptions::new();- options.write(true).create_new(true);- #[cfg(unix)]- {- use std::os::unix::fs::OpenOptionsExt;- options.mode(if executable { 0o700 } else { 0o600 });- }- let mut file = match options.open(&temporary) {- Ok(file) => file,- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,- Err(error) => {- return Err(CompanionError::io(- "create temporary file",- &temporary,- error,- ));- }- };- if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {- let _ = fs::remove_file(&temporary);- return Err(CompanionError::io(- "write temporary file",- &temporary,- error,- ));- }- drop(file);- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let mode = if executable { 0o700 } else { 0o600 };- if let Err(error) = fs::set_permissions(&temporary, fs::Permissions::from_mode(mode)) {- let _ = fs::remove_file(&temporary);- return Err(CompanionError::io("set permissions", &temporary, error));- }- }- if let Err(error) = rename_replace(&temporary, destination) {- let _ = fs::remove_file(&temporary);- return Err(error);- }- validate_regular_file(- destination,- OwnerRequirement::Current,- Some(if executable { 0o700 } else { 0o600 }),- executable,- )?;- return Ok(());- }- Err(CompanionError::new(format!(- "could not allocate a temporary file for {}",- destination.display()- )))-}--fn atomic_copy(source: &Path, root: &Path, destination: &Path) -> Result<(), CompanionError> {- let bytes = read_limited(source, 64 * 1024 * 1024)?;- atomic_write(root, destination, &bytes, true)-}--fn validate_flatpak_binary(path: &Path) -> Result<PathBuf, CompanionError> {- absolute_root(path.as_os_str(), "flatpak binary")?;- let canonical = fs::canonicalize(path)- .map_err(|error| CompanionError::io("resolve flatpak binary", path, error))?;- absolute_root(canonical.as_os_str(), "resolved flatpak binary")?;- validate_executable_parent_chain(&canonical)?;- validate_regular_file(&canonical, OwnerRequirement::CurrentOrRoot, None, true)?;- Ok(canonical)-}--pub fn install_companion(- paths: &CompanionPaths,- source_executable: &Path,- flatpak_bin: &Path,- allowlist: &NativeMessagingAllowlist,- force: bool,-) -> Result<(), CompanionError> {- let canonical_flatpak = validate_flatpak_binary(flatpak_bin)?;- let canonical_source = validate_source_executable(source_executable)?;-- for destination in std::iter::once(&paths.binary)- .chain(std::iter::once(&paths.config))- .chain(paths.manifests.iter().map(|target| &target.path))- {- validate_private_parent(destination_root(paths, destination)?, destination, true)?;- }-- let existing_config = validate_private_file(paths, &paths.config, 0o600)- .ok()- .and_then(|()| read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64).ok())- .and_then(|bytes| serde_json::from_slice::<CompanionConfig>(&bytes).ok());- let config_owned = existing_config.as_ref().is_some_and(|config| {- config.schema_version == CONFIG_SCHEMA_VERSION && config.installed_binary == paths.binary- });-- if path_entry_exists(&paths.config)- && (path_entry_is_symlink(&paths.config) || !config_owned)- && !force- {- return Err(CompanionError::new(format!(- "refusing to replace unowned config {}; pass --force",- paths.config.display()- )));- }- for target in &paths.manifests {- let manifest_owned = validate_private_file(paths, &target.path, 0o600).is_ok()- && manifest_points_to(&target.path, &paths.binary);- if path_entry_exists(&target.path)- && (path_entry_is_symlink(&target.path) || !manifest_owned)- && !force- {- return Err(CompanionError::new(format!(- "refusing to replace unowned manifest {}; pass --force",- target.path.display()- )));- }- }- let source_is_installed =- fs::canonicalize(&paths.binary).is_ok_and(|installed| installed == canonical_source);- let binary_owned = validate_private_file(paths, &paths.binary, 0o700).is_ok() && config_owned;- if !source_is_installed- && path_entry_exists(&paths.binary)- && (path_entry_is_symlink(&paths.binary) || !binary_owned)- && !force- {- return Err(CompanionError::new(format!(- "refusing to replace unowned binary {}; pass --force",- paths.binary.display()- )));- }-- if source_is_installed {- validate_private_file(paths, &paths.binary, 0o700)?;- } else {- atomic_copy(source_executable, &paths.data_root, &paths.binary)?;- }- let config = CompanionConfig::new(canonical_flatpak, paths.binary.clone());- let mut config_bytes = serde_json::to_vec_pretty(&config)- .map_err(|error| CompanionError::new(format!("serialize config: {error}")))?;- config_bytes.push(b'\n');- atomic_write(&paths.config_root, &paths.config, &config_bytes, false)?;- for target in &paths.manifests {- atomic_write(- destination_root(paths, &target.path)?,- &target.path,- &manifest_bytes(target, &paths.binary, allowlist)?,- false,- )?;- }- Ok(())-}--pub fn load_companion_config(- paths: &CompanionPaths,- current_executable: &Path,-) -> Result<CompanionConfig, CompanionError> {- validate_private_file(paths, &paths.config, 0o600)?;- validate_private_file(paths, &paths.binary, 0o700)?;- let bytes = read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64)?;- let config: CompanionConfig = serde_json::from_slice(&bytes)- .map_err(|error| CompanionError::new(format!("invalid companion config: {error}")))?;- let expected_executable = fs::canonicalize(&paths.binary).map_err(|error| {- CompanionError::io("resolve installed executable", &paths.binary, error)- })?;- let actual_executable = fs::canonicalize(current_executable).map_err(|error| {- CompanionError::io("resolve current executable", current_executable, error)- })?;- if config.schema_version != CONFIG_SCHEMA_VERSION- || config.installed_binary != paths.binary- || actual_executable != expected_executable- {- return Err(CompanionError::new(- "companion config does not own this executable",- ));- }- let canonical_flatpak = validate_flatpak_binary(&config.flatpak_bin)?;- if canonical_flatpak != config.flatpak_bin {- return Err(CompanionError::new(- "configured flatpak binary path is not canonical",- ));- }- Ok(config)-}--#[derive(Clone, Debug, Eq, PartialEq)]-pub struct CompanionStatus {- pub installed: bool,- pub issues: Vec<String>,-}--pub fn companion_status(- paths: &CompanionPaths,- allowlist: &NativeMessagingAllowlist,-) -> CompanionStatus {- let mut issues = Vec::new();- let config = validate_private_file(paths, &paths.config, 0o600)- .and_then(|()| read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64))- .ok()- .and_then(|bytes| serde_json::from_slice::<CompanionConfig>(&bytes).ok());- if config.as_ref().is_none_or(|config| {- config.schema_version != CONFIG_SCHEMA_VERSION || config.installed_binary != paths.binary- }) {- issues.push("config missing, malformed, or unowned".into());- } else if let Some(config) = &config- && !validate_flatpak_binary(&config.flatpak_bin)- .is_ok_and(|canonical| canonical == config.flatpak_bin)- {- issues.push("configured flatpak binary is unavailable or unsafe".into());- }-- if validate_private_file(paths, &paths.binary, 0o700).is_err() {- issues.push("installed companion binary is missing or unsafe".into());- }-- for target in &paths.manifests {- let expected = manifest_bytes(target, &paths.binary, allowlist)- .ok()- .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());- let actual = validate_private_file(paths, &target.path, 0o600)- .and_then(|()| read_limited(&target.path, MAX_BROKER_MESSAGE_BYTES as u64))- .ok()- .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());- if expected.is_none() || expected != actual {- issues.push(format!(- "manifest missing or stale: {}",- target.path.display()- ));- }- }-- CompanionStatus {- installed: issues.is_empty(),- issues,- }-}--pub fn uninstall_companion(paths: &CompanionPaths) -> Result<(), CompanionError> {- let destinations = std::iter::once(&paths.binary)- .chain(std::iter::once(&paths.config))- .chain(paths.manifests.iter().map(|target| &target.path));- for destination in destinations.clone() {- validate_existing_private_parent_prefix(- destination_root(paths, destination)?,- destination,- )?;- }- if !destinations.clone().any(|path| path_entry_exists(path)) {- return Ok(());- }-- for destination in destinations {- if !path_entry_exists(destination) {- continue;- }- validate_private_parent(destination_root(paths, destination)?, destination, false)?;- validate_regular_file(destination, OwnerRequirement::Current, None, false)?;- }-- let config_owned = if path_entry_exists(&paths.config) {- validate_private_file(paths, &paths.config, 0o600).is_ok()- && read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64)- .ok()- .and_then(|bytes| serde_json::from_slice::<CompanionConfig>(&bytes).ok())- .is_some_and(|config| {- config.schema_version == CONFIG_SCHEMA_VERSION- && config.installed_binary == paths.binary- })- } else {- false- };- let mut manifests_to_remove = Vec::new();- for target in &paths.manifests {- if path_entry_exists(&target.path)- && validate_private_file(paths, &target.path, 0o600).is_ok()- && manifest_points_to(&target.path, &paths.binary)- {- manifests_to_remove.push(&target.path);- }- }- if config_owned && path_entry_exists(&paths.binary) {- validate_private_file(paths, &paths.binary, 0o700)?;- }-- for manifest in manifests_to_remove {- fs::remove_file(manifest)- .map_err(|error| CompanionError::io("remove manifest", manifest, error))?;- }- if config_owned {- fs::remove_file(&paths.config)- .map_err(|error| CompanionError::io("remove config", &paths.config, error))?;- }- if config_owned && paths.binary.exists() {- fs::remove_file(&paths.binary)- .map_err(|error| CompanionError::io("remove companion binary", &paths.binary, error))?;- }- Ok(())-}--pub trait FlatpakRuntime {- fn call_broker(&mut self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError>;- fn launch_app(&mut self) -> bool;-}--pub fn resolve_flatpak_request<R: FlatpakRuntime>(- allow_launch: bool,- runtime: &mut R,-) -> ResolveResult {- match runtime.call_broker(BrokerOperation::Probe) {- Ok(result @ ResolveResult::RequestPair { .. }) => return result,- Ok(ResolveResult::Error {- error: ResolveError::NotRunning,- }) => {}- Ok(_) | Err(_) if !allow_launch => {- return ResolveResult::Error {- error: ResolveError::NotRunning,- };- }- Ok(_) | Err(_) => {- return ResolveResult::Error {- error: ResolveError::NotInstalled,- };- }- }-- if !allow_launch {- return ResolveResult::Error {- error: ResolveError::NotRunning,- };- }- if !runtime.launch_app() {- return ResolveResult::Error {- error: ResolveError::NotInstalled,- };- }- match runtime.call_broker(BrokerOperation::WaitForEndpoint) {- Ok(result @ ResolveResult::RequestPair { .. }) => result,- Ok(_) | Err(_) => ResolveResult::Error {- error: ResolveError::LaunchFailed,- },- }-}--pub struct FlatpakProcessRuntime {- flatpak_bin: PathBuf,-}--impl FlatpakProcessRuntime {- pub fn new(flatpak_bin: PathBuf) -> Self {- Self { flatpak_bin }- }-- fn wait_for_child(- mut child: std::process::Child,- timeout: Duration,- ) -> Result<(ExitStatus, Vec<u8>), CompanionError> {- let Some(stdout) = child.stdout.take() else {- let _ = child.kill();- let _ = child.wait();- return Err(CompanionError::new("broker stdout pipe unavailable"));- };- let (sender, receiver) = mpsc::sync_channel(1);- if let Err(error) = thread::Builder::new()- .name("flatpak-broker-output".into())- .spawn(move || {- let mut output = Vec::new();- let maximum = BROKER_HEADER_BYTES + MAX_BROKER_MESSAGE_BYTES + 1;- let result = stdout- .take(maximum as u64)- .read_to_end(&mut output)- .map(|_| output);- let _ = sender.send(result);- })- {- let _ = child.kill();- let _ = child.wait();- return Err(CompanionError::new(format!("spawn output reader: {error}")));- }-- let deadline = Instant::now()- .checked_add(timeout)- .ok_or_else(|| CompanionError::new("broker deadline overflow"))?;- let status = loop {- match child.try_wait() {- Ok(Some(status)) => break status,- Ok(None) if Instant::now() < deadline => thread::sleep(CHILD_POLL_INTERVAL),- Ok(None) => {- let _ = child.kill();- let _ = child.wait();- return Err(CompanionError::new("Flatpak broker timed out"));- }- Err(error) => {- let _ = child.kill();- let _ = child.wait();- return Err(CompanionError::new(format!(- "wait for Flatpak broker: {error}"- )));- }- }- };- let output = receiver- .recv_timeout(OUTPUT_DRAIN_TIMEOUT)- .map_err(|_| CompanionError::new("Flatpak broker stdout did not close"))?- .map_err(|error| CompanionError::new(format!("read Flatpak broker stdout: {error}")))?;- if output.len() > BROKER_HEADER_BYTES + MAX_BROKER_MESSAGE_BYTES {- return Err(CompanionError::new("Flatpak broker output exceeded limit"));- }- Ok((status, output))- }-- fn invoke_broker(&self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError> {- let mut child = Command::new(&self.flatpak_bin)- .arg("run")- .arg(format!("--command={FLATPAK_BROKER_COMMAND}"))- .arg(MOTRIX_FLATPAK_ID)- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::inherit())- .spawn()- .map_err(|error| CompanionError::new(format!("start Flatpak broker: {error}")))?;- let Some(mut stdin) = child.stdin.take() else {- let _ = child.kill();- let _ = child.wait();- return Err(CompanionError::new("broker stdin pipe unavailable"));- };- if let Err(error) = write_broker_message(&mut stdin, &BrokerRequest { operation }) {- let _ = child.kill();- let _ = child.wait();- return Err(CompanionError::new(format!(- "write broker request: {error}"- )));- }- drop(stdin);- let timeout = match operation {- BrokerOperation::Probe => PROBE_PROCESS_TIMEOUT,- BrokerOperation::WaitForEndpoint => WAIT_PROCESS_TIMEOUT,- };- let (status, output) = Self::wait_for_child(child, timeout)?;- if !status.success() {- return Err(CompanionError::new(format!(- "Flatpak broker exited with {status}"- )));- }- let result = decode_broker_response(&output)- .map_err(|error| CompanionError::new(format!("validate broker response: {error}")))?;- let expected = matches!(- (operation, &result),- (BrokerOperation::Probe, ResolveResult::RequestPair { .. })- | (- BrokerOperation::Probe,- ResolveResult::Error {- error: ResolveError::NotRunning- }- )- | (- BrokerOperation::WaitForEndpoint,- ResolveResult::RequestPair { .. }- )- | (- BrokerOperation::WaitForEndpoint,- ResolveResult::Error {- error: ResolveError::LaunchFailed- }- )- );- if !expected {- return Err(CompanionError::new(- "broker returned a result invalid for the requested operation",- ));- }- Ok(result)- }-}--impl FlatpakRuntime for FlatpakProcessRuntime {- fn call_broker(&mut self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError> {- self.invoke_broker(operation)- }-- fn launch_app(&mut self) -> bool {- let mut command = Command::new(&self.flatpak_bin);- command- .arg("run")- .arg(MOTRIX_FLATPAK_ID)- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null());- #[cfg(unix)]- {- use std::os::unix::process::CommandExt;- command.process_group(0);- }- match command.spawn() {- Ok(mut child) => {- thread::spawn(move || {- let _ = child.wait();- });- true- }- Err(_) => false,- }- }-}-#[cfg(test)]-mod tests {- use std::collections::VecDeque;- use std::ffi::{OsStr, OsString};- use std::fs;- use std::path::{Path, PathBuf};- #[cfg(unix)]- use std::time::Duration;- use std::time::{SystemTime, UNIX_EPOCH};-- use serde_json::{Value, json};-- use super::{- BrowserCaller, CompanionError, FlatpakRuntime, ManifestFamily, companion_status,- embedded_allowlist, install_companion, resolve_companion_paths, resolve_flatpak_request,- uninstall_companion, validate_browser_caller,- };- #[cfg(unix)]- use super::{- CompanionCommand, FlatpakProcessRuntime, load_companion_config, parse_companion_command,- };- use crate::broker_protocol::BrokerOperation;- #[cfg(unix)]- use crate::broker_protocol::encode_broker_message;- use crate::resolve::{ResolveError, ResolveResult};-- const CHROMIUM_ID: &str = "ibpkjhgpbidfmbmomagmldcdlpbmchgi";- const FIREFOX_ID: &str = "[email protected]";- const NONCE: &str = "AbCdEfGhIjKlMnOpQrStUv";-- struct TempDir {- path: PathBuf,- }-- impl TempDir {- fn new(label: &str) -> Self {- let id = SystemTime::now()- .duration_since(UNIX_EPOCH)- .expect("clock")- .as_nanos();- let temporary_root =- fs::canonicalize(std::env::temp_dir()).expect("canonical temporary directory");- let path = temporary_root.join(format!(- "motrix-flatpak-companion-{label}-{}-{id}",- std::process::id()- ));- fs::create_dir_all(&path).expect("create temp directory");- Self { path }- }- }-- impl Drop for TempDir {- fn drop(&mut self) {- let _ = fs::remove_dir_all(&self.path);- }- }-- fn make_executable(path: &Path, contents: &[u8]) {- fs::create_dir_all(path.parent().expect("executable parent")).expect("create parent");- fs::write(path, contents).expect("write executable");- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("make executable");- }- }-- #[cfg(unix)]- fn set_mode(path: &Path, mode: u32) {- use std::os::unix::fs::PermissionsExt;- fs::set_permissions(path, fs::Permissions::from_mode(mode)).expect("set mode");- }-- #[cfg(unix)]- fn assert_private_directory_chain(root: &Path, destination: &Path) {- use std::os::unix::fs::PermissionsExt;-- let parent = destination.parent().expect("destination parent");- let relative = parent.strip_prefix(root).expect("destination under root");- let mut directory = root.to_path_buf();- assert_eq!(- fs::symlink_metadata(&directory)- .expect("root metadata")- .permissions()- .mode()- & 0o7777,- 0o700,- "unexpected mode for {}",- directory.display()- );- for component in relative.components() {- directory.push(component.as_os_str());- assert_eq!(- fs::symlink_metadata(&directory)- .expect("directory metadata")- .permissions()- .mode()- & 0o7777,- 0o700,- "unexpected mode for {}",- directory.display()- );- }- }-- fn explicit_paths(temp: &TempDir) -> super::CompanionPaths {- let data = temp.path.join("data");- let config = temp.path.join("config");- resolve_companion_paths(- &temp.path.join("home"),- Some(data.as_os_str()),- Some(config.as_os_str()),- )- .expect("resolve paths")- }-- #[test]- fn resolves_xdg_and_documented_fallback_paths() {- let temp = TempDir::new("paths");- let home = temp.path.join("home");- let fallback = resolve_companion_paths(&home, None, None).expect("fallback paths");- assert_eq!(- fallback.binary,- home.join(".local/share/motrix/native-messaging/motrix-flatpak-native-host")- );- assert_eq!(- fallback.config,- home.join(".config/motrix/native-messaging/flatpak-companion.json")- );- assert_eq!(fallback.manifests.len(), 4);- assert_eq!(- fallback- .manifests- .iter()- .filter(|target| target.family == ManifestFamily::Firefox)- .map(|target| target.path.clone())- .collect::<Vec<_>>(),- vec![home.join(".mozilla/native-messaging-hosts/app.motrix.bridge.json")]- );-- let explicit = explicit_paths(&temp);- assert!(explicit.binary.starts_with(temp.path.join("data")));- assert!(explicit.config.starts_with(temp.path.join("config")));- assert_eq!(- explicit- .manifests- .iter()- .filter(|target| target.family == ManifestFamily::Chromium)- .count(),- 3- );-- let empty_xdg = resolve_companion_paths(&home, Some(OsStr::new("")), Some(OsStr::new("")))- .expect("empty XDG values use fallbacks");- assert_eq!(empty_xdg.binary, fallback.binary);- assert_eq!(empty_xdg.config, fallback.config);- }-- #[cfg(unix)]- #[test]- fn parses_only_the_documented_management_cli() {- assert_eq!(- parse_companion_command(&[]).expect("browser mode"),- CompanionCommand::Browser- );- assert_eq!(- parse_companion_command(&[OsString::from("install")]).expect("default install"),- CompanionCommand::Install {- flatpak_bin: PathBuf::from("/usr/bin/flatpak"),- force: false,- }- );- assert_eq!(- parse_companion_command(&[- OsString::from("install"),- OsString::from("--force"),- OsString::from("--flatpak-bin"),- OsString::from("/opt/flatpak/bin/flatpak"),- ])- .expect("custom install"),- CompanionCommand::Install {- flatpak_bin: PathBuf::from("/opt/flatpak/bin/flatpak"),- force: true,- }- );- assert!(- parse_companion_command(&[- OsString::from("install"),- OsString::from("--flatpak-bin"),- OsString::from("relative/flatpak"),- ])- .is_err()- );- assert!(- parse_companion_command(&[OsString::from("status"), OsString::from("extra")]).is_err()- );- }-- #[test]- fn validates_exact_browser_caller_shapes_before_broker_access() {- let temp = TempDir::new("caller");- let paths = explicit_paths(&temp);- let allowlist = embedded_allowlist().expect("embedded allowlist");-- for origin in [- format!("chrome-extension://{CHROMIUM_ID}"),- format!("chrome-extension://{CHROMIUM_ID}/"),- ] {- assert_eq!(- validate_browser_caller(&[origin.into()], &allowlist, &paths)- .expect("Chromium caller"),- BrowserCaller::Chromium {- extension_id: CHROMIUM_ID.into()- }- );- }- for invalid in [- format!("chrome-extension://{CHROMIUM_ID}//"),- "chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/".into(),- format!("https://{CHROMIUM_ID}/"),- ] {- assert!(- validate_browser_caller(&[invalid.into()], &allowlist, &paths).is_err(),- "accepted invalid Chromium caller"- );- }-- let firefox_manifest = paths- .manifests- .iter()- .find(|target| target.family == ManifestFamily::Firefox)- .expect("Firefox target")- .path- .clone();- assert_eq!(- validate_browser_caller(- &[- firefox_manifest.clone().into_os_string(),- OsString::from(FIREFOX_ID),- ],- &allowlist,- &paths,- )- .expect("Firefox caller"),- BrowserCaller::Firefox {- extension_id: FIREFOX_ID.into()- }- );- assert!(- validate_browser_caller(- &[- firefox_manifest- .with_file_name("other.json")- .into_os_string(),- OsString::from(FIREFOX_ID),- ],- &allowlist,- &paths,- )- .is_err()- );- assert!(validate_browser_caller(&[], &allowlist, &paths).is_err());- assert!(- validate_browser_caller(- &[- OsString::from(format!("chrome-extension://{CHROMIUM_ID}/")),- OsString::from("unexpected"),- OsString::from("argument"),- ],- &allowlist,- &paths,- )- .is_err()- );- }-- #[test]- fn install_writes_binary_config_and_all_browser_manifests() {- let temp = TempDir::new("install");- let paths = explicit_paths(&temp);- let source = temp.path.join("source-companion");- let flatpak = temp.path.join("bin/flatpak");- make_executable(&source, b"companion-binary");- make_executable(&flatpak, b"flatpak-binary");- let allowlist = embedded_allowlist().expect("embedded allowlist");-- install_companion(&paths, &source, &flatpak, &allowlist, false).expect("install");- assert_eq!(- fs::read(&paths.binary).expect("installed binary"),- b"companion-binary"- );- let config: Value = serde_json::from_slice(&fs::read(&paths.config).expect("config"))- .expect("parse config");- assert_eq!(config["schemaVersion"], 1);- assert_eq!(- config["flatpakBin"],- fs::canonicalize(&flatpak)- .expect("canonical flatpak")- .to_string_lossy()- .as_ref()- );- assert_eq!(- config["installedBinary"],- paths.binary.to_string_lossy().as_ref()- );-- for target in &paths.manifests {- let manifest: Value = serde_json::from_slice(- &fs::read(&target.path)- .unwrap_or_else(|_| panic!("read {}", target.path.display())),- )- .expect("parse manifest");- assert_eq!(manifest["name"], "app.motrix.bridge");- assert_eq!(manifest["path"], paths.binary.to_string_lossy().as_ref());- assert_eq!(manifest["type"], "stdio");- match target.family {- ManifestFamily::Chromium => assert_eq!(- manifest["allowed_origins"],- json!([format!("chrome-extension://{CHROMIUM_ID}/")])- ),- ManifestFamily::Firefox => {- assert_eq!(manifest["allowed_extensions"], json!([FIREFOX_ID]))- }- }- }- assert!(companion_status(&paths, &allowlist).installed);-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- assert_eq!(- fs::metadata(&paths.binary)- .expect("binary metadata")- .permissions()- .mode()- & 0o777,- 0o700- );- assert_eq!(- fs::metadata(&paths.config)- .expect("config metadata")- .permissions()- .mode()- & 0o777,- 0o600- );- for target in &paths.manifests {- assert_eq!(- fs::metadata(&target.path)- .expect("manifest metadata")- .permissions()- .mode()- & 0o7777,- 0o600- );- }- assert_private_directory_chain(&paths.data_root, &paths.binary);- assert_private_directory_chain(&paths.config_root, &paths.config);- for target in &paths.manifests {- let root = match target.family {- ManifestFamily::Chromium => &paths.config_root,- ManifestFamily::Firefox => &paths.home_root,- };- assert_private_directory_chain(root, &target.path);- }- }- }-- #[test]- #[cfg(unix)]- fn install_rejects_symlinked_or_other_writable_private_directories() {- use std::os::unix::fs::symlink;-- let symlink_temp = TempDir::new("symlink-root");- let symlink_paths = explicit_paths(&symlink_temp);- let source = symlink_temp.path.join("source-companion");- let flatpak = symlink_temp.path.join("bin/flatpak");- make_executable(&source, b"companion");- make_executable(&flatpak, b"flatpak");- let redirect = symlink_temp.path.join("redirect");- fs::create_dir(&redirect).expect("create redirect");- symlink(&redirect, &symlink_paths.data_root).expect("symlink data root");- let allowlist = embedded_allowlist().expect("allowlist");- assert!(install_companion(&symlink_paths, &source, &flatpak, &allowlist, true,).is_err());- assert!(!redirect.join("motrix").exists());- assert!(uninstall_companion(&symlink_paths).is_err());-- let writable_temp = TempDir::new("writable-parent");- let writable_paths = explicit_paths(&writable_temp);- let source = writable_temp.path.join("source-companion");- let flatpak = writable_temp.path.join("bin/flatpak");- make_executable(&source, b"companion");- make_executable(&flatpak, b"flatpak");- fs::create_dir(&writable_paths.config_root).expect("create config root");- let insecure = writable_paths.config_root.join("google-chrome");- fs::create_dir(&insecure).expect("create insecure browser directory");- set_mode(&insecure, 0o777);- assert!(install_companion(&writable_paths, &source, &flatpak, &allowlist, true,).is_err());- assert!(!writable_paths.binary.exists());-- let ancestor_temp = TempDir::new("writable-ancestor");- let shared = ancestor_temp.path.join("shared");- fs::create_dir(&shared).expect("create shared ancestor");- set_mode(&shared, 0o777);- let data_root = shared.join("victim-data");- fs::create_dir(&data_root).expect("create private data root");- set_mode(&data_root, 0o700);- let ancestor_paths = resolve_companion_paths(- &ancestor_temp.path.join("home"),- Some(data_root.as_os_str()),- Some(ancestor_temp.path.join("config").as_os_str()),- )- .expect("resolve paths below writable ancestor");- let source = ancestor_temp.path.join("source-companion");- let flatpak = ancestor_temp.path.join("bin/flatpak");- make_executable(&source, b"companion");- make_executable(&flatpak, b"flatpak");- assert!(- install_companion(&ancestor_paths, &source, &flatpak, &allowlist, true).is_err(),- "a private root below a non-sticky writable ancestor was accepted"- );- assert!(!ancestor_paths.binary.exists());- }-- #[test]- #[cfg(unix)]- fn install_validates_source_and_canonicalizes_a_safe_flatpak_binary() {- use std::os::unix::fs::symlink;-- let temp = TempDir::new("executables");- let paths = explicit_paths(&temp);- let source = temp.path.join("source-companion");- let flatpak = temp.path.join("bin/flatpak");- make_executable(&source, b"companion");- make_executable(&flatpak, b"flatpak");- let allowlist = embedded_allowlist().expect("allowlist");-- set_mode(&source, 0o777);- assert!(install_companion(&paths, &source, &flatpak, &allowlist, true).is_err());- set_mode(&source, 0o755);- set_mode(&flatpak, 0o777);- assert!(install_companion(&paths, &source, &flatpak, &allowlist, true).is_err());- set_mode(&flatpak, 0o755);-- let insecure_parent = temp.path.join("insecure-flatpak-parent");- fs::create_dir(&insecure_parent).expect("create insecure parent");- set_mode(&insecure_parent, 0o777);- let insecure_flatpak = insecure_parent.join("flatpak");- make_executable(&insecure_flatpak, b"flatpak");- assert!(install_companion(&paths, &source, &insecure_flatpak, &allowlist, true,).is_err());-- let flatpak_link = temp.path.join("flatpak-link");- symlink(&flatpak, &flatpak_link).expect("create flatpak symlink");- install_companion(&paths, &source, &flatpak_link, &allowlist, true)- .expect("install through canonicalized flatpak path");- let config: Value = serde_json::from_slice(&fs::read(&paths.config).expect("config"))- .expect("parse config");- assert_eq!(- config["flatpakBin"],- fs::canonicalize(&flatpak)- .expect("canonical flatpak")- .to_string_lossy()- .as_ref()- );- }-- #[test]- #[cfg(unix)]- fn status_load_and_uninstall_fail_closed_for_unsafe_installation_entries() {- use std::os::unix::fs::symlink;-- let temp = TempDir::new("fail-closed");- let paths = explicit_paths(&temp);- let source = temp.path.join("source-companion");- let flatpak = temp.path.join("bin/flatpak");- make_executable(&source, b"companion");- make_executable(&flatpak, b"flatpak");- let allowlist = embedded_allowlist().expect("allowlist");- install_companion(&paths, &source, &flatpak, &allowlist, false).expect("install");-- set_mode(&paths.binary, 0o777);- assert!(!companion_status(&paths, &allowlist).installed);- assert!(load_companion_config(&paths, &paths.binary).is_err());- assert!(uninstall_companion(&paths).is_err());- set_mode(&paths.binary, 0o700);-- fs::remove_file(&paths.config).expect("remove config");- symlink(paths.config.with_extension("missing"), &paths.config)- .expect("create dangling config symlink");- assert!(!companion_status(&paths, &allowlist).installed);- assert!(load_companion_config(&paths, &paths.binary).is_err());- assert!(uninstall_companion(&paths).is_err());-- fs::remove_file(&paths.config).expect("remove config symlink");- install_companion(&paths, &source, &flatpak, &allowlist, true).expect("repair install");- let manifest = &paths.manifests[0].path;- fs::remove_file(manifest).expect("remove manifest");- symlink(manifest.with_extension("missing"), manifest)- .expect("create dangling manifest symlink");- assert!(!companion_status(&paths, &allowlist).installed);- assert!(uninstall_companion(&paths).is_err());- }-- #[test]- fn install_refuses_unowned_files_unless_force_is_explicit() {- let temp = TempDir::new("conflict");- let paths = explicit_paths(&temp);- let source = temp.path.join("source-companion");- let flatpak = temp.path.join("bin/flatpak");- make_executable(&source, b"new-companion");- make_executable(&flatpak, b"flatpak");- let allowlist = embedded_allowlist().expect("embedded allowlist");-- let conflict = &paths.manifests[0].path;- fs::create_dir_all(conflict.parent().expect("manifest parent")).expect("create parent");- fs::write(- conflict,- br#"{"name":"org.example.foreign","path":"/foreign"}"#,- )- .expect("write foreign manifest");- assert!(install_companion(&paths, &source, &flatpak, &allowlist, false).is_err());- assert!(!paths.binary.exists());- install_companion(&paths, &source, &flatpak, &allowlist, true).expect("forced install");-- let second = TempDir::new("binary-conflict");- let second_paths = explicit_paths(&second);- fs::create_dir_all(second_paths.binary.parent().expect("binary parent"))- .expect("create binary parent");- fs::write(&second_paths.binary, b"foreign-binary").expect("foreign binary");- assert!(install_companion(&second_paths, &source, &flatpak, &allowlist, false,).is_err());- assert_eq!(- fs::read(&second_paths.binary).expect("preserved foreign binary"),- b"foreign-binary"- );- }-- #[test]- fn uninstall_removes_only_manifests_still_owned_by_the_companion() {- let temp = TempDir::new("uninstall");- let paths = explicit_paths(&temp);- let source = temp.path.join("source-companion");- let flatpak = temp.path.join("bin/flatpak");- make_executable(&source, b"companion");- make_executable(&flatpak, b"flatpak");- let allowlist = embedded_allowlist().expect("embedded allowlist");- install_companion(&paths, &source, &flatpak, &allowlist, false).expect("install");-- let foreign = &paths.manifests[0].path;- fs::write(- foreign,- br#"{"name":"org.example.foreign","path":"/foreign"}"#,- )- .expect("replace one manifest");- uninstall_companion(&paths).expect("uninstall");-- assert!(foreign.exists(), "foreign manifest must be preserved");- for target in paths.manifests.iter().skip(1) {- assert!(!target.path.exists(), "owned manifest was preserved");- }- assert!(!paths.config.exists());- assert!(!paths.binary.exists());- }-- struct FakeRuntime {- responses: VecDeque<Result<ResolveResult, CompanionError>>,- calls: Vec<BrokerOperation>,- launch_result: bool,- launch_calls: usize,- }-- impl FakeRuntime {- fn new(responses: Vec<Result<ResolveResult, CompanionError>>) -> Self {- Self {- responses: responses.into(),- calls: Vec::new(),- launch_result: true,- launch_calls: 0,- }- }- }-- impl FlatpakRuntime for FakeRuntime {- fn call_broker(- &mut self,- operation: BrokerOperation,- ) -> Result<ResolveResult, CompanionError> {- self.calls.push(operation);- self.responses.pop_front().expect("queued broker response")- }-- fn launch_app(&mut self) -> bool {- self.launch_calls += 1;- self.launch_result- }- }-- fn error(error: ResolveError) -> ResolveResult {- ResolveResult::Error { error }- }-- #[test]- fn flatpak_resolution_probes_then_launches_then_waits_without_weakening_errors() {- let pair = ResolveResult::request_pair(55_809, NONCE.into());- let mut live = FakeRuntime::new(vec![Ok(pair.clone())]);- assert_eq!(resolve_flatpak_request(true, &mut live), pair);- assert_eq!(live.calls, vec![BrokerOperation::Probe]);- assert_eq!(live.launch_calls, 0);-- let mut no_launch = FakeRuntime::new(vec![Ok(error(ResolveError::NotRunning))]);- assert_eq!(- resolve_flatpak_request(false, &mut no_launch),- error(ResolveError::NotRunning)- );- assert_eq!(no_launch.launch_calls, 0);-- let pair = ResolveResult::request_pair(55_810, NONCE.into());- let mut launched =- FakeRuntime::new(vec![Ok(error(ResolveError::NotRunning)), Ok(pair.clone())]);- assert_eq!(resolve_flatpak_request(true, &mut launched), pair);- assert_eq!(- launched.calls,- vec![BrokerOperation::Probe, BrokerOperation::WaitForEndpoint]- );- assert_eq!(launched.launch_calls, 1);-- let mut unavailable = FakeRuntime::new(vec![Err(CompanionError::new("not installed"))]);- assert_eq!(- resolve_flatpak_request(true, &mut unavailable),- error(ResolveError::NotInstalled)- );- assert_eq!(unavailable.launch_calls, 0);-- let mut launch_failed = FakeRuntime::new(vec![- Ok(error(ResolveError::NotRunning)),- Err(CompanionError::new("wait failed")),- ]);- assert_eq!(- resolve_flatpak_request(true, &mut launch_failed),- error(ResolveError::LaunchFailed)- );- }-- #[cfg(unix)]- fn shell_octal(bytes: &[u8]) -> String {- bytes.iter().map(|byte| format!("\\{byte:03o}")).collect()- }-- #[cfg(unix)]- fn shell_quote(path: &Path) -> String {- format!("'{}'", path.to_string_lossy().replace('\'', "'\"'\"'"))- }-- #[test]- #[cfg(unix)]- fn process_runtime_uses_fixed_flatpak_commands_and_rejects_stdout_pollution() {- let temp = TempDir::new("runtime-process");- let flatpak = temp.path.join("flatpak");- let marker = temp.path.join("launched");- let response = encode_broker_message(&error(ResolveError::NotRunning))- .expect("encode broker response");- let script = format!(- "#!/bin/sh\n\- if [ \"$#\" -eq 2 ]; then\n\- [ \"$1\" = run ] && [ \"$2\" = app.motrix.native ] || exit 91\n\- : > {}\n\- exit 0\n\- fi\n\- [ \"$#\" -eq 3 ] || exit 92\n\- [ \"$1\" = run ] || exit 93\n\- [ \"$2\" = --command=motrix-native-host-broker ] || exit 94\n\- [ \"$3\" = app.motrix.native ] || exit 95\n\- cat >/dev/null\n\- printf '{}'\n",- shell_quote(&marker),- shell_octal(&response),- );- make_executable(&flatpak, script.as_bytes());-- let mut runtime = FlatpakProcessRuntime::new(flatpak.clone());- assert_eq!(- runtime- .call_broker(BrokerOperation::Probe)- .expect("probe broker"),- error(ResolveError::NotRunning)- );- assert!(runtime.launch_app());- for _ in 0..100 {- if marker.exists() {- break;- }- std::thread::sleep(Duration::from_millis(5));- }- assert!(marker.exists(), "fixed Flatpak launch command was not used");-- let polluted_script = format!(- "#!/bin/sh\ncat >/dev/null\nprintf '{}x'\n",- shell_octal(&response)- );- make_executable(&flatpak, polluted_script.as_bytes());- assert!(runtime.call_broker(BrokerOperation::Probe).is_err());-- let unexpected = encode_broker_message(&error(ResolveError::LaunchFailed))- .expect("encode unexpected response");- let unexpected_script = format!(- "#!/bin/sh\ncat >/dev/null\nprintf '{}'\n",- shell_octal(&unexpected)- );- make_executable(&flatpak, unexpected_script.as_bytes());- assert!(runtime.call_broker(BrokerOperation::Probe).is_err());- }-- #[test]- fn allowlist_file_is_strict_and_matches_manifest_contract() {- let allowlist = embedded_allowlist().expect("embedded allowlist");- assert_eq!(allowlist.chromium, [CHROMIUM_ID]);- assert_eq!(allowlist.firefox, [FIREFOX_ID]);- assert!(!super::is_chromium_extension_id(- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaA"- ));- assert!(!super::is_firefox_extension_id("invalid [email protected]"));- assert!(super::absolute_root(OsStr::new("relative"), "path").is_err());- }-}+use allowlist::{is_chromium_extension_id, is_firefox_extension_id};+#[cfg(test)]+use paths::absolute_root;diff --git a/packages/native-host/src/flatpak_companion/allowlist.rs b/packages/native-host/src/flatpak_companion/allowlist.rsnew file mode 100644index 00000000..dc7190aa--- /dev/null+++ b/packages/native-host/src/flatpak_companion/allowlist.rs@@ -0,0 +1,54 @@+use serde::Deserialize;++use super::CompanionError;++const EMBEDDED_ALLOWLIST: &str =+ include_str!("../../../../src/shared/config/native-messaging-extensions.json");++#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]+#[serde(deny_unknown_fields)]+pub struct NativeMessagingAllowlist {+ pub chromium: Vec<String>,+ pub firefox: Vec<String>,+}++pub fn embedded_allowlist() -> Result<NativeMessagingAllowlist, CompanionError> {+ let allowlist: NativeMessagingAllowlist = serde_json::from_str(EMBEDDED_ALLOWLIST)+ .map_err(|error| CompanionError::new(format!("invalid embedded allowlist: {error}")))?;+ if allowlist.chromium.is_empty() || allowlist.firefox.is_empty() {+ return Err(CompanionError::new("embedded allowlist must not be empty"));+ }+ for id in &allowlist.chromium {+ if !is_chromium_extension_id(id) {+ return Err(CompanionError::new(format!(+ "invalid embedded Chromium extension ID: {id}"+ )));+ }+ }+ for id in &allowlist.firefox {+ if !is_firefox_extension_id(id) {+ return Err(CompanionError::new(format!(+ "invalid embedded Firefox extension ID: {id}"+ )));+ }+ }+ Ok(allowlist)+}++pub(super) fn is_chromium_extension_id(id: &str) -> bool {+ id.len() == 32 && id.bytes().all(|byte| (b'a'..=b'p').contains(&byte))+}++pub(super) fn is_firefox_extension_id(id: &str) -> bool {+ let mut parts = id.split('@');+ matches!(+ (parts.next(), parts.next(), parts.next()),+ (Some(left), Some(right), None) if !left.is_empty() && !right.is_empty()+ && !id.bytes().any(|byte| byte.is_ascii_whitespace())+ ) || (id.starts_with('{')+ && id.ends_with('}')+ && id.len() == 38+ && id[1..id.len() - 1]+ .bytes()+ .all(|byte| byte.is_ascii_hexdigit() || byte == b'-'))+}diff --git a/packages/native-host/src/flatpak_companion/command.rs b/packages/native-host/src/flatpak_companion/command.rsnew file mode 100644index 00000000..744d215c--- /dev/null+++ b/packages/native-host/src/flatpak_companion/command.rs@@ -0,0 +1,126 @@+use std::ffi::OsString;+use std::path::PathBuf;++use super::allowlist::NativeMessagingAllowlist;+use super::paths::{CompanionPaths, ManifestFamily, absolute_root};+use super::{CompanionError, DEFAULT_FLATPAK_BIN};++#[derive(Clone, Debug, Eq, PartialEq)]+pub enum CompanionCommand {+ Browser,+ Install { flatpak_bin: PathBuf, force: bool },+ Status,+ Uninstall,+ Help,+ Version,+}++pub fn parse_companion_command(args: &[OsString]) -> Result<CompanionCommand, CompanionError> {+ let Some(first) = args.first().and_then(|value| value.to_str()) else {+ return Ok(CompanionCommand::Browser);+ };+ match first {+ "install" => {+ let mut flatpak_bin = None;+ let mut force = false;+ let mut index = 1;+ while index < args.len() {+ let flag = args[index]+ .to_str()+ .ok_or_else(|| CompanionError::new("install arguments must be UTF-8"))?;+ match flag {+ "--force" if !force => force = true,+ "--force" => return Err(CompanionError::new("--force provided twice")),+ "--flatpak-bin" if flatpak_bin.is_none() => {+ index += 1;+ let value = args+ .get(index)+ .ok_or_else(|| CompanionError::new("--flatpak-bin requires a value"))?;+ flatpak_bin = Some(absolute_root(value, "--flatpak-bin")?);+ }+ "--flatpak-bin" => {+ return Err(CompanionError::new("--flatpak-bin provided twice"));+ }+ _ => {+ return Err(CompanionError::new(format!(+ "unknown install argument: {flag}"+ )));+ }+ }+ index += 1;+ }+ Ok(CompanionCommand::Install {+ flatpak_bin: flatpak_bin.unwrap_or_else(|| PathBuf::from(DEFAULT_FLATPAK_BIN)),+ force,+ })+ }+ "status" if args.len() == 1 => Ok(CompanionCommand::Status),+ "uninstall" if args.len() == 1 => Ok(CompanionCommand::Uninstall),+ "--help" if args.len() == 1 => Ok(CompanionCommand::Help),+ "--version" if args.len() == 1 => Ok(CompanionCommand::Version),+ "status" | "uninstall" | "--help" | "--version" => {+ Err(CompanionError::new(format!("{first} takes no arguments")))+ }+ _ => Ok(CompanionCommand::Browser),+ }+}++#[derive(Clone, Debug, Eq, PartialEq)]+pub enum BrowserCaller {+ Chromium { extension_id: String },+ Firefox { extension_id: String },+}++pub fn validate_browser_caller(+ args: &[OsString],+ allowlist: &NativeMessagingAllowlist,+ paths: &CompanionPaths,+) -> Result<BrowserCaller, CompanionError> {+ if args.len() == 1 {+ let origin = args[0]+ .to_str()+ .ok_or_else(|| CompanionError::new("Chromium caller origin must be UTF-8"))?;+ let extension_id = origin+ .strip_prefix("chrome-extension://")+ .map(|value| value.strip_suffix('/').unwrap_or(value))+ .filter(|value| !value.contains('/'))+ .ok_or_else(|| CompanionError::new("invalid Chromium caller origin"))?;+ if !allowlist+ .chromium+ .iter()+ .any(|allowed| allowed == extension_id)+ {+ return Err(CompanionError::new("Chromium caller is not allowlisted"));+ }+ return Ok(BrowserCaller::Chromium {+ extension_id: extension_id.into(),+ });+ }++ if args.len() == 2 {+ let manifest_path = PathBuf::from(&args[0]);+ let expected_manifest = paths+ .manifests+ .iter()+ .find(|target| target.family == ManifestFamily::Firefox)+ .map(|target| &target.path);+ if !manifest_path.is_absolute() || Some(&manifest_path) != expected_manifest {+ return Err(CompanionError::new("unexpected Firefox manifest path"));+ }+ let extension_id = args[1]+ .to_str()+ .ok_or_else(|| CompanionError::new("Firefox caller ID must be UTF-8"))?;+ if !allowlist+ .firefox+ .iter()+ .any(|allowed| allowed == extension_id)+ {+ return Err(CompanionError::new("Firefox caller is not allowlisted"));+ }+ return Ok(BrowserCaller::Firefox {+ extension_id: extension_id.into(),+ });+ }++ Err(CompanionError::new("missing or malformed browser caller"))+}diff --git a/packages/native-host/src/flatpak_companion/installation.rs b/packages/native-host/src/flatpak_companion/installation.rsnew file mode 100644index 00000000..380b08bc--- /dev/null+++ b/packages/native-host/src/flatpak_companion/installation.rs@@ -0,0 +1,268 @@+use std::fs;+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use super::CompanionError;+use super::allowlist::NativeMessagingAllowlist;+use super::manifest::{manifest_bytes, manifest_points_to};+use super::paths::CompanionPaths;+use super::secure_fs::{+ OwnerRequirement, atomic_copy, atomic_write, destination_root, path_entry_exists,+ path_entry_is_symlink, read_limited, validate_existing_private_parent_prefix,+ validate_flatpak_binary, validate_private_file, validate_private_parent, validate_regular_file,+ validate_source_executable,+};+use crate::broker_protocol::MAX_BROKER_MESSAGE_BYTES;++const CONFIG_SCHEMA_VERSION: u32 = 1;++#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct CompanionConfig {+ schema_version: u32,+ flatpak_bin: PathBuf,+ installed_binary: PathBuf,+}++impl CompanionConfig {+ fn new(flatpak_bin: PathBuf, installed_binary: PathBuf) -> Self {+ Self {+ schema_version: CONFIG_SCHEMA_VERSION,+ flatpak_bin,+ installed_binary,+ }+ }++ pub fn flatpak_bin(&self) -> &Path {+ &self.flatpak_bin+ }+}++pub fn install_companion(+ paths: &CompanionPaths,+ source_executable: &Path,+ flatpak_bin: &Path,+ allowlist: &NativeMessagingAllowlist,+ force: bool,+) -> Result<(), CompanionError> {+ let canonical_flatpak = validate_flatpak_binary(flatpak_bin)?;+ let canonical_source = validate_source_executable(source_executable)?;++ for destination in std::iter::once(&paths.binary)+ .chain(std::iter::once(&paths.config))+ .chain(paths.manifests.iter().map(|target| &target.path))+ {+ validate_private_parent(destination_root(paths, destination)?, destination, true)?;+ }++ let existing_config = validate_private_file(paths, &paths.config, 0o600)+ .ok()+ .and_then(|()| read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64).ok())+ .and_then(|bytes| serde_json::from_slice::<CompanionConfig>(&bytes).ok());+ let config_owned = existing_config.as_ref().is_some_and(|config| {+ config.schema_version == CONFIG_SCHEMA_VERSION && config.installed_binary == paths.binary+ });++ if path_entry_exists(&paths.config)+ && (path_entry_is_symlink(&paths.config) || !config_owned)+ && !force+ {+ return Err(CompanionError::new(format!(+ "refusing to replace unowned config {}; pass --force",+ paths.config.display()+ )));+ }+ for target in &paths.manifests {+ let manifest_owned = validate_private_file(paths, &target.path, 0o600).is_ok()+ && manifest_points_to(&target.path, &paths.binary);+ if path_entry_exists(&target.path)+ && (path_entry_is_symlink(&target.path) || !manifest_owned)+ && !force+ {+ return Err(CompanionError::new(format!(+ "refusing to replace unowned manifest {}; pass --force",+ target.path.display()+ )));+ }+ }+ let source_is_installed =+ fs::canonicalize(&paths.binary).is_ok_and(|installed| installed == canonical_source);+ let binary_owned = validate_private_file(paths, &paths.binary, 0o700).is_ok() && config_owned;+ if !source_is_installed+ && path_entry_exists(&paths.binary)+ && (path_entry_is_symlink(&paths.binary) || !binary_owned)+ && !force+ {+ return Err(CompanionError::new(format!(+ "refusing to replace unowned binary {}; pass --force",+ paths.binary.display()+ )));+ }++ if source_is_installed {+ validate_private_file(paths, &paths.binary, 0o700)?;+ } else {+ atomic_copy(source_executable, &paths.data_root, &paths.binary)?;+ }+ let config = CompanionConfig::new(canonical_flatpak, paths.binary.clone());+ let mut config_bytes = serde_json::to_vec_pretty(&config)+ .map_err(|error| CompanionError::new(format!("serialize config: {error}")))?;+ config_bytes.push(b'\n');+ atomic_write(&paths.config_root, &paths.config, &config_bytes, false)?;+ for target in &paths.manifests {+ atomic_write(+ destination_root(paths, &target.path)?,+ &target.path,+ &manifest_bytes(target, &paths.binary, allowlist)?,+ false,+ )?;+ }+ Ok(())+}++pub fn load_companion_config(+ paths: &CompanionPaths,+ current_executable: &Path,+) -> Result<CompanionConfig, CompanionError> {+ validate_private_file(paths, &paths.config, 0o600)?;+ validate_private_file(paths, &paths.binary, 0o700)?;+ let bytes = read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64)?;+ let config: CompanionConfig = serde_json::from_slice(&bytes)+ .map_err(|error| CompanionError::new(format!("invalid companion config: {error}")))?;+ let expected_executable = fs::canonicalize(&paths.binary).map_err(|error| {+ CompanionError::io("resolve installed executable", &paths.binary, error)+ })?;+ let actual_executable = fs::canonicalize(current_executable).map_err(|error| {+ CompanionError::io("resolve current executable", current_executable, error)+ })?;+ if config.schema_version != CONFIG_SCHEMA_VERSION+ || config.installed_binary != paths.binary+ || actual_executable != expected_executable+ {+ return Err(CompanionError::new(+ "companion config does not own this executable",+ ));+ }+ let canonical_flatpak = validate_flatpak_binary(&config.flatpak_bin)?;+ if canonical_flatpak != config.flatpak_bin {+ return Err(CompanionError::new(+ "configured flatpak binary path is not canonical",+ ));+ }+ Ok(config)+}++#[derive(Clone, Debug, Eq, PartialEq)]+pub struct CompanionStatus {+ pub installed: bool,+ pub issues: Vec<String>,+}++pub fn companion_status(+ paths: &CompanionPaths,+ allowlist: &NativeMessagingAllowlist,+) -> CompanionStatus {+ let mut issues = Vec::new();+ let config = validate_private_file(paths, &paths.config, 0o600)+ .and_then(|()| read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64))+ .ok()+ .and_then(|bytes| serde_json::from_slice::<CompanionConfig>(&bytes).ok());+ if config.as_ref().is_none_or(|config| {+ config.schema_version != CONFIG_SCHEMA_VERSION || config.installed_binary != paths.binary+ }) {+ issues.push("config missing, malformed, or unowned".into());+ } else if let Some(config) = &config+ && !validate_flatpak_binary(&config.flatpak_bin)+ .is_ok_and(|canonical| canonical == config.flatpak_bin)+ {+ issues.push("configured flatpak binary is unavailable or unsafe".into());+ }++ if validate_private_file(paths, &paths.binary, 0o700).is_err() {+ issues.push("installed companion binary is missing or unsafe".into());+ }++ for target in &paths.manifests {+ let expected = manifest_bytes(target, &paths.binary, allowlist)+ .ok()+ .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());+ let actual = validate_private_file(paths, &target.path, 0o600)+ .and_then(|()| read_limited(&target.path, MAX_BROKER_MESSAGE_BYTES as u64))+ .ok()+ .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());+ if expected.is_none() || expected != actual {+ issues.push(format!(+ "manifest missing or stale: {}",+ target.path.display()+ ));+ }+ }++ CompanionStatus {+ installed: issues.is_empty(),+ issues,+ }+}++pub fn uninstall_companion(paths: &CompanionPaths) -> Result<(), CompanionError> {+ let destinations = std::iter::once(&paths.binary)+ .chain(std::iter::once(&paths.config))+ .chain(paths.manifests.iter().map(|target| &target.path));+ for destination in destinations.clone() {+ validate_existing_private_parent_prefix(+ destination_root(paths, destination)?,+ destination,+ )?;+ }+ if !destinations.clone().any(|path| path_entry_exists(path)) {+ return Ok(());+ }++ for destination in destinations {+ if !path_entry_exists(destination) {+ continue;+ }+ validate_private_parent(destination_root(paths, destination)?, destination, false)?;+ validate_regular_file(destination, OwnerRequirement::Current, None, false)?;+ }++ let config_owned = if path_entry_exists(&paths.config) {+ validate_private_file(paths, &paths.config, 0o600).is_ok()+ && read_limited(&paths.config, MAX_BROKER_MESSAGE_BYTES as u64)+ .ok()+ .and_then(|bytes| serde_json::from_slice::<CompanionConfig>(&bytes).ok())+ .is_some_and(|config| {+ config.schema_version == CONFIG_SCHEMA_VERSION+ && config.installed_binary == paths.binary+ })+ } else {+ false+ };+ let mut manifests_to_remove = Vec::new();+ for target in &paths.manifests {+ if path_entry_exists(&target.path)+ && validate_private_file(paths, &target.path, 0o600).is_ok()+ && manifest_points_to(&target.path, &paths.binary)+ {+ manifests_to_remove.push(&target.path);+ }+ }+ if config_owned && path_entry_exists(&paths.binary) {+ validate_private_file(paths, &paths.binary, 0o700)?;+ }++ for manifest in manifests_to_remove {+ fs::remove_file(manifest)+ .map_err(|error| CompanionError::io("remove manifest", manifest, error))?;+ }+ if config_owned {+ fs::remove_file(&paths.config)+ .map_err(|error| CompanionError::io("remove config", &paths.config, error))?;+ }+ if config_owned && paths.binary.exists() {+ fs::remove_file(&paths.binary)+ .map_err(|error| CompanionError::io("remove companion binary", &paths.binary, error))?;+ }+ Ok(())+}diff --git a/packages/native-host/src/flatpak_companion/manifest.rs b/packages/native-host/src/flatpak_companion/manifest.rsnew file mode 100644index 00000000..de117b8e--- /dev/null+++ b/packages/native-host/src/flatpak_companion/manifest.rs@@ -0,0 +1,76 @@+use std::path::{Path, PathBuf};++use serde::{Deserialize, Serialize};++use super::allowlist::NativeMessagingAllowlist;+use super::paths::{ManifestFamily, ManifestTarget};+use super::secure_fs::read_limited;+use super::{CompanionError, NATIVE_MESSAGING_HOST_NAME};+use crate::broker_protocol::MAX_BROKER_MESSAGE_BYTES;++const MANIFEST_DESCRIPTION: &str = "Motrix browser download bridge";++#[derive(Serialize)]+struct ChromiumManifest<'a> {+ name: &'static str,+ description: &'static str,+ path: &'a Path,+ r#type: &'static str,+ allowed_origins: Vec<String>,+}++#[derive(Serialize)]+struct FirefoxManifest<'a> {+ name: &'static str,+ description: &'static str,+ path: &'a Path,+ r#type: &'static str,+ allowed_extensions: &'a [String],+}++pub(super) fn manifest_bytes(+ target: &ManifestTarget,+ binary: &Path,+ allowlist: &NativeMessagingAllowlist,+) -> Result<Vec<u8>, CompanionError> {+ let value = match target.family {+ ManifestFamily::Chromium => serde_json::to_value(ChromiumManifest {+ name: NATIVE_MESSAGING_HOST_NAME,+ description: MANIFEST_DESCRIPTION,+ path: binary,+ r#type: "stdio",+ allowed_origins: allowlist+ .chromium+ .iter()+ .map(|id| format!("chrome-extension://{id}/"))+ .collect(),+ }),+ ManifestFamily::Firefox => serde_json::to_value(FirefoxManifest {+ name: NATIVE_MESSAGING_HOST_NAME,+ description: MANIFEST_DESCRIPTION,+ path: binary,+ r#type: "stdio",+ allowed_extensions: &allowlist.firefox,+ }),+ }+ .map_err(|error| CompanionError::new(format!("serialize manifest: {error}")))?;+ let mut bytes = serde_json::to_vec_pretty(&value)+ .map_err(|error| CompanionError::new(format!("serialize manifest: {error}")))?;+ bytes.push(b'\n');+ Ok(bytes)+}++#[derive(Deserialize)]+struct ManifestOwnership {+ name: String,+ path: PathBuf,+}++pub(super) fn manifest_points_to(path: &Path, binary: &Path) -> bool {+ let Ok(bytes) = read_limited(path, MAX_BROKER_MESSAGE_BYTES as u64) else {+ return false;+ };+ serde_json::from_slice::<ManifestOwnership>(&bytes).is_ok_and(|manifest| {+ manifest.name == NATIVE_MESSAGING_HOST_NAME && manifest.path == binary+ })+}diff --git a/packages/native-host/src/flatpak_companion/paths.rs b/packages/native-host/src/flatpak_companion/paths.rsnew file mode 100644index 00000000..e7b986b7--- /dev/null+++ b/packages/native-host/src/flatpak_companion/paths.rs@@ -0,0 +1,122 @@+use std::ffi::OsStr;+use std::path::{Component, Path, PathBuf};++use super::{CompanionError, FLATPAK_COMPANION_BINARY};++const MANIFEST_FILE_NAME: &str = "app.motrix.bridge.json";++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ManifestFamily {+ Chromium,+ Firefox,+}++#[derive(Clone, Debug, Eq, PartialEq)]+pub struct ManifestTarget {+ pub family: ManifestFamily,+ pub path: PathBuf,+}++#[derive(Clone, Debug, Eq, PartialEq)]+pub struct CompanionPaths {+ pub home_root: PathBuf,+ pub data_root: PathBuf,+ pub config_root: PathBuf,+ pub binary: PathBuf,+ pub config: PathBuf,+ pub manifests: Vec<ManifestTarget>,+}++pub(super) fn absolute_root(value: &OsStr, label: &str) -> Result<PathBuf, CompanionError> {+ let text = value+ .to_str()+ .ok_or_else(|| CompanionError::new(format!("{label} must be valid UTF-8")))?;+ if text.is_empty() || text.trim() != text {+ return Err(CompanionError::new(format!(+ "{label} must not be empty or padded"+ )));+ }+ let path = PathBuf::from(value);+ if !path.is_absolute()+ || path.parent().is_none()+ || path+ .components()+ .any(|component| matches!(component, Component::CurDir | Component::ParentDir))+ {+ return Err(CompanionError::new(format!(+ "{label} must be a canonical absolute path"+ )));+ }+ Ok(path)+}++pub fn resolve_companion_paths(+ home: &Path,+ xdg_data_home: Option<&OsStr>,+ xdg_config_home: Option<&OsStr>,+) -> Result<CompanionPaths, CompanionError> {+ let home = absolute_root(home.as_os_str(), "home")?;+ let data_home = match xdg_data_home {+ Some(value) if !value.is_empty() => absolute_root(value, "XDG_DATA_HOME")?,+ Some(_) | None => home.join(".local").join("share"),+ };+ let config_home = match xdg_config_home {+ Some(value) if !value.is_empty() => absolute_root(value, "XDG_CONFIG_HOME")?,+ Some(_) | None => home.join(".config"),+ };+ let binary = data_home+ .join("motrix")+ .join("native-messaging")+ .join(FLATPAK_COMPANION_BINARY);+ let config = config_home+ .join("motrix")+ .join("native-messaging")+ .join("flatpak-companion.json");+ let manifests = vec![+ ManifestTarget {+ family: ManifestFamily::Chromium,+ path: config_home+ .join("google-chrome")+ .join("NativeMessagingHosts")+ .join(MANIFEST_FILE_NAME),+ },+ ManifestTarget {+ family: ManifestFamily::Chromium,+ path: config_home+ .join("chromium")+ .join("NativeMessagingHosts")+ .join(MANIFEST_FILE_NAME),+ },+ ManifestTarget {+ family: ManifestFamily::Chromium,+ path: config_home+ .join("microsoft-edge")+ .join("NativeMessagingHosts")+ .join(MANIFEST_FILE_NAME),+ },+ ManifestTarget {+ family: ManifestFamily::Firefox,+ path: home+ .join(".mozilla")+ .join("native-messaging-hosts")+ .join(MANIFEST_FILE_NAME),+ },+ ];+ Ok(CompanionPaths {+ home_root: home,+ data_root: data_home,+ config_root: config_home,+ binary,+ config,+ manifests,+ })+}++pub fn current_companion_paths() -> Result<CompanionPaths, CompanionError> {+ let home = home::home_dir().ok_or_else(|| CompanionError::new("home directory unavailable"))?;+ resolve_companion_paths(+ &home,+ std::env::var_os("XDG_DATA_HOME").as_deref(),+ std::env::var_os("XDG_CONFIG_HOME").as_deref(),+ )+}diff --git a/packages/native-host/src/flatpak_companion/runtime.rs b/packages/native-host/src/flatpak_companion/runtime.rsnew file mode 100644index 00000000..86afbea5--- /dev/null+++ b/packages/native-host/src/flatpak_companion/runtime.rs@@ -0,0 +1,226 @@+use std::io::Read;+use std::path::PathBuf;+use std::process::{Command, ExitStatus, Stdio};+use std::sync::mpsc;+use std::thread;+use std::time::{Duration, Instant};++use super::{CompanionError, FLATPAK_BROKER_COMMAND, MOTRIX_FLATPAK_ID};+use crate::broker_protocol::{+ BROKER_HEADER_BYTES, BrokerOperation, BrokerRequest, MAX_BROKER_MESSAGE_BYTES,+ decode_broker_response, write_broker_message,+};+use crate::resolve::{ResolveError, ResolveResult};++const PROBE_PROCESS_TIMEOUT: Duration = Duration::from_secs(10);+// The broker's endpoint polling deadline is independently fixed at 15s. Give+// Flatpak process startup enough headroom without extending that security+// boundary on slower hosts.+const WAIT_PROCESS_TIMEOUT: Duration = Duration::from_secs(30);+const OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);+const CHILD_POLL_INTERVAL: Duration = Duration::from_millis(10);++pub trait FlatpakRuntime {+ fn call_broker(&mut self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError>;+ fn launch_app(&mut self) -> bool;+}++pub fn resolve_flatpak_request<R: FlatpakRuntime>(+ allow_launch: bool,+ runtime: &mut R,+) -> ResolveResult {+ match runtime.call_broker(BrokerOperation::Probe) {+ Ok(result @ ResolveResult::RequestPair { .. }) => return result,+ Ok(ResolveResult::Error {+ error: ResolveError::NotRunning,+ }) => {}+ Ok(_) | Err(_) if !allow_launch => {+ return ResolveResult::Error {+ error: ResolveError::NotRunning,+ };+ }+ Ok(_) | Err(_) => {+ return ResolveResult::Error {+ error: ResolveError::NotInstalled,+ };+ }+ }++ if !allow_launch {+ return ResolveResult::Error {+ error: ResolveError::NotRunning,+ };+ }+ if !runtime.launch_app() {+ return ResolveResult::Error {+ error: ResolveError::NotInstalled,+ };+ }+ match runtime.call_broker(BrokerOperation::WaitForEndpoint) {+ Ok(result @ ResolveResult::RequestPair { .. }) => result,+ Ok(_) | Err(_) => ResolveResult::Error {+ error: ResolveError::LaunchFailed,+ },+ }+}++pub struct FlatpakProcessRuntime {+ flatpak_bin: PathBuf,+}++impl FlatpakProcessRuntime {+ pub fn new(flatpak_bin: PathBuf) -> Self {+ Self { flatpak_bin }+ }++ fn wait_for_child(+ mut child: std::process::Child,+ timeout: Duration,+ ) -> Result<(ExitStatus, Vec<u8>), CompanionError> {+ let Some(stdout) = child.stdout.take() else {+ let _ = child.kill();+ let _ = child.wait();+ return Err(CompanionError::new("broker stdout pipe unavailable"));+ };+ let (sender, receiver) = mpsc::sync_channel(1);+ if let Err(error) = thread::Builder::new()+ .name("flatpak-broker-output".into())+ .spawn(move || {+ let mut output = Vec::new();+ let maximum = BROKER_HEADER_BYTES + MAX_BROKER_MESSAGE_BYTES + 1;+ let result = stdout+ .take(maximum as u64)+ .read_to_end(&mut output)+ .map(|_| output);+ let _ = sender.send(result);+ })+ {+ let _ = child.kill();+ let _ = child.wait();+ return Err(CompanionError::new(format!("spawn output reader: {error}")));+ }++ let deadline = Instant::now()+ .checked_add(timeout)+ .ok_or_else(|| CompanionError::new("broker deadline overflow"))?;+ let status = loop {+ match child.try_wait() {+ Ok(Some(status)) => break status,+ Ok(None) if Instant::now() < deadline => thread::sleep(CHILD_POLL_INTERVAL),+ Ok(None) => {+ let _ = child.kill();+ let _ = child.wait();+ return Err(CompanionError::new("Flatpak broker timed out"));+ }+ Err(error) => {+ let _ = child.kill();+ let _ = child.wait();+ return Err(CompanionError::new(format!(+ "wait for Flatpak broker: {error}"+ )));+ }+ }+ };+ let output = receiver+ .recv_timeout(OUTPUT_DRAIN_TIMEOUT)+ .map_err(|_| CompanionError::new("Flatpak broker stdout did not close"))?+ .map_err(|error| CompanionError::new(format!("read Flatpak broker stdout: {error}")))?;+ if output.len() > BROKER_HEADER_BYTES + MAX_BROKER_MESSAGE_BYTES {+ return Err(CompanionError::new("Flatpak broker output exceeded limit"));+ }+ Ok((status, output))+ }++ fn invoke_broker(&self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError> {+ let mut child = Command::new(&self.flatpak_bin)+ .arg("run")+ .arg(format!("--command={FLATPAK_BROKER_COMMAND}"))+ .arg(MOTRIX_FLATPAK_ID)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::inherit())+ .spawn()+ .map_err(|error| CompanionError::new(format!("start Flatpak broker: {error}")))?;+ let Some(mut stdin) = child.stdin.take() else {+ let _ = child.kill();+ let _ = child.wait();+ return Err(CompanionError::new("broker stdin pipe unavailable"));+ };+ if let Err(error) = write_broker_message(&mut stdin, &BrokerRequest { operation }) {+ let _ = child.kill();+ let _ = child.wait();+ return Err(CompanionError::new(format!(+ "write broker request: {error}"+ )));+ }+ drop(stdin);+ let timeout = match operation {+ BrokerOperation::Probe => PROBE_PROCESS_TIMEOUT,+ BrokerOperation::WaitForEndpoint => WAIT_PROCESS_TIMEOUT,+ };+ let (status, output) = Self::wait_for_child(child, timeout)?;+ if !status.success() {+ return Err(CompanionError::new(format!(+ "Flatpak broker exited with {status}"+ )));+ }+ let result = decode_broker_response(&output)+ .map_err(|error| CompanionError::new(format!("validate broker response: {error}")))?;+ let expected = matches!(+ (operation, &result),+ (BrokerOperation::Probe, ResolveResult::RequestPair { .. })+ | (+ BrokerOperation::Probe,+ ResolveResult::Error {+ error: ResolveError::NotRunning+ }+ )+ | (+ BrokerOperation::WaitForEndpoint,+ ResolveResult::RequestPair { .. }+ )+ | (+ BrokerOperation::WaitForEndpoint,+ ResolveResult::Error {+ error: ResolveError::LaunchFailed+ }+ )+ );+ if !expected {+ return Err(CompanionError::new(+ "broker returned a result invalid for the requested operation",+ ));+ }+ Ok(result)+ }+}++impl FlatpakRuntime for FlatpakProcessRuntime {+ fn call_broker(&mut self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError> {+ self.invoke_broker(operation)+ }++ fn launch_app(&mut self) -> bool {+ let mut command = Command::new(&self.flatpak_bin);+ command+ .arg("run")+ .arg(MOTRIX_FLATPAK_ID)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ command.process_group(0);+ }+ match command.spawn() {+ Ok(mut child) => {+ thread::spawn(move || {+ let _ = child.wait();+ });+ true+ }+ Err(_) => false,+ }+ }+}diff --git a/packages/native-host/src/flatpak_companion/secure_fs.rs b/packages/native-host/src/flatpak_companion/secure_fs.rsnew file mode 100644index 00000000..4fcfb07b--- /dev/null+++ b/packages/native-host/src/flatpak_companion/secure_fs.rs@@ -0,0 +1,484 @@+use std::ffi::OsStr;+use std::fs::{self, File, OpenOptions};+use std::io::{Read, Write};+use std::path::{Component, Path, PathBuf};+use std::time::{SystemTime, UNIX_EPOCH};++use super::CompanionError;+use super::paths::{CompanionPaths, ManifestFamily, absolute_root};++pub(super) fn read_limited(path: &Path, maximum: u64) -> Result<Vec<u8>, CompanionError> {+ let file = File::open(path).map_err(|error| CompanionError::io("open", path, error))?;+ let mut bytes = Vec::new();+ file.take(maximum + 1)+ .read_to_end(&mut bytes)+ .map_err(|error| CompanionError::io("read", path, error))?;+ if bytes.len() as u64 > maximum {+ return Err(CompanionError::new(format!(+ "{} exceeds {maximum} bytes",+ path.display()+ )));+ }+ Ok(bytes)+}++pub(super) fn path_entry_exists(path: &Path) -> bool {+ match fs::symlink_metadata(path) {+ Ok(_) => true,+ Err(error) => error.kind() != std::io::ErrorKind::NotFound,+ }+}++pub(super) fn path_entry_is_symlink(path: &Path) -> bool {+ fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())+}++#[derive(Clone, Copy)]+pub(super) enum OwnerRequirement {+ Current,+ CurrentOrRoot,+}++#[cfg(unix)]+fn effective_user_id() -> u32 {+ unsafe extern "C" {+ fn geteuid() -> u32;+ }++ // SAFETY: geteuid has no preconditions and does not dereference pointers.+ unsafe { geteuid() }+}++fn entry_metadata(path: &Path) -> Result<Option<fs::Metadata>, CompanionError> {+ match fs::symlink_metadata(path) {+ Ok(metadata) => Ok(Some(metadata)),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(error) => Err(CompanionError::io("inspect", path, error)),+ }+}++fn validate_owner(+ path: &Path,+ metadata: &fs::Metadata,+ requirement: OwnerRequirement,+) -> Result<(), CompanionError> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;++ let owner = metadata.uid();+ let current = effective_user_id();+ let accepted = owner == current+ || matches!(requirement, OwnerRequirement::CurrentOrRoot) && owner == 0;+ if !accepted {+ return Err(CompanionError::new(format!(+ "{} is not owned by the current user{}",+ path.display(),+ if matches!(requirement, OwnerRequirement::CurrentOrRoot) {+ " or root"+ } else {+ ""+ }+ )));+ }+ }+ #[cfg(not(unix))]+ let _ = (path, metadata, requirement);+ Ok(())+}++fn validate_directory(+ path: &Path,+ requirement: OwnerRequirement,+ allow_shared_sticky: bool,+) -> Result<(), CompanionError> {+ let metadata = fs::symlink_metadata(path)+ .map_err(|error| CompanionError::io("inspect directory", path, error))?;+ if metadata.file_type().is_symlink() || !metadata.is_dir() {+ return Err(CompanionError::new(format!(+ "{} is not a real directory",+ path.display()+ )));+ }+ validate_owner(path, &metadata, requirement)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;++ let mode = metadata.permissions().mode();+ if mode & 0o022 != 0 && !(allow_shared_sticky && mode & 0o1000 != 0) {+ return Err(CompanionError::new(format!(+ "{} is writable by another user",+ path.display()+ )));+ }+ }+ #[cfg(not(unix))]+ let _ = allow_shared_sticky;+ Ok(())+}++fn create_private_directory(path: &Path) -> Result<(), CompanionError> {+ #[cfg(unix)]+ let mut builder = fs::DirBuilder::new();+ #[cfg(unix)]+ {+ use std::os::unix::fs::DirBuilderExt;+ builder.mode(0o700);+ }+ #[cfg(not(unix))]+ let builder = fs::DirBuilder::new();+ let created = match builder.create(path) {+ Ok(()) => true,+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,+ Err(error) => return Err(CompanionError::io("create directory", path, error)),+ };+ if !created {+ return validate_directory(path, OwnerRequirement::Current, false);+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(path, fs::Permissions::from_mode(0o700))+ .map_err(|error| CompanionError::io("set directory permissions", path, error))?;+ }+ validate_directory(path, OwnerRequirement::Current, false)+}++fn prepare_private_root(root: &Path, create: bool) -> Result<(), CompanionError> {+ match entry_metadata(root)? {+ Some(_) => {+ validate_executable_parent_chain(root)?;+ return validate_directory(root, OwnerRequirement::Current, false);+ }+ None if !create => {+ return Err(CompanionError::new(format!(+ "private root is missing: {}",+ root.display()+ )));+ }+ None => {}+ }++ let mut missing = vec![root.to_path_buf()];+ let mut cursor = root+ .parent()+ .ok_or_else(|| CompanionError::new(format!("{} has no parent", root.display())))?;+ loop {+ match entry_metadata(cursor)? {+ Some(_) => {+ if cursor.parent().is_some() {+ validate_executable_parent_chain(cursor)?;+ }+ validate_directory(cursor, OwnerRequirement::CurrentOrRoot, true)?;+ break;+ }+ None => missing.push(cursor.to_path_buf()),+ }+ cursor = cursor.parent().ok_or_else(|| {+ CompanionError::new(format!("no existing ancestor for {}", root.display()))+ })?;+ }++ for directory in missing.iter().rev() {+ create_private_directory(directory)?;+ }+ validate_directory(root, OwnerRequirement::Current, false)+}++pub(super) fn validate_private_parent(+ root: &Path,+ path: &Path,+ create: bool,+) -> Result<(), CompanionError> {+ let parent = path+ .parent()+ .ok_or_else(|| CompanionError::new(format!("{} has no parent", path.display())))?;+ let relative = parent.strip_prefix(root).map_err(|_| {+ CompanionError::new(format!(+ "{} escapes private root {}",+ path.display(),+ root.display()+ ))+ })?;+ prepare_private_root(root, create)?;++ let mut directory = root.to_path_buf();+ for component in relative.components() {+ let Component::Normal(name) = component else {+ return Err(CompanionError::new(format!(+ "{} has a non-canonical component",+ path.display()+ )));+ };+ directory.push(name);+ match entry_metadata(&directory)? {+ Some(_) => validate_directory(&directory, OwnerRequirement::Current, false)?,+ None if create => create_private_directory(&directory)?,+ None => {+ return Err(CompanionError::new(format!(+ "private directory is missing: {}",+ directory.display()+ )));+ }+ }+ }+ Ok(())+}++pub(super) fn validate_existing_private_parent_prefix(+ root: &Path,+ path: &Path,+) -> Result<(), CompanionError> {+ let parent = path+ .parent()+ .ok_or_else(|| CompanionError::new(format!("{} has no parent", path.display())))?;+ let relative = parent.strip_prefix(root).map_err(|_| {+ CompanionError::new(format!(+ "{} escapes private root {}",+ path.display(),+ root.display()+ ))+ })?;+ if entry_metadata(root)?.is_none() {+ return Ok(());+ }+ validate_directory(root, OwnerRequirement::Current, false)?;++ let mut directory = root.to_path_buf();+ for component in relative.components() {+ let Component::Normal(name) = component else {+ return Err(CompanionError::new(format!(+ "{} has a non-canonical component",+ path.display()+ )));+ };+ directory.push(name);+ if entry_metadata(&directory)?.is_none() {+ return Ok(());+ }+ validate_directory(&directory, OwnerRequirement::Current, false)?;+ }+ Ok(())+}++pub(super) fn destination_root<'a>(+ paths: &'a CompanionPaths,+ destination: &Path,+) -> Result<&'a Path, CompanionError> {+ if destination == paths.binary {+ return Ok(&paths.data_root);+ }+ if destination == paths.config {+ return Ok(&paths.config_root);+ }+ if let Some(target) = paths+ .manifests+ .iter()+ .find(|target| target.path == destination)+ {+ return Ok(match target.family {+ ManifestFamily::Chromium => &paths.config_root,+ ManifestFamily::Firefox => &paths.home_root,+ });+ }+ Err(CompanionError::new(format!(+ "unknown companion destination: {}",+ destination.display()+ )))+}++pub(super) fn validate_regular_file(+ path: &Path,+ requirement: OwnerRequirement,+ exact_mode: Option<u32>,+ executable: bool,+) -> Result<(), CompanionError> {+ let metadata = fs::symlink_metadata(path)+ .map_err(|error| CompanionError::io("inspect file", path, error))?;+ if metadata.file_type().is_symlink() || !metadata.is_file() {+ return Err(CompanionError::new(format!(+ "{} is not a real regular file",+ path.display()+ )));+ }+ validate_owner(path, &metadata, requirement)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;++ let mode = metadata.permissions().mode();+ if let Some(expected) = exact_mode {+ if mode & 0o7777 != expected {+ return Err(CompanionError::new(format!(+ "{} has mode {:04o}; expected {expected:04o}",+ path.display(),+ mode & 0o7777+ )));+ }+ } else if mode & 0o022 != 0 {+ return Err(CompanionError::new(format!(+ "{} is writable by another user",+ path.display()+ )));+ }+ if executable && mode & 0o111 == 0 {+ return Err(CompanionError::new(format!(+ "{} is not executable",+ path.display()+ )));+ }+ }+ #[cfg(not(unix))]+ let _ = (exact_mode, executable);+ Ok(())+}++pub(super) fn validate_private_file(+ paths: &CompanionPaths,+ path: &Path,+ expected_mode: u32,+) -> Result<(), CompanionError> {+ validate_private_parent(destination_root(paths, path)?, path, false)?;+ validate_regular_file(+ path,+ OwnerRequirement::Current,+ Some(expected_mode),+ expected_mode == 0o700,+ )+}++fn validate_executable_parent_chain(path: &Path) -> Result<(), CompanionError> {+ let parent = path+ .parent()+ .ok_or_else(|| CompanionError::new(format!("{} has no parent", path.display())))?;+ let mut ancestors = parent.ancestors().collect::<Vec<_>>();+ ancestors.reverse();+ for directory in ancestors {+ validate_directory(directory, OwnerRequirement::CurrentOrRoot, true)?;+ }+ Ok(())+}++pub(super) fn validate_source_executable(path: &Path) -> Result<PathBuf, CompanionError> {+ absolute_root(path.as_os_str(), "companion executable")?;+ validate_regular_file(path, OwnerRequirement::Current, None, true)?;+ let canonical = fs::canonicalize(path)+ .map_err(|error| CompanionError::io("resolve companion executable", path, error))?;+ validate_executable_parent_chain(&canonical)?;+ Ok(canonical)+}++fn temporary_path(destination: &Path, attempt: u32) -> Result<PathBuf, CompanionError> {+ let parent = destination+ .parent()+ .ok_or_else(|| CompanionError::new("destination has no parent"))?;+ let name = destination+ .file_name()+ .and_then(OsStr::to_str)+ .ok_or_else(|| CompanionError::new("destination name must be UTF-8"))?;+ let timestamp = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos();+ Ok(parent.join(format!(+ ".{name}.{}.{}.{}.tmp",+ std::process::id(),+ timestamp,+ attempt+ )))+}++fn rename_replace(source: &Path, destination: &Path) -> Result<(), CompanionError> {+ #[cfg(windows)]+ if destination.exists() {+ fs::remove_file(destination)+ .map_err(|error| CompanionError::io("remove old file", destination, error))?;+ }+ fs::rename(source, destination)+ .map_err(|error| CompanionError::io("replace file", destination, error))+}++pub(super) fn atomic_write(+ root: &Path,+ destination: &Path,+ bytes: &[u8],+ executable: bool,+) -> Result<(), CompanionError> {+ #[cfg(not(unix))]+ let _ = executable;+ validate_private_parent(root, destination, true)?;+ for attempt in 0..16 {+ let temporary = temporary_path(destination, attempt)?;+ let mut options = OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.mode(if executable { 0o700 } else { 0o600 });+ }+ let mut file = match options.open(&temporary) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(error) => {+ return Err(CompanionError::io(+ "create temporary file",+ &temporary,+ error,+ ));+ }+ };+ if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {+ let _ = fs::remove_file(&temporary);+ return Err(CompanionError::io(+ "write temporary file",+ &temporary,+ error,+ ));+ }+ drop(file);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = if executable { 0o700 } else { 0o600 };+ if let Err(error) = fs::set_permissions(&temporary, fs::Permissions::from_mode(mode)) {+ let _ = fs::remove_file(&temporary);+ return Err(CompanionError::io("set permissions", &temporary, error));+ }+ }+ if let Err(error) = rename_replace(&temporary, destination) {+ let _ = fs::remove_file(&temporary);+ return Err(error);+ }+ validate_regular_file(+ destination,+ OwnerRequirement::Current,+ Some(if executable { 0o700 } else { 0o600 }),+ executable,+ )?;+ return Ok(());+ }+ Err(CompanionError::new(format!(+ "could not allocate a temporary file for {}",+ destination.display()+ )))+}++pub(super) fn atomic_copy(+ source: &Path,+ root: &Path,+ destination: &Path,+) -> Result<(), CompanionError> {+ let bytes = read_limited(source, 64 * 1024 * 1024)?;+ atomic_write(root, destination, &bytes, true)+}++pub(super) fn validate_flatpak_binary(path: &Path) -> Result<PathBuf, CompanionError> {+ absolute_root(path.as_os_str(), "flatpak binary")?;+ let canonical = fs::canonicalize(path)+ .map_err(|error| CompanionError::io("resolve flatpak binary", path, error))?;+ absolute_root(canonical.as_os_str(), "resolved flatpak binary")?;+ validate_executable_parent_chain(&canonical)?;+ validate_regular_file(&canonical, OwnerRequirement::CurrentOrRoot, None, true)?;+ Ok(canonical)+}diff --git a/packages/native-host/src/flatpak_companion/tests.rs b/packages/native-host/src/flatpak_companion/tests.rsnew file mode 100644index 00000000..7115c369--- /dev/null+++ b/packages/native-host/src/flatpak_companion/tests.rs@@ -0,0 +1,720 @@+use std::collections::VecDeque;+use std::ffi::{OsStr, OsString};+use std::fs;+use std::path::{Path, PathBuf};+#[cfg(unix)]+use std::time::Duration;+use std::time::{SystemTime, UNIX_EPOCH};++use serde_json::{Value, json};++use super::{+ BrowserCaller, CompanionError, FlatpakRuntime, ManifestFamily, companion_status,+ embedded_allowlist, install_companion, resolve_companion_paths, resolve_flatpak_request,+ uninstall_companion, validate_browser_caller,+};+#[cfg(unix)]+use super::{+ CompanionCommand, FlatpakProcessRuntime, load_companion_config, parse_companion_command,+};+use crate::broker_protocol::BrokerOperation;+#[cfg(unix)]+use crate::broker_protocol::encode_broker_message;+use crate::resolve::{ResolveError, ResolveResult};++const CHROMIUM_ID: &str = "lggbokfckofcgjndaboioakcmincinpo";+const EDGE_ID: &str = "efcflljngohddnmfmebiamigoikmdfbf";+const FIREFOX_ID: &str = "[email protected]";+const NONCE: &str = "AbCdEfGhIjKlMnOpQrStUv";++struct TempDir {+ path: PathBuf,+}++impl TempDir {+ fn new(label: &str) -> Self {+ let id = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("clock")+ .as_nanos();+ let temporary_root =+ fs::canonicalize(std::env::temp_dir()).expect("canonical temporary directory");+ let path = temporary_root.join(format!(+ "motrix-flatpak-companion-{label}-{}-{id}",+ std::process::id()+ ));+ fs::create_dir_all(&path).expect("create temp directory");+ Self { path }+ }+}++impl Drop for TempDir {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.path);+ }+}++fn make_executable(path: &Path, contents: &[u8]) {+ fs::create_dir_all(path.parent().expect("executable parent")).expect("create parent");+ fs::write(path, contents).expect("write executable");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("make executable");+ }+}++#[cfg(unix)]+fn set_mode(path: &Path, mode: u32) {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(path, fs::Permissions::from_mode(mode)).expect("set mode");+}++#[cfg(unix)]+fn assert_private_directory_chain(root: &Path, destination: &Path) {+ use std::os::unix::fs::PermissionsExt;++ let parent = destination.parent().expect("destination parent");+ let relative = parent.strip_prefix(root).expect("destination under root");+ let mut directory = root.to_path_buf();+ assert_eq!(+ fs::symlink_metadata(&directory)+ .expect("root metadata")+ .permissions()+ .mode()+ & 0o7777,+ 0o700,+ "unexpected mode for {}",+ directory.display()+ );+ for component in relative.components() {+ directory.push(component.as_os_str());+ assert_eq!(+ fs::symlink_metadata(&directory)+ .expect("directory metadata")+ .permissions()+ .mode()+ & 0o7777,+ 0o700,+ "unexpected mode for {}",+ directory.display()+ );+ }+}++fn explicit_paths(temp: &TempDir) -> super::CompanionPaths {+ let data = temp.path.join("data");+ let config = temp.path.join("config");+ resolve_companion_paths(+ &temp.path.join("home"),+ Some(data.as_os_str()),+ Some(config.as_os_str()),+ )+ .expect("resolve paths")+}++#[test]+fn resolves_xdg_and_documented_fallback_paths() {+ let temp = TempDir::new("paths");+ let home = temp.path.join("home");+ let fallback = resolve_companion_paths(&home, None, None).expect("fallback paths");+ assert_eq!(+ fallback.binary,+ home.join(".local/share/motrix/native-messaging/motrix-flatpak-native-host")+ );+ assert_eq!(+ fallback.config,+ home.join(".config/motrix/native-messaging/flatpak-companion.json")+ );+ assert_eq!(fallback.manifests.len(), 4);+ assert_eq!(+ fallback+ .manifests+ .iter()+ .filter(|target| target.family == ManifestFamily::Firefox)+ .map(|target| target.path.clone())+ .collect::<Vec<_>>(),+ vec![home.join(".mozilla/native-messaging-hosts/app.motrix.bridge.json")]+ );++ let explicit = explicit_paths(&temp);+ assert!(explicit.binary.starts_with(temp.path.join("data")));+ assert!(explicit.config.starts_with(temp.path.join("config")));+ assert_eq!(+ explicit+ .manifests+ .iter()+ .filter(|target| target.family == ManifestFamily::Chromium)+ .count(),+ 3+ );++ let empty_xdg = resolve_companion_paths(&home, Some(OsStr::new("")), Some(OsStr::new("")))+ .expect("empty XDG values use fallbacks");+ assert_eq!(empty_xdg.binary, fallback.binary);+ assert_eq!(empty_xdg.config, fallback.config);+}++#[cfg(unix)]+#[test]+fn parses_only_the_documented_management_cli() {+ assert_eq!(+ parse_companion_command(&[]).expect("browser mode"),+ CompanionCommand::Browser+ );+ assert_eq!(+ parse_companion_command(&[OsString::from("install")]).expect("default install"),+ CompanionCommand::Install {+ flatpak_bin: PathBuf::from("/usr/bin/flatpak"),+ force: false,+ }+ );+ assert_eq!(+ parse_companion_command(&[+ OsString::from("install"),+ OsString::from("--force"),+ OsString::from("--flatpak-bin"),+ OsString::from("/opt/flatpak/bin/flatpak"),+ ])+ .expect("custom install"),+ CompanionCommand::Install {+ flatpak_bin: PathBuf::from("/opt/flatpak/bin/flatpak"),+ force: true,+ }+ );+ assert!(+ parse_companion_command(&[+ OsString::from("install"),+ OsString::from("--flatpak-bin"),+ OsString::from("relative/flatpak"),+ ])+ .is_err()+ );+ assert!(parse_companion_command(&[OsString::from("status"), OsString::from("extra")]).is_err());+}++#[test]+fn validates_exact_browser_caller_shapes_before_broker_access() {+ let temp = TempDir::new("caller");+ let paths = explicit_paths(&temp);+ let allowlist = embedded_allowlist().expect("embedded allowlist");++ for extension_id in [CHROMIUM_ID, EDGE_ID] {+ for origin in [+ format!("chrome-extension://{extension_id}"),+ format!("chrome-extension://{extension_id}/"),+ ] {+ assert_eq!(+ validate_browser_caller(&[origin.into()], &allowlist, &paths)+ .expect("Chromium caller"),+ BrowserCaller::Chromium {+ extension_id: extension_id.into()+ }+ );+ }+ }+ for invalid in [+ format!("chrome-extension://{CHROMIUM_ID}//"),+ "chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/".into(),+ format!("https://{CHROMIUM_ID}/"),+ ] {+ assert!(+ validate_browser_caller(&[invalid.into()], &allowlist, &paths).is_err(),+ "accepted invalid Chromium caller"+ );+ }++ let firefox_manifest = paths+ .manifests+ .iter()+ .find(|target| target.family == ManifestFamily::Firefox)+ .expect("Firefox target")+ .path+ .clone();+ assert_eq!(+ validate_browser_caller(+ &[+ firefox_manifest.clone().into_os_string(),+ OsString::from(FIREFOX_ID),+ ],+ &allowlist,+ &paths,+ )+ .expect("Firefox caller"),+ BrowserCaller::Firefox {+ extension_id: FIREFOX_ID.into()+ }+ );+ assert!(+ validate_browser_caller(+ &[+ firefox_manifest+ .with_file_name("other.json")+ .into_os_string(),+ OsString::from(FIREFOX_ID),+ ],+ &allowlist,+ &paths,+ )+ .is_err()+ );+ assert!(validate_browser_caller(&[], &allowlist, &paths).is_err());+ assert!(+ validate_browser_caller(+ &[+ OsString::from(format!("chrome-extension://{CHROMIUM_ID}/")),+ OsString::from("unexpected"),+ OsString::from("argument"),+ ],+ &allowlist,+ &paths,+ )+ .is_err()+ );+}++#[test]+fn install_writes_binary_config_and_all_browser_manifests() {+ let temp = TempDir::new("install");+ let paths = explicit_paths(&temp);+ let source = temp.path.join("source-companion");+ let flatpak = temp.path.join("bin/flatpak");+ make_executable(&source, b"companion-binary");+ make_executable(&flatpak, b"flatpak-binary");+ let allowlist = embedded_allowlist().expect("embedded allowlist");++ install_companion(&paths, &source, &flatpak, &allowlist, false).expect("install");+ assert_eq!(+ fs::read(&paths.binary).expect("installed binary"),+ b"companion-binary"+ );+ let config: Value =+ serde_json::from_slice(&fs::read(&paths.config).expect("config")).expect("parse config");+ assert_eq!(config["schemaVersion"], 1);+ assert_eq!(+ config["flatpakBin"],+ fs::canonicalize(&flatpak)+ .expect("canonical flatpak")+ .to_string_lossy()+ .as_ref()+ );+ assert_eq!(+ config["installedBinary"],+ paths.binary.to_string_lossy().as_ref()+ );++ for target in &paths.manifests {+ let manifest: Value = serde_json::from_slice(+ &fs::read(&target.path).unwrap_or_else(|_| panic!("read {}", target.path.display())),+ )+ .expect("parse manifest");+ assert_eq!(manifest["name"], "app.motrix.bridge");+ assert_eq!(manifest["path"], paths.binary.to_string_lossy().as_ref());+ assert_eq!(manifest["type"], "stdio");+ match target.family {+ ManifestFamily::Chromium => assert_eq!(+ manifest["allowed_origins"],+ json!([+ format!("chrome-extension://{CHROMIUM_ID}/"),+ format!("chrome-extension://{EDGE_ID}/")+ ])+ ),+ ManifestFamily::Firefox => {+ assert_eq!(manifest["allowed_extensions"], json!([FIREFOX_ID]))+ }+ }+ }+ assert!(companion_status(&paths, &allowlist).installed);++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ fs::metadata(&paths.binary)+ .expect("binary metadata")+ .permissions()+ .mode()+ & 0o777,+ 0o700+ );+ assert_eq!(+ fs::metadata(&paths.config)+ .expect("config metadata")+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );+ for target in &paths.manifests {+ assert_eq!(+ fs::metadata(&target.path)+ .expect("manifest metadata")+ .permissions()+ .mode()+ & 0o7777,+ 0o600+ );+ }+ assert_private_directory_chain(&paths.data_root, &paths.binary);+ assert_private_directory_chain(&paths.config_root, &paths.config);+ for target in &paths.manifests {+ let root = match target.family {+ ManifestFamily::Chromium => &paths.config_root,+ ManifestFamily::Firefox => &paths.home_root,+ };+ assert_private_directory_chain(root, &target.path);+ }+ }+}++#[test]+#[cfg(unix)]+fn install_rejects_symlinked_or_other_writable_private_directories() {+ use std::os::unix::fs::symlink;++ let symlink_temp = TempDir::new("symlink-root");+ let symlink_paths = explicit_paths(&symlink_temp);+ let source = symlink_temp.path.join("source-companion");+ let flatpak = symlink_temp.path.join("bin/flatpak");+ make_executable(&source, b"companion");+ make_executable(&flatpak, b"flatpak");+ let redirect = symlink_temp.path.join("redirect");+ fs::create_dir(&redirect).expect("create redirect");+ symlink(&redirect, &symlink_paths.data_root).expect("symlink data root");+ let allowlist = embedded_allowlist().expect("allowlist");+ assert!(install_companion(&symlink_paths, &source, &flatpak, &allowlist, true,).is_err());+ assert!(!redirect.join("motrix").exists());+ assert!(uninstall_companion(&symlink_paths).is_err());++ let writable_temp = TempDir::new("writable-parent");+ let writable_paths = explicit_paths(&writable_temp);+ let source = writable_temp.path.join("source-companion");+ let flatpak = writable_temp.path.join("bin/flatpak");+ make_executable(&source, b"companion");+ make_executable(&flatpak, b"flatpak");+ fs::create_dir(&writable_paths.config_root).expect("create config root");+ let insecure = writable_paths.config_root.join("google-chrome");+ fs::create_dir(&insecure).expect("create insecure browser directory");+ set_mode(&insecure, 0o777);+ assert!(install_companion(&writable_paths, &source, &flatpak, &allowlist, true,).is_err());+ assert!(!writable_paths.binary.exists());++ let ancestor_temp = TempDir::new("writable-ancestor");+ let shared = ancestor_temp.path.join("shared");+ fs::create_dir(&shared).expect("create shared ancestor");+ set_mode(&shared, 0o777);+ let data_root = shared.join("victim-data");+ fs::create_dir(&data_root).expect("create private data root");+ set_mode(&data_root, 0o700);+ let ancestor_paths = resolve_companion_paths(+ &ancestor_temp.path.join("home"),+ Some(data_root.as_os_str()),+ Some(ancestor_temp.path.join("config").as_os_str()),+ )+ .expect("resolve paths below writable ancestor");+ let source = ancestor_temp.path.join("source-companion");+ let flatpak = ancestor_temp.path.join("bin/flatpak");+ make_executable(&source, b"companion");+ make_executable(&flatpak, b"flatpak");+ assert!(+ install_companion(&ancestor_paths, &source, &flatpak, &allowlist, true).is_err(),+ "a private root below a non-sticky writable ancestor was accepted"+ );+ assert!(!ancestor_paths.binary.exists());+}++#[test]+#[cfg(unix)]+fn install_validates_source_and_canonicalizes_a_safe_flatpak_binary() {+ use std::os::unix::fs::symlink;++ let temp = TempDir::new("executables");+ let paths = explicit_paths(&temp);+ let source = temp.path.join("source-companion");+ let flatpak = temp.path.join("bin/flatpak");+ make_executable(&source, b"companion");+ make_executable(&flatpak, b"flatpak");+ let allowlist = embedded_allowlist().expect("allowlist");++ set_mode(&source, 0o777);+ assert!(install_companion(&paths, &source, &flatpak, &allowlist, true).is_err());+ set_mode(&source, 0o755);+ set_mode(&flatpak, 0o777);+ assert!(install_companion(&paths, &source, &flatpak, &allowlist, true).is_err());+ set_mode(&flatpak, 0o755);++ let insecure_parent = temp.path.join("insecure-flatpak-parent");+ fs::create_dir(&insecure_parent).expect("create insecure parent");+ set_mode(&insecure_parent, 0o777);+ let insecure_flatpak = insecure_parent.join("flatpak");+ make_executable(&insecure_flatpak, b"flatpak");+ assert!(install_companion(&paths, &source, &insecure_flatpak, &allowlist, true,).is_err());++ let flatpak_link = temp.path.join("flatpak-link");+ symlink(&flatpak, &flatpak_link).expect("create flatpak symlink");+ install_companion(&paths, &source, &flatpak_link, &allowlist, true)+ .expect("install through canonicalized flatpak path");+ let config: Value =+ serde_json::from_slice(&fs::read(&paths.config).expect("config")).expect("parse config");+ assert_eq!(+ config["flatpakBin"],+ fs::canonicalize(&flatpak)+ .expect("canonical flatpak")+ .to_string_lossy()+ .as_ref()+ );+}++#[test]+#[cfg(unix)]+fn status_load_and_uninstall_fail_closed_for_unsafe_installation_entries() {+ use std::os::unix::fs::symlink;++ let temp = TempDir::new("fail-closed");+ let paths = explicit_paths(&temp);+ let source = temp.path.join("source-companion");+ let flatpak = temp.path.join("bin/flatpak");+ make_executable(&source, b"companion");+ make_executable(&flatpak, b"flatpak");+ let allowlist = embedded_allowlist().expect("allowlist");+ install_companion(&paths, &source, &flatpak, &allowlist, false).expect("install");++ set_mode(&paths.binary, 0o777);+ assert!(!companion_status(&paths, &allowlist).installed);+ assert!(load_companion_config(&paths, &paths.binary).is_err());+ assert!(uninstall_companion(&paths).is_err());+ set_mode(&paths.binary, 0o700);++ fs::remove_file(&paths.config).expect("remove config");+ symlink(paths.config.with_extension("missing"), &paths.config)+ .expect("create dangling config symlink");+ assert!(!companion_status(&paths, &allowlist).installed);+ assert!(load_companion_config(&paths, &paths.binary).is_err());+ assert!(uninstall_companion(&paths).is_err());++ fs::remove_file(&paths.config).expect("remove config symlink");+ install_companion(&paths, &source, &flatpak, &allowlist, true).expect("repair install");+ let manifest = &paths.manifests[0].path;+ fs::remove_file(manifest).expect("remove manifest");+ symlink(manifest.with_extension("missing"), manifest)+ .expect("create dangling manifest symlink");+ assert!(!companion_status(&paths, &allowlist).installed);+ assert!(uninstall_companion(&paths).is_err());+}++#[test]+fn install_refuses_unowned_files_unless_force_is_explicit() {+ let temp = TempDir::new("conflict");+ let paths = explicit_paths(&temp);+ let source = temp.path.join("source-companion");+ let flatpak = temp.path.join("bin/flatpak");+ make_executable(&source, b"new-companion");+ make_executable(&flatpak, b"flatpak");+ let allowlist = embedded_allowlist().expect("embedded allowlist");++ let conflict = &paths.manifests[0].path;+ fs::create_dir_all(conflict.parent().expect("manifest parent")).expect("create parent");+ fs::write(+ conflict,+ br#"{"name":"org.example.foreign","path":"/foreign"}"#,+ )+ .expect("write foreign manifest");+ assert!(install_companion(&paths, &source, &flatpak, &allowlist, false).is_err());+ assert!(!paths.binary.exists());+ install_companion(&paths, &source, &flatpak, &allowlist, true).expect("forced install");++ let second = TempDir::new("binary-conflict");+ let second_paths = explicit_paths(&second);+ fs::create_dir_all(second_paths.binary.parent().expect("binary parent"))+ .expect("create binary parent");+ fs::write(&second_paths.binary, b"foreign-binary").expect("foreign binary");+ assert!(install_companion(&second_paths, &source, &flatpak, &allowlist, false,).is_err());+ assert_eq!(+ fs::read(&second_paths.binary).expect("preserved foreign binary"),+ b"foreign-binary"+ );+}++#[test]+fn uninstall_removes_only_manifests_still_owned_by_the_companion() {+ let temp = TempDir::new("uninstall");+ let paths = explicit_paths(&temp);+ let source = temp.path.join("source-companion");+ let flatpak = temp.path.join("bin/flatpak");+ make_executable(&source, b"companion");+ make_executable(&flatpak, b"flatpak");+ let allowlist = embedded_allowlist().expect("embedded allowlist");+ install_companion(&paths, &source, &flatpak, &allowlist, false).expect("install");++ let foreign = &paths.manifests[0].path;+ fs::write(+ foreign,+ br#"{"name":"org.example.foreign","path":"/foreign"}"#,+ )+ .expect("replace one manifest");+ uninstall_companion(&paths).expect("uninstall");++ assert!(foreign.exists(), "foreign manifest must be preserved");+ for target in paths.manifests.iter().skip(1) {+ assert!(!target.path.exists(), "owned manifest was preserved");+ }+ assert!(!paths.config.exists());+ assert!(!paths.binary.exists());+}++struct FakeRuntime {+ responses: VecDeque<Result<ResolveResult, CompanionError>>,+ calls: Vec<BrokerOperation>,+ launch_result: bool,+ launch_calls: usize,+}++impl FakeRuntime {+ fn new(responses: Vec<Result<ResolveResult, CompanionError>>) -> Self {+ Self {+ responses: responses.into(),+ calls: Vec::new(),+ launch_result: true,+ launch_calls: 0,+ }+ }+}++impl FlatpakRuntime for FakeRuntime {+ fn call_broker(&mut self, operation: BrokerOperation) -> Result<ResolveResult, CompanionError> {+ self.calls.push(operation);+ self.responses.pop_front().expect("queued broker response")+ }++ fn launch_app(&mut self) -> bool {+ self.launch_calls += 1;+ self.launch_result+ }+}++fn error(error: ResolveError) -> ResolveResult {+ ResolveResult::Error { error }+}++#[test]+fn flatpak_resolution_probes_then_launches_then_waits_without_weakening_errors() {+ let pair = ResolveResult::request_pair(55_809, NONCE.into());+ let mut live = FakeRuntime::new(vec![Ok(pair.clone())]);+ assert_eq!(resolve_flatpak_request(true, &mut live), pair);+ assert_eq!(live.calls, vec![BrokerOperation::Probe]);+ assert_eq!(live.launch_calls, 0);++ let mut no_launch = FakeRuntime::new(vec![Ok(error(ResolveError::NotRunning))]);+ assert_eq!(+ resolve_flatpak_request(false, &mut no_launch),+ error(ResolveError::NotRunning)+ );+ assert_eq!(no_launch.launch_calls, 0);++ let pair = ResolveResult::request_pair(55_810, NONCE.into());+ let mut launched =+ FakeRuntime::new(vec![Ok(error(ResolveError::NotRunning)), Ok(pair.clone())]);+ assert_eq!(resolve_flatpak_request(true, &mut launched), pair);+ assert_eq!(+ launched.calls,+ vec![BrokerOperation::Probe, BrokerOperation::WaitForEndpoint]+ );+ assert_eq!(launched.launch_calls, 1);++ let mut unavailable = FakeRuntime::new(vec![Err(CompanionError::new("not installed"))]);+ assert_eq!(+ resolve_flatpak_request(true, &mut unavailable),+ error(ResolveError::NotInstalled)+ );+ assert_eq!(unavailable.launch_calls, 0);++ let mut launch_failed = FakeRuntime::new(vec![+ Ok(error(ResolveError::NotRunning)),+ Err(CompanionError::new("wait failed")),+ ]);+ assert_eq!(+ resolve_flatpak_request(true, &mut launch_failed),+ error(ResolveError::LaunchFailed)+ );+}++#[cfg(unix)]+fn shell_octal(bytes: &[u8]) -> String {+ bytes.iter().map(|byte| format!("\\{byte:03o}")).collect()+}++#[cfg(unix)]+fn shell_quote(path: &Path) -> String {+ format!("'{}'", path.to_string_lossy().replace('\'', "'\"'\"'"))+}++#[test]+#[cfg(unix)]+fn process_runtime_uses_fixed_flatpak_commands_and_rejects_stdout_pollution() {+ let temp = TempDir::new("runtime-process");+ let flatpak = temp.path.join("flatpak");+ let marker = temp.path.join("launched");+ let response =+ encode_broker_message(&error(ResolveError::NotRunning)).expect("encode broker response");+ let script = format!(+ "#!/bin/sh\n\+ if [ \"$#\" -eq 2 ]; then\n\+ [ \"$1\" = run ] && [ \"$2\" = app.motrix.native ] || exit 91\n\+ : > {}\n\+ exit 0\n\+ fi\n\+ [ \"$#\" -eq 3 ] || exit 92\n\+ [ \"$1\" = run ] || exit 93\n\+ [ \"$2\" = --command=motrix-native-host-broker ] || exit 94\n\+ [ \"$3\" = app.motrix.native ] || exit 95\n\+ cat >/dev/null\n\+ printf '{}'\n",+ shell_quote(&marker),+ shell_octal(&response),+ );+ make_executable(&flatpak, script.as_bytes());++ let mut runtime = FlatpakProcessRuntime::new(flatpak.clone());+ assert_eq!(+ runtime+ .call_broker(BrokerOperation::Probe)+ .expect("probe broker"),+ error(ResolveError::NotRunning)+ );+ assert!(runtime.launch_app());+ for _ in 0..100 {+ if marker.exists() {+ break;+ }+ std::thread::sleep(Duration::from_millis(5));+ }+ assert!(marker.exists(), "fixed Flatpak launch command was not used");++ let polluted_script = format!(+ "#!/bin/sh\ncat >/dev/null\nprintf '{}x'\n",+ shell_octal(&response)+ );+ make_executable(&flatpak, polluted_script.as_bytes());+ assert!(runtime.call_broker(BrokerOperation::Probe).is_err());++ let unexpected = encode_broker_message(&error(ResolveError::LaunchFailed))+ .expect("encode unexpected response");+ let unexpected_script = format!(+ "#!/bin/sh\ncat >/dev/null\nprintf '{}'\n",+ shell_octal(&unexpected)+ );+ make_executable(&flatpak, unexpected_script.as_bytes());+ assert!(runtime.call_broker(BrokerOperation::Probe).is_err());+}++#[test]+fn allowlist_file_is_strict_and_matches_manifest_contract() {+ let allowlist = embedded_allowlist().expect("embedded allowlist");+ assert_eq!(allowlist.chromium, [CHROMIUM_ID, EDGE_ID]);+ assert_eq!(allowlist.firefox, [FIREFOX_ID]);+ assert!(!super::is_chromium_extension_id(+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaA"+ ));+ assert!(!super::is_firefox_extension_id("invalid [email protected]"));+ assert!(super::absolute_root(OsStr::new("relative"), "path").is_err());+}diff --git a/packages/native-host/src/lib.rs b/packages/native-host/src/lib.rsindex 014f9e33..0ff24b9f 100644--- a/packages/native-host/src/lib.rs+++ b/packages/native-host/src/lib.rs@@ -49,6 +49,21 @@ pub enum HostRequest {},}+impl HostRequest {+ pub fn allow_launch(&self) -> bool {+ match self {+ Self::Legacy { allow_launch } | Self::Bootstrap { allow_launch, .. } => *allow_launch,+ }+ }++ pub fn bootstrap_binding_pub(&self) -> Option<&[u8; 32]> {+ match self {+ Self::Bootstrap { binding_pub, .. } => Some(binding_pub),+ Self::Legacy { .. } => None,+ }+ }+}+/// Parses `{ action: "bootstrap", protocolVersion: 1, bindingPub, allowLaunch?/// }` (§9.1) while preserving the v1 `parse_allow_launch` semantics for/// anything else. A `bootstrap` object whose `protocolVersion` is not thediff --git a/packages/native-host/src/log.rs b/packages/native-host/src/log.rsindex 28ac91a7..a73dd09c 100644--- a/packages/native-host/src/log.rs+++ b/packages/native-host/src/log.rs@@ -139,7 +139,7 @@ mod tests {protocol_version: 1,server_generation: "gen-1".into(),browser: "chromium".into(),- caller_id: "ibpkjhgpbidfmbmomagmldcdlpbmchgi".into(),+ caller_id: "lggbokfckofcgjndaboioakcmincinpo".into(),exp: 1_755_600_000,binding_pub: "SECRETPUB".into(),mac: "SECRETMAC".into(),diff --git a/packages/native-host/src/main.rs b/packages/native-host/src/main.rsindex 4121da0d..19b9a483 100644--- a/packages/native-host/src/main.rs+++ b/packages/native-host/src/main.rs@@ -1,4 +1,6 @@+use std::fmt;use std::io::{self, Read};+use std::path::Path;use std::process::ExitCode;use std::time::{SystemTime, UNIX_EPOCH};@@ -6,7 +8,8 @@ use motrix_native_host::caller::extract_caller_identity;use motrix_native_host::endpoint::EndpointFile;use motrix_native_host::log::NativeHostLogger;use motrix_native_host::protocol::{- INPUT_TIMEOUT, MAX_MESSAGE_BYTES, read_message_with_timeout, write_message,+ INPUT_TIMEOUT, MAX_MESSAGE_BYTES, ProtocolError, TimedReadError, read_message_with_timeout,+ write_message,};use motrix_native_host::resolve::{ResolveResult, resolve_endpoint};use motrix_native_host::runtime::SystemResolveDeps;@@ -14,6 +17,23 @@ use motrix_native_host::ticket::{NmTicket, TICKET_LIFETIME_SECONDS, TicketInputsuse motrix_native_host::user_data::{native_host_bridge_data_dir, native_host_user_data_dir};use motrix_native_host::{HostRequest, parse_host_request};+#[derive(Debug)]+enum RunError {+ Read(TimedReadError),+ MalformedRequest,+ Write(ProtocolError),+}++impl fmt::Display for RunError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Read(error) => write!(formatter, "read_message failed: {error}"),+ Self::MalformedRequest => formatter.write_str("received malformed JSON value"),+ Self::Write(error) => write!(formatter, "write_message failed: {error}"),+ }+ }+}+/// Mints a ticket for a `bootstrap` request when every trusted input is/// available (`docs/bridge-pairing-protocol.md` §9.1/§9.2); otherwise/// returns `None` so the caller replies ticketless. Never fabricates a@@ -45,42 +65,18 @@ fn mint_ticket_for_bootstrap(endpoint: &EndpointFile, binding_pub: &[u8; 32]) ->Some(mint_ticket(local_token, &inputs))}-fn run() -> ExitCode {- let user_data = native_host_user_data_dir();- let bridge_data = native_host_bridge_data_dir(user_data.as_deref());- let logger = NativeHostLogger::from_bridge_data(bridge_data.as_deref());- logger.log(&format!(- "=== spawned argv_count={} ===",- std::env::args_os().count().saturating_sub(1)- ));-- let input = match read_message_with_timeout(io::stdin(), INPUT_TIMEOUT) {- Ok(value) => value,- Err(error) => {- logger.log(&format!("read_message failed: {error}; exit 1"));- return ExitCode::FAILURE;- }- };- let Some(request) = parse_host_request(&input) else {- logger.log("received malformed JSON value; exit 1");- return ExitCode::FAILURE;- };- let allow_launch = match &request {- HostRequest::Legacy { allow_launch } | HostRequest::Bootstrap { allow_launch, .. } => {- *allow_launch- }- };- logger.log(&format!("received start; allowLaunch={allow_launch}"));+fn read_request() -> Result<HostRequest, RunError> {+ let input = read_message_with_timeout(io::stdin(), INPUT_TIMEOUT).map_err(RunError::Read)?;+ parse_host_request(&input).ok_or(RunError::MalformedRequest)+}- let mut deps = SystemResolveDeps::from_bridge_data(bridge_data.as_deref());- let result = match resolve_endpoint(allow_launch, &mut deps) {+fn resolve_request(request: &HostRequest, bridge_data: Option<&Path>) -> ResolveResult {+ let mut deps = SystemResolveDeps::from_bridge_data(bridge_data);+ match resolve_endpoint(request.allow_launch(), &mut deps) {Ok(resolved) => {- let ticket = match &request {- HostRequest::Bootstrap { binding_pub, .. } => {- mint_ticket_for_bootstrap(&resolved.endpoint, binding_pub)- }- HostRequest::Legacy { .. } => None,- };+ let ticket = request+ .bootstrap_binding_pub()+ .and_then(|binding_pub| mint_ticket_for_bootstrap(&resolved.endpoint, binding_pub));match ticket {Some(ticket) => ResolveResult::request_pair_with_ticket(resolved.endpoint.port,@@ -91,16 +87,15 @@ fn run() -> ExitCode {}}Err(error) => ResolveResult::Error { error },- };- logger.log_resolve_result(&result);+ }+}+fn write_response(result: &ResolveResult) -> Result<(), RunError> {let stdout = io::stdout();- let mut stdout_lock = stdout.lock();- if let Err(error) = write_message(&mut stdout_lock, &result) {- logger.log(&format!("write_message failed: {error}; exit 1"));- return ExitCode::FAILURE;- }+ write_message(&mut stdout.lock(), result).map_err(RunError::Write)+}+fn drain_trailing_input(logger: &NativeHostLogger) {// Native Messaging hosts traditionally stay alive until the browser closes// their stdin pipe. Drain at most one bounded message of unexpected trailing// input so a peer cannot stream unbounded data through this one-shot host.@@ -111,12 +106,39 @@ fn run() -> ExitCode {.take((MAX_MESSAGE_BYTES.saturating_add(1)) as u64);if io::copy(&mut trailing, &mut io::sink()).is_ok_and(|read| read > MAX_MESSAGE_BYTES as u64) {logger.log("trailing native messaging input exceeded limit; exit 0");- return ExitCode::SUCCESS;+ } else {+ logger.log("stdin end; exit 0");}- logger.log("stdin end; exit 0");- ExitCode::SUCCESS+}++fn run(bridge_data: Option<&Path>, logger: &NativeHostLogger) -> Result<(), RunError> {+ let request = read_request()?;+ logger.log(&format!(+ "received start; allowLaunch={}",+ request.allow_launch()+ ));++ let result = resolve_request(&request, bridge_data);+ logger.log_resolve_result(&result);+ write_response(&result)?;+ drain_trailing_input(logger);+ Ok(())}fn main() -> ExitCode {- run()+ let user_data = native_host_user_data_dir();+ let bridge_data = native_host_bridge_data_dir(user_data.as_deref());+ let logger = NativeHostLogger::from_bridge_data(bridge_data.as_deref());+ logger.log(&format!(+ "=== spawned argv_count={} ===",+ std::env::args_os().count().saturating_sub(1)+ ));++ match run(bridge_data.as_deref(), &logger) {+ Ok(()) => ExitCode::SUCCESS,+ Err(error) => {+ logger.log(&format!("{error}; exit 1"));+ ExitCode::FAILURE+ }+ }}diff --git a/packages/native-host/src/user_data.rs b/packages/native-host/src/user_data.rsindex 8fc56b3b..3e01bc23 100644--- a/packages/native-host/src/user_data.rs+++ b/packages/native-host/src/user_data.rs@@ -1,7 +1,22 @@use std::ffi::OsStr;+use std::fs::File;+use std::io::Read;use std::path::{Component, Path, PathBuf};+use serde::Deserialize;+use crate::MOTRIX_FLATPAK_ID;+use crate::endpoint::is_owner_only;++pub const DEVELOPMENT_HOST_CONFIG_NAME: &str = "motrix-native-host.dev.json";+const MAX_DEVELOPMENT_HOST_CONFIG_BYTES: usize = 4 * 1024;++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct DevelopmentHostConfig {+ #[serde(rename = "bridgeDataDir")]+ bridge_data_dir: String,+}#[derive(Clone, Copy, Debug, Eq, PartialEq)]pub enum NativeHostPlatform {@@ -83,12 +98,52 @@ pub fn resolve_bridge_data_dir(}pub fn native_host_bridge_data_dir(user_data: Option<&Path>) -> Option<PathBuf> {- resolve_bridge_data_dir(+ let override_data_dir = std::env::var_os("MOTRIX_BRIDGE_DATA_DIR");+ let development_data_dir = if override_data_dir.is_none() {+ std::env::current_exe()+ .ok()+ .as_deref()+ .and_then(read_development_bridge_data_dir)+ } else {+ None+ };+ resolve_native_host_bridge_data_dir(user_data,- std::env::var_os("MOTRIX_BRIDGE_DATA_DIR").as_deref(),+ override_data_dir.as_deref(),+ development_data_dir,)}+fn resolve_native_host_bridge_data_dir(+ user_data: Option<&Path>,+ override_data_dir: Option<&OsStr>,+ development_data_dir: Option<PathBuf>,+) -> Option<PathBuf> {+ match override_data_dir {+ Some(value) => resolve_bridge_data_dir(user_data, Some(value)),+ None => development_data_dir.or_else(|| user_data.map(|base| base.join("bridge"))),+ }+}++fn read_development_bridge_data_dir(executable_path: &Path) -> Option<PathBuf> {+ let config_path = executable_path.parent()?.join(DEVELOPMENT_HOST_CONFIG_NAME);+ let file = File::open(config_path).ok()?;+ if !is_owner_only(&file) {+ return None;+ }++ let mut bytes = Vec::new();+ file.take((MAX_DEVELOPMENT_HOST_CONFIG_BYTES + 1) as u64)+ .read_to_end(&mut bytes)+ .ok()?;+ if bytes.len() > MAX_DEVELOPMENT_HOST_CONFIG_BYTES {+ return None;+ }++ let config: DevelopmentHostConfig = serde_json::from_slice(&bytes).ok()?;+ absolute_directory_from_env(OsStr::new(&config.bridge_data_dir))+}+/// Resolve the bridge directory visible inside the Motrix Flatpak sandbox.////// The broker must not fall back to the host user's home directory: that can@@ -135,16 +190,36 @@ pub fn bridge_endpoint_path(bridge_data_dir: &Path) -> PathBuf {#[cfg(test)]mod tests {use std::ffi::OsStr;+ #[cfg(unix)]+ use std::fs;use std::path::{Path, PathBuf};+ #[cfg(unix)]+ use std::time::{SystemTime, UNIX_EPOCH};#[cfg(unix)]use super::resolve_flatpak_bridge_data_dir;use super::resolve_native_host_user_data_dir_from_optional_home;+ #[cfg(unix)]+ use super::{DEVELOPMENT_HOST_CONFIG_NAME, read_development_bridge_data_dir};use super::{NativeHostPlatform, bridge_endpoint_path, endpoint_path, resolve_bridge_data_dir,- resolve_native_host_user_data_dir,+ resolve_native_host_bridge_data_dir, resolve_native_host_user_data_dir,};+ #[cfg(unix)]+ fn temp_dir(label: &str) -> PathBuf {+ let id = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .expect("clock")+ .as_nanos();+ let path = std::env::temp_dir().join(format!(+ "motrix-native-host-user-data-{label}-{}-{id}",+ std::process::id()+ ));+ fs::create_dir_all(&path).expect("create temp directory");+ path+ }+#[test]fn resolves_macos_and_linux_paths() {assert_eq!(@@ -241,6 +316,57 @@ mod tests {assert_eq!(resolve_bridge_data_dir(None, None), None);}+ #[test]+ fn development_config_precedes_the_production_profile_but_not_the_environment() {+ let root = std::env::temp_dir().join("motrix-native-host-precedence");+ let production = root.join("Motrix");+ let development = root.join("Motrix-dev").join("bridge");+ let override_dir = root.join("custom").join("bridge");+ assert_eq!(+ resolve_native_host_bridge_data_dir(+ Some(production.as_path()),+ None,+ Some(development.clone()),+ ),+ Some(development)+ );+ assert_eq!(+ resolve_native_host_bridge_data_dir(+ Some(production.as_path()),+ Some(override_dir.as_os_str()),+ Some(root.join("Motrix-dev").join("bridge")),+ ),+ Some(override_dir)+ );+ }++ #[cfg(unix)]+ #[test]+ fn reads_only_an_owner_only_development_config_beside_the_executable() {+ use std::os::unix::fs::PermissionsExt;++ let directory = temp_dir("development-config");+ let executable = directory.join("motrix-native-host");+ let config_path = directory.join(DEVELOPMENT_HOST_CONFIG_NAME);+ fs::write(+ &config_path,+ r#"{"bridgeDataDir":"/data/Motrix-dev/bridge"}"#,+ )+ .expect("write development config");+ fs::set_permissions(&config_path, fs::Permissions::from_mode(0o600))+ .expect("secure development config");++ assert_eq!(+ read_development_bridge_data_dir(&executable),+ Some(PathBuf::from("/data/Motrix-dev/bridge"))+ );++ fs::set_permissions(&config_path, fs::Permissions::from_mode(0o644))+ .expect("widen development config permissions");+ assert_eq!(read_development_bridge_data_dir(&executable), None);+ fs::remove_dir_all(directory).expect("remove temp directory");+ }+#[cfg(unix)]#[test]fn flatpak_bridge_requires_the_exact_app_id_and_absolute_xdg_config_home() {diff --git a/packages/native-host/tests/flatpak_companion_integration.rs b/packages/native-host/tests/flatpak_companion_integration.rsindex f54f7d62..745eb742 100644--- a/packages/native-host/tests/flatpak_companion_integration.rs+++ b/packages/native-host/tests/flatpak_companion_integration.rs@@ -11,7 +11,8 @@ use motrix_native_host::protocol::{read_message, write_message};use motrix_native_host::resolve::{ResolveError, ResolveResult};use serde_json::{Value, json};-const CHROMIUM_ID: &str = "ibpkjhgpbidfmbmomagmldcdlpbmchgi";+const CHROMIUM_ID: &str = "lggbokfckofcgjndaboioakcmincinpo";+const EDGE_ID: &str = "efcflljngohddnmfmebiamigoikmdfbf";struct TempDir {path: PathBuf,@@ -257,6 +258,23 @@ fn installed_companion_validates_caller_and_reencodes_broker_output() {);assert_eq!(fs::read(&invoked).expect("invocation marker"), b"x");+ let edge_output = run_browser(+ &installed,+ &temp,+ &format!("chrome-extension://{EDGE_ID}/"),+ &browser_wire(false),+ );+ assert!(+ edge_output.status.success(),+ "Edge browser mode failed: {}",+ String::from_utf8_lossy(&edge_output.stderr)+ );+ assert_eq!(+ decode_only_browser_frame(&edge_output.stdout),+ json!({ "error": "motrix-not-running" })+ );+ assert_eq!(fs::read(&invoked).expect("invocation marker"), b"xx");+let rejected = run_browser(&installed,&temp,@@ -267,7 +285,7 @@ fn installed_companion_validates_caller_and_reencodes_broker_output() {assert!(rejected.stdout.is_empty());assert_eq!(fs::read(&invoked).expect("unchanged invocation marker"),- b"x",+ b"xx","untrusted caller reached Flatpak");diff --git a/packages/native-host/tests/host_integration.rs b/packages/native-host/tests/host_integration.rsindex e79afe77..1750fb6f 100644--- a/packages/native-host/tests/host_integration.rs+++ b/packages/native-host/tests/host_integration.rs@@ -343,7 +343,7 @@ fn subprocess_rejects_primitive_malformed_truncated_and_oversized_input() {// binding pub = 32 bytes of 0x07, base64url no-pad (spec §9.1/§9.2).const BOOTSTRAP_BINDING_PUB: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";-const BOOTSTRAP_CALLER_ARGV: &str = "chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/";+const BOOTSTRAP_CALLER_ARGV: &str = "chrome-extension://lggbokfckofcgjndaboioakcmincinpo/";fn bootstrap_wire(allow_launch: bool) -> Vec<u8> {encode(&json!({@@ -389,7 +389,7 @@ fn bootstrap_request_returns_ticketed_pair_frame_and_never_leaks_secrets() {let ticket = &frame["nmTicket"];assert_eq!(ticket["v"], 1);assert_eq!(ticket["purpose"], "mbp1-attestation");- assert_eq!(ticket["callerId"], "ibpkjhgpbidfmbmomagmldcdlpbmchgi");+ assert_eq!(ticket["callerId"], "lggbokfckofcgjndaboioakcmincinpo");assert_eq!(ticket["browser"], "chromium");assert_eq!(ticket["bindingPub"], BOOTSTRAP_BINDING_PUB);let exp = ticket["exp"].as_u64().expect("exp");diff --git a/scripts/engine.lock.json b/scripts/engine.lock.jsonindex fcc5ac89..346b7c61 100644--- a/scripts/engine.lock.json+++ b/scripts/engine.lock.json@@ -1,50 +1,50 @@{"engine": "aria2","repo": "motrixapp/aria2",- "tag": "v1.37.0-motrix.11",- "version": "1.37.0-motrix.11",+ "tag": "v1.37.0-motrix.12",+ "version": "1.37.0-motrix.12","assets": {"darwin-arm64": {- "file": "aria2c-1.37.0-motrix.11-darwin-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.12-darwin-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "cda62246b0a31d63147d4e706fae50334abf6486d4d6b9d8ba10e5a03f41d110",- "binarySha256": "382a2d4d98216368195db5fc7f1e3c859d7b3b46be74d4ab4bbe6e4ab02f7acd"+ "archiveSha256": "2840fff685b167363dc28d7abe0fa2494b37612e843f50bc800c82d1a8e6abf9",+ "binarySha256": "3cea06e46cb96e97fd5415606238bc829c5a96114d58539aacb613f3ab1d162c"},"darwin-x64": {- "file": "aria2c-1.37.0-motrix.11-darwin-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.12-darwin-x64.tar.gz","bin": "aria2c",- "archiveSha256": "bc332ba48439f103d9c067bc2183d4fd96276a1c366561e8995652a3ddf4b981",- "binarySha256": "a781a07ff464cd661e567f44bf8bbd9da82673fc2616cd8dcbd5410ba27d1457"+ "archiveSha256": "52cc4394cd16b7bcdcbf10bc8922419f616ca53dec490b1f488c21e5361d270e",+ "binarySha256": "596a46cb2fca72cf5a5ded79e3a31eb339ad7e76a5f1b5d8c5362e2ca5945c8b"},"win32-x64": {- "file": "aria2c-1.37.0-motrix.11-win32-x64.zip",+ "file": "aria2c-1.37.0-motrix.12-win32-x64.zip","bin": "aria2c.exe",- "archiveSha256": "218b414baf9f25ea4b619bb5d81166be4907736aabf3357cf3c1cf92bb4bcb73",- "binarySha256": "810f794962dc7c381e271c2c73d4682708a815fecc59716308ececca786b21db"+ "archiveSha256": "223e1a8bb1ae09e757d101dbf1eb1ff4c966cc18e94533f83c2f7107cd516804",+ "binarySha256": "1939e4c95851f9f5e4164bbcf5a5d81bfee7fa31b1cd9c689e97c2e1faaa4cff"},"win32-ia32": {- "file": "aria2c-1.37.0-motrix.11-win32-ia32.zip",+ "file": "aria2c-1.37.0-motrix.12-win32-ia32.zip","bin": "aria2c.exe",- "archiveSha256": "38c9145577bc668e8771e01f52c72a93bd877cf7aed378a015a08e054ad62494",- "binarySha256": "182b0f635926b9d19833f4189d776f7a7a1a0740c43b7faa4f8b4e5679a90bfb"+ "archiveSha256": "e918f01f62a430d2528fba10ce739d253cec2b53cc307fbf7768be755e397e81",+ "binarySha256": "894cb58d526efdafba67b56e41c58effacfb683b107e3386b7cecb0a5c6b888a"},"linux-x64": {- "file": "aria2c-1.37.0-motrix.11-linux-x64.tar.gz",+ "file": "aria2c-1.37.0-motrix.12-linux-x64.tar.gz","bin": "aria2c",- "archiveSha256": "fdfa0f63281763b66ada47fa824835485ff3eea5ceba6c42abd4034debb63c55",- "binarySha256": "2e8a419decb782ff6baffbd6c4c4af007dc94fc4e13b6a1d9e89de586b42ccb5"+ "archiveSha256": "01154ab255bb4313339bd63091e4ddb21996c23fe8fb0ee59d24a2f44b490b16",+ "binarySha256": "5028997089de58841858ba91532775d90f2198dbaa58b835d4ca637d768df176"},"linux-arm64": {- "file": "aria2c-1.37.0-motrix.11-linux-arm64.tar.gz",+ "file": "aria2c-1.37.0-motrix.12-linux-arm64.tar.gz","bin": "aria2c",- "archiveSha256": "1ad0f4aa9b70106910def5994d65155f5085ae990d8bab6e8775e04fd838829f",- "binarySha256": "6edc0174c8f94b8e005a135f1806de03bafcfb3fd07ba5320222b9c1b9b1f736"+ "archiveSha256": "3d585e05cfcbdf206b9ef77a5374b8430525a6b108973adca8e7a92548e98f8a",+ "binarySha256": "1b63459a9939fde39c31937c03b2ef07a614c0b3851a82d70b92569b175df1b3"},"linux-arm": {- "file": "aria2c-1.37.0-motrix.11-linux-armv7l.tar.gz",+ "file": "aria2c-1.37.0-motrix.12-linux-armv7l.tar.gz","bin": "aria2c",- "archiveSha256": "dbb90189eb60f49fb367651a3d3bf7ebb2600e131ed6f73da621d5af9d457dc7",- "binarySha256": "f68b85e6faa1aec143331f763b692bd87fa09512286fbd995f3c96904d3aa4c8"+ "archiveSha256": "d3c6c511a04041b992e5805a1047fd4a2f5725c0969a28d00c67bf00f99c8cfb",+ "binarySha256": "f3d824ad203cbdfea462177df49ca1202bf3cd75035be5554712d3b9c4aebc11"}}}diff --git a/scripts/generate-bridge-pairing-vectors.mjs b/scripts/generate-bridge-pairing-vectors.mjsindex c734f8f7..a6a37821 100644--- a/scripts/generate-bridge-pairing-vectors.mjs+++ b/scripts/generate-bridge-pairing-vectors.mjs@@ -255,8 +255,8 @@ const codeDisplayed = 'MTX7-K2Q9'const codeNormalized = 'MTX7K2Q9'const pairNonce = 'vec-nonce-8f3a1c5e7b2d4a90'const browser = 'chromium'-const verifiedOrigin = 'chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi'-const claimedExtensionId = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+const verifiedOrigin = 'chrome-extension://lggbokfckofcgjndaboioakcmincinpo'+const claimedExtensionId = 'lggbokfckofcgjndaboioakcmincinpo'const clientInstallationId = '5f0b6f9e-8a3d-4c5e-9b2a-7d1e4f6a8c0b'const instanceId = '0d9c2b7a-4e6f-4a1b-8c3d-2e5f7a9b1c4d'const xSeed = unhex(diff --git a/scripts/verify-flatpak-packaging.mjs b/scripts/verify-flatpak-packaging.mjsindex a0698719..fe8e6311 100644--- a/scripts/verify-flatpak-packaging.mjs+++ b/scripts/verify-flatpak-packaging.mjs@@ -18,8 +18,8 @@ export const FLATPAK_BUILDER_TOOLS_COMMIT =// tag resolves to is pinned by hand (and cross-checked against the manifest).export const ARIA2_SOURCE = Object.freeze({url: 'https://github.com/motrixapp/aria2.git',- // v1.37.0-motrix.11 — current Motrix aria2 fork release- commit: 'ab003d49360bac776ada3e967821410f527c00a6',+ // v1.37.0-motrix.12 — current Motrix aria2 fork release+ commit: 'c9143bbf9c16f8c8563e41e7da2a23face4d5a8c',})const PNPM_SOURCE = Object.freeze({@@ -600,7 +600,7 @@ export async function verifyFlatpakPackaging(root = REPO_ROOT) {workflow.includes("self.path != '/nonce'") &&workflow.includes("self.headers.get('X-Motrix-Bridge') != '1'") &&workflow.includes(- 'chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/'+ 'chrome-extension://lggbokfckofcgjndaboioakcmincinpo/') &&workflow.includes(COMPANION_PAIR_FRAME_HEX),'workflow must run the x86_64 Browser Native Messaging companion smoke'diff --git a/src/core/bridge/extension-identity-resolver.test.ts b/src/core/bridge/extension-identity-resolver.test.tsindex 88e4593d..b0ade107 100644--- a/src/core/bridge/extension-identity-resolver.test.ts+++ b/src/core/bridge/extension-identity-resolver.test.ts@@ -9,7 +9,7 @@ import {} from './extension-identity-resolver'import { TrustedExtensionRegistry } from './trusted-extension-registry'-const BUILTIN_CHROMIUM_ID = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+const BUILTIN_CHROMIUM_ID = 'lggbokfckofcgjndaboioakcmincinpo'const BUILTIN_FIREFOX_ID = '[email protected]'const OTHER_CHROMIUM_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'const DEV_CHROMIUM_ID = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'diff --git a/src/core/bridge/mbp1/pair-session.test.ts b/src/core/bridge/mbp1/pair-session.test.tsindex e3705d90..4d4214a6 100644--- a/src/core/bridge/mbp1/pair-session.test.ts+++ b/src/core/bridge/mbp1/pair-session.test.ts@@ -50,7 +50,7 @@ const PROOF_LABEL = utf8ToBytes('MBP1/ticket-proof/v1')const INSTANCE_ID = '0d9c2b7a-4e6f-4a1b-8c3d-2e5f7a9b1c4d'const SERVER_GENERATION = '3c2b1a09-8f7e-4d6c-b5a4-93827160f0e1'const LOCAL_TOKEN = 'vector-local-token-0123456789abcdef'-const EXTENSION_ID = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+const EXTENSION_ID = 'lggbokfckofcgjndaboioakcmincinpo'const ORIGIN = `chrome-extension://${EXTENSION_ID}`const INSTALLATION_ID = '5f0b6f9e-8a3d-4c5e-9b2a-7d1e4f6a8c0b'const PAIR_NONCE = 'vec-nonce-8f3a1c5e7b2d4a90'diff --git a/src/core/bridge/mbp1/reconnect-session.test.ts b/src/core/bridge/mbp1/reconnect-session.test.tsindex 29b4d4e1..3467f51e 100644--- a/src/core/bridge/mbp1/reconnect-session.test.ts+++ b/src/core/bridge/mbp1/reconnect-session.test.ts@@ -24,7 +24,7 @@ import type {import { ReconnectSession } from './reconnect-session'const INSTANCE_ID = '0d9c2b7a-4e6f-4a1b-8c3d-2e5f7a9b1c4d'-const EXTENSION_ID = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+const EXTENSION_ID = 'lggbokfckofcgjndaboioakcmincinpo'const ORIGIN = `chrome-extension://${EXTENSION_ID}`const ATTACKER_ORIGIN = 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'const CREDENTIAL_ID = 'a5e3c9f0-1b2d-4e6f-8a9c-0d1e2f3a4b5c'diff --git a/src/core/bridge/trusted-extension-registry.test.ts b/src/core/bridge/trusted-extension-registry.test.tsindex bc966551..491a427c 100644--- a/src/core/bridge/trusted-extension-registry.test.ts+++ b/src/core/bridge/trusted-extension-registry.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'import { TrustedExtensionRegistry } from './trusted-extension-registry'const BUILTIN = [- { id: 'ibpkjhgpbidfmbmomagmldcdlpbmchgi', browser: 'chromium' as const },+ { id: 'lggbokfckofcgjndaboioakcmincinpo', browser: 'chromium' as const },{ id: '[email protected]', browser: 'firefox' as const },]diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex 8d80ccee..e9fca3a6 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -301,12 +301,19 @@ function createNativeMessagingInstallation(): NativeMessagingInstallation {devOverride: process.env.MOTRIX_BRIDGE_HOST_BIN,...(snap ? { snapInstanceName: snap.instanceName } : {}),})+ const developmentBridgeDataDir = app.isPackaged+ ? undefined+ : resolveBridgeDataDir(+ app.getPath('userData'),+ process.env.MOTRIX_BRIDGE_DATA_DIR+ )return {installer: new NativeMessagingInstaller({hostBinaryPath,manifestRoot: snap?.realHome ?? home,platform: installationPlatform,+ ...(developmentBridgeDataDir ? { developmentBridgeDataDir } : {}),...(installationPlatform === 'win32'? { windowsRoamingAppData: app.getPath('appData') }: {}),diff --git a/src/main/bridge/native-host-path.test.ts b/src/main/bridge/native-host-path.test.tsindex 7371c5e6..44bec87d 100644--- a/src/main/bridge/native-host-path.test.ts+++ b/src/main/bridge/native-host-path.test.ts@@ -141,7 +141,7 @@ describe('resolveNativeHostBinaryPath', () => {})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})@@ -191,7 +191,7 @@ describe('resolveNativeHostBinaryPath', () => {})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})diff --git a/src/main/bridge/native-messaging-extensions.test.ts b/src/main/bridge/native-messaging-extensions.test.tsindex 39a36590..5c6d7a15 100644--- a/src/main/bridge/native-messaging-extensions.test.ts+++ b/src/main/bridge/native-messaging-extensions.test.ts@@ -27,7 +27,10 @@ describe('native messaging extension allowlist', () => {// repository; changing either side requires changing both.it('allowlists the store-signed extension identities', () => {expect(nativeMessagingExtensions.chromium).toContain(- 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+ 'lggbokfckofcgjndaboioakcmincinpo'+ )+ expect(nativeMessagingExtensions.chromium).toContain(+ 'efcflljngohddnmfmebiamigoikmdfbf')expect(nativeMessagingExtensions.firefox).toContain(diff --git a/src/main/bridge/native-messaging-installer.test.ts b/src/main/bridge/native-messaging-installer.test.tsindex a9e42f70..d9fb3614 100644--- a/src/main/bridge/native-messaging-installer.test.ts+++ b/src/main/bridge/native-messaging-installer.test.ts@@ -1,10 +1,11 @@-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { dirname, join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import {computeManifestPaths,computeRegistryEntries,+ DEVELOPMENT_HOST_CONFIG_NAME,NativeMessagingInstaller,type RegistryEntry,type RegistryView,@@ -53,7 +54,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {platform: 'darwin',})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})const chromeContent = JSON.parse(@@ -68,10 +69,42 @@ describe('NativeMessagingInstaller.syncManifests', () => {expect(chromeContent.name).toBe('app.motrix.bridge')expect(chromeContent.path).toBe('/path/to/motrix-bridge-host')expect(chromeContent.allowed_origins).toContain(- 'chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/'+ 'chrome-extension://lggbokfckofcgjndaboioakcmincinpo/')})+ it("binds a development host to Electron's selected bridge directory", async () => {+ const hostBinaryPath = join(dir, 'native-host', 'motrix-native-host')+ const developmentBridgeDataDir = join(dir, 'Motrix-dev', 'bridge')+ const installer = new NativeMessagingInstaller({+ hostBinaryPath,+ manifestRoot: dir,+ platform: 'darwin',+ developmentBridgeDataDir,+ })++ await installer.syncManifests({+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],+ firefox: ['[email protected]'],+ })++ const configPath = join(+ dirname(hostBinaryPath),+ DEVELOPMENT_HOST_CONFIG_NAME+ )+ expect(JSON.parse(await readFile(configPath, 'utf-8'))).toEqual({+ bridgeDataDir: developmentBridgeDataDir,+ })+ if (process.platform !== 'win32') {+ expect((await stat(configPath)).mode & 0o777).toBe(0o600)+ }++ await installer.unregister()+ await expect(readFile(configPath, 'utf-8')).rejects.toMatchObject({+ code: 'ENOENT',+ })+ })+it('writes the chromium-family manifest to the Debian Chromium path on Linux', async () => {const hostBinaryPath = '/opt/Motrix/resources/bin/motrix-native-host'const installer = new NativeMessagingInstaller({@@ -80,7 +113,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {platform: 'linux',})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})const chromium = JSON.parse(@@ -95,7 +128,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {expect(chromium.name).toBe('app.motrix.bridge')expect(chromium.path).toBe(hostBinaryPath)expect(chromium.allowed_origins).toEqual([- 'chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/',+ 'chrome-extension://lggbokfckofcgjndaboioakcmincinpo/',])})@@ -137,7 +170,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {await writeFile(paths.firefox, firefoxSentinel)await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})await installer.unregister()@@ -153,7 +186,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {description: 'Motrix browser download bridge',path: `${dir}/.local/share/motrix/native-messaging/motrix-flatpak-native-host`,type: 'stdio',- allowed_origins: ['chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/'],+ allowed_origins: ['chrome-extension://lggbokfckofcgjndaboioakcmincinpo/'],}await mkdir(dirname(paths.chrome), { recursive: true })await writeFile(paths.chrome, JSON.stringify(flatpakManifest))@@ -195,7 +228,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {platform: 'linux',})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})@@ -213,7 +246,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {platform: 'linux',})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})@@ -390,7 +423,7 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {},})await installer.syncManifests({- chromium: ['ibpkjhgpbidfmbmomagmldcdlpbmchgi'],+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],firefox: ['[email protected]'],})expect(written).toEqual([])diff --git a/src/main/bridge/native-messaging-installer.ts b/src/main/bridge/native-messaging-installer.tsindex 64f0bc4c..15b09e90 100644--- a/src/main/bridge/native-messaging-installer.ts+++ b/src/main/bridge/native-messaging-installer.ts@@ -1,7 +1,8 @@import { execFile } from 'node:child_process'-import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'+import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises'import { dirname, join, posix } from 'node:path'import { promisify } from 'node:util'+import writeFileAtomic from 'write-file-atomic'const execFileAsync = promisify(execFile)@@ -50,6 +51,7 @@ const MANIFEST_HOST_NAME = 'app.motrix.bridge'const MANIFEST_DESCRIPTION = 'Motrix browser download bridge'const WINDOWS_REGISTRY_VIEWS: RegistryView[] = ['32', '64']const FLATPAK_COMPANION_BINARY = 'motrix-flatpak-native-host'+export const DEVELOPMENT_HOST_CONFIG_NAME = 'motrix-native-host.dev.json'interface ManifestOwnership {allowed_extensions?: unknown@@ -257,6 +259,12 @@ export interface InstallerOptions {* companion must own both the launcher and manifests.*/registrationMode?: 'managed' | 'external'+ /**+ * Development-only bridge directory selected by Electron. When present,+ * sync writes an owner-only sidecar beside the development host executable+ * so a browser-spawned host resolves the same isolated user-data profile.+ */+ developmentBridgeDataDir?: string}export interface SyncArgs {@@ -288,6 +296,8 @@ export class NativeMessagingInstaller {async syncManifests(args: SyncArgs): Promise<void> {if (this.opts.registrationMode === 'external') return+ await this.writeDevelopmentHostConfig()+const paths = computeManifestPaths(this.opts.platform,this.opts.manifestRoot,@@ -358,6 +368,35 @@ export class NativeMessagingInstaller {await Promise.all(manifestPaths.map((filePath) => this.removeOwnedManifest(filePath)))+ await this.removeDevelopmentHostConfig()+ }++ private developmentHostConfigPath(): string | null {+ return this.opts.developmentBridgeDataDir+ ? join(dirname(this.opts.hostBinaryPath), DEVELOPMENT_HOST_CONFIG_NAME)+ : null+ }++ private async writeDevelopmentHostConfig(): Promise<void> {+ const filePath = this.developmentHostConfigPath()+ if (!filePath) return++ await mkdir(dirname(filePath), { recursive: true })+ await writeFileAtomic(+ filePath,+ JSON.stringify({+ bridgeDataDir: this.opts.developmentBridgeDataDir,+ }),+ { mode: 0o600 }+ )+ if (this.opts.platform !== 'win32') {+ await chmod(filePath, 0o600)+ }+ }++ private async removeDevelopmentHostConfig(): Promise<void> {+ const filePath = this.developmentHostConfigPath()+ if (filePath) await rm(filePath, { force: true })}private async writeJson(filePath: string, obj: object): Promise<void> {diff --git a/src/renderer/routes/downloads/inspector/peers-tab.tsx b/src/renderer/routes/downloads/inspector/peers-tab.tsxindex 85b3c37d..a7aec482 100644--- a/src/renderer/routes/downloads/inspector/peers-tab.tsx+++ b/src/renderer/routes/downloads/inspector/peers-tab.tsx@@ -26,9 +26,9 @@ const ROW_HEIGHT = 28// one is chosen at render time by PeersTab so disabled GeoIP doesn't// burn 64px of layout for empty cells.const GRID_COLS_WITH_GEO =- 'grid-cols-[28px_36px_minmax(0,2fr)_minmax(0,3fr)_72px_72px_64px_56px]'+ 'grid-cols-[28px_36px_minmax(0,2.5fr)_minmax(0,3fr)_72px_72px_64px_56px]'const GRID_COLS_BASE =- 'grid-cols-[minmax(0,2fr)_minmax(0,3fr)_72px_72px_64px_56px]'+ 'grid-cols-[minmax(0,2.5fr)_minmax(0,3fr)_72px_72px_64px_56px]'/*** Compose the BT peer flags column. Mirrors the convention used bydiff --git a/src/server/bridge/bootstrap.test.ts b/src/server/bridge/bootstrap.test.tsindex 674c1d9d..d5658ddb 100644--- a/src/server/bridge/bootstrap.test.ts+++ b/src/server/bridge/bootstrap.test.ts@@ -369,7 +369,7 @@ describe('bootstrapBridgeForServer', () => {// The public bundle is not merely connectable: a real first-pair channel// reaches the shell receiver's validated download/submit handler.- const extensionId = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+ const extensionId = 'lggbokfckofcgjndaboioakcmincinpo'const handshake = await startPair({port: runtime.port,origin: `chrome-extension://${extensionId}`,@@ -500,7 +500,7 @@ describe('bootstrapBridgeForServer', () => {if (cliToken === undefined) throw new Error('CLI pairing token missing')emit.mockClear()- const extensionId = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+ const extensionId = 'lggbokfckofcgjndaboioakcmincinpo'const handshake = await startPair({port: runtime.port,origin: `chrome-extension://${extensionId}`,diff --git a/src/server/bridge/remote-extension-wss.integration.test.ts b/src/server/bridge/remote-extension-wss.integration.test.tsindex cadeb8b4..0ac823f3 100644--- a/src/server/bridge/remote-extension-wss.integration.test.ts+++ b/src/server/bridge/remote-extension-wss.integration.test.ts@@ -25,7 +25,7 @@ import {} from './bootstrap'import { parseRemoteExtensionConfig } from './remote-extension-config'-const EXTENSION_ID = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+const EXTENSION_ID = 'lggbokfckofcgjndaboioakcmincinpo'function receiver(): ServerExtensionReceiver {return {diff --git a/src/shared/config/native-messaging-extensions.json b/src/shared/config/native-messaging-extensions.jsonindex d0b82117..7e0e231e 100644--- a/src/shared/config/native-messaging-extensions.json+++ b/src/shared/config/native-messaging-extensions.json@@ -1,4 +1,7 @@{- "chromium": ["ibpkjhgpbidfmbmomagmldcdlpbmchgi"],+ "chromium": [+ "lggbokfckofcgjndaboioakcmincinpo",+ "efcflljngohddnmfmebiamigoikmdfbf"+ ],"firefox": ["[email protected]"]}diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex d66d6448..7a45ba24 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -109,7 +109,7 @@"showMotrix": "Show Motrix","manual": "Manual","checkUpdates": "Check for Updates",- "preferences": "Preferences",+ "preferences": "Settings","quit": "Quit"},"panel": {@@ -1682,7 +1682,7 @@"app": {"title": "Motrix","about": "About Motrix",- "preferences": "Preferences…",+ "preferences": "Settings…","checkForUpdates": "Check for Updates…","show": "Show Motrix","hide": "Hide Motrix",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 5380c5d5..0fe8f343 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -108,7 +108,7 @@"showMotrix": "显示 Motrix","manual": "使用手册","checkUpdates": "检查更新",- "preferences": "偏好设置",+ "preferences": "设置","quit": "退出"},"panel": {@@ -1660,7 +1660,7 @@"app": {"title": "Motrix","about": "关于 Motrix",- "preferences": "偏好设置…",+ "preferences": "设置…","checkForUpdates": "检查更新…","show": "显示 Motrix","hide": "隐藏 Motrix",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 8d36547f..631c9458 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -108,7 +108,7 @@"showMotrix": "顯示 Motrix","manual": "使用手冊","checkUpdates": "檢查更新",- "preferences": "偏好設定",+ "preferences": "設定","quit": "結束"},"panel": {@@ -1668,7 +1668,7 @@"app": {"title": "Motrix","about": "關於 Motrix",- "preferences": "偏好設定…",+ "preferences": "設定…","checkForUpdates": "檢查更新…","show": "顯示 Motrix","hide": "隱藏 Motrix",diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.tsindex 7e7ea6df..348cb67f 100644--- a/tests/check-third-party-notices.test.ts+++ b/tests/check-third-party-notices.test.ts@@ -412,9 +412,9 @@ describe('third-party graph dependency notices', () => {expect(notice).toContain('SFNS-Regular.ttf')expect(notice).toContain('https://developer.apple.com/fonts/')- expect(notice).toContain('1.37.0-motrix.11')+ expect(notice).toContain('1.37.0-motrix.12')expect(notice).toContain(- 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.11'+ 'https://github.com/motrixapp/aria2/tree/v1.37.0-motrix.12')expect(notice).toContain('GPL-2.0-or-later')expect(notice).toContain('THIRD_PARTY_LICENSES/aria2-COPYING')diff --git a/tests/generate-third-party-notices.test.ts b/tests/generate-third-party-notices.test.tsindex 6ff95278..5ec97e9d 100644--- a/tests/generate-third-party-notices.test.ts+++ b/tests/generate-third-party-notices.test.ts@@ -164,7 +164,7 @@ describe('third-party notice generator', () => {expect(bundle.packageCount).toBeGreaterThan(100)expect(inventory).toContain('| @xyflow/react | 12.11.3 |')- expect(inventory).toContain('| aria2 | 1.37.0-motrix.11 |')+ expect(inventory).toContain('| aria2 | 1.37.0-motrix.12 |')expect(inventory).toContain('| motrix.filename-template | 1.1.1 |')expect(inventory).toContain('Apple San Francisco tray font')expect(licenses).toContain('GNU GENERAL PUBLIC LICENSE')diff --git a/tests/scripts/flatpak-native-host.test.ts b/tests/scripts/flatpak-native-host.test.tsindex e83c5b09..8516858d 100644--- a/tests/scripts/flatpak-native-host.test.ts+++ b/tests/scripts/flatpak-native-host.test.ts@@ -112,7 +112,7 @@ describe('Flatpak native-host boundary', () => {`bridge_dir="\${XDG_CONFIG_HOME:?}/motrix/bridge"`)expect(workflow).toContain(- 'chrome-extension://ibpkjhgpbidfmbmomagmldcdlpbmchgi/'+ 'chrome-extension://lggbokfckofcgjndaboioakcmincinpo/')expect(workflow).toContain("self.path != '/discovery'")expect(workflow).toContain("self.path != '/nonce'")