Skip to content

A full-featured download manager.

feat(bridge): enable appimage browser cold launch (#2116)

Dr_rOotcf885fff41af
diff --git a/e2e/bridge/README.md b/e2e/bridge/README.md
index 305a54cf..3666f6a1 100644
--- a/e2e/bridge/README.md
+++ b/e2e/bridge/README.md
@@ -1,5 +1,43 @@
# Bridge E2E — `motrix-cli` ↔ Electron / Server
+## AppImage browser cold launch
+
+`appimage-cold-launch.spec.ts` runs the real packaged AppImage and unpacked
+Chromium/Firefox extensions in temporary profiles. It enables browser launch
+through Settings, pairs through the UI, terminates the AppImage, verifies that
+its FUSE mount disappeared, reconnects with the original credentials, and checks
+the bytes of a real local download. It also moves the AppImage, repairs from its
+new location, and verifies disable, re-enable and removal preserve pairing.
+MBP1 and Native Messaging v1 are exercised without protocol substitutes.
+
+Use a native Linux test machine with FUSE, working unprivileged user namespaces,
+Xvfb and the ordinary host browsers downloaded by Playwright. The test preserves
+the packaged Electron fuses and browser sandbox. Snap/Flatpak browsers are outside
+this suite. Add `127.0.0.1 appimage.motrix.test` to the test machine's hosts file;
+the test requires that exact loopback resolution and never downloads public data.
+
+Build this AppImage through the normal build/staging/electron-builder path and
+build the companion extension from `motrixapp/motrix-extension` with
+`pnpm build:chromium` and `pnpm build:firefox`. Set absolute artifact paths:
+
+```bash
+pnpm exec playwright install --with-deps chromium firefox
+MOTRIX_APPIMAGE_ARTIFACT=/path/to/Motrix.AppImage \
+MOTRIX_EXTENSION_BUILD=/path/to/extension/dist/chromium \
+MOTRIX_FIREFOX_EXTENSION_BUILD=/path/to/extension/dist/firefox \
+xvfb-run -a pnpm test:e2e --config e2e/bridge/appimage.playwright.config.ts
+```
+
+Chromium is required by the dedicated config; omit the Firefox build to skip
+that leg. `MOTRIX_CHROMIUM_EXECUTABLE` selects another ordinary Chromium browser
+binary for a separate compatibility run. Record the actual browser, architecture
+and artifact revisions with the result; one architecture does not certify another.
+Tests remove their profiles and registrations. Remove the hosts-file fixture
+after testing. Traces, screenshots and video are disabled so pairing passwords
+cannot enter artifacts.
+
+---
+
End-to-end acceptance for the **MDXP bridge** as exercised by the real
[`motrix` CLI](https://github.com/motrixapp/cli) — the published `@motrix/cli`
npm package, consumed here as a devDependency — covering the two halves the
diff --git a/e2e/bridge/README.zh-CN.md b/e2e/bridge/README.zh-CN.md
index a87bde97..37ed7b26 100644
--- a/e2e/bridge/README.zh-CN.md
+++ b/e2e/bridge/README.zh-CN.md
@@ -1,5 +1,38 @@
# Bridge E2E — `motrix-cli` ↔ Electron / Server
+## AppImage 浏览器冷启动
+
+`appimage-cold-launch.spec.ts` 在临时数据目录中运行真实打包的 AppImage 和
+Chromium/Firefox 扩展。测试通过设置启用浏览器唤起、在界面中首配、终止
+AppImage 并确认 FUSE 挂载消失,然后使用原凭据重连,检查真实本地下载的文件
+内容。还会移动 AppImage,从新位置修复,并验证停用、重新启用和移除不会删除
+配对。整个流程使用既有 MBP1 和 Native Messaging v1。
+
+测试机需要原生 Linux、FUSE、可用的非特权 user namespace、Xvfb,以及 Playwright
+下载的普通宿主浏览器。测试保留打包的 Electron fuses 和浏览器 sandbox;
+Snap/Flatpak 浏览器不在此套件范围内。在测试机 hosts 文件中添加
+`127.0.0.1 appimage.motrix.test`;测试要求该域名明确解析到本机,不下载公网数据。
+
+通过正常构建、staging 和 electron-builder 流程生成 AppImage,并在
+`motrixapp/motrix-extension` 中分别运行 `pnpm build:chromium` 和
+`pnpm build:firefox`。使用产物的绝对路径执行:
+
+```bash
+pnpm exec playwright install --with-deps chromium firefox
+MOTRIX_APPIMAGE_ARTIFACT=/path/to/Motrix.AppImage \
+MOTRIX_EXTENSION_BUILD=/path/to/extension/dist/chromium \
+MOTRIX_FIREFOX_EXTENSION_BUILD=/path/to/extension/dist/firefox \
+xvfb-run -a pnpm test:e2e --config e2e/bridge/appimage.playwright.config.ts
+```
+
+专用配置要求提供 Chromium 产物;不提供 Firefox 产物时跳过该链路。
+`MOTRIX_CHROMIUM_EXECUTABLE` 可指定另一个普通 Chromium 浏览器的可执行文件,
+用于单独进行兼容性验证。记录实际浏览器、架构和产物修订;一种架构通过不代表
+其他架构也通过。测试会删除临时数据目录和注册文件,完成后需移除 hosts 测试
+条目。为避免配对密码进入产物,关闭 trace、截图和录像。
+
+---
+
本目录提供 **MDXP bridge** 的端到端验收测试,由真实的
[`motrix` CLI](https://github.com/motrixapp/cli)(已发布的 `@motrix/cli` npm 包,
此处作为 devDependency 消费)驱动,覆盖
diff --git a/e2e/bridge/appimage-cold-launch.spec.ts b/e2e/bridge/appimage-cold-launch.spec.ts
new file mode 100644
index 00000000..4d38c057
--- /dev/null
+++ b/e2e/bridge/appimage-cold-launch.spec.ts
@@ -0,0 +1,583 @@
+import { spawn } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { lookup } from 'node:dns/promises'
+import {
+ chmod,
+ copyFile,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import {
+ type Browser,
+ type BrowserContext,
+ chromium,
+ expect,
+ test,
+} from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../../src/core/settings/migrations'
+import {
+ type ExtensionPage,
+ launchNativeFirefox,
+} from '../helpers/firefox-native-extension'
+import { getFreePort } from '../helpers/free-port'
+
+test.use({ trace: 'off', screenshot: 'off', video: 'off' })
+
+async function extensionState(
+ page: ExtensionPage
+): Promise<{ state?: string; pairingCode?: unknown }> {
+ return page.evaluate(async () => {
+ const runtime = (
+ globalThis as typeof globalThis & {
+ chrome: {
+ runtime: {
+ sendMessage(
+ message: unknown
+ ): Promise<{ state?: string; pairingCode?: unknown }>
+ }
+ }
+ }
+ ).chrome.runtime
+ return runtime.sendMessage({ kind: 'bg.getState' })
+ })
+}
+async function credentialIds(page: ExtensionPage): Promise<string[]> {
+ return page.evaluate(async () => {
+ const browser = (
+ globalThis as typeof globalThis & {
+ chrome: { storage: { local: { get(key: string): Promise<unknown> } } }
+ }
+ ).chrome
+ const stored = await browser.storage.local.get('motrix.mbp1.credentials')
+ const ids = new Set<string>()
+ const visit = (value: unknown): void => {
+ if (!value || typeof value !== 'object') return
+ for (const [key, child] of Object.entries(value)) {
+ if (key === 'credentialId' && typeof child === 'string') ids.add(child)
+ else visit(child)
+ }
+ }
+ visit(stored)
+ return [...ids].sort()
+ })
+}
+
+/** Only processes carrying this test's unique profile are eligible for cleanup. */
+async function stopProfile(profile: string): Promise<void> {
+ // The owner-only endpoint was created inside this test's private profile.
+ // Some Electron processes restrict reading their environment after startup.
+ try {
+ const endpoint = JSON.parse(
+ await readFile(join(profile, 'bridge/endpoint.json'), 'utf8')
+ ) as { pid?: number }
+ if (Number.isInteger(endpoint.pid) && endpoint.pid! > 1)
+ process.kill(endpoint.pid!, 'SIGTERM')
+ } catch {
+ /* The bridge has already stopped. */
+ }
+ for (const name of await readdir('/proc')) {
+ if (!/^\d+$/u.test(name)) continue
+ try {
+ const env = await readFile(`/proc/${name}/environ`, 'utf8')
+ if (env.split('\0').includes(`MOTRIX_USER_DATA=${profile}`))
+ process.kill(Number(name), 'SIGTERM')
+ } catch {
+ /* Process exited, or belongs to another user. */
+ }
+ }
+}
+
+for (const browserName of ['chromium', 'firefox'] as const) {
+ test(`real ${browserName} + AppImage: consent, pair, unmount, browser wake, original-credential reconnect and download`, async () => {
+ test.skip(
+ process.platform !== 'linux',
+ 'AppImage requires a Linux kernel and FUSE'
+ )
+ const artifact = process.env.MOTRIX_APPIMAGE_ARTIFACT
+ const extension =
+ browserName === 'firefox'
+ ? process.env.MOTRIX_FIREFOX_EXTENSION_BUILD
+ : process.env.MOTRIX_EXTENSION_BUILD
+ test.skip(
+ !artifact || !extension,
+ 'Requires real AppImage and extension builds'
+ )
+ if (!artifact || !extension)
+ throw new Error(
+ 'Set MOTRIX_APPIMAGE_ARTIFACT and MOTRIX_EXTENSION_BUILD to actual build artifacts'
+ )
+ // The download contract requires a DNS hostname. Map this reserved test
+ // domain to 127.0.0.1 in the Linux test machine's hosts file.
+ const downloadHost = 'appimage.motrix.test'
+ expect((await lookup(downloadHost)).address).toBe('127.0.0.1')
+ const root = await realpath(
+ await mkdtemp(join(homedir(), '.motrix-appimage-e2e-'))
+ )
+ await chmod(root, 0o700)
+ const profile = join(root, 'app-profile')
+ let image = join(root, 'Motrix 中文 test.AppImage')
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ HOME: root,
+ XDG_DATA_HOME: join(root, '.local/share'),
+ XDG_CONFIG_HOME: join(root, '.config'),
+ LANG: 'en_US.UTF-8',
+ }
+ delete env.CHROME_CONFIG_HOME
+ delete env.MOTRIX_USER_DATA
+ delete env.MOTRIX_BRIDGE_DATA_DIR
+ await mkdir(profile, { mode: 0o700 })
+ await copyFile(artifact, image)
+ await chmod(image, 0o500)
+ await writeFile(
+ join(profile, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ bridge: { instanceId: randomUUID() },
+ engine: { dnsMode: 'system' },
+ onboarding: { disclaimerAccepted: true },
+ app: {
+ language: 'en-US',
+ checkForUpdatesOnLaunch: false,
+ warnBeforeQuit: false,
+ defaultSaveDir: join(root, 'downloads'),
+ },
+ })
+ )
+ // Desktop integration is independent; the test explicitly enables only browser launch.
+ await writeFile(
+ join(profile, 'appimage-integration.json'),
+ JSON.stringify({ decision: 'declined', nmConsent: 'declined' })
+ )
+ const debugPort = await getFreePort()
+ const endpointPath = join(profile, 'bridge/endpoint.json')
+ const nativeConfig = join(
+ root,
+ '.local/share/motrix/native-messaging/appimage/appimage.json'
+ )
+ const appSession: {
+ browser: Browser | null
+ process: ReturnType<typeof spawn> | null
+ } = { browser: null, process: null }
+ let browser: BrowserContext | null = null
+ let firefoxSession: Awaited<ReturnType<typeof launchNativeFirefox>> | null =
+ null
+ const downloadServer = createServer((_req, res) => {
+ res.writeHead(200, {
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Length': 1024,
+ })
+ res.end(Buffer.alloc(1024, 42))
+ })
+ await new Promise<void>((resolve) =>
+ downloadServer.listen(0, '127.0.0.1', resolve)
+ )
+ const address = downloadServer.address()
+ if (address === null || typeof address === 'string')
+ throw new Error('No download fixture port')
+ const openImage = async () => {
+ // Chromium's renderer debugging switch does not require weakening the
+ // packaged Electron fuses or enabling Node inspector arguments.
+ appSession.process = spawn(
+ image,
+ [`--remote-debugging-port=${debugPort}`],
+ {
+ env: {
+ ...env,
+ MOTRIX_USER_DATA: profile,
+ MOTRIX_RPC_PORT: String(await getFreePort()),
+ },
+ stdio: 'ignore',
+ }
+ )
+ await expect
+ .poll(async () => {
+ try {
+ return (await fetch(`http://127.0.0.1:${debugPort}/json/version`))
+ .ok
+ } catch {
+ return false
+ }
+ })
+ .toBe(true)
+ appSession.browser = await chromium.connectOverCDP(
+ `http://127.0.0.1:${debugPort}`
+ )
+ const appContext = appSession.browser.contexts()[0]
+ if (!appContext) throw new Error('No application browser context')
+ await expect
+ .poll(() => appContext.pages().some((p) => p.url().includes('w=main')))
+ .toBe(true)
+ const main = appContext.pages().find((p) => p.url().includes('w=main'))
+ if (!main) throw new Error('No main window')
+ await main.getByRole('link', { name: 'Settings', exact: true }).click()
+ await main.getByText('Integration', { exact: true }).first().click()
+ return main
+ }
+ try {
+ const main = await openImage()
+ await expect(readFile(nativeConfig)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ await main
+ .getByRole('button', { name: 'Enable browser launch', exact: true })
+ .click()
+ await expect(
+ main.getByTestId('appimage-native-host').getByRole('status')
+ ).toContainText('Local installation checks passed')
+ console.info('AppImage E2E: browser launch explicitly installed')
+ const config = JSON.parse(await readFile(nativeConfig, 'utf8')) as {
+ appImagePath: string
+ bridgeDataDir: string
+ }
+ expect(config.appImagePath).toBe(image)
+ expect(config.bridgeDataDir).toBe(join(profile, 'bridge'))
+ const warmEndpoint = JSON.parse(await readFile(endpointPath, 'utf8')) as {
+ port: number
+ generation: string
+ }
+ const discovery = await fetch(
+ `http://127.0.0.1:${warmEndpoint.port}/discovery`
+ )
+ expect(discovery.ok).toBe(true)
+ expect(await discovery.json()).toMatchObject({
+ app: 'motrix-bridge',
+ instanceId: expect.stringMatching(/\S/u),
+ })
+ const mountsBefore = await readFile('/proc/self/mountinfo', 'utf8')
+ const originalMount = mountsBefore
+ .split('\n')
+ .find((line) => line.includes('.mount_') && line.includes('Motrix'))
+ ?.split(' ')[4]
+ if (!originalMount)
+ throw new Error(
+ 'The test requires a mounted AppImage, not an extracted directory'
+ )
+ let page: ExtensionPage
+ if (browserName === 'firefox') {
+ const firefoxProfile = join(root, 'firefox-profile')
+ await mkdir(firefoxProfile, { mode: 0o700 })
+ firefoxSession = await launchNativeFirefox({
+ profile: firefoxProfile,
+ extension,
+ env,
+ })
+ page = firefoxSession.page
+ } else {
+ browser = await chromium.launchPersistentContext(
+ join(root, '.config/chromium'),
+ {
+ headless: false,
+ chromiumSandbox: true,
+ locale: 'en-US',
+ env,
+ ...(process.env.MOTRIX_CHROMIUM_EXECUTABLE
+ ? { executablePath: process.env.MOTRIX_CHROMIUM_EXECUTABLE }
+ : {}),
+ args: [
+ `--disable-extensions-except=${extension}`,
+ `--load-extension=${extension}`,
+ '--lang=en-US',
+ '--no-proxy-server',
+ ],
+ }
+ )
+ const worker =
+ browser.serviceWorkers()[0] ??
+ (await browser.waitForEvent('serviceworker'))
+ const id = new URL(worker.url()).hostname
+ // Unpacked builds have a local ID. Register it through the shipped UI,
+ // with the same trust level as any user-added extension.
+ await main.getByRole('button', { name: /Trusted extensions/u }).click()
+ await main
+ .getByRole('textbox', { name: 'Extension ID', exact: true })
+ .fill(id)
+ await main.getByRole('button', { name: 'Add', exact: true }).click()
+ await expect(
+ main.getByRole('textbox', { name: 'Extension ID', exact: true })
+ ).toHaveValue('')
+ const chromiumPage = await browser.newPage()
+ await chromiumPage.goto(`chrome-extension://${id}/options.html`)
+ page = chromiumPage
+ }
+ const click = async (
+ name: string,
+ selector = 'button',
+ dialogOnly = false
+ ) => {
+ await expect
+ .poll(() =>
+ page.evaluate(
+ ({ name, selector, dialogOnly }) => {
+ const scope = dialogOnly
+ ? document.querySelector('[role="dialog"]')
+ : document
+ const button = [
+ ...(scope?.querySelectorAll<HTMLElement>(selector) ?? []),
+ ].find(
+ (node) =>
+ (node.getAttribute('aria-label') ??
+ node.textContent?.trim()) === name
+ )
+ if (!button || button.matches(':disabled')) return false
+ button.click()
+ return true
+ },
+ { name, selector, dialogOnly }
+ )
+ )
+ .toBe(true)
+ }
+ await click('Integration', '[role="tab"]')
+ await click('Pair')
+ await expect
+ .poll(async () => {
+ await page.evaluate((port) => {
+ const candidate = [
+ ...document.querySelectorAll('[role="listitem"]'),
+ ].find((node) => node.textContent?.includes(String(port)))
+ const choose = [
+ ...(candidate?.querySelectorAll('button') ?? []),
+ ].find((button) => button.textContent?.trim() === 'Choose')
+ choose?.click()
+ }, warmEndpoint.port)
+ return Boolean((await extensionState(page)).pairingCode)
+ })
+ .toBe(true)
+ let pairingCode: string | null = null
+ await expect
+ .poll(async () => {
+ pairingCode = await main
+ .locator('span.font-mono')
+ .evaluateAll(
+ (nodes) =>
+ nodes
+ .map((n) => n.textContent?.trim() ?? '')
+ .find((s) =>
+ /^[0-9A-HJKMNP-TV-Z]{4}-[0-9A-HJKMNP-TV-Z]{4}$/u.test(s)
+ ) ?? null
+ )
+ return pairingCode !== null
+ })
+ .toBe(true)
+ // Keep the password out of Playwright action logs and assertion output.
+ await expect
+ .poll(() =>
+ page.evaluate(() =>
+ Boolean(document.querySelector('#pairing-code-input'))
+ )
+ )
+ .toBe(true)
+ await page.evaluate((value: string | null) => {
+ const input = document.querySelector<HTMLInputElement>(
+ '#pairing-code-input'
+ )
+ if (!input || !value) throw new Error('Pairing input unavailable')
+ Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ 'value'
+ )?.set?.call(input, value.replace('-', ''))
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ }, pairingCode)
+ pairingCode = null
+ await click('Pair', 'button', true)
+ await expect
+ .poll(async () => (await extensionState(page)).state)
+ .toBe('connected')
+ console.info('AppImage E2E: first pairing authenticated')
+ await expect
+ .poll(() =>
+ page.evaluate(() =>
+ [...document.querySelectorAll('button')].some(
+ (button) =>
+ button.textContent?.trim() === 'Reconnect' && !button.disabled
+ )
+ )
+ )
+ .toBe(true)
+ const retainedIds = await credentialIds(page)
+ expect(retainedIds.length).toBeGreaterThan(0)
+ appSession.process?.kill('SIGTERM')
+ await stopProfile(profile)
+ await expect
+ .poll(async () => {
+ try {
+ await fetch(`http://127.0.0.1:${warmEndpoint.port}/discovery`)
+ return false
+ } catch {
+ return true
+ }
+ })
+ .toBe(true)
+ await expect
+ .poll(async () =>
+ (await readFile('/proc/self/mountinfo', 'utf8')).includes(
+ originalMount
+ )
+ )
+ .toBe(false)
+ await expect
+ .poll(async () => (await extensionState(page)).state)
+ .toBe('disconnected')
+ await click('Reconnect')
+ await expect
+ .poll(async () => (await extensionState(page)).state)
+ .toBe('connected')
+ console.info('AppImage E2E: browser cold launch reconnected')
+ expect((await extensionState(page)).pairingCode).toBeUndefined()
+ expect(await credentialIds(page)).toEqual(retainedIds)
+ const coldEndpoint = JSON.parse(await readFile(endpointPath, 'utf8')) as {
+ generation: string
+ port: number
+ }
+ expect(coldEndpoint.generation).not.toBe(warmEndpoint.generation)
+ const response = await page.evaluate(async (url) => {
+ const runtime = (
+ globalThis as typeof globalThis & {
+ chrome: {
+ runtime: { sendMessage(message: unknown): Promise<unknown> }
+ }
+ }
+ ).chrome.runtime
+ return runtime.sendMessage({
+ kind: 'bg.submitDownload',
+ payload: {
+ source: {
+ pageUrl: url,
+ pageTitle: 'AppImage cold launch E2E',
+ detectedAt: Date.now(),
+ },
+ selection: { kind: 'direct', primary: { url } },
+ meta: {
+ suggestedFilename: 'appimage-e2e.bin',
+ qualityLabel: 'source',
+ },
+ },
+ })
+ }, `http://${downloadHost}:${address.port}/appimage-e2e.bin`)
+ expect(response).toMatchObject({ taskId: expect.any(String) })
+ await expect
+ .poll(async () => {
+ try {
+ return (await readFile(join(root, 'downloads/appimage-e2e.bin')))
+ .length
+ } catch {
+ return 0
+ }
+ })
+ .toBe(1024)
+ console.info('AppImage E2E: download completed with retained credentials')
+ expect(await readFile(join(root, 'downloads/appimage-e2e.bin'))).toEqual(
+ Buffer.alloc(1024, 42)
+ )
+
+ await stopProfile(profile)
+ await expect
+ .poll(async () => {
+ try {
+ await fetch(`http://127.0.0.1:${coldEndpoint.port}/discovery`)
+ return false
+ } catch {
+ return true
+ }
+ })
+ .toBe(true)
+ const moved = join(root, 'Moved 中文 "AppImage".AppImage')
+ await rename(image, moved)
+ image = moved
+ const settings = await openImage()
+ const section = settings.getByTestId('appimage-native-host')
+ await section
+ .getByRole('button', { name: 'Use this AppImage', exact: true })
+ .click()
+ await expect(section.getByRole('status')).toContainText(
+ 'Local installation checks passed'
+ )
+ expect(
+ JSON.parse(await readFile(nativeConfig, 'utf8')).appImagePath
+ ).toBe(moved)
+ console.info('AppImage E2E: moved image repaired explicitly')
+
+ await settings
+ .getByRole('switch', {
+ name: 'Send downloads from browser extensions',
+ exact: true,
+ })
+ .click()
+ await settings.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect
+ .poll(
+ async () => JSON.parse(await readFile(nativeConfig, 'utf8')).enabled
+ )
+ .toBe(false)
+ await settings.getByText('Integration', { exact: true }).first().click()
+ await settings
+ .getByRole('switch', {
+ name: 'Send downloads from browser extensions',
+ exact: true,
+ })
+ .click()
+ await settings.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect
+ .poll(
+ async () => JSON.parse(await readFile(nativeConfig, 'utf8')).enabled
+ )
+ .toBe(true)
+ await settings.getByText('Integration', { exact: true }).first().click()
+ await settings
+ .getByTestId('appimage-native-host')
+ .getByRole('button', { name: 'Remove browser launch', exact: true })
+ .click()
+ await expect
+ .poll(
+ async () => JSON.parse(await readFile(nativeConfig, 'utf8')).consent
+ )
+ .toBe('declined')
+ const removedConfig = JSON.parse(
+ await readFile(nativeConfig, 'utf8')
+ ) as { enabled: boolean; manifests: { path: string }[] }
+ expect(removedConfig.enabled).toBe(false)
+ for (const manifest of removedConfig.manifests) {
+ await expect(readFile(manifest.path)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ }
+ await expect(
+ readFile(
+ join(
+ root,
+ '.local/share/motrix/native-messaging/appimage/motrix-appimage-native-host'
+ )
+ )
+ ).rejects.toMatchObject({ code: 'ENOENT' })
+ expect(await credentialIds(page)).toEqual(retainedIds)
+ console.info(
+ 'AppImage E2E: disable, re-enable and removal preserve pairing'
+ )
+ } finally {
+ await browser?.close().catch(() => {})
+ await firefoxSession?.close().catch(() => {})
+ await appSession.browser?.close().catch(() => {})
+ await stopProfile(profile)
+ appSession.process?.kill('SIGTERM')
+ await new Promise<void>((resolve) =>
+ downloadServer.close(() => resolve())
+ )
+ await rm(root, {
+ recursive: true,
+ force: true,
+ maxRetries: 20,
+ retryDelay: 250,
+ })
+ }
+ })
+}
diff --git a/e2e/bridge/appimage.playwright.config.ts b/e2e/bridge/appimage.playwright.config.ts
new file mode 100644
index 00000000..106e0de0
--- /dev/null
+++ b/e2e/bridge/appimage.playwright.config.ts
@@ -0,0 +1,23 @@
+import { defineConfig } from '@playwright/test'
+
+if (
+ !process.env.MOTRIX_APPIMAGE_ARTIFACT ||
+ !process.env.MOTRIX_EXTENSION_BUILD
+) {
+ throw new Error(
+ 'Set MOTRIX_APPIMAGE_ARTIFACT and MOTRIX_EXTENSION_BUILD to real builds'
+ )
+}
+
+export default defineConfig({
+ testDir: '.',
+ testMatch: 'appimage-cold-launch.spec.ts',
+ workers: 1,
+ retries: 0,
+ timeout: 120_000,
+ expect: { timeout: 20_000 },
+ reporter: [['list']],
+ // Pairing passwords must not enter traces, screenshots or video.
+ use: { trace: 'off', screenshot: 'off', video: 'off' },
+ outputDir: '../test-results/appimage',
+})
diff --git a/e2e/helpers/firefox-native-extension.ts b/e2e/helpers/firefox-native-extension.ts
new file mode 100644
index 00000000..86e114c9
--- /dev/null
+++ b/e2e/helpers/firefox-native-extension.ts
@@ -0,0 +1,150 @@
+import { spawn } from 'node:child_process'
+import { writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { firefox } from '@playwright/test'
+import WebSocket from 'ws'
+import { getFreePort } from './free-port'
+
+export interface ExtensionPage {
+ evaluate<R, A = undefined>(
+ fn: (arg: A) => R | Promise<R>,
+ arg?: A
+ ): Promise<R>
+}
+
+/** Firefox's native BiDi installer exercises the actual installed extension. */
+export async function launchNativeFirefox(input: {
+ profile: string
+ extension: string
+ env: NodeJS.ProcessEnv
+}): Promise<{ page: ExtensionPage; close(): Promise<void> }> {
+ const uuid = 'fbff0d6e-e992-42ed-b009-a07a0bf86f7d'
+ await writeFile(
+ join(input.profile, 'user.js'),
+ [
+ `user_pref("extensions.webextensions.uuids", ${JSON.stringify(JSON.stringify({ '[email protected]': uuid }))});`,
+ 'user_pref("intl.locale.requested", "en-US");',
+ ].join('\n')
+ )
+ const port = await getFreePort()
+ const process = spawn(
+ firefox.executablePath(),
+ [
+ '--headless',
+ '--no-remote',
+ '--profile',
+ input.profile,
+ '--remote-debugging-port',
+ String(port),
+ '--remote-allow-system-access',
+ ],
+ { env: input.env, stdio: 'ignore' }
+ )
+ let socket: WebSocket | undefined
+ const pending = new Map<
+ number,
+ { resolve(value: unknown): void; reject(error: Error): void }
+ >()
+ let sequence = 0
+ const close = async () => {
+ socket?.close()
+ for (const request of pending.values())
+ request.reject(new Error('Firefox closed'))
+ if (process.exitCode === null) {
+ process.kill('SIGTERM')
+ await new Promise<void>((resolve) =>
+ process.once('exit', () => resolve())
+ )
+ }
+ }
+ try {
+ const deadline = Date.now() + 20_000
+ while (Date.now() < deadline && !socket) {
+ const candidate = new WebSocket(`ws://127.0.0.1:${port}/session`)
+ const opened = await new Promise<boolean>((resolve) => {
+ candidate.once('open', () => resolve(true))
+ candidate.once('error', () => resolve(false))
+ })
+ if (opened) socket = candidate
+ else await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ if (!socket) throw new Error('Firefox BiDi did not start')
+ socket.on('message', (data) => {
+ const response = JSON.parse(String(data)) as {
+ id: number
+ type: string
+ result?: unknown
+ }
+ const request = pending.get(response.id)
+ if (!request) return
+ pending.delete(response.id)
+ if (response.type === 'error')
+ request.reject(new Error('Firefox BiDi command failed'))
+ else request.resolve(response.result)
+ })
+ const command = (method: string, params: unknown): Promise<unknown> => {
+ const id = ++sequence
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ pending.delete(id)
+ reject(new Error(`Firefox ${method} timed out`))
+ }, 20_000)
+ pending.set(id, {
+ resolve: (value) => {
+ clearTimeout(timeout)
+ resolve(value)
+ },
+ reject: (error) => {
+ clearTimeout(timeout)
+ reject(error)
+ },
+ })
+ socket?.send(JSON.stringify({ id, method, params }))
+ })
+ }
+ await command('session.new', {
+ capabilities: { alwaysMatch: { browserName: 'firefox' } },
+ })
+ await command('webExtension.install', {
+ extensionData: { type: 'path', path: input.extension },
+ })
+ const tree = (await command('browsingContext.getTree', {})) as {
+ contexts: { context: string }[]
+ }
+ const context = tree.contexts[0]?.context
+ if (!context) throw new Error('Firefox did not expose a browsing context')
+ await command('browsingContext.navigate', {
+ context,
+ url: `moz-extension://${uuid}/options.html`,
+ wait: 'complete',
+ })
+ return {
+ close,
+ page: {
+ async evaluate<R, A = undefined>(
+ fn: (arg: A) => R | Promise<R>,
+ arg?: A
+ ): Promise<R> {
+ // Serialize only the result to avoid depending on BiDi's nested
+ // RemoteValue representation. Exception details can contain secrets.
+ const response = (await command('script.evaluate', {
+ expression: `(async () => JSON.stringify(await (${fn.toString()})(${JSON.stringify(arg)})))()`,
+ target: { context },
+ awaitPromise: true,
+ resultOwnership: 'none',
+ })) as { type: string; result?: { value?: string } }
+ if (response.type !== 'success')
+ throw new Error('Firefox extension evaluation failed')
+ return (
+ response.result?.value === undefined
+ ? undefined
+ : JSON.parse(response.result.value)
+ ) as R
+ },
+ },
+ }
+ } catch (error) {
+ await close()
+ throw error
+ }
+}
diff --git a/packages/native-host/src/appimage_config.rs b/packages/native-host/src/appimage_config.rs
new file mode 100644
index 00000000..ea128ba2
--- /dev/null
+++ b/packages/native-host/src/appimage_config.rs
@@ -0,0 +1,323 @@
+//! The AppImage copy uses a distinct executable name and an owner-only sidecar.
+//! This is a local launch configuration, not a Native Messaging protocol version.
+use std::fs::{self, File};
+use std::io::{Read, Seek};
+use std::os::unix::fs::MetadataExt;
+use std::path::{Component, Path, PathBuf};
+use std::process::Command;
+use std::time::{Duration, Instant};
+
+use serde::Deserialize;
+use sha2::{Digest, Sha256};
+
+use crate::endpoint::{effective_user_id, is_owner_only};
+use crate::launcher::spawn_configured;
+
+pub const HOST_NAME: &str = "motrix-appimage-native-host";
+
+#[derive(Clone, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct AppImageConfig {
+ schema_version: u32,
+ install_id: String,
+ consent: String,
+ enabled: bool,
+ app_image_path: PathBuf,
+ pub user_data_dir: PathBuf,
+ pub bridge_data_dir: PathBuf,
+ arch: String,
+ host_sha256: String,
+ app_image_sha256: String,
+ manifests: Vec<ManifestReceipt>,
+}
+
+#[derive(Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct ManifestReceipt {
+ path: PathBuf,
+ sha256: String,
+}
+
+fn valid_path(path: &Path) -> bool {
+ path.is_absolute()
+ && path
+ .to_str()
+ .is_some_and(|s| !s.chars().any(char::is_control))
+ && !path
+ .components()
+ .any(|c| matches!(c, Component::CurDir | Component::ParentDir))
+}
+
+fn valid_hash(hash: &str) -> bool {
+ hash.len() == 64
+ && hash
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+}
+
+fn safe_parents(path: &Path) -> Option<()> {
+ for parent in path.ancestors().skip(1) {
+ let stat = fs::symlink_metadata(parent).ok()?;
+ let sticky_root = stat.uid() == 0 && stat.mode() & 0o1000 != 0;
+ if !stat.is_dir()
+ || (stat.uid() != 0 && stat.uid() != effective_user_id())
+ || (stat.mode() & 0o022 != 0 && !sticky_root)
+ {
+ return None;
+ }
+ }
+ Some(())
+}
+
+fn hash_executable(file: &mut File, arch: &str) -> Option<String> {
+ let before = file.metadata().ok()?;
+ if !before.is_file()
+ || before.uid() != effective_user_id()
+ || before.mode() & 0o022 != 0
+ || before.mode() & 0o111 == 0
+ {
+ return None;
+ }
+ let mut header = [0_u8; 20];
+ file.read_exact(&mut header).ok()?;
+ let machine = match arch {
+ "x64" => 62,
+ "arm64" => 183,
+ _ => return None,
+ };
+ if &header[..4] != b"\x7fELF"
+ || header[4] != 2
+ || header[5] != 1
+ || u16::from_le_bytes([header[18], header[19]]) != machine
+ {
+ return None;
+ }
+ file.rewind().ok()?;
+ let mut hash = Sha256::new();
+ let mut buffer = [0_u8; 64 * 1024];
+ let deadline = Instant::now() + Duration::from_secs(3);
+ let mut total = 0_u64;
+ loop {
+ let count = file.read(&mut buffer).ok()?;
+ if count == 0 {
+ break;
+ }
+ total += count as u64;
+ if total > 2_u64.pow(31) || Instant::now() > deadline {
+ return None;
+ }
+ hash.update(&buffer[..count]);
+ }
+ let after = file.metadata().ok()?;
+ if before.size() != after.size()
+ || before.mtime_nsec() != after.mtime_nsec()
+ || before.mtime() != after.mtime()
+ || before.ctime() != after.ctime()
+ || before.ctime_nsec() != after.ctime_nsec()
+ {
+ return None;
+ }
+ Some(format!("{:x}", hash.finalize()))
+}
+
+impl AppImageConfig {
+ fn read(executable: &Path) -> Option<Self> {
+ safe_parents(executable)?;
+ let config_path = executable.parent()?.join("appimage.json");
+ if !fs::symlink_metadata(&config_path).ok()?.is_file() {
+ return None;
+ }
+ let file = File::open(config_path).ok()?;
+ if !is_owner_only(&file) || file.metadata().ok()?.len() > 16 * 1024 {
+ return None;
+ }
+ let config: Self = serde_json::from_reader(file.take(16 * 1024 + 1)).ok()?;
+ let architecture = match std::env::consts::ARCH {
+ "x86_64" => "x64",
+ "aarch64" => "arm64",
+ _ => return None,
+ };
+ let valid_id = config.install_id.len() == 36
+ && config.install_id.bytes().enumerate().all(|(i, b)| {
+ if [8, 13, 18, 23].contains(&i) {
+ b == b'-'
+ } else {
+ b.is_ascii_hexdigit()
+ }
+ });
+ if config.schema_version != 1
+ || !valid_id
+ || config.consent != "accepted"
+ || !config.enabled
+ || config.arch != architecture
+ || !valid_path(&config.app_image_path)
+ || !valid_path(&config.user_data_dir)
+ || !valid_path(&config.bridge_data_dir)
+ || !valid_hash(&config.host_sha256)
+ || !valid_hash(&config.app_image_sha256)
+ || config.manifests.len() > 4
+ || config
+ .manifests
+ .iter()
+ .any(|m| !valid_path(&m.path) || !valid_hash(&m.sha256))
+ {
+ return None;
+ }
+ // Hash the executing inode, including during an atomic replacement.
+ // Opening the executable's old pathname could read the new version.
+ let mut running = File::open("/proc/self/exe").ok()?;
+ if hash_executable(&mut running, &config.arch)? != config.host_sha256 {
+ return None;
+ }
+ Some(config)
+ }
+
+ pub fn launch(&self) -> bool {
+ self.launch_checked().unwrap_or(false)
+ }
+
+ fn launch_checked(&self) -> Option<bool> {
+ safe_parents(&self.app_image_path)?;
+ if fs::canonicalize(&self.app_image_path).ok()? != self.app_image_path {
+ return None;
+ }
+ let mut file = File::open(&self.app_image_path).ok()?;
+ if hash_executable(&mut file, &self.arch)? != self.app_image_sha256 {
+ return None;
+ }
+ let opened = file.metadata().ok()?;
+ let named = fs::symlink_metadata(&self.app_image_path).ok()?;
+ if !named.is_file() || opened.dev() != named.dev() || opened.ino() != named.ino() {
+ return None;
+ }
+ let mut command = Command::new(&self.app_image_path);
+ for (name, _) in std::env::vars_os() {
+ let key = name.to_string_lossy();
+ if key.starts_with("APPIMAGE")
+ || key == "APPDIR"
+ || key == "ARGV0"
+ || key.starts_with("LD_")
+ || key.starts_with("NODE_")
+ || key.starts_with("ELECTRON_")
+ || key == "SNAP"
+ || key == "FLATPAK_ID"
+ {
+ command.env_remove(name);
+ }
+ }
+ command
+ .env("MOTRIX_USER_DATA", &self.user_data_dir)
+ .env("MOTRIX_BRIDGE_DATA_DIR", &self.bridge_data_dir);
+ Some(spawn_configured(command))
+ }
+}
+
+/// `Err` is a broken AppImage installation, never permission to use system paths.
+pub fn load_current() -> Result<Option<AppImageConfig>, &'static str> {
+ let executable = std::env::current_exe().map_err(|_| "executable unavailable")?;
+ let name = executable
+ .file_name()
+ .and_then(|s| s.to_str())
+ .unwrap_or("");
+ if name.strip_suffix(" (deleted)").unwrap_or(name) != HOST_NAME {
+ return Ok(None);
+ }
+ AppImageConfig::read(&executable)
+ .map(Some)
+ .ok_or("AppImage configuration invalid")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static NEXT: AtomicU64 = AtomicU64::new(0);
+
+ struct Fixture {
+ directory: PathBuf,
+ executable: PathBuf,
+ config: serde_json::Value,
+ }
+ impl Fixture {
+ fn new() -> Self {
+ let directory = std::env::temp_dir().join(format!(
+ "motrix-appimage-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, Ordering::Relaxed)
+ ));
+ fs::create_dir(&directory).unwrap();
+ fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
+ let executable = directory.join(HOST_NAME);
+ let arch = match std::env::consts::ARCH {
+ "aarch64" => "arm64",
+ _ => "x64",
+ };
+ let current = std::env::current_exe().unwrap();
+ let sha = hash_executable(&mut File::open(&current).unwrap(), arch).unwrap();
+ let config = serde_json::json!({
+ "schemaVersion": 1, "installId": "ae55c69c-0480-4df4-a12b-38dc3a724c14",
+ "consent": "accepted", "enabled": true, "appImagePath": current,
+ "userDataDir": directory, "bridgeDataDir": directory.join("bridge"),
+ "arch": arch, "hostSha256": sha, "appImageSha256": sha, "manifests": [],
+ });
+ Self {
+ directory,
+ executable,
+ config,
+ }
+ }
+ fn save(&self) {
+ let path = self.directory.join("appimage.json");
+ fs::write(&path, serde_json::to_vec(&self.config).unwrap()).unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
+ }
+ }
+ impl Drop for Fixture {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.directory);
+ }
+ }
+
+ #[test]
+ fn loads_private_config_for_the_running_inode() {
+ let fixture = Fixture::new();
+ fixture.save();
+ let config = AppImageConfig::read(&fixture.executable).unwrap();
+ assert_eq!(config.bridge_data_dir, fixture.directory.join("bridge"));
+ }
+
+ #[test]
+ fn rejects_disabled_unknown_or_mismatched_installations() {
+ for (field, value) in [
+ ("enabled", serde_json::json!(false)),
+ ("consent", serde_json::json!("declined")),
+ ("schemaVersion", serde_json::json!(2)),
+ ("hostSha256", serde_json::json!("0".repeat(64))),
+ ("appImagePath", serde_json::json!("relative/image")),
+ ("unexpected", serde_json::json!(true)),
+ ] {
+ let mut fixture = Fixture::new();
+ fixture.config[field] = value;
+ fixture.save();
+ assert!(
+ AppImageConfig::read(&fixture.executable).is_none(),
+ "{field}"
+ );
+ }
+ }
+
+ #[test]
+ fn rejects_readable_config_and_symlink_config() {
+ let fixture = Fixture::new();
+ fixture.save();
+ let path = fixture.directory.join("appimage.json");
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
+ assert!(AppImageConfig::read(&fixture.executable).is_none());
+ let other = fixture.directory.join("other.json");
+ fs::rename(&path, &other).unwrap();
+ fs::set_permissions(&other, fs::Permissions::from_mode(0o600)).unwrap();
+ std::os::unix::fs::symlink(&other, &path).unwrap();
+ assert!(AppImageConfig::read(&fixture.executable).is_none());
+ }
+}
diff --git a/packages/native-host/src/endpoint.rs b/packages/native-host/src/endpoint.rs
index 893f3fc4..2f84964d 100644
--- a/packages/native-host/src/endpoint.rs
+++ b/packages/native-host/src/endpoint.rs
@@ -16,7 +16,7 @@ pub struct EndpointFile {
}
#[cfg(unix)]
-fn effective_user_id() -> u32 {
+pub(crate) fn effective_user_id() -> u32 {
unsafe extern "C" {
fn geteuid() -> u32;
}
diff --git a/packages/native-host/src/launcher.rs b/packages/native-host/src/launcher.rs
index 560ed674..674f29fd 100644
--- a/packages/native-host/src/launcher.rs
+++ b/packages/native-host/src/launcher.rs
@@ -137,6 +137,10 @@ fn configure_detached(command: &mut Command) {
fn spawn_detached(spec: LaunchCommand) -> bool {
let mut command = Command::new(spec.program);
command.args(spec.args);
+ spawn_configured(command)
+}
+
+pub(crate) fn spawn_configured(mut command: Command) -> bool {
configure_detached(&mut command);
match command.spawn() {
Ok(mut child) => {
diff --git a/packages/native-host/src/lib.rs b/packages/native-host/src/lib.rs
index 0ff24b9f..59cb5b7e 100644
--- a/packages/native-host/src/lib.rs
+++ b/packages/native-host/src/lib.rs
@@ -1,3 +1,5 @@
+#[cfg(target_os = "linux")]
+pub mod appimage_config;
pub mod broker_protocol;
pub mod caller;
pub mod canonical;
diff --git a/packages/native-host/src/main.rs b/packages/native-host/src/main.rs
index 19b9a483..cd1b0326 100644
--- a/packages/native-host/src/main.rs
+++ b/packages/native-host/src/main.rs
@@ -71,7 +71,17 @@ fn read_request() -> Result<HostRequest, RunError> {
}
fn resolve_request(request: &HostRequest, bridge_data: Option<&Path>) -> ResolveResult {
- let mut deps = SystemResolveDeps::from_bridge_data(bridge_data);
+ let deps = SystemResolveDeps::from_bridge_data(bridge_data);
+ #[cfg(target_os = "linux")]
+ let deps = match motrix_native_host::appimage_config::load_current() {
+ Ok(config) => deps.with_appimage(config),
+ Err(_) => {
+ return ResolveResult::Error {
+ error: motrix_native_host::resolve::ResolveError::LaunchFailed,
+ };
+ }
+ };
+ let mut deps = deps;
match resolve_endpoint(request.allow_launch(), &mut deps) {
Ok(resolved) => {
let ticket = request
@@ -128,6 +138,12 @@ fn run(bridge_data: Option<&Path>, logger: &NativeHostLogger) -> Result<(), RunE
fn main() -> ExitCode {
let user_data = native_host_user_data_dir();
let bridge_data = native_host_bridge_data_dir(user_data.as_deref());
+ #[cfg(target_os = "linux")]
+ let bridge_data = match motrix_native_host::appimage_config::load_current() {
+ Ok(Some(config)) => Some(config.bridge_data_dir),
+ Ok(None) => bridge_data,
+ Err(_) => None,
+ };
let logger = NativeHostLogger::from_bridge_data(bridge_data.as_deref());
logger.log(&format!(
"=== spawned argv_count={} ===",
diff --git a/packages/native-host/src/runtime.rs b/packages/native-host/src/runtime.rs
index febcdc8b..de51f7b4 100644
--- a/packages/native-host/src/runtime.rs
+++ b/packages/native-host/src/runtime.rs
@@ -16,14 +16,27 @@ use crate::user_data::bridge_endpoint_path;
/// never exercises the launch capability.
pub struct SystemResolveDeps {
endpoint_path: Option<PathBuf>,
+ #[cfg(target_os = "linux")]
+ appimage: Option<crate::appimage_config::AppImageConfig>,
}
impl SystemResolveDeps {
pub fn from_bridge_data(bridge_data: Option<&Path>) -> Self {
Self {
endpoint_path: bridge_data.map(bridge_endpoint_path),
+ #[cfg(target_os = "linux")]
+ appimage: None,
}
}
+
+ #[cfg(target_os = "linux")]
+ pub fn with_appimage(mut self, config: Option<crate::appimage_config::AppImageConfig>) -> Self {
+ if let Some(ref c) = config {
+ self.endpoint_path = Some(bridge_endpoint_path(&c.bridge_data_dir));
+ }
+ self.appimage = config;
+ self
+ }
}
impl ResolveDeps for SystemResolveDeps {
@@ -40,6 +53,10 @@ impl ResolveDeps for SystemResolveDeps {
}
fn launch(&mut self) -> bool {
+ #[cfg(target_os = "linux")]
+ if let Some(ref config) = self.appimage {
+ return config.launch();
+ }
launch_motrix()
}
diff --git a/src/main/bridge/appimage-native-host-electron.ts b/src/main/bridge/appimage-native-host-electron.ts
new file mode 100644
index 00000000..5828f889
--- /dev/null
+++ b/src/main/bridge/appimage-native-host-electron.ts
@@ -0,0 +1,25 @@
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+import { app } from 'electron'
+import { AppImageNativeHost } from './appimage-native-host'
+import { resolveBridgeDataDir } from './snap-environment'
+
+let installation: AppImageNativeHost | null = null
+
+export function getAppImageNativeHost(): AppImageNativeHost | null {
+ if (process.platform !== 'linux' || !app.isPackaged || !process.env.APPIMAGE)
+ return null
+ installation ??= new AppImageNativeHost({
+ home: homedir(),
+ env: process.env,
+ appImagePath: process.env.APPIMAGE,
+ sourceHostPath: join(process.resourcesPath, 'bin/motrix-native-host'),
+ userDataDir: app.getPath('userData'),
+ bridgeDataDir: resolveBridgeDataDir(
+ app.getPath('userData'),
+ process.env.MOTRIX_BRIDGE_DATA_DIR
+ ),
+ arch: process.arch,
+ })
+ return installation
+}
diff --git a/src/main/bridge/appimage-native-host.test.ts b/src/main/bridge/appimage-native-host.test.ts
new file mode 100644
index 00000000..9a38a851
--- /dev/null
+++ b/src/main/bridge/appimage-native-host.test.ts
@@ -0,0 +1,249 @@
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rename,
+ rm,
+ symlink,
+ 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 {
+ AppImageNativeHost,
+ type AppImageNativeHostOptions,
+} from './appimage-native-host'
+import { computeManifestPaths } from './native-messaging-installer'
+
+const ids = { chromium: ['a'.repeat(32)], firefox: ['[email protected]'] }
+let root: string
+let options: AppImageNativeHostOptions
+let host: AppImageNativeHost
+function elf(marker = 0): Buffer {
+ const bytes = Buffer.alloc(256, marker)
+ bytes.write('\x7fELF')
+ bytes[4] = 2
+ bytes[5] = 1
+ bytes.writeUInt16LE(183, 18)
+ return bytes
+}
+beforeEach(async () => {
+ root = await realpath(await mkdtemp(join(tmpdir(), 'motrix-appimage-')))
+ await chmod(root, 0o700)
+ const appImagePath = join(root, 'Motrix 中文 image.AppImage')
+ const sourceHostPath = join(root, 'motrix-native-host')
+ await writeFile(appImagePath, elf(1), { mode: 0o500 })
+ await writeFile(sourceHostPath, elf(2), { mode: 0o500 })
+ options = {
+ home: root,
+ env: {},
+ appImagePath,
+ sourceHostPath,
+ arch: 'arm64',
+ userDataDir: join(root, 'profile'),
+ bridgeDataDir: join(root, 'profile/bridge'),
+ systemManifestRoots: [],
+ }
+ host = new AppImageNativeHost(options)
+})
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true })
+})
+const configPath = () => join(host.directory, 'appimage.json')
+const paths = () => Object.values(computeManifestPaths('linux', root))
+
+describe('AppImage Native Host installation', () => {
+ it('requires explicit consent, installs a stable copy, and keeps it across refreshes', async () => {
+ await host.sync(ids)
+ await expect(readFile(configPath())).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ expect(await host.configure('enable', ids, true)).toMatchObject({
+ enabled: true,
+ healthy: true,
+ currentTarget: true,
+ })
+ const first = JSON.parse(await readFile(configPath(), 'utf8'))
+ for (const path of paths())
+ expect(JSON.parse(await readFile(path, 'utf8')).path).toBe(host.hostPath)
+ await host.sync(ids)
+ expect(JSON.parse(await readFile(configPath(), 'utf8')).installId).toBe(
+ first.installId
+ )
+ await rm(options.sourceHostPath)
+ expect(await host.inspect()).toMatchObject({ healthy: true })
+ })
+
+ it('stops wake on disable and removal, but only removal revokes consent', async () => {
+ await host.configure('enable', ids, true)
+ await host.suspend()
+ expect(await host.inspect()).toMatchObject({
+ enabled: false,
+ consent: 'accepted',
+ })
+ for (const path of paths())
+ await expect(readFile(path)).rejects.toMatchObject({ code: 'ENOENT' })
+ await host.sync(ids)
+ expect(await host.inspect()).toMatchObject({ healthy: true })
+ await host.configure('remove', ids, true)
+ await host.sync(ids)
+ expect(await host.inspect()).toMatchObject({
+ enabled: false,
+ consent: 'declined',
+ })
+ await expect(readFile(host.hostPath)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ expect(await readFile(options.appImagePath)).toEqual(elf(1))
+ })
+
+ it('preserves foreign manifests on install and on removal', async () => {
+ const path = paths()[0]
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, '{"path":"/other/host"}')
+ expect(await host.configure('enable', ids, true)).toMatchObject({
+ issue: 'conflict',
+ })
+ await expect(readFile(configPath())).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ await rm(path)
+ await host.configure('enable', ids, true)
+ await writeFile(path, 'external owner')
+ expect(await host.configure('remove', ids, true)).toMatchObject({
+ issue: 'conflict',
+ enabled: false,
+ })
+ expect(await readFile(path, 'utf8')).toBe('external owner')
+ })
+
+ it('revokes launch before attempting cleanup of a damaged update receipt', async () => {
+ await host.configure('enable', ids, true)
+ await writeFile(`${configPath()}.bak`, 'damaged', { mode: 0o600 })
+ expect(await host.configure('remove', ids, true)).toMatchObject({
+ consent: 'declined',
+ enabled: false,
+ issue: 'invalid',
+ })
+ expect(await readFile(`${configPath()}.bak`, 'utf8')).toBe('damaged')
+ })
+
+ it('rejects symlinks and unsafe source permissions', async () => {
+ await chmod(options.appImagePath, 0o777)
+ expect(await host.configure('enable', ids, true)).toMatchObject({
+ issue: 'permissions',
+ })
+ await chmod(options.appImagePath, 0o500)
+ const path = paths()[0]
+ await mkdir(dirname(path), { recursive: true })
+ await symlink(options.appImagePath, path)
+ expect(await host.configure('enable', ids, true)).toMatchObject({
+ issue: 'permissions',
+ })
+ expect(await readFile(options.appImagePath)).toEqual(elf(1))
+ })
+
+ it('moves only after an explicit repair from the intended image', async () => {
+ await host.configure('enable', ids, true)
+ const moved = join(root, 'Moved "image".AppImage')
+ await rename(options.appImagePath, moved)
+ const next = new AppImageNativeHost({ ...options, appImagePath: moved })
+ await next.sync(ids)
+ expect(await next.inspect()).toMatchObject({
+ healthy: false,
+ issue: 'missing',
+ currentTarget: false,
+ })
+ expect(await next.configure('repair', ids, true)).toMatchObject({
+ healthy: true,
+ currentTarget: true,
+ })
+ })
+
+ it('detects source replacement and refreshes only after running the same path', async () => {
+ await host.configure('enable', ids, true)
+ await chmod(options.appImagePath, 0o700)
+ await writeFile(options.appImagePath, elf(3))
+ expect(await host.inspect()).toMatchObject({
+ healthy: false,
+ issue: 'sourceChanged',
+ })
+ await host.sync(ids)
+ expect(await host.inspect()).toMatchObject({ healthy: true })
+ })
+
+ it('repairs a missing host and old manifests using the interrupted-update receipt', async () => {
+ await host.configure('enable', ids, true)
+ const original = await readFile(configPath(), 'utf8')
+ await writeFile(`${configPath()}.bak`, original, { mode: 0o600 })
+ const interrupted = JSON.parse(original)
+ interrupted.manifests = interrupted.manifests.map(
+ (m: { path: string }) => ({ ...m, sha256: '0'.repeat(64) })
+ )
+ await writeFile(configPath(), JSON.stringify(interrupted))
+ await rm(host.hostPath)
+ expect(await host.configure('repair', ids, true)).toMatchObject({
+ healthy: true,
+ })
+ await expect(readFile(`${configPath()}.bak`)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ })
+
+ it('does not take over a different user-data profile', async () => {
+ await host.configure('enable', ids, true)
+ const other = new AppImageNativeHost({
+ ...options,
+ userDataDir: join(root, 'other'),
+ })
+ expect(await other.configure('enable', ids, true)).toMatchObject({
+ issue: 'conflict',
+ })
+ expect(await host.inspect()).toMatchObject({ healthy: true })
+ await host.suspend()
+ expect(await other.configure('enable', ids, true)).toMatchObject({
+ issue: 'conflict',
+ })
+ expect(await host.inspect()).toMatchObject({ enabled: false })
+ })
+
+ it('allows only one profile to claim a new shared installation', async () => {
+ const other = new AppImageNativeHost({
+ ...options,
+ userDataDir: join(root, 'other'),
+ })
+ const results = await Promise.all([
+ host.configure('enable', ids, true),
+ other.configure('enable', ids, true),
+ ])
+ expect(
+ results.filter((result) => result.supported && result.healthy)
+ ).toHaveLength(1)
+ expect(
+ results.filter(
+ (result) => result.supported && result.issue === 'conflict'
+ )
+ ).toHaveLength(1)
+ })
+
+ it('uses XDG browser paths but keeps Firefox in its native manifest directory', async () => {
+ const env = {
+ XDG_CONFIG_HOME: join(root, 'config'),
+ CHROME_CONFIG_HOME: join(root, 'chrome-config'),
+ XDG_DATA_HOME: join(root, 'data'),
+ }
+ const scoped = new AppImageNativeHost({ ...options, env })
+ expect(await scoped.configure('enable', ids, true)).toMatchObject({
+ healthy: true,
+ })
+ const output = computeManifestPaths('linux', root, undefined, env)
+ expect(output.chrome).toContain('/chrome-config/')
+ expect(output.firefox).toBe(
+ join(root, '.mozilla/native-messaging-hosts/app.motrix.bridge.json')
+ )
+ expect(scoped.hostPath).toContain('/data/motrix/')
+ })
+})
diff --git a/src/main/bridge/appimage-native-host.ts b/src/main/bridge/appimage-native-host.ts
new file mode 100644
index 00000000..20ebe50d
--- /dev/null
+++ b/src/main/bridge/appimage-native-host.ts
@@ -0,0 +1,517 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { constants } from 'node:fs'
+import {
+ chmod,
+ copyFile,
+ type FileHandle,
+ link,
+ lstat,
+ mkdir,
+ open,
+ realpath,
+ rename,
+ rm,
+} from 'node:fs/promises'
+import { dirname, isAbsolute, join, normalize } from 'node:path'
+import type {
+ AppImageNativeHostIssue,
+ AppImageNativeHostView,
+} from '@shared/schemas/appimage-native-host'
+import writeFileAtomic from 'write-file-atomic'
+import { z } from 'zod'
+import {
+ computeManifestPaths,
+ type SyncArgs,
+} from './native-messaging-installer'
+
+export const APPIMAGE_HOST_NAME = 'motrix-appimage-native-host'
+const CONFIG_NAME = 'appimage.json'
+const MAX_CONFIG_BYTES = 16 * 1024
+const absolutePath = z
+ .string()
+ .refine(
+ (p) =>
+ isAbsolute(p) &&
+ normalize(p) === p &&
+ !Array.from(p).some(
+ (c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127
+ )
+ )
+const hash = z.string().regex(/^[a-f0-9]{64}$/u)
+const configSchema = z.strictObject({
+ schemaVersion: z.literal(1),
+ installId: z.uuid(),
+ consent: z.enum(['accepted', 'declined']),
+ enabled: z.boolean(),
+ appImagePath: absolutePath,
+ userDataDir: absolutePath,
+ bridgeDataDir: absolutePath,
+ arch: z.enum(['x64', 'arm64']),
+ hostSha256: hash,
+ appImageSha256: hash,
+ manifests: z
+ .array(z.strictObject({ path: absolutePath, sha256: hash }))
+ .max(4),
+})
+type Config = z.infer<typeof configSchema>
+
+export interface AppImageNativeHostOptions {
+ home: string
+ env: NodeJS.ProcessEnv
+ appImagePath: string
+ sourceHostPath: string
+ userDataDir: string
+ bridgeDataDir: string
+ arch: string
+ /** Tests use isolated system directories. Production checks the real roots. */
+ systemManifestRoots?: string[]
+}
+
+class InstallError extends Error {
+ constructor(readonly issue: AppImageNativeHostIssue) {
+ super(issue)
+ }
+}
+function code(error: unknown): unknown {
+ return typeof error === 'object' && error !== null && 'code' in error
+ ? error.code
+ : undefined
+}
+function digest(data: string | Buffer): string {
+ return createHash('sha256').update(data).digest('hex')
+}
+function xdg(value: string | undefined, fallback: string): string {
+ return value && isAbsolute(value) ? value : fallback
+}
+
+/** Private files are never opened through a symlink. Ancestors may be root owned. */
+async function checkParents(path: string): Promise<void> {
+ let current = path
+ for (;;) {
+ try {
+ const stat = await lstat(current)
+ const stickyRoot = stat.uid === 0 && (stat.mode & 0o1000) !== 0
+ if (
+ !stat.isDirectory() ||
+ stat.isSymbolicLink() ||
+ (stat.uid !== process.getuid?.() && stat.uid !== 0) ||
+ ((stat.mode & 0o022) !== 0 && !stickyRoot)
+ )
+ throw new InstallError('permissions')
+ } catch (error) {
+ if (code(error) !== 'ENOENT') throw error
+ }
+ const parent = dirname(current)
+ if (parent === current) return
+ current = parent
+ }
+}
+
+async function readOwned(
+ path: string,
+ privateFile = false
+): Promise<Buffer | null> {
+ await checkParents(dirname(path))
+ let file: FileHandle
+ try {
+ file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
+ } catch (error) {
+ if (code(error) === 'ENOENT') return null
+ throw error
+ }
+ try {
+ const stat = await file.stat()
+ if (
+ !stat.isFile() ||
+ stat.uid !== process.getuid?.() ||
+ (stat.mode & (privateFile ? 0o077 : 0o022)) !== 0
+ )
+ throw new InstallError('permissions')
+ if (stat.size > MAX_CONFIG_BYTES) throw new InstallError('invalid')
+ return await file.readFile()
+ } finally {
+ await file.close()
+ }
+}
+
+async function binaryHash(
+ path: string,
+ arch: string,
+ owned: boolean
+): Promise<string> {
+ await checkParents(dirname(path))
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
+ try {
+ const before = await file.stat()
+ if (
+ !before.isFile() ||
+ (before.mode & 0o111) === 0 ||
+ (before.mode & 0o022) !== 0 ||
+ (owned && before.uid !== process.getuid?.())
+ )
+ throw new InstallError('permissions')
+ const header = Buffer.alloc(20)
+ await file.read(header, 0, header.length, 0)
+ const machine = arch === 'x64' ? 62 : arch === 'arm64' ? 183 : -1
+ if (
+ header.subarray(0, 4).toString('hex') !== '7f454c46' ||
+ header[4] !== 2 ||
+ header[5] !== 1 ||
+ header.readUInt16LE(18) !== machine
+ )
+ throw new InstallError('invalid')
+ const sha = createHash('sha256')
+ const started = Date.now()
+ let size = 0
+ for await (const chunk of file.createReadStream({
+ start: 0,
+ autoClose: false,
+ })) {
+ size += chunk.length
+ if (size > 2 ** 31 || Date.now() - started > 5000)
+ throw new InstallError('io')
+ sha.update(chunk)
+ }
+ const after = await file.stat()
+ const named = await lstat(path)
+ if (
+ before.size !== after.size ||
+ before.mtimeMs !== after.mtimeMs ||
+ before.ctimeMs !== after.ctimeMs ||
+ after.ino !== named.ino ||
+ after.dev !== named.dev
+ )
+ throw new InstallError('sourceChanged')
+ return sha.digest('hex')
+ } finally {
+ await file.close()
+ }
+}
+
+export class AppImageNativeHost {
+ readonly directory: string
+ readonly hostPath: string
+ private readonly configPath: string
+ private transition: Promise<unknown> = Promise.resolve()
+
+ constructor(private readonly options: AppImageNativeHostOptions) {
+ this.directory = join(
+ xdg(options.env.XDG_DATA_HOME, join(options.home, '.local/share')),
+ 'motrix/native-messaging/appimage'
+ )
+ this.hostPath = join(this.directory, APPIMAGE_HOST_NAME)
+ this.configPath = join(this.directory, CONFIG_NAME)
+ }
+
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
+ const next = this.transition.then(operation, operation)
+ this.transition = next.catch(() => {})
+ return next
+ }
+
+ private async config(path = this.configPath): Promise<Config | null> {
+ const bytes = await readOwned(path, true)
+ if (!bytes) return null
+ const parsed = configSchema.safeParse(JSON.parse(bytes.toString('utf8')))
+ if (!parsed.success) throw new InstallError('invalid')
+ if (parsed.data.userDataDir !== this.options.userDataDir)
+ throw new InstallError('conflict')
+ return parsed.data
+ }
+
+ private manifests(ids: SyncArgs): Map<string, string> {
+ const paths = computeManifestPaths(
+ 'linux',
+ this.options.home,
+ undefined,
+ this.options.env
+ )
+ const entries = new Map<string, string>()
+ for (const [browser, path] of Object.entries(paths)) {
+ entries.set(
+ path,
+ JSON.stringify(
+ {
+ name: 'app.motrix.bridge',
+ description: 'Motrix browser download bridge',
+ path: this.hostPath,
+ type: 'stdio',
+ ...(browser === 'firefox'
+ ? { allowed_extensions: ids.firefox }
+ : {
+ allowed_origins: ids.chromium.map(
+ (id) => `chrome-extension://${id}/`
+ ),
+ }),
+ },
+ null,
+ 2
+ )
+ )
+ }
+ return entries
+ }
+
+ private async assertManifest(
+ path: string,
+ configs: (Config | null)[],
+ legacy?: string
+ ): Promise<boolean> {
+ const bytes = await readOwned(path)
+ if (!bytes) return false
+ const matches = configs.some((c) =>
+ c?.manifests.some((r) => r.path === path && r.sha256 === digest(bytes))
+ )
+ if (!matches && bytes.toString('utf8') !== legacy)
+ throw new InstallError('conflict')
+ return true
+ }
+
+ private async writeNew(path: string, data: string): Promise<void> {
+ await checkParents(dirname(path))
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
+ const temp = `${path}.${randomUUID()}.tmp`
+ try {
+ await writeFileAtomic(temp, data, { mode: 0o600 })
+ await link(temp, path)
+ } finally {
+ await rm(temp, { force: true })
+ }
+ }
+
+ private async install(ids: SyncArgs, enabled: boolean): Promise<void> {
+ const old = await this.config()
+ const backup = await this.config(`${this.configPath}.bak`)
+ const entries = this.manifests(ids)
+ for (const root of this.options.systemManifestRoots ?? [
+ '/etc/opt/chrome/native-messaging-hosts',
+ '/etc/chromium/native-messaging-hosts',
+ '/etc/opt/edge/native-messaging-hosts',
+ '/usr/lib/mozilla/native-messaging-hosts',
+ '/usr/lib64/mozilla/native-messaging-hosts',
+ ]) {
+ try {
+ await lstat(join(root, 'app.motrix.bridge.json'))
+ throw new InstallError('conflict')
+ } catch (error) {
+ if (code(error) !== 'ENOENT') throw error
+ }
+ }
+ const existed = new Map<string, boolean>()
+ for (const [path, content] of entries) {
+ const legacy = JSON.stringify(
+ { ...JSON.parse(content), path: this.options.sourceHostPath },
+ null,
+ 2
+ )
+ existed.set(path, await this.assertManifest(path, [old, backup], legacy))
+ }
+ const image = await realpath(this.options.appImagePath)
+ absolutePath.parse(image)
+ const appImageSha256 = await binaryHash(image, this.options.arch, true)
+ const hostSha256 = await binaryHash(
+ this.options.sourceHostPath,
+ this.options.arch,
+ false
+ )
+ try {
+ const existingHash = await binaryHash(
+ this.hostPath,
+ this.options.arch,
+ true
+ )
+ if (
+ ![hostSha256, old?.hostSha256, backup?.hostSha256].includes(
+ existingHash
+ )
+ )
+ throw new InstallError('conflict')
+ } catch (error) {
+ if (code(error) !== 'ENOENT') throw error
+ }
+ await checkParents(this.directory)
+ await mkdir(this.directory, { recursive: true, mode: 0o700 })
+ const directoryStat = await lstat(this.directory)
+ if (
+ directoryStat.uid !== process.getuid?.() ||
+ (directoryStat.mode & 0o077) !== 0
+ )
+ throw new InstallError('permissions')
+ const next = configSchema.parse({
+ schemaVersion: 1,
+ installId: old?.installId ?? randomUUID(),
+ consent: 'accepted',
+ enabled,
+ appImagePath: image,
+ userDataDir: this.options.userDataDir,
+ bridgeDataDir: this.options.bridgeDataDir,
+ arch: this.options.arch,
+ hostSha256,
+ appImageSha256,
+ manifests: [...entries].map(([path, content]) => ({
+ path,
+ sha256: digest(content),
+ })),
+ })
+ // Claim the shared slot before replacing the executable. A competing
+ // profile cannot write its own config over the winner.
+ if (!old)
+ await this.writeNew(
+ this.configPath,
+ JSON.stringify({ ...next, enabled: false })
+ )
+ if (old && !backup)
+ await this.writeNew(`${this.configPath}.bak`, JSON.stringify(old))
+ const temp = join(this.directory, `${randomUUID()}.tmp`)
+ try {
+ await copyFile(this.options.sourceHostPath, temp, constants.COPYFILE_EXCL)
+ await chmod(temp, 0o500)
+ if ((await binaryHash(temp, this.options.arch, true)) !== hostSha256)
+ throw new InstallError('sourceChanged')
+ await rename(temp, this.hostPath)
+ await writeFileAtomic(this.configPath, JSON.stringify(next), {
+ mode: 0o600,
+ })
+ if (enabled) {
+ for (const [path, content] of entries) {
+ if (existed.get(path)) {
+ await this.assertManifest(
+ path,
+ [old, backup],
+ JSON.stringify(
+ { ...JSON.parse(content), path: this.options.sourceHostPath },
+ null,
+ 2
+ )
+ )
+ await writeFileAtomic(path, content, { mode: 0o600 })
+ } else await this.writeNew(path, content)
+ if ((await readOwned(path))?.toString('utf8') !== content)
+ throw new InstallError('io')
+ }
+ }
+ await rm(`${this.configPath}.bak`, { force: true })
+ } finally {
+ await rm(temp, { force: true })
+ }
+ }
+
+ /** Runtime refresh never grants consent or switches to a different image. */
+ async sync(ids: SyncArgs): Promise<void> {
+ return this.enqueue(async () => {
+ const config = await this.config()
+ if (config?.consent !== 'accepted') return
+ if (config.appImagePath !== (await realpath(this.options.appImagePath)))
+ return
+ await this.install(ids, true)
+ })
+ }
+
+ async suspend(): Promise<void> {
+ return this.enqueue(() => this.disable(false))
+ }
+
+ private async disable(remove: boolean): Promise<void> {
+ const config = await this.config()
+ if (!config) return
+ await writeFileAtomic(
+ this.configPath,
+ JSON.stringify({
+ ...config,
+ enabled: false,
+ consent: remove ? 'declined' : config.consent,
+ }),
+ { mode: 0o600 }
+ )
+ const backup = await this.config(`${this.configPath}.bak`)
+ let failure: unknown
+ for (const path of new Set(
+ [config, backup].flatMap((c) => c?.manifests.map((m) => m.path) ?? [])
+ )) {
+ try {
+ if (await this.assertManifest(path, [config, backup])) await rm(path)
+ } catch (error) {
+ failure ??= error
+ }
+ }
+ if (remove) {
+ try {
+ const actual = await binaryHash(this.hostPath, config.arch, true)
+ if (actual !== config.hostSha256 && actual !== backup?.hostSha256)
+ throw new InstallError('conflict')
+ await rm(this.hostPath)
+ } catch (error) {
+ if (code(error) !== 'ENOENT') failure ??= error
+ }
+ }
+ if (failure) throw failure
+ await rm(`${this.configPath}.bak`, { force: true })
+ }
+
+ async configure(
+ action: 'enable' | 'repair' | 'remove',
+ ids: SyncArgs,
+ enabled: boolean
+ ): Promise<AppImageNativeHostView> {
+ return this.enqueue(async () => {
+ try {
+ if (action === 'remove') await this.disable(true)
+ else await this.install(ids, enabled)
+ return await this.inspect()
+ } catch (error) {
+ return this.inspect(this.issue(error))
+ }
+ })
+ }
+
+ async inspect(
+ issue: AppImageNativeHostIssue | null = null
+ ): Promise<AppImageNativeHostView> {
+ let config: Config | null = null
+ try {
+ config = await this.config()
+ if (config?.enabled && config.consent === 'accepted') {
+ if (
+ (await binaryHash(this.hostPath, config.arch, true)) !==
+ config.hostSha256 ||
+ (await binaryHash(config.appImagePath, config.arch, true)) !==
+ config.appImageSha256
+ )
+ throw new InstallError('sourceChanged')
+ for (const entry of config.manifests) {
+ if (!(await this.assertManifest(entry.path, [config])))
+ throw new InstallError('missing')
+ }
+ }
+ } catch (error) {
+ issue ??= this.issue(error)
+ }
+ let currentTarget = false
+ try {
+ currentTarget =
+ config?.appImagePath === (await realpath(this.options.appImagePath))
+ } catch {
+ /* A moved image remains repairable from its new location. */
+ }
+ return {
+ supported: true,
+ consent: config?.consent ?? 'unset',
+ enabled: config?.enabled ?? false,
+ target: config?.appImagePath ?? this.options.appImagePath,
+ currentTarget,
+ healthy: config?.enabled === true && issue === null,
+ issue,
+ }
+ }
+
+ private issue(error: unknown): AppImageNativeHostIssue {
+ if (error instanceof InstallError) return error.issue
+ if (code(error) === 'ENOENT') return 'missing'
+ if (code(error) === 'EEXIST') return 'conflict'
+ if (['EACCES', 'EPERM', 'ELOOP'].includes(String(code(error))))
+ return 'permissions'
+ if (error instanceof SyntaxError || error instanceof z.ZodError)
+ return 'invalid'
+ return 'io'
+ }
+}
diff --git a/src/main/bridge/bridge-manager.test.ts b/src/main/bridge/bridge-manager.test.ts
index f1d47237..940bbe1e 100644
--- a/src/main/bridge/bridge-manager.test.ts
+++ b/src/main/bridge/bridge-manager.test.ts
@@ -24,6 +24,38 @@ function makeRuntime(): BridgeRuntime {
}
describe('BridgeManager', () => {
+ it('preserves an established AppImage installation when runtime startup fails', async () => {
+ const unregister = vi.fn().mockResolvedValue(undefined)
+ const manager = new BridgeManager(
+ async () => {
+ throw new Error('listener unavailable')
+ },
+ unregister,
+ false
+ )
+ await expect(manager.start()).rejects.toThrow('listener unavailable')
+ expect(unregister).not.toHaveBeenCalled()
+ await manager.setEnabled(false)
+ expect(unregister).toHaveBeenCalledOnce()
+ })
+
+ it('disables native launch before stopping the running listener', async () => {
+ const runtime = makeRuntime()
+ const order: string[] = []
+ const manager = new BridgeManager(
+ async () => runtime,
+ async () => {
+ order.push('unregister')
+ }
+ )
+ vi.mocked(runtime.shutdown).mockImplementation(async () => {
+ order.push('shutdown')
+ })
+ await manager.start()
+ await manager.setEnabled(false)
+ expect(order).toEqual(['unregister', 'shutdown'])
+ })
+
it('start() calls factory and stores runtime', async () => {
const runtime = makeRuntime()
const factory = vi.fn().mockResolvedValue(runtime)
diff --git a/src/main/bridge/bridge-manager.ts b/src/main/bridge/bridge-manager.ts
index e9b1dc3b..c292c8e8 100644
--- a/src/main/bridge/bridge-manager.ts
+++ b/src/main/bridge/bridge-manager.ts
@@ -21,7 +21,8 @@ export class BridgeManager {
constructor(
private factory: BridgeRuntimeFactory,
- private unregisterNativeMessaging?: NativeMessagingUnregister
+ private unregisterNativeMessaging?: NativeMessagingUnregister,
+ private readonly cleanupOnStartFailure = true
) {}
get current(): BridgeRuntime | null {
@@ -70,7 +71,8 @@ export class BridgeManager {
try {
runtime = await this.factory()
} catch (startError) {
- if (!this.unregisterNativeMessaging) throw startError
+ if (!this.unregisterNativeMessaging || !this.cleanupOnStartFailure)
+ throw startError
this.cleanupPending = true
try {
await this.unregisterNativeMessaging()
@@ -117,15 +119,6 @@ export class BridgeManager {
this.cleanupPending = true
}
- let shutdownError: unknown
- if (r) {
- try {
- await r.shutdown()
- } catch (error) {
- shutdownError = error
- }
- }
-
let unregisterError: unknown
if (shouldUnregister) {
const pendingUnregister = this.pendingUnregister
@@ -143,6 +136,17 @@ export class BridgeManager {
}
}
+ // Disable launch before stopping the listener; otherwise a browser could
+ // restart the application during the master-switch transition.
+ let shutdownError: unknown
+ if (r) {
+ try {
+ await r.shutdown()
+ } catch (error) {
+ shutdownError = error
+ }
+ }
+
if (shutdownError && unregisterError) {
throw new AggregateError(
[shutdownError, unregisterError],
diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.ts
index dab00279..9a5aaf37 100644
--- a/src/main/bridge/index.ts
+++ b/src/main/bridge/index.ts
@@ -65,6 +65,7 @@ import { app, ipcMain } from 'electron'
import { CancellationTokenSource } from 'vscode-jsonrpc'
import { registerTrustedIpcHandler } from '../ipc/trusted-ipc'
import { i18n } from '../lib/i18n'
+import { getAppImageNativeHost } from './appimage-native-host-electron'
import { isPackagedLinuxFlatpak } from './flatpak-environment'
import { resolveNativeHostBinaryPath } from './native-host-path'
import {
@@ -311,6 +312,8 @@ function createNativeMessagingInstallation(): NativeMessagingInstallation {
return {
installer: new NativeMessagingInstaller({
+ appImage: getAppImageNativeHost(),
+ env: process.env,
hostBinaryPath,
manifestRoot: snap?.realHome ?? home,
platform: installationPlatform,
@@ -337,6 +340,12 @@ export async function syncNativeMessagingManifests(args: {
try {
await args.installer.syncManifests(args.manifests)
} catch (error) {
+ if (args.installer.preserveOnStartupFailure) {
+ ;(args.warn ?? console.warn)(
+ 'AppImage browser launch needs repair in settings'
+ )
+ return
+ }
const code =
typeof error === 'object' && error !== null && 'code' in error
? (error as { code?: unknown }).code
@@ -783,7 +792,10 @@ export async function bootstrapBridge(args: {
const { installer, snap } = createNativeMessagingInstallation()
let preserveNativeMessagingRegistration = false
ownership.own('native-messaging-manifests', async () => {
- if (!preserveNativeMessagingRegistration) {
+ if (
+ !preserveNativeMessagingRegistration &&
+ !installer.preserveOnStartupFailure
+ ) {
await installer.unregister()
}
})
diff --git a/src/main/bridge/native-messaging-installer.test.ts b/src/main/bridge/native-messaging-installer.test.ts
index d9fb3614..65a0b4c6 100644
--- a/src/main/bridge/native-messaging-installer.test.ts
+++ b/src/main/bridge/native-messaging-installer.test.ts
@@ -210,7 +210,7 @@ describe('NativeMessagingInstaller.syncManifests', () => {
)
})
- it('repairs a stale file that only resembles a companion manifest', async () => {
+ it('preserves an unowned file that only resembles a companion manifest', async () => {
const paths = computeManifestPaths('linux', dir)
await mkdir(dirname(paths.chrome), { recursive: true })
await writeFile(
@@ -227,13 +227,15 @@ describe('NativeMessagingInstaller.syncManifests', () => {
manifestRoot: dir,
platform: 'linux',
})
- await installer.syncManifests({
- chromium: ['lggbokfckofcgjndaboioakcmincinpo'],
- firefox: ['[email protected]'],
- })
+ await expect(
+ installer.syncManifests({
+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],
+ firefox: ['[email protected]'],
+ })
+ ).rejects.toThrow('conflict')
expect(JSON.parse(await readFile(paths.chrome, 'utf-8')).path).toBe(
- hostBinaryPath
+ '/tmp/motrix-flatpak-native-host'
)
})
diff --git a/src/main/bridge/native-messaging-installer.ts b/src/main/bridge/native-messaging-installer.ts
index 15b09e90..0839969d 100644
--- a/src/main/bridge/native-messaging-installer.ts
+++ b/src/main/bridge/native-messaging-installer.ts
@@ -1,8 +1,9 @@
import { execFile } from 'node:child_process'
-import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
-import { dirname, join, posix } from 'node:path'
+import { chmod, lstat, mkdir, readFile, rm } from 'node:fs/promises'
+import { dirname, isAbsolute, join, posix } from 'node:path'
import { promisify } from 'node:util'
import writeFileAtomic from 'write-file-atomic'
+import type { AppImageNativeHost } from './appimage-native-host'
const execFileAsync = promisify(execFile)
@@ -113,7 +114,8 @@ function isOwnedManifest(value: unknown, hostBinaryPath: string): boolean {
export function computeManifestPaths(
platform: Platform,
home: string,
- windowsRoamingAppData?: string
+ windowsRoamingAppData?: string,
+ env: NodeJS.ProcessEnv = {}
): ManifestPaths {
if (platform === 'darwin') {
return {
@@ -123,11 +125,19 @@ export function computeManifestPaths(
}
}
if (platform === 'linux') {
+ const config =
+ env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME)
+ ? env.XDG_CONFIG_HOME
+ : `${home}/.config`
+ const chromeConfig =
+ env.CHROME_CONFIG_HOME && isAbsolute(env.CHROME_CONFIG_HOME)
+ ? env.CHROME_CONFIG_HOME
+ : config
return {
- chrome: `${home}/.config/google-chrome/NativeMessagingHosts/${MANIFEST_NAME}`,
- chromium: `${home}/.config/chromium/NativeMessagingHosts/${MANIFEST_NAME}`,
+ chrome: `${chromeConfig}/google-chrome/NativeMessagingHosts/${MANIFEST_NAME}`,
+ chromium: `${chromeConfig}/chromium/NativeMessagingHosts/${MANIFEST_NAME}`,
firefox: `${home}/.mozilla/native-messaging-hosts/${MANIFEST_NAME}`,
- edge: `${home}/.config/microsoft-edge/NativeMessagingHosts/${MANIFEST_NAME}`,
+ edge: `${config}/microsoft-edge/NativeMessagingHosts/${MANIFEST_NAME}`,
}
}
// win32: registry-based discovery. Use the resolved Roaming AppData known
@@ -230,6 +240,8 @@ async function regDeleteKey(
}
export interface InstallerOptions {
+ appImage?: AppImageNativeHost | null
+ env?: NodeJS.ProcessEnv
/** Absolute path to the Native Messaging host executable. */
hostBinaryPath: string
/**
@@ -293,7 +305,12 @@ interface FirefoxManifest {
export class NativeMessagingInstaller {
constructor(private readonly opts: InstallerOptions) {}
+ get preserveOnStartupFailure(): boolean {
+ return this.opts.appImage != null
+ }
+
async syncManifests(args: SyncArgs): Promise<void> {
+ if (this.opts.appImage) return this.opts.appImage.sync(args)
if (this.opts.registrationMode === 'external') return
await this.writeDevelopmentHostConfig()
@@ -301,7 +318,8 @@ export class NativeMessagingInstaller {
const paths = computeManifestPaths(
this.opts.platform,
this.opts.manifestRoot,
- this.opts.windowsRoamingAppData
+ this.opts.windowsRoamingAppData,
+ this.opts.env
)
const chromiumManifest: ChromiumManifest = {
@@ -344,12 +362,14 @@ export class NativeMessagingInstaller {
}
async unregister(): Promise<void> {
+ if (this.opts.appImage) return this.opts.appImage.suspend()
if (this.opts.registrationMode === 'external') return
const paths = computeManifestPaths(
this.opts.platform,
this.opts.manifestRoot,
- this.opts.windowsRoamingAppData
+ this.opts.windowsRoamingAppData,
+ this.opts.env
)
const registryEntries = computeRegistryEntries(this.opts.platform, paths)
const deleteRegistry = this.opts.registryDeleter ?? regDeleteKey
@@ -400,14 +420,31 @@ export class NativeMessagingInstaller {
}
private async writeJson(filePath: string, obj: object): Promise<void> {
- if (
- this.opts.platform === 'linux' &&
- (await this.readManifest(filePath).then(isFlatpakCompanionManifest))
- ) {
- return
+ if (this.opts.platform === 'linux') {
+ try {
+ const stat = await lstat(filePath)
+ if (!stat.isFile() || stat.isSymbolicLink())
+ throw new Error('Native Messaging manifest conflict')
+ const existing = await this.readManifest(filePath)
+ if (isFlatpakCompanionManifest(existing)) return
+ if (!isOwnedManifest(existing, this.opts.hostBinaryPath))
+ throw new Error('Native Messaging manifest conflict')
+ } catch (error) {
+ if (
+ !(
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'ENOENT'
+ )
+ )
+ throw error
+ }
}
await mkdir(dirname(filePath), { recursive: true })
- await writeFile(filePath, JSON.stringify(obj, null, 2), 'utf-8')
+ await writeFileAtomic(filePath, JSON.stringify(obj, null, 2), {
+ mode: 0o600,
+ })
}
private async removeOwnedManifest(filePath: string): Promise<void> {
@@ -415,6 +452,12 @@ export class NativeMessagingInstaller {
await rm(filePath, { force: true })
return
}
+ try {
+ if (!(await lstat(filePath)).isFile()) return
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
+ throw error
+ }
const manifest = await this.readManifest(filePath)
if (isOwnedManifest(manifest, this.opts.hostBinaryPath)) {
await rm(filePath, { force: true })
@@ -434,7 +477,7 @@ export class NativeMessagingInstaller {
return null
}
// Malformed or unreadable files are not treated as owned during
- // unregister. syncManifests may still repair them by overwriting.
+ // unregister. Linux sync also treats these as conflicts.
return null
}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index be710117..8f70ca72 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -2479,8 +2479,10 @@ async function initializeMainProcess(): Promise<void> {
pluginHost: pluginHost!,
})
}
- bridgeManager = new BridgeManager(createBridgeRuntime, () =>
- nativeMessagingInstaller.unregister()
+ bridgeManager = new BridgeManager(
+ createBridgeRuntime,
+ () => nativeMessagingInstaller.unregister(),
+ !nativeMessagingInstaller.preserveOnStartupFailure
)
const registryClient = new RegistryClient({
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 4ca95b9a..692a7db1 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -76,6 +76,7 @@ import { swapMagnetMetadataForBt } from '@core/torrent/swap-magnet-metadata-for-
import type { TorrentParser } from '@core/torrent/torrent-parser'
import type { TrackerManager } from '@core/tracker'
import type { NatManager } from '@motrix/nat'
+import nativeMessagingExtensions from '@shared/config/native-messaging-extensions.json'
import { AppError, ErrorCode } from '@shared/errors'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
@@ -86,6 +87,7 @@ import {
taskCreateRequestSchema,
torrentBatchCreateOptionsSchema,
} from '@shared/schemas/add-task'
+import { appImageNativeHostActionSchema } from '@shared/schemas/appimage-native-host'
import {
removeTasksPayloadSchema,
taskIdsPayloadSchema,
@@ -114,6 +116,7 @@ import {
shell,
} from 'electron'
import { z } from 'zod'
+import { getAppImageNativeHost } from '../bridge/appimage-native-host-electron'
import type { BridgeManager } from '../bridge/bridge-manager'
import type { CliToolService } from '../cli/cli-tool-service'
import { MenuContextPatchSchema } from '../commands/context-schema'
@@ -1233,6 +1236,23 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
}),
+ [Commands.ConfigureAppImageNativeHost]: async (raw: unknown) => {
+ const action = appImageNativeHostActionSchema.parse(raw)
+ const registry = bridgeManager.current?.registry
+ return (
+ (await getAppImageNativeHost()?.configure(
+ action,
+ registry
+ ? {
+ chromium: registry.listManifestIds('chromium'),
+ firefox: registry.listManifestIds('firefox'),
+ }
+ : nativeMessagingExtensions,
+ settingsManager.getApp().browserBridgeEnabled
+ )) ?? { supported: false }
+ )
+ },
+
[Commands.RemoveAppImageIntegration]: async () =>
removeAppImageIntegrationFromSettings({
getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 05986894..555c9611 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -43,6 +43,7 @@ import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspect
import type { GetTransferStatsParams } from '@shared/types/stats'
import type { GetTaskActivityParams } from '@shared/types/task-activity'
import { ipcMain, session } from 'electron'
+import { getAppImageNativeHost } from '../bridge/appimage-native-host-electron'
import type { CliToolService } from '../cli/cli-tool-service'
import type { UpdateManager } from '../core/update-manager'
import { getAppImageIntegrationView } from '../platform/appimage-integration-host'
@@ -188,6 +189,9 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
getMagnetEnabled: () => settingsManager.getApp().protocols.magnet,
}),
+ [Queries.GetAppImageNativeHostStatus]: async () =>
+ (await getAppImageNativeHost()?.inspect()) ?? { supported: false },
+
[Queries.GetLinuxDefaultAssociations]: async () =>
getLinuxDefaultAssociations(),
diff --git a/src/main/platform/appimage-integration-host.ts b/src/main/platform/appimage-integration-host.ts
index 6a996d68..9bcd0e72 100644
--- a/src/main/platform/appimage-integration-host.ts
+++ b/src/main/platform/appimage-integration-host.ts
@@ -246,7 +246,4 @@ export async function reconcileAppImageIntegrationFromSettings(
}
}
-// TODO(Layer 3a): the browser bridge unconditionally syncs native-messaging
-// manifests on startup (src/main/bridge/index.ts:648). That sync must become
-// gated on this module's `nmConsent` once Layer 3a lands, so an AppImage that
-// declined desktop integration never writes NM manifests. Not changed here.
+// Browser launch consent and installation live independently in bridge/appimage-native-host.ts.
diff --git a/src/main/platform/appimage-integration.ts b/src/main/platform/appimage-integration.ts
index 100aefd9..4e5157e5 100644
--- a/src/main/platform/appimage-integration.ts
+++ b/src/main/platform/appimage-integration.ts
@@ -18,9 +18,8 @@ import { z } from 'zod'
// unit-testable without touching the real filesystem or spawning `xdg-*`.
//
// Scope boundary: this is desktop integration only. Native-messaging host
-// installation (Layer 3a) is intentionally NOT performed here — the `nmConsent`
-// sub-consent is threaded through the record and the transaction leaves marked
-// TODO seams where the NM copy/sync steps will slot in.
+// installation and consent are owned independently by the browser bridge.
+// The legacy nmConsent field is retained for persisted-record compatibility.
// ── Persisted record ────────────────────────────────────
@@ -36,9 +35,7 @@ export interface IntegrationRecord {
owner: IntegrationOwner
desktopId: string | null
status: IntegrationStatus
- // Dependent sub-consent for native-messaging host installation (Layer 3a).
- // Only meaningful once `decision === 'accepted'`; `declined` means no NM
- // writes ever happen.
+ // Legacy value only. Desktop consent never authorizes browser launch.
nmConsent: NmConsent
// The scheme/mime default handlers recorded before we overrode them, so a
// later removal can restore what the user had.
@@ -748,8 +745,7 @@ async function readIconState(
// Write the desktop file + icon and commit the URL-scheme defaults. Returns the
// next record. On any failure the record is marked `failed` so the next launch
-// retries. Ordering is transactional per the design: (native-messaging host —
-// Layer 3a TODO) → desktop file + icon → default commit.
+// retries. Desktop files and icons are installed before changing defaults.
async function installSelfIntegration(
deps: AppImageIntegrationDeps,
record: IntegrationRecord
@@ -878,10 +874,6 @@ async function installSelfIntegration(
let iconSha256: string | null = record.iconSha256
try {
- // TODO(Layer 3a): when `record.nmConsent === 'accepted'`, copy the native
- // host to a stable path and sync its NM manifests here, before the desktop
- // file, so the transaction unwinds NM last. Not implemented in Layer 2.
-
await deps.fs.mkdirp(applicationsDir(dataHome))
await deps.fs.writeText(
desktopPath,
@@ -1105,8 +1097,8 @@ export async function inspectSystemIntegration(
: { ...record, status: 'failed' }
}
-// Reverse-order teardown driven from the settings page. NM removal is a Layer 3a
-// TODO. Restores the recorded defaults FIRST and only deletes our files if the
+// Desktop teardown driven from settings. Restores the recorded defaults
+// FIRST and only deletes our files if the
// restore succeeded — otherwise a deleted desktop would leave a dangling
// default handler behind.
export async function removeSystemIntegration(
@@ -1127,9 +1119,6 @@ export async function removeSystemIntegration(
const desktopPath = desktopEntryFilePath(dataHome)
const icon = iconFilePath(dataHome)
- // TODO(Layer 3a): unregister native-messaging manifests / remove the stable
- // host copy first, mirroring the install order in reverse.
-
const schemeRestored = await restoreDefault(
deps,
SCHEME_MIME,
diff --git a/src/renderer/routes/settings/cards/integration/appimage-native-host-section.tsx b/src/renderer/routes/settings/cards/integration/appimage-native-host-section.tsx
new file mode 100644
index 00000000..33d8fd1e
--- /dev/null
+++ b/src/renderer/routes/settings/cards/integration/appimage-native-host-section.tsx
@@ -0,0 +1,110 @@
+import { Button } from '@renderer/components/ui/button'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import {
+ type AppImageNativeHostView,
+ appImageNativeHostViewSchema,
+} from '@shared/schemas/appimage-native-host'
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export function AppImageNativeHostSection() {
+ const { t } = useTranslation()
+ const [view, setView] = useState<AppImageNativeHostView>({ supported: false })
+ const [busy, setBusy] = useState(false)
+ const [failed, setFailed] = useState(false)
+ useEffect(() => {
+ let stale = false
+ transport
+ .invoke(Queries.GetAppImageNativeHostStatus)
+ .then((value) => {
+ const parsed = appImageNativeHostViewSchema.safeParse(value)
+ if (!stale && parsed.success) setView(parsed.data)
+ })
+ .catch(() => {})
+ return () => {
+ stale = true
+ }
+ }, [])
+ if (!view.supported) return null
+ const run = async (action: 'enable' | 'repair' | 'remove') => {
+ setBusy(true)
+ setFailed(false)
+ try {
+ setView(
+ appImageNativeHostViewSchema.parse(
+ await transport.invoke(Commands.ConfigureAppImageNativeHost, action)
+ )
+ )
+ } catch {
+ setFailed(true)
+ } finally {
+ setBusy(false)
+ }
+ }
+ const status = failed
+ ? 'io'
+ : (view.issue ?? (view.healthy ? 'ready' : 'disabled'))
+ return (
+ <div className="space-y-2" data-testid="appimage-native-host">
+ <div className="space-y-1">
+ <p className="text-sm font-medium">
+ {t('settings.integration.appimageHost.title')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings.integration.appimageHost.desc')}
+ </p>
+ <p className="break-all text-xs text-muted-foreground">{view.target}</p>
+ <p className="text-xs" role="status">
+ {t(`settings.integration.appimageHost.status.${status}`)}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={busy}
+ onClick={() => run(view.consent === 'accepted' ? 'repair' : 'enable')}
+ >
+ {t(
+ `settings.integration.appimageHost.${view.consent !== 'accepted' ? 'enable' : view.currentTarget ? 'repair' : 'useCurrent'}`
+ )}
+ </Button>
+ {view.consent === 'accepted' && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={busy}
+ onClick={() => run('remove')}
+ >
+ {t('settings.integration.appimageHost.remove')}
+ </Button>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => {
+ void navigator.clipboard
+ .writeText(
+ JSON.stringify({
+ enabled: view.enabled,
+ consent: view.consent,
+ healthy: view.healthy,
+ issue: view.issue,
+ currentTarget: view.currentTarget,
+ })
+ )
+ .catch(() => setFailed(true))
+ }}
+ >
+ {t('settings.integration.appimageHost.copyDiagnostics')}
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
index 51ecfe34..36b29803 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
@@ -23,6 +23,7 @@ import { useTranslation } from 'react-i18next'
import { z } from 'zod'
import type { SettingsCardDialogProps } from '../card-types'
import { AppImageIntegrationSection } from './appimage-integration-section'
+import { AppImageNativeHostSection } from './appimage-native-host-section'
import { BrowserExtensionsSection } from './browser-extensions-section'
import { CLIClientsSection } from './cli-clients-section'
import { CliToolSection } from './cli-tool-section'
@@ -168,6 +169,7 @@ export function IntegrationDialog({
{t('settings.integration.browser.title')}
</h3>
<BrowserExtensionsSection />
+ {!isWeb && <AppImageNativeHostSection />}
</section>
<Separator />
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 683f321f..fc4fc4cd 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1700,6 +1700,25 @@
"externalManaged": "Desktop integration is provided by another Motrix install."
},
"movedHint": "If you move the AppImage while Motrix is closed, links may fail to launch until you start Motrix once from its new location."
+ },
+ "appimageHost": {
+ "title": "AppImage browser launch",
+ "desc": "Allow an extension to open this AppImage when you click Connect. Enable browser integration to use it.",
+ "enable": "Enable browser launch",
+ "repair": "Repair",
+ "useCurrent": "Use this AppImage",
+ "remove": "Remove browser launch",
+ "copyDiagnostics": "Copy diagnostics",
+ "status": {
+ "ready": "Local installation checks passed. Connect from your browser to verify it.",
+ "disabled": "Browser launch is disabled.",
+ "conflict": "Another installation owns these files. Remove its browser integration first.",
+ "permissions": "Check that the files are executable and writable only by your account.",
+ "invalid": "The installation record or executable is invalid.",
+ "sourceChanged": "The AppImage changed. Run the intended version and repair the installation.",
+ "missing": "A required file is missing. Run the AppImage from its current location and repair.",
+ "io": "The operation failed. Check disk access and try Repair."
+ }
}
}
},
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 4700ee7d..41acb477 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1686,6 +1686,25 @@
"externalManaged": "桌面集成由另一个 Motrix 安装提供。"
},
"movedHint": "如果在 Motrix 未运行时移动 AppImage,链接可能无法唤起,直到你从新位置手动启动一次 Motrix。"
+ },
+ "appimageHost": {
+ "title": "AppImage 浏览器唤起",
+ "desc": "允许扩展在点击连接时打开此 AppImage。使用前请开启浏览器集成。",
+ "enable": "启用浏览器唤起",
+ "repair": "修复",
+ "useCurrent": "改用当前 AppImage",
+ "remove": "移除浏览器唤起",
+ "copyDiagnostics": "复制诊断",
+ "status": {
+ "ready": "本机安装检查通过,请从浏览器连接验证。",
+ "disabled": "浏览器唤起已停用。",
+ "conflict": "其他安装占用了这些文件,请先移除其浏览器集成。",
+ "permissions": "请检查文件可执行,且只有当前账户有写入权限。",
+ "invalid": "安装记录或可执行文件无效。",
+ "sourceChanged": "AppImage 已变化,请运行需要使用的版本并修复安装。",
+ "missing": "缺少必要文件,请从当前位置运行 AppImage 并修复。",
+ "io": "操作失败,请检查磁盘访问权限后重试修复。"
+ }
}
}
},
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index b5916cf2..09146e25 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1686,6 +1686,25 @@
"externalManaged": "桌面整合由另一個 Motrix 安裝提供。"
},
"movedHint": "如果在 Motrix 未執行時移動 AppImage,連結可能無法喚起,直到您從新位置手動啟動一次 Motrix。"
+ },
+ "appimageHost": {
+ "title": "AppImage 瀏覽器喚起",
+ "desc": "允許擴充功能在點選連線時開啟此 AppImage。使用前請開啟瀏覽器整合。",
+ "enable": "啟用瀏覽器喚起",
+ "repair": "修復",
+ "useCurrent": "改用目前的 AppImage",
+ "remove": "移除瀏覽器喚起",
+ "copyDiagnostics": "複製診斷",
+ "status": {
+ "ready": "本機安裝檢查通過,請從瀏覽器連線驗證。",
+ "disabled": "瀏覽器喚起已停用。",
+ "conflict": "其他安裝佔用了這些檔案,請先移除其瀏覽器整合。",
+ "permissions": "請檢查檔案可執行,且只有目前帳戶有寫入權限。",
+ "invalid": "安裝紀錄或執行檔無效。",
+ "sourceChanged": "AppImage 已變更,請執行需要使用的版本並修復安裝。",
+ "missing": "缺少必要檔案,請從目前位置執行 AppImage 並修復。",
+ "io": "操作失敗,請檢查磁碟存取權限後重試修復。"
+ }
}
}
},
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 83d7eb37..49c2caa2 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -85,6 +85,7 @@ export const Commands = {
// Linux AppImage desktop integration (settings-driven enable/remove).
// Both return the refreshed `AppImageIntegrationView`.
EnableAppImageIntegration: 'command:enableAppImageIntegration',
+ ConfigureAppImageNativeHost: 'command:configureAppImageNativeHost',
RemoveAppImageIntegration: 'command:removeAppImageIntegration',
RevealInFolder: 'command:revealInFolder',
// Menu
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index a69b8523..375b4a34 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -74,6 +74,7 @@ export const Queries = {
// Linux AppImage desktop integration; returns `AppImageIntegrationView`
// ({ supported: false } outside a packaged Linux AppImage).
GetAppImageIntegrationStatus: 'query:getAppImageIntegrationStatus',
+ GetAppImageNativeHostStatus: 'query:getAppImageNativeHostStatus',
GetLinuxDefaultAssociations: 'query:getLinuxDefaultAssociations',
GetWindowsDefaultAssociations: 'query:getWindowsDefaultAssociations',
GetApplicationMenu: 'query:getApplicationMenu',
diff --git a/src/shared/schemas/appimage-native-host.ts b/src/shared/schemas/appimage-native-host.ts
new file mode 100644
index 00000000..2e9514e5
--- /dev/null
+++ b/src/shared/schemas/appimage-native-host.ts
@@ -0,0 +1,33 @@
+import { z } from 'zod'
+
+export const appImageNativeHostActionSchema = z.enum([
+ 'enable',
+ 'repair',
+ 'remove',
+])
+export const appImageNativeHostIssueSchema = z.enum([
+ 'conflict',
+ 'permissions',
+ 'invalid',
+ 'sourceChanged',
+ 'missing',
+ 'io',
+])
+export const appImageNativeHostViewSchema = z.discriminatedUnion('supported', [
+ z.object({ supported: z.literal(false) }),
+ z.object({
+ supported: z.literal(true),
+ enabled: z.boolean(),
+ consent: z.enum(['unset', 'accepted', 'declined']),
+ target: z.string(),
+ currentTarget: z.boolean(),
+ healthy: z.boolean(),
+ issue: appImageNativeHostIssueSchema.nullable(),
+ }),
+])
+export type AppImageNativeHostView = z.infer<
+ typeof appImageNativeHostViewSchema
+>
+export type AppImageNativeHostIssue = z.infer<
+ typeof appImageNativeHostIssueSchema
+>