Skip to content

A full-featured download manager.

fix(bridge): restore Windows desktop startup (#2066)

Dr_rOot16c3472d80f1
diff --git a/packages/native-host/src/endpoint.rs b/packages/native-host/src/endpoint.rs
index 958448f4..893f3fc4 100644
--- a/packages/native-host/src/endpoint.rs
+++ b/packages/native-host/src/endpoint.rs
@@ -334,12 +334,23 @@ fn copy_sid(sid: windows_sys::Win32::Security::PSID) -> Option<Vec<u8>> {
Some(buffer)
}
-/// Reads `endpoint.json`, keeping the ticket-minting fields only when the
-/// file passes the platform's `is_owner_only` above (§9.1): Unix mode-0600
-/// owner check, or its deliberately-weaker Windows owner+DACL analogue.
+/// Reads `endpoint.json`, keeping the ticket-minting fields on Windows. The
+/// normal production file lives in the current user's application-data
+/// directory; an explicit bridge-directory override opts into trusting that
+/// location. Windows DACLs vary enough across otherwise normal installations
+/// that treating an unfamiliar ACL as an attestation failure creates a worse
+/// outcome: a silent, ticketless bootstrap that changes pairing behaviour.
+///
+/// Unix keeps the mode-0600 owner check required by §9.1. The Windows
+/// `is_owner_only` implementation remains in use for the development-only
+/// configuration beside the native-host executable, whose location is not
+/// intrinsically scoped to the current user's application data.
pub fn read_endpoint(file_path: &Path) -> Option<EndpointFile> {
let file = File::open(file_path).ok()?;
- let owner_only = is_owner_only(&file);
+ #[cfg(unix)]
+ let credentials_are_trusted = is_owner_only(&file);
+ #[cfg(windows)]
+ let credentials_are_trusted = true;
let mut limited: Take<File> = file.take((MAX_ENDPOINT_BYTES + 1) as u64);
let mut bytes = Vec::new();
limited.read_to_end(&mut bytes).ok()?;
@@ -350,10 +361,10 @@ pub fn read_endpoint(file_path: &Path) -> Option<EndpointFile> {
if endpoint.port == 0 {
return None;
}
- // Degrade, don't fail: a non-0600 file still reports its port so the
- // host can bootstrap, but cannot serve as the attestation root, so the
- // ticket-minting fields are dropped rather than trusted.
- if !owner_only {
+ // On Unix, degrade rather than fail when the mode-0600 attestation check
+ // fails. Windows intentionally retains credentials for a readable, valid
+ // endpoint in its selected bridge-data namespace; see above.
+ if !credentials_are_trusted {
endpoint.local_token = None;
endpoint.generation = None;
}
@@ -529,13 +540,13 @@ mod tests {
assert_eq!(endpoint.generation.as_deref(), Some("gen-1"));
}
- /// The Windows analogue of `group_readable_file_keeps_token_but_drops...`:
- /// a third party who is *not* already omnipotent can write the file, so it
- /// cannot root an attestation (§9.1) and the ticket-minting fields must be
- /// dropped while the port still comes through.
+ /// Endpoint discovery on Windows prioritises a stable desktop experience:
+ /// unfamiliar or permissive DACLs must not silently change the bootstrap
+ /// protocol to its ticketless form. The stricter DACL policy is retained
+ /// for development configuration files beside the executable.
#[cfg(windows)]
#[test]
- fn dacl_granting_a_third_party_drops_token_fields() {
+ fn permissive_dacl_keeps_endpoint_credentials() {
let path = write_endpoint_fixture("endpoint-win-lax.json");
set_owner_only_dacl(&path);
// `*S-1-1-0` is Everyone, by SID so the test does not depend on the
@@ -544,8 +555,8 @@ mod tests {
let endpoint = read_endpoint(&path).expect("endpoint parses");
assert_eq!(endpoint.port, 55_809);
- assert_eq!(endpoint.local_token, None);
- assert_eq!(endpoint.generation, None);
+ assert_eq!(endpoint.local_token.as_deref(), Some("tok-abc"));
+ assert_eq!(endpoint.generation.as_deref(), Some("gen-1"));
}
#[cfg(unix)]
diff --git a/src/core/bridge/bridge-data-dir-lock.ts b/src/core/bridge/bridge-data-dir-lock.ts
index be8667fc..a279c47b 100644
--- a/src/core/bridge/bridge-data-dir-lock.ts
+++ b/src/core/bridge/bridge-data-dir-lock.ts
@@ -11,7 +11,8 @@ const NO_FOLLOW = constants.O_NOFOLLOW ?? 0
const LOCK_MODE = 0o600
export const BRIDGE_DATA_DIR_LOCK_FILE_NAME = '.motrix-bridge.lock'
-const RECOVERY_GUARD_FILE_NAME = '.motrix-bridge.lock.recovery'
+export const BRIDGE_DATA_DIR_LOCK_RECOVERY_GUARD_FILE_NAME =
+ '.motrix-bridge.lock.recovery'
export const BRIDGE_DATA_DIR_LOCK_UNAVAILABLE =
'bridge data directory lock unavailable'
@@ -250,7 +251,7 @@ export async function acquireBridgeDataDirLock(
lockPath = path.join(canonicalDirectory, BRIDGE_DATA_DIR_LOCK_FILE_NAME)
const recoveryGuardPath = path.join(
canonicalDirectory,
- RECOVERY_GUARD_FILE_NAME
+ BRIDGE_DATA_DIR_LOCK_RECOVERY_GUARD_FILE_NAME
)
if (claims.has(lockPath)) throw new ExistingLockError()
diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.ts
index 36278f24..7889e997 100644
--- a/src/main/bridge/bootstrap-lifecycle.test.ts
+++ b/src/main/bridge/bootstrap-lifecycle.test.ts
@@ -220,6 +220,49 @@ describe('desktop bridge bootstrap ownership', () => {
await expect(lstat(lockPath)).rejects.toMatchObject({ code: 'ENOENT' })
})
+ it('starts on Windows after cleaning default desktop crash residue', async () => {
+ const originalPlatform = process.platform
+ const originalOverride = process.env.MOTRIX_BRIDGE_DATA_DIR
+ const bridgeDirectory = join(userDataDir, 'bridge')
+ const localToken = 'L'.repeat(43)
+ let runtime: Awaited<ReturnType<typeof bootstrapBridge>> = null
+
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ delete process.env.MOTRIX_BRIDGE_DATA_DIR
+ try {
+ await mkdir(bridgeDirectory, { recursive: true })
+ await writeFile(
+ join(bridgeDirectory, BRIDGE_DATA_DIR_LOCK_FILE_NAME),
+ 'crashed desktop lock'
+ )
+ await writeFile(
+ join(bridgeDirectory, 'extension-pairings.json.lock'),
+ 'crashed projection writer'
+ )
+ await writeFile(join(bridgeDirectory, 'endpoint.json'), 'stale endpoint')
+ await writeFile(join(bridgeDirectory, 'local-token'), localToken)
+
+ runtime = await bootstrapBridge(args())
+
+ expect(runtime).not.toBeNull()
+ expect(EndpointFileWriter.prototype.write).toHaveBeenCalledOnce()
+ await expect(
+ readFile(join(bridgeDirectory, 'local-token'), 'utf8')
+ ).resolves.toBe(localToken)
+ await expect(
+ lstat(join(bridgeDirectory, 'extension-pairings.json.lock'))
+ ).rejects.toMatchObject({ code: 'ENOENT' })
+ } finally {
+ await runtime?.shutdown()
+ Object.defineProperty(process, 'platform', { value: originalPlatform })
+ if (originalOverride === undefined) {
+ delete process.env.MOTRIX_BRIDGE_DATA_DIR
+ } else {
+ process.env.MOTRIX_BRIDGE_DATA_DIR = originalOverride
+ }
+ }
+ })
+
it('releases the data-root lock when the first store load fails', async () => {
const failure = new Error('pairing store unavailable')
vi.spyOn(PairingService.prototype, 'load').mockRejectedValueOnce(failure)
diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.ts
index e9fca3a6..aaecb7e3 100644
--- a/src/main/bridge/index.ts
+++ b/src/main/bridge/index.ts
@@ -79,6 +79,7 @@ import {
resolveBridgeDataDir,
resolvePackagedLinuxSnapEnvironment,
} from './snap-environment'
+import { recoverDefaultWindowsDesktopBridgeResidue } from './windows-desktop-startup-recovery'
/**
* A plugin contributes to the mux pre-resolve seam when it is an enabled
@@ -432,6 +433,12 @@ export async function bootstrapBridge(args: {
process.env.MOTRIX_BRIDGE_DATA_DIR
)
await mkdir(dataDir, { recursive: true })
+ await recoverDefaultWindowsDesktopBridgeResidue({
+ platform: process.platform,
+ dataDirectory: dataDir,
+ bridgeDataDirectoryOverride: process.env.MOTRIX_BRIDGE_DATA_DIR,
+ authority: args.bridgeDataDirLockRecoveryAuthority,
+ })
const ownership = new BridgeOwnership()
try {
// This is the first bridge-state acquisition. No store is loaded and no
diff --git a/src/main/bridge/windows-desktop-startup-recovery.test.ts b/src/main/bridge/windows-desktop-startup-recovery.test.ts
new file mode 100644
index 00000000..60ae5270
--- /dev/null
+++ b/src/main/bridge/windows-desktop-startup-recovery.test.ts
@@ -0,0 +1,155 @@
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,
+ BRIDGE_DATA_DIR_LOCK_RECOVERY_GUARD_FILE_NAME,
+ BRIDGE_DATA_DIR_LOCK_UNAVAILABLE,
+ type BridgeDataDirLockRecoveryAuthority,
+} from '@core/bridge/bridge-data-dir-lock'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { recoverDefaultWindowsDesktopBridgeResidue } from './windows-desktop-startup-recovery'
+
+const RESIDUE_NAMES = [
+ 'endpoint.json',
+ 'extension-pairings.json.lock',
+ BRIDGE_DATA_DIR_LOCK_RECOVERY_GUARD_FILE_NAME,
+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,
+] as const
+
+describe('recoverDefaultWindowsDesktopBridgeResidue', () => {
+ let root: string
+ let bridgeDirectory: string
+ let authority: BridgeDataDirLockRecoveryAuthority
+ let ownsProcess: boolean
+ let assertExclusiveProcessOwnership: BridgeDataDirLockRecoveryAuthority['assertExclusiveProcessOwnership']
+
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'motrix-windows-recovery-'))
+ bridgeDirectory = join(root, 'bridge')
+ await mkdir(bridgeDirectory)
+ ownsProcess = true
+ assertExclusiveProcessOwnership = vi.fn(() => ownsProcess)
+ authority = {
+ ownershipEpoch: 'W'.repeat(43),
+ assertExclusiveProcessOwnership,
+ }
+ })
+
+ afterEach(async () => {
+ await rm(root, { recursive: true, force: true })
+ })
+
+ it('removes only startup residue from the default Windows desktop root', async () => {
+ for (const fileName of RESIDUE_NAMES) {
+ await writeFile(join(bridgeDirectory, fileName), 'residue')
+ }
+ await writeFile(join(bridgeDirectory, 'local-token'), 'preserved-token')
+ await writeFile(join(bridgeDirectory, 'pairing.json'), 'preserved-pairing')
+
+ await recoverDefaultWindowsDesktopBridgeResidue({
+ platform: 'win32',
+ dataDirectory: bridgeDirectory,
+ bridgeDataDirectoryOverride: undefined,
+ authority,
+ })
+
+ expect(assertExclusiveProcessOwnership).toHaveBeenCalledOnce()
+ for (const fileName of RESIDUE_NAMES) {
+ await expect(
+ lstat(join(bridgeDirectory, fileName))
+ ).rejects.toMatchObject({ code: 'ENOENT' })
+ }
+ await expect(
+ readFile(join(bridgeDirectory, 'local-token'), 'utf8')
+ ).resolves.toBe('preserved-token')
+ await expect(
+ readFile(join(bridgeDirectory, 'pairing.json'), 'utf8')
+ ).resolves.toBe('preserved-pairing')
+ })
+
+ it.each([
+ ['darwin', false],
+ ['linux', false],
+ ['win32', true],
+ ] as const)(
+ 'does nothing on platform %s with custom override %s',
+ async (platform, usesCustomOverride) => {
+ const lockPath = join(bridgeDirectory, BRIDGE_DATA_DIR_LOCK_FILE_NAME)
+ await writeFile(lockPath, 'preserved')
+
+ await recoverDefaultWindowsDesktopBridgeResidue({
+ platform,
+ dataDirectory: bridgeDirectory,
+ bridgeDataDirectoryOverride: usesCustomOverride
+ ? bridgeDirectory
+ : undefined,
+ authority,
+ })
+
+ expect(assertExclusiveProcessOwnership).not.toHaveBeenCalled()
+ await expect(readFile(lockPath, 'utf8')).resolves.toBe('preserved')
+ }
+ )
+
+ it('keeps residue when Electron no longer owns the app lock', async () => {
+ ownsProcess = false
+ const lockPath = join(bridgeDirectory, BRIDGE_DATA_DIR_LOCK_FILE_NAME)
+ await writeFile(lockPath, 'preserved')
+
+ await expect(
+ recoverDefaultWindowsDesktopBridgeResidue({
+ platform: 'win32',
+ dataDirectory: bridgeDirectory,
+ bridgeDataDirectoryOverride: undefined,
+ authority,
+ })
+ ).rejects.toThrow(BRIDGE_DATA_DIR_LOCK_UNAVAILABLE)
+ await expect(readFile(lockPath, 'utf8')).resolves.toBe('preserved')
+ })
+
+ it.runIf(process.platform !== 'win32')(
+ 'unlinks a final symlink without touching its target',
+ async () => {
+ const target = join(root, 'outside-target')
+ const endpointPath = join(bridgeDirectory, 'endpoint.json')
+ await writeFile(target, 'preserved')
+ await symlink(target, endpointPath)
+
+ await recoverDefaultWindowsDesktopBridgeResidue({
+ platform: 'win32',
+ dataDirectory: bridgeDirectory,
+ bridgeDataDirectoryOverride: undefined,
+ authority,
+ })
+
+ await expect(lstat(endpointPath)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ await expect(readFile(target, 'utf8')).resolves.toBe('preserved')
+ }
+ )
+
+ it('fails closed on an unexpected directory', async () => {
+ const endpointPath = join(bridgeDirectory, 'endpoint.json')
+ await mkdir(endpointPath)
+
+ await expect(
+ recoverDefaultWindowsDesktopBridgeResidue({
+ platform: 'win32',
+ dataDirectory: bridgeDirectory,
+ bridgeDataDirectoryOverride: undefined,
+ authority,
+ })
+ ).rejects.toThrow(BRIDGE_DATA_DIR_LOCK_UNAVAILABLE)
+ expect((await lstat(endpointPath)).isDirectory()).toBe(true)
+ })
+})
diff --git a/src/main/bridge/windows-desktop-startup-recovery.ts b/src/main/bridge/windows-desktop-startup-recovery.ts
new file mode 100644
index 00000000..6152ecfc
--- /dev/null
+++ b/src/main/bridge/windows-desktop-startup-recovery.ts
@@ -0,0 +1,79 @@
+import { lstat, unlink } from 'node:fs/promises'
+import { join } from 'node:path'
+import {
+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,
+ BRIDGE_DATA_DIR_LOCK_RECOVERY_GUARD_FILE_NAME,
+ BRIDGE_DATA_DIR_LOCK_UNAVAILABLE,
+ type BridgeDataDirLockRecoveryAuthority,
+} from '@core/bridge/bridge-data-dir-lock'
+
+const OWNERSHIP_EPOCH_PATTERN = /^[A-Za-z0-9_-]{43}$/u
+const WINDOWS_DESKTOP_RESIDUE_FILE_NAMES = [
+ 'endpoint.json',
+ 'extension-pairings.json.lock',
+ BRIDGE_DATA_DIR_LOCK_RECOVERY_GUARD_FILE_NAME,
+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,
+] as const
+
+export interface WindowsDesktopStartupRecoveryOptions {
+ readonly platform: NodeJS.Platform
+ readonly dataDirectory: string
+ readonly bridgeDataDirectoryOverride: string | undefined
+ readonly authority: BridgeDataDirLockRecoveryAuthority
+}
+
+function unavailable(): Error {
+ return new Error(BRIDGE_DATA_DIR_LOCK_UNAVAILABLE)
+}
+
+/**
+ * Migrate crash residue created by desktop betas that could not recover their
+ * bridge lock on Windows. This is limited to Electron's default private data
+ * root, where the already-held app single-instance lock is the owner proof.
+ * Server and explicitly shared/custom roots keep the core fail-closed policy.
+ */
+export async function recoverDefaultWindowsDesktopBridgeResidue(
+ options: WindowsDesktopStartupRecoveryOptions
+): Promise<void> {
+ if (
+ options.platform !== 'win32' ||
+ options.bridgeDataDirectoryOverride !== undefined
+ ) {
+ return
+ }
+
+ if (!OWNERSHIP_EPOCH_PATTERN.test(options.authority.ownershipEpoch)) {
+ throw unavailable()
+ }
+
+ let authorized = false
+ try {
+ authorized =
+ (await options.authority.assertExclusiveProcessOwnership()) === true
+ } catch {
+ throw unavailable()
+ }
+ if (!authorized) throw unavailable()
+
+ for (const fileName of WINDOWS_DESKTOP_RESIDUE_FILE_NAMES) {
+ const filePath = join(options.dataDirectory, fileName)
+ let metadata: Awaited<ReturnType<typeof lstat>>
+ try {
+ metadata = await lstat(filePath)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
+ throw unavailable()
+ }
+
+ // unlink removes a final symlink itself, never its target. Directories and
+ // other unexpected filesystem objects remain untouched and fail closed.
+ if (!metadata.isFile() && !metadata.isSymbolicLink()) {
+ throw unavailable()
+ }
+ try {
+ await unlink(filePath)
+ } catch {
+ throw unavailable()
+ }
+ }
+}
diff --git a/src/main/launcher.test.ts b/src/main/launcher.test.ts
index d8bdea51..f4c94b03 100644
--- a/src/main/launcher.test.ts
+++ b/src/main/launcher.test.ts
@@ -1,18 +1,25 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { mockRequestLock, mockExit, mockGetLoginItemSettings, mockOn } =
- vi.hoisted(() => ({
- mockRequestLock: vi.fn().mockReturnValue(true),
- mockExit: vi.fn(),
- mockGetLoginItemSettings: vi.fn().mockReturnValue({
- wasOpenedAtLogin: false,
- }),
- mockOn: vi.fn(),
- }))
+const {
+ mockRequestLock,
+ mockHasSingleInstanceLock,
+ mockExit,
+ mockGetLoginItemSettings,
+ mockOn,
+} = vi.hoisted(() => ({
+ mockRequestLock: vi.fn().mockReturnValue(true),
+ mockHasSingleInstanceLock: vi.fn().mockReturnValue(true),
+ mockExit: vi.fn(),
+ mockGetLoginItemSettings: vi.fn().mockReturnValue({
+ wasOpenedAtLogin: false,
+ }),
+ mockOn: vi.fn(),
+}))
vi.mock('electron', () => ({
app: {
requestSingleInstanceLock: mockRequestLock,
+ hasSingleInstanceLock: mockHasSingleInstanceLock,
exit: mockExit,
getLoginItemSettings: mockGetLoginItemSettings,
on: mockOn,
@@ -39,6 +46,7 @@ describe('setupLauncher', () => {
vi.clearAllMocks()
mockOn.mockReset()
mockRequestLock.mockReturnValue(true)
+ mockHasSingleInstanceLock.mockReturnValue(true)
callbacks.onProtocolUrl.mockClear()
callbacks.onTorrentFile.mockClear()
callbacks.onShowWindow.mockClear()
@@ -68,6 +76,11 @@ describe('setupLauncher', () => {
expect(
handle.bridgeDataDirLockRecoveryAuthority?.assertExclusiveProcessOwnership()
).toBe(true)
+
+ mockHasSingleInstanceLock.mockReturnValue(false)
+ expect(
+ handle.bridgeDataDirLockRecoveryAuthority?.assertExclusiveProcessOwnership()
+ ).toBe(false)
})
it('creates a fresh recovery epoch for each successful process ownership session', () => {
diff --git a/src/main/launcher.ts b/src/main/launcher.ts
index 40973f0b..07e938d4 100644
--- a/src/main/launcher.ts
+++ b/src/main/launcher.ts
@@ -66,7 +66,7 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
const bridgeDataDirLockRecoveryAuthority: BridgeDataDirLockRecoveryAuthority =
Object.freeze({
ownershipEpoch,
- assertExclusiveProcessOwnership: () => true,
+ assertExclusiveProcessOwnership: () => app.hasSingleInstanceLock(),
})
// Detect login launch