Skip to content

A full-featured download manager.

fix(bridge): isolate browser registration failures (#2118)

Dr_rOot92d0ff93bab8
diff --git a/e2e/bridge/native-messaging-registration.spec.ts b/e2e/bridge/native-messaging-registration.spec.ts
new file mode 100644
index 00000000..323ce8b9
--- /dev/null
+++ b/e2e/bridge/native-messaging-registration.spec.ts
@@ -0,0 +1,147 @@
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { join, resolve } from 'node:path'
+import { _electron as electron } from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../../src/core/settings/migrations'
+import {
+ BridgeQueries,
+ type BridgeStatusInfo,
+} from '../../src/shared/protocol/bridge'
+import { expect, test } from '../fixtures/electron-app'
+
+test('a denied Edge directory preserves discovery and recovers on restart', async ({
+ userDataDir,
+ rpcPort,
+}) => {
+ test.skip(process.platform !== 'darwin', 'macOS browser registration paths')
+ const repo = resolve(import.meta.dirname, '../..')
+ const isolatedHome = join(userDataDir, 'home')
+ const support = join(isolatedHome, 'Library/Application Support')
+ const denied = join(support, 'Microsoft Edge')
+ const marker = join(userDataDir, 'deny-edge')
+ const fixtureApp = join(userDataDir, 'app')
+ await mkdir(fixtureApp, { recursive: true })
+ await writeFile(marker, '')
+ const metadata = JSON.parse(
+ await readFile(join(repo, 'package.json'), 'utf8')
+ )
+ await writeFile(
+ join(fixtureApp, 'package.json'),
+ JSON.stringify({ ...metadata, main: 'main.cjs' })
+ )
+ // Override only this test process's home lookup and Edge mkdir. The real
+ // packaged JS, IPC, endpoint writer and HTTP listener run unchanged, while
+ // every native-messaging file stays inside the fixture's temporary root.
+ await writeFile(
+ join(fixtureApp, 'main.cjs'),
+ `require('electron').app.getAppPath = () => ${JSON.stringify(repo)};
+const os = require('node:os');
+os.homedir = () => ${JSON.stringify(isolatedHome)};
+const fs = require('node:fs/promises');
+const mkdir = fs.mkdir;
+fs.mkdir = async (path, ...args) => {
+ if (String(path).startsWith(${JSON.stringify(denied)}) && require('node:fs').existsSync(${JSON.stringify(marker)})) {
+ throw Object.assign(new Error('Edge directory denied by test'), { code: 'EPERM', syscall: 'mkdir', path });
+ }
+ return mkdir(path, ...args);
+};
+require(${JSON.stringify(join(repo, 'dist/main/index.cjs'))});
+`
+ )
+ await writeFile(
+ join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ onboarding: { disclaimerAccepted: true },
+ app: { browserBridgeEnabled: true },
+ })
+ )
+ const launch = () =>
+ electron.launch({
+ args: [fixtureApp],
+ cwd: userDataDir,
+ env: {
+ ...process.env,
+ NODE_ENV: 'test',
+ MOTRIX_USER_DATA: userDataDir,
+ MOTRIX_RPC_PORT: String(rpcPort),
+ MOTRIX_DEFAULT_SAVE_DIR: join(userDataDir, 'downloads'),
+ MOTRIX_BRIDGE_DATA_DIR: join(userDataDir, 'bridge'),
+ MOTRIX_BRIDGE_HOST_BIN: join(userDataDir, 'native-host'),
+ },
+ })
+
+ for (const edgeDenied of [true, false]) {
+ const app = await launch()
+ try {
+ const page = await app.firstWindow()
+ await page.waitForLoadState('domcontentloaded')
+ const getStatus = (): Promise<BridgeStatusInfo | null> =>
+ page.evaluate(async (channel) => {
+ try {
+ const api = (
+ window as unknown as {
+ motrix: { invoke(query: string): Promise<BridgeStatusInfo> }
+ }
+ ).motrix
+ return await api.invoke(channel)
+ } catch {
+ return null
+ }
+ }, BridgeQueries.GetStatus)
+ await expect
+ .poll(getStatus)
+ .toMatchObject({ extensionPairingHealth: 'ready' })
+ const status = await getStatus()
+ if (!status) throw new Error('bridge status missing')
+ if (edgeDenied) {
+ const log = await readFile(join(userDataDir, 'logs/motrix.log'), 'utf8')
+ expect(log.includes('Native Messaging registration failed')).toBe(true)
+ expect(log.includes('EPERM')).toBe(true)
+ }
+ const endpoint = JSON.parse(
+ await readFile(join(userDataDir, 'bridge/endpoint.json'), 'utf8')
+ )
+ expect(endpoint.port).toBe(status.port)
+ const discovery = await fetch(`http://127.0.0.1:${status.port}/discovery`)
+ expect(discovery.ok).toBe(true)
+ expect(await discovery.json()).toMatchObject({ app: 'motrix-bridge' })
+ for (const channel of [
+ BridgeQueries.ListTrusted,
+ BridgeQueries.ListPaired,
+ ]) {
+ expect(
+ await page.evaluate((query) => {
+ const api = (
+ window as unknown as {
+ motrix: { invoke(channel: string): Promise<unknown> }
+ }
+ ).motrix
+ return api.invoke(query)
+ }, channel)
+ ).toBeInstanceOf(Array)
+ }
+ for (const browser of [
+ 'Google/Chrome',
+ 'Mozilla',
+ ...(edgeDenied ? [] : ['Microsoft Edge']),
+ ]) {
+ const file = join(
+ support,
+ browser,
+ 'NativeMessagingHosts/app.motrix.bridge.json'
+ )
+ expect(JSON.parse(await readFile(file, 'utf8')).name).toBe(
+ 'app.motrix.bridge'
+ )
+ }
+ await page.getByRole('link', { name: 'Settings', exact: true }).click()
+ await page.getByText('Integration', { exact: true }).first().click()
+ await expect(
+ page.getByRole('heading', { name: 'Browser extensions', exact: true })
+ ).toBeVisible()
+ } finally {
+ await app.close()
+ }
+ await rm(marker, { force: true })
+ }
+})
diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.ts
index e55114c2..89f49cb3 100644
--- a/src/main/bridge/bootstrap-lifecycle.test.ts
+++ b/src/main/bridge/bootstrap-lifecycle.test.ts
@@ -19,14 +19,33 @@ import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'
import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'
import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'
import * as taskCreation from '@core/task/create-task-handler'
-import type { BridgeStatusInfo } from '@shared/protocol/bridge'
+import {
+ BridgeCommands,
+ BridgeQueries,
+ type BridgeStatusInfo,
+} from '@shared/protocol/bridge'
import { EngineState } from '@shared/types/engine'
import {
makeDirectSubmit,
makeExtensionContext,
} from '@test-utils/bridge-receiver'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { NativeMessagingInstaller } from './native-messaging-installer'
+import {
+ computeManifestPaths,
+ NativeMessagingInstaller,
+} from './native-messaging-installer'
+
+const registrationLog = vi.hoisted(() => ({ warn: vi.fn() }))
+vi.mock('@core/logger', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@core/logger')>()
+ return {
+ ...actual,
+ getLogger: (module: string) =>
+ module === 'native-messaging'
+ ? registrationLog
+ : actual.getLogger(module),
+ }
+})
const electron = vi.hoisted(() => ({
userDataDir: '',
@@ -137,6 +156,8 @@ function args(): Parameters<typeof bootstrapBridge>[0] {
}
}
+const realManifestSync = NativeMessagingInstaller.prototype.syncManifests
+
describe('desktop bridge bootstrap ownership', () => {
let userDataDir: string
const activeChannels = new Set<string>()
@@ -148,6 +169,7 @@ describe('desktop bridge bootstrap ownership', () => {
snapRuntime.enabled = false
snapRuntime.instanceName = 'motrix_work'
activeChannels.clear()
+ registrationLog.warn.mockReset()
electron.handle.mockReset()
electron.removeHandler.mockReset()
electron.handle.mockImplementation((channel: string) => {
@@ -177,7 +199,7 @@ describe('desktop bridge bootstrap ownership', () => {
vi.spyOn(
NativeMessagingInstaller.prototype,
'syncManifests'
- ).mockResolvedValue()
+ ).mockResolvedValue({ failures: [] })
vi.spyOn(
NativeMessagingInstaller.prototype,
'unregister'
@@ -501,8 +523,17 @@ describe('desktop bridge bootstrap ownership', () => {
})
vi.mocked(
NativeMessagingInstaller.prototype.syncManifests
- ).mockRejectedValueOnce(permissionError)
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ ).mockResolvedValueOnce({
+ failures: [
+ {
+ browser: 'chrome',
+ path: '/test/chrome',
+ operation: 'manifest',
+ error: permissionError,
+ },
+ ],
+ })
+ const warn = registrationLog.warn
const runtime = await bootstrapBridge(args())
@@ -523,7 +554,198 @@ describe('desktop bridge bootstrap ownership', () => {
}
)
- it('rolls back EACCES outside a packaged Linux Snap', async () => {
+ it.each(['EPERM', 'EACCES'] as const)(
+ 'keeps Chrome, Firefox, endpoint and IPC live after Edge fails with %s',
+ async (code) => {
+ const installer = new NativeMessagingInstaller({
+ platform: 'darwin',
+ manifestRoot: userDataDir,
+ hostBinaryPath: '/test/native-host',
+ })
+ const paths = computeManifestPaths('darwin', userDataDir)
+ const manifestIO = installer as unknown as {
+ writeJson(path: string, object: object): Promise<void>
+ }
+ const writeJson = manifestIO.writeJson.bind(installer)
+ let denied = true
+ vi.spyOn(manifestIO, 'writeJson').mockImplementation(
+ async (path, object) => {
+ if (denied && path === paths.edge)
+ throw Object.assign(new Error('permission denied'), { code })
+ return writeJson(path, object)
+ }
+ )
+ vi.mocked(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).mockImplementation((ids) => realManifestSync.call(installer, ids))
+ const warn = registrationLog.warn
+ const runtime = await bootstrapBridge(args())
+ try {
+ expect(runtime).not.toBeNull()
+ for (const path of [paths.chrome, paths.firefox]) {
+ expect(JSON.parse(await readFile(path, 'utf-8')).name).toBe(
+ 'app.motrix.bridge'
+ )
+ }
+ expect(EndpointFileWriter.prototype.write).toHaveBeenCalledOnce()
+ expect(WebSocketBridgeServer.prototype.stop).not.toHaveBeenCalled()
+ expect(
+ NativeMessagingInstaller.prototype.unregister
+ ).not.toHaveBeenCalled()
+ expect(activeChannels).toContain(BridgeQueries.ListPaired)
+ expect(activeChannels).toContain(BridgeQueries.ListTrusted)
+ const status = electron.handle.mock.calls.find(
+ ([channel]) => channel === BridgeQueries.GetStatus
+ )?.[1]
+ await expect(status?.()).resolves.toMatchObject({
+ degraded: false,
+ })
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining(`"code":"${code}"`)
+ )
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('"browser":"edge"')
+ )
+ } finally {
+ await runtime?.shutdown()
+ }
+ denied = false
+ const recovered = await bootstrapBridge(args())
+ try {
+ expect(JSON.parse(await readFile(paths.edge!, 'utf-8')).name).toBe(
+ 'app.motrix.bridge'
+ )
+ const status = electron.handle.mock.calls.findLast(
+ ([channel]) => channel === BridgeQueries.GetStatus
+ )?.[1]
+ await expect(status?.()).resolves.toMatchObject({
+ degraded: false,
+ })
+ } finally {
+ await recovered?.shutdown()
+ }
+ }
+ )
+
+ it('keeps the bridge discoverable when every browser registration fails', async () => {
+ vi.mocked(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).mockResolvedValueOnce({
+ failures: (['chrome', 'edge', 'firefox'] as const).map((browser) => ({
+ browser,
+ path: `/test/${browser}`,
+ operation: 'manifest',
+ error: Object.assign(new Error('denied'), { code: 'EPERM' }),
+ })),
+ })
+ const runtime = await bootstrapBridge(args())
+ try {
+ expect(runtime).not.toBeNull()
+ expect(EndpointFileWriter.prototype.write).toHaveBeenCalledOnce()
+ expect(WebSocketBridgeServer.prototype.stop).not.toHaveBeenCalled()
+ const status = electron.handle.mock.calls.find(
+ ([channel]) => channel === BridgeQueries.GetStatus
+ )?.[1]
+ await expect(status?.()).resolves.toMatchObject({
+ degraded: false,
+ })
+ } finally {
+ await runtime?.shutdown()
+ }
+ })
+
+ it('logs a failed trust sync and accepts a successful later edit', async () => {
+ const runtime = await bootstrapBridge(args())
+ const handler = (key: string) =>
+ electron.handle.mock.calls.find(([channel]) => channel === key)?.[1]
+ try {
+ vi.mocked(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).mockResolvedValueOnce({
+ failures: [
+ {
+ browser: 'edge',
+ path: '/test/edge',
+ operation: 'manifest',
+ error: new Error('denied'),
+ },
+ ],
+ })
+ const id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
+ await handler(BridgeCommands.AddTrusted)?.(
+ {},
+ { id, browser: 'chromium' }
+ )
+ expect(runtime?.registry.list().some((entry) => entry.id === id)).toBe(
+ true
+ )
+ expect(registrationLog.warn).toHaveBeenCalledOnce()
+ expect(registrationLog.warn).toHaveBeenCalledWith(
+ expect.stringContaining('"browser":"edge"')
+ )
+ await handler(BridgeCommands.RemoveTrusted)?.(
+ {},
+ { id, browser: 'chromium' }
+ )
+ expect(runtime?.registry.list().some((entry) => entry.id === id)).toBe(
+ false
+ )
+ expect(registrationLog.warn).toHaveBeenCalledOnce()
+ } finally {
+ await runtime?.shutdown()
+ }
+ })
+
+ it('serializes trust snapshots and drains queued updates before shutdown', async () => {
+ const runtime = await bootstrapBridge(args())
+ const handler = (key: string) =>
+ electron.handle.mock.calls.find(([channel]) => channel === key)?.[1]
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ vi.mocked(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).mockImplementationOnce(async () => {
+ await gate
+ return { failures: [] }
+ })
+ const id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
+ const added = handler(BridgeCommands.AddTrusted)?.(
+ {},
+ { id, browser: 'chromium' }
+ )
+ await vi.waitFor(() =>
+ expect(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).toHaveBeenCalledTimes(2)
+ )
+ const removed = handler(BridgeCommands.RemoveTrusted)?.(
+ {},
+ { id, browser: 'chromium' }
+ )
+ let stopped = false
+ const shutdown = runtime?.shutdown().then(() => {
+ stopped = true
+ })
+ await Promise.resolve()
+ expect(stopped).toBe(false)
+ expect(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).toHaveBeenCalledTimes(2)
+ expect(runtime?.registry.list().some((entry) => entry.id === id)).toBe(true)
+ release()
+ await Promise.all([added, removed, shutdown])
+ expect(stopped).toBe(true)
+ const snapshots = vi.mocked(
+ NativeMessagingInstaller.prototype.syncManifests
+ ).mock.calls
+ expect(snapshots[1]?.[0].chromium).toContain(id)
+ expect(snapshots[2]?.[0].chromium).not.toContain(id)
+ expect(WebSocketBridgeServer.prototype.stop).toHaveBeenCalledOnce()
+ })
+
+ it('rolls back shared host preparation errors outside a packaged Linux Snap', async () => {
const permissionError = Object.assign(new Error('permission denied'), {
code: 'EACCES',
})
diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.ts
index 9a5aaf37..ea05b9ca 100644
--- a/src/main/bridge/index.ts
+++ b/src/main/bridge/index.ts
@@ -42,6 +42,7 @@ import {
import type { BridgeReceiverDeps } from '@core/bridge-receiver/bridge-receiver'
import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'
import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'
+import { getLogger } from '@core/logger'
import { urlMatchesHostPermissions } from '@core/plugin/hooks/eligibility'
import type { PluginHost } from '@core/plugin/host/plugin-host'
import type { PluginRegistry } from '@core/plugin/plugin-registry'
@@ -70,6 +71,7 @@ import { isPackagedLinuxFlatpak } from './flatpak-environment'
import { resolveNativeHostBinaryPath } from './native-host-path'
import {
NativeMessagingInstaller,
+ type NativeMessagingSyncResult,
type Platform,
type SyncArgs,
} from './native-messaging-installer'
@@ -82,6 +84,8 @@ import {
} from './snap-environment'
import { recoverDefaultWindowsDesktopBridgeResidue } from './windows-desktop-startup-recovery'
+const nativeMessagingLog = getLogger('native-messaging')
+
/**
* A plugin contributes to the mux pre-resolve seam when it is an enabled
* `site-resolver` that declares a PUBLIC command whose id is
@@ -337,13 +341,14 @@ export async function syncNativeMessagingManifests(args: {
snap: PackagedLinuxSnapEnvironment | null
warn?: (message: string) => void
}): Promise<void> {
+ const warn =
+ args.warn ?? ((message: string) => nativeMessagingLog.warn(message))
+ let result: NativeMessagingSyncResult
try {
- await args.installer.syncManifests(args.manifests)
+ result = await args.installer.syncManifests(args.manifests)
} catch (error) {
if (args.installer.preserveOnStartupFailure) {
- ;(args.warn ?? console.warn)(
- 'AppImage browser launch needs repair in settings'
- )
+ warn('AppImage browser launch needs repair in settings')
return
}
const code =
@@ -358,7 +363,35 @@ export async function syncNativeMessagingManifests(args: {
throw error
}
- const warn = args.warn ?? console.warn
+ warn(
+ `Browser Native Messaging registration is blocked by Snap confinement. Run "sudo snap connect ${args.snap.instanceName}:browser-native-messaging", then restart Motrix.`
+ )
+ return
+ }
+ let permissionDenied = false
+ for (const failure of result.failures) {
+ const error = failure.error
+ const code =
+ typeof error === 'object' && error !== null && 'code' in error
+ ? error.code
+ : undefined
+ permissionDenied ||= code === 'EACCES' || code === 'EPERM'
+ warn(
+ `Native Messaging registration failed: ${JSON.stringify({
+ browser: failure.browser,
+ path: failure.path,
+ operation: failure.operation,
+ registryView: failure.registryView,
+ code,
+ message: error instanceof Error ? error.message : String(error),
+ })}`
+ )
+ }
+ if (
+ permissionDenied &&
+ args.snap &&
+ isValidSnapInstanceName(args.snap.instanceName)
+ ) {
warn(
`Browser Native Messaging registration is blocked by Snap confinement. Run "sudo snap connect ${args.snap.instanceName}:browser-native-messaging", then restart Motrix.`
)
@@ -820,6 +853,27 @@ export async function bootstrapBridge(args: {
bridgeIdentity.serverGeneration
)
+ // Serialize registry edits with their manifest snapshots. A later edit
+ // must not be overwritten by a slower earlier sync, and shutdown drains
+ // these writes before disposing registration ownership.
+ let nativeMessagingSync = Promise.resolve()
+ ownership.own('native-messaging-sync', () => nativeMessagingSync)
+ const updateTrustedExtensions = (update: () => Promise<void>) => {
+ const next = nativeMessagingSync.then(async () => {
+ await update()
+ await syncNativeMessagingManifests({
+ installer,
+ snap,
+ manifests: {
+ chromium: registry.listManifestIds('chromium'),
+ firefox: registry.listManifestIds('firefox'),
+ },
+ })
+ })
+ nativeMessagingSync = next.catch(() => {})
+ return next
+ }
+
// Renderer IPC. Track exact channels as each registration succeeds; a
// later duplicate/fault removes the earlier subset during rollback.
const installedIpcChannels: string[] = []
@@ -924,34 +978,17 @@ export async function bootstrapBridge(args: {
label?: string
}
) => {
- await registry.add(
- params.id,
- params.browser,
- 'user-added',
- params.label
+ await updateTrustedExtensions(() =>
+ registry.add(params.id, params.browser, 'user-added', params.label)
)
- await syncNativeMessagingManifests({
- installer,
- snap,
- manifests: {
- chromium: registry.listManifestIds('chromium'),
- firefox: registry.listManifestIds('firefox'),
- },
- })
}
)
installIpcHandler(
BridgeCommands.RemoveTrusted,
async (_e, params: { id: string; browser: 'chromium' | 'firefox' }) => {
- await registry.remove(params.id, params.browser)
- await syncNativeMessagingManifests({
- installer,
- snap,
- manifests: {
- chromium: registry.listManifestIds('chromium'),
- firefox: registry.listManifestIds('firefox'),
- },
- })
+ await updateTrustedExtensions(() =>
+ registry.remove(params.id, params.browser)
+ )
}
)
diff --git a/src/main/bridge/native-messaging-installer.test.ts b/src/main/bridge/native-messaging-installer.test.ts
index 65a0b4c6..3f4a4989 100644
--- a/src/main/bridge/native-messaging-installer.test.ts
+++ b/src/main/bridge/native-messaging-installer.test.ts
@@ -1,7 +1,7 @@
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
computeManifestPaths,
computeRegistryEntries,
@@ -227,12 +227,24 @@ describe('NativeMessagingInstaller.syncManifests', () => {
manifestRoot: dir,
platform: 'linux',
})
- await expect(
- installer.syncManifests({
- chromium: ['lggbokfckofcgjndaboioakcmincinpo'],
- firefox: ['[email protected]'],
- })
- ).rejects.toThrow('conflict')
+ const result = await installer.syncManifests({
+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],
+ firefox: ['[email protected]'],
+ })
+ expect(result.failures).toEqual([
+ {
+ browser: 'chrome',
+ path: paths.chrome,
+ operation: 'manifest',
+ error: expect.any(Error),
+ },
+ ])
+ expect(result.failures[0]?.error).toMatchObject({
+ message: 'Native Messaging manifest conflict',
+ })
+ expect(JSON.parse(await readFile(paths.firefox, 'utf-8')).path).toBe(
+ hostBinaryPath
+ )
expect(JSON.parse(await readFile(paths.chrome, 'utf-8')).path).toBe(
'/tmp/motrix-flatpak-native-host'
@@ -269,6 +281,88 @@ describe('NativeMessagingInstaller.syncManifests', () => {
code: 'ENOENT',
})
})
+
+ it.each(['chrome', 'edge', 'firefox'] as const)(
+ 'continues after a blocked %s directory and repairs it on retry',
+ async (browser) => {
+ const paths = computeManifestPaths('darwin', dir)
+ const blocked = dirname(paths[browser]!)
+ await mkdir(dirname(blocked), { recursive: true })
+ await writeFile(blocked, 'not a directory')
+ const installer = new NativeMessagingInstaller({
+ hostBinaryPath: '/path/to/native-host',
+ manifestRoot: dir,
+ platform: 'darwin',
+ })
+ const ids = {
+ chromium: ['lggbokfckofcgjndaboioakcmincinpo'],
+ firefox: ['[email protected]'],
+ }
+ const result = await installer.syncManifests(ids)
+ expect(result.failures).toEqual([
+ {
+ browser,
+ path: paths[browser],
+ operation: 'manifest',
+ error: expect.any(Error),
+ },
+ ])
+ for (const [other, path] of Object.entries(paths)) {
+ if (other !== browser)
+ expect(JSON.parse(await readFile(path, 'utf-8')).name).toBe(
+ 'app.motrix.bridge'
+ )
+ }
+ expect(await readFile(blocked, 'utf-8')).toBe('not a directory')
+ await rm(blocked)
+ expect(await installer.syncManifests(ids)).toEqual({ failures: [] })
+ expect(JSON.parse(await readFile(paths[browser]!, 'utf-8')).name).toBe(
+ 'app.motrix.bridge'
+ )
+ }
+ )
+
+ it('reports every blocked browser when all target directories fail', async () => {
+ const paths = computeManifestPaths('darwin', dir)
+ for (const path of Object.values(paths)) {
+ await mkdir(dirname(dirname(path)), { recursive: true })
+ await writeFile(dirname(path), 'blocked')
+ }
+ const installer = new NativeMessagingInstaller({
+ hostBinaryPath: '/path/to/native-host',
+ manifestRoot: dir,
+ platform: 'darwin',
+ })
+ const result = await installer.syncManifests({ chromium: [], firefox: [] })
+ expect(result.failures.map((failure) => failure.browser)).toEqual([
+ 'chrome',
+ 'edge',
+ 'firefox',
+ ])
+ })
+
+ it('continues after an atomic manifest write fails', async () => {
+ const paths = computeManifestPaths('darwin', dir)
+ await mkdir(paths.edge!, { recursive: true })
+ const installer = new NativeMessagingInstaller({
+ hostBinaryPath: '/path/to/native-host',
+ manifestRoot: dir,
+ platform: 'darwin',
+ })
+ const result = await installer.syncManifests({ chromium: [], firefox: [] })
+ expect(result.failures).toEqual([
+ {
+ browser: 'edge',
+ path: paths.edge,
+ operation: 'manifest',
+ error: expect.any(Error),
+ },
+ ])
+ expect((await stat(paths.edge!)).isDirectory()).toBe(true)
+ expect(JSON.parse(await readFile(paths.firefox, 'utf-8')).name).toBe(
+ 'app.motrix.bridge'
+ )
+ })
})
describe('computeManifestPaths (win32)', () => {
@@ -431,6 +525,75 @@ describe('NativeMessagingInstaller.syncManifests (win32)', () => {
expect(written).toEqual([])
})
+ it('isolates a denied registry view and still registers every other target', async () => {
+ const error = Object.assign(new Error('denied'), { code: 'EPERM' })
+ const registryWriter = vi.fn(
+ async (entry: RegistryEntry, view: RegistryView) => {
+ if (entry.keyPath.includes('Google') && view === '32') throw error
+ }
+ )
+ const installer = new NativeMessagingInstaller({
+ hostBinaryPath: '/native-host.exe',
+ manifestRoot: dir,
+ platform: 'win32',
+ registryWriter,
+ })
+ const result = await installer.syncManifests({ chromium: [], firefox: [] })
+ expect(registryWriter).toHaveBeenCalledTimes(6)
+ expect(result.failures).toEqual([
+ {
+ browser: 'chrome',
+ path: 'HKCU\\SOFTWARE\\Google\\Chrome\\NativeMessagingHosts\\app.motrix.bridge',
+ operation: 'registry',
+ registryView: '32',
+ error,
+ },
+ ])
+ })
+
+ it('does not register a failed manifest but still registers later browsers', async () => {
+ const paths = computeManifestPaths('win32', dir)
+ await mkdir(paths.edge!, { recursive: true })
+ const registryWriter = vi.fn(async () => {})
+ const installer = new NativeMessagingInstaller({
+ hostBinaryPath: '/native-host.exe',
+ manifestRoot: dir,
+ platform: 'win32',
+ registryWriter,
+ })
+ const result = await installer.syncManifests({ chromium: [], firefox: [] })
+ expect(result.failures.map((failure) => failure.browser)).toEqual(['edge'])
+ expect(registryWriter).toHaveBeenCalledTimes(4)
+ expect(registryWriter).not.toHaveBeenCalledWith(
+ expect.objectContaining({ value: paths.edge }),
+ expect.anything()
+ )
+ })
+
+ it('cleans other registry entries and manifests even when one removal fails', async () => {
+ const error = new Error('registry denied')
+ const registryDeleter = vi.fn(
+ async (entry: RegistryEntry, view: RegistryView) => {
+ if (entry.keyPath.includes('Google') && view === '32') throw error
+ }
+ )
+ const installer = new NativeMessagingInstaller({
+ hostBinaryPath: '/native-host.exe',
+ manifestRoot: dir,
+ platform: 'win32',
+ registryWriter: async () => {},
+ registryDeleter,
+ })
+ await installer.syncManifests({ chromium: [], firefox: [] })
+ await expect(installer.unregister()).rejects.toMatchObject({
+ errors: [error],
+ })
+ expect(registryDeleter).toHaveBeenCalledTimes(6)
+ for (const path of Object.values(computeManifestPaths('win32', dir))) {
+ await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' })
+ }
+ })
+
it('unregisters all Windows hosts and removes their manifests', async () => {
const deleted: Array<{ entry: RegistryEntry; view: RegistryView }> = []
const installer = new NativeMessagingInstaller({
diff --git a/src/main/bridge/native-messaging-installer.ts b/src/main/bridge/native-messaging-installer.ts
index 0839969d..31e8a51e 100644
--- a/src/main/bridge/native-messaging-installer.ts
+++ b/src/main/bridge/native-messaging-installer.ts
@@ -286,6 +286,18 @@ export interface SyncArgs {
firefox: string[]
}
+export interface NativeMessagingRegistrationFailure {
+ browser: keyof ManifestPaths
+ path: string
+ operation: 'manifest' | 'registry'
+ registryView?: RegistryView
+ error: unknown
+}
+
+export interface NativeMessagingSyncResult {
+ failures: NativeMessagingRegistrationFailure[]
+}
+
interface ChromiumManifest {
name: string
description: string
@@ -309,9 +321,12 @@ export class NativeMessagingInstaller {
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
+ async syncManifests(args: SyncArgs): Promise<NativeMessagingSyncResult> {
+ if (this.opts.appImage) {
+ await this.opts.appImage.sync(args)
+ return { failures: [] }
+ }
+ if (this.opts.registrationMode === 'external') return { failures: [] }
await this.writeDevelopmentHostConfig()
@@ -329,14 +344,6 @@ export class NativeMessagingInstaller {
type: 'stdio',
allowed_origins: args.chromium.map((id) => `chrome-extension://${id}/`),
}
- await this.writeJson(paths.chrome, chromiumManifest)
- if (paths.chromium) {
- await this.writeJson(paths.chromium, chromiumManifest)
- }
- if (paths.edge) {
- await this.writeJson(paths.edge, chromiumManifest)
- }
-
const firefoxManifest: FirefoxManifest = {
name: MANIFEST_HOST_NAME,
description: MANIFEST_DESCRIPTION,
@@ -344,21 +351,45 @@ export class NativeMessagingInstaller {
type: 'stdio',
allowed_extensions: args.firefox,
}
- await this.writeJson(paths.firefox, firefoxManifest)
-
- // Windows: register each browser's host key so the JSON files are
- // discoverable. computeRegistryEntries returns [] on macOS/Linux (which use
- // file-based discovery), so the registration is a no-op there. The keys are
- // independent. Register both views because Chrome and Firefox query the
- // 32-bit view before the native view, and an older registration must not
- // shadow the current host path.
+ const failures: NativeMessagingRegistrationFailure[] = []
const writeRegistry = this.opts.registryWriter ?? regAddDefaultValue
const registryEntries = computeRegistryEntries(this.opts.platform, paths)
- await Promise.all(
- registryEntries.flatMap((entry) =>
- WINDOWS_REGISTRY_VIEWS.map((view) => writeRegistry(entry, view))
- )
- )
+ // Each browser owns an independent registration. A denied directory or
+ // conflicting manifest must not disable the other browsers or the bridge.
+ for (const browser of ['chrome', 'chromium', 'edge', 'firefox'] as const) {
+ const path = paths[browser]
+ if (!path) continue
+ try {
+ await this.writeJson(
+ path,
+ browser === 'firefox' ? firefoxManifest : chromiumManifest
+ )
+ } catch (error) {
+ failures.push({ browser, path, operation: 'manifest', error })
+ // Never advertise a manifest that this attempt could not update.
+ continue
+ }
+ for (const entry of registryEntries.filter(
+ (item) => item.value === path
+ )) {
+ // Both registry views are independent, too. A failed 32-bit update
+ // must not prevent the 64-bit view or later browsers from updating.
+ for (const registryView of WINDOWS_REGISTRY_VIEWS) {
+ try {
+ await writeRegistry(entry, registryView)
+ } catch (error) {
+ failures.push({
+ browser,
+ path: `${entry.hive}\\${entry.keyPath}`,
+ operation: 'registry',
+ registryView,
+ error,
+ })
+ }
+ }
+ }
+ }
+ return { failures }
}
async unregister(): Promise<void> {
@@ -373,22 +404,27 @@ export class NativeMessagingInstaller {
)
const registryEntries = computeRegistryEntries(this.opts.platform, paths)
const deleteRegistry = this.opts.registryDeleter ?? regDeleteKey
- await Promise.all(
- registryEntries.flatMap((entry) =>
- WINDOWS_REGISTRY_VIEWS.map((view) => deleteRegistry(entry, view))
- )
- )
-
const manifestPaths = [
paths.chrome,
paths.chromium,
paths.edge,
paths.firefox,
].filter((filePath): filePath is string => filePath !== undefined)
- await Promise.all(
- manifestPaths.map((filePath) => this.removeOwnedManifest(filePath))
+ // Drain every removal before reporting failures so disable/re-enable
+ // cannot race a removal left running by a rejected Promise.all.
+ const results = await Promise.allSettled([
+ ...registryEntries.flatMap((entry) =>
+ WINDOWS_REGISTRY_VIEWS.map((view) => deleteRegistry(entry, view))
+ ),
+ ...manifestPaths.map((filePath) => this.removeOwnedManifest(filePath)),
+ this.removeDevelopmentHostConfig(),
+ ])
+ const errors = results.flatMap((result) =>
+ result.status === 'rejected' ? [result.reason] : []
)
- await this.removeDevelopmentHostConfig()
+ if (errors.length > 0) {
+ throw new AggregateError(errors, 'Native Messaging cleanup failed')
+ }
}
private developmentHostConfigPath(): string | null {