Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

Feat: add per-connection proxy configuration and improve network interface handling (#32)

Shreyansh Kushwahad49abcde758b
diff --git a/e2e/network.spec.ts b/e2e/network.spec.ts
index 4ff9c20..e5ea58f 100644
--- a/e2e/network.spec.ts
+++ b/e2e/network.spec.ts
@@ -1,7 +1,7 @@
import { expect, test } from '@playwright/test'
import { createServer, type IncomingMessage } from 'node:http'
-import type { AddressInfo } from 'node:net'
-import type { NetworkInterfaceInfo } from '../src/shared/types'
+import { connect as netConnect, type AddressInfo } from 'node:net'
+import type { NetworkInterfaceInfo, ProxyConfig } from '../src/shared/types'
import { StreamConnection } from '../src/main/network/routes'
const iface: NetworkInterfaceInfo = {
@@ -168,3 +168,188 @@ test('reconnect drops its sockets, and the next request opens a new one @smoke',
await new Promise<void>((resolve) => server.close(() => resolve()))
}
})
+
+test('invalid proxy details fail and never fall back to direct download @smoke', async () => {
+ let directServerHit = false
+ const targetServer = createServer((_req, res) => {
+ directServerHit = true
+ res.end('direct hit')
+ })
+ await new Promise<void>((resolve) => targetServer.listen(0, '127.0.0.1', resolve))
+ const targetPort = (targetServer.address() as AddressInfo).port
+
+ // Proxy pointing to an unused port that will fail connection
+ const proxyConfig: ProxyConfig = {
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: 59998
+ }
+
+ const connection = new StreamConnection(() => loopback, {
+ timeoutMs: 1500,
+ proxy: () => proxyConfig
+ })
+
+ try {
+ const url = new URL(`http://127.0.0.1:${targetPort}/download`)
+ await expect(connection.request(url, {})).rejects.toThrow()
+ // CRITICAL: The direct server must NOT be contacted! Direct fallback is strictly forbidden!
+ expect(directServerHit).toBe(false)
+ } finally {
+ connection.close()
+ await new Promise<void>((resolve) => targetServer.close(() => resolve()))
+ }
+})
+
+test('proxy authentication failure fails and never falls back to direct download @smoke', async () => {
+ let targetServerHit = false
+ const targetServer = createServer((_req, res) => {
+ targetServerHit = true
+ res.end('target payload')
+ })
+ await new Promise<void>((resolve) => targetServer.listen(0, '127.0.0.1', resolve))
+ const targetPort = (targetServer.address() as AddressInfo).port
+
+ // Proxy requiring auth and rejecting wrong credentials with HTTP 407
+ const proxyServer = createServer()
+ proxyServer.on('connect', (_req, clientSocket) => {
+ clientSocket.write('HTTP/1.1 407 Proxy Authentication Required\r\n\r\n')
+ clientSocket.end()
+ })
+ await new Promise<void>((resolve) => proxyServer.listen(0, '127.0.0.1', resolve))
+ const proxyPort = (proxyServer.address() as AddressInfo).port
+
+ const proxyConfig: ProxyConfig = {
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: proxyPort,
+ username: 'invalidUser',
+ password: 'wrongPassword'
+ }
+
+ const connection = new StreamConnection(() => loopback, {
+ timeoutMs: 2000,
+ proxy: () => proxyConfig
+ })
+
+ try {
+ const url = new URL(`http://127.0.0.1:${targetPort}/download`)
+ await expect(connection.request(url, {})).rejects.toThrow(
+ /Proxy authentication required|HTTP 407/i
+ )
+ expect(targetServerHit).toBe(false)
+ } finally {
+ connection.close()
+ await new Promise<void>((resolve) => proxyServer.close(() => resolve()))
+ await new Promise<void>((resolve) => targetServer.close(() => resolve()))
+ }
+})
+
+test('valid HTTP proxy tunnels requests through the proxy @smoke', async () => {
+ let proxyConnectCount = 0
+ const targetServer = createServer((_req, res) => {
+ res.end('proxied data')
+ })
+ await new Promise<void>((resolve) => targetServer.listen(0, '127.0.0.1', resolve))
+ const targetPort = (targetServer.address() as AddressInfo).port
+
+ const proxyServer = createServer()
+ proxyServer.on('connect', (req, clientSocket, head) => {
+ proxyConnectCount++
+ const [tHost, tPort] = req.url!.split(':')
+ const targetSocket = netConnect(Number(tPort), tHost, () => {
+ clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+ if (head && head.length > 0) targetSocket.write(head)
+ targetSocket.pipe(clientSocket)
+ clientSocket.pipe(targetSocket)
+ })
+ targetSocket.on('error', () => clientSocket.destroy())
+ clientSocket.on('error', () => targetSocket.destroy())
+ })
+ await new Promise<void>((resolve) => proxyServer.listen(0, '127.0.0.1', resolve))
+ const proxyPort = (proxyServer.address() as AddressInfo).port
+
+ const proxyConfig: ProxyConfig = {
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: proxyPort
+ }
+
+ const connection = new StreamConnection(() => loopback, {
+ timeoutMs: 2000,
+ proxy: () => proxyConfig
+ })
+
+ try {
+ const url = new URL(`http://127.0.0.1:${targetPort}/download`)
+ const { res } = await connection.request(url, {})
+ expect(await body(res)).toBe('proxied data')
+ expect(proxyConnectCount).toBe(1)
+ } finally {
+ connection.close()
+ await new Promise<void>((resolve) => proxyServer.close(() => resolve()))
+ await new Promise<void>((resolve) => targetServer.close(() => resolve()))
+ }
+})
+
+test('proxy settings update dynamically on reconnect @smoke', async () => {
+ const targetServer = createServer((_req, res) => {
+ res.end('dynamic ok')
+ })
+ await new Promise<void>((resolve) => targetServer.listen(0, '127.0.0.1', resolve))
+ const targetPort = (targetServer.address() as AddressInfo).port
+
+ const proxyServer = createServer()
+ proxyServer.on('connect', (req, clientSocket, head) => {
+ const [tHost, tPort] = req.url!.split(':')
+ const targetSocket = netConnect(Number(tPort), tHost, () => {
+ clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
+ if (head && head.length > 0) targetSocket.write(head)
+ targetSocket.pipe(clientSocket)
+ clientSocket.pipe(targetSocket)
+ })
+ targetSocket.on('error', () => clientSocket.destroy())
+ clientSocket.on('error', () => targetSocket.destroy())
+ })
+ await new Promise<void>((resolve) => proxyServer.listen(0, '127.0.0.1', resolve))
+ const proxyPort = (proxyServer.address() as AddressInfo).port
+
+ // Initially wrong proxy
+ let activeProxy: ProxyConfig = {
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: 59997
+ }
+
+ const connection = new StreamConnection(() => loopback, {
+ timeoutMs: 1500,
+ proxy: () => activeProxy
+ })
+
+ try {
+ const url = new URL(`http://127.0.0.1:${targetPort}/download`)
+ // Fails with invalid proxy
+ await expect(connection.request(url, {})).rejects.toThrow()
+
+ // Switch to working proxy and reconnect
+ activeProxy = {
+ enabled: true,
+ type: 'http',
+ host: '127.0.0.1',
+ port: proxyPort
+ }
+ connection.reconnect()
+
+ // Succeeds through working proxy
+ const { res } = await connection.request(url, {})
+ expect(await body(res)).toBe('dynamic ok')
+ } finally {
+ connection.close()
+ await new Promise<void>((resolve) => proxyServer.close(() => resolve()))
+ await new Promise<void>((resolve) => targetServer.close(() => resolve()))
+ }
+})
diff --git a/package.json b/package.json
index 64d90d4..071d63b 100644
--- a/package.json
+++ b/package.json
@@ -73,11 +73,12 @@
"vite": "^7.2.6"
},
"allowScripts": {
}
}
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 2271c7f..4d3b1c3 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -23,6 +23,7 @@ import {
type HttpDownloadNetwork,
type HttpDownloadState,
type NetworkInterfaceInfo,
+ type NetworkPreferences,
type NetworkStatus,
type HttpProbeResult,
type StartDownloadRequest,
@@ -360,6 +361,7 @@ export class DownloadManager {
private scheduleTimer?: NodeJS.Timeout
/** Each network's addresses as last seen, by id: what tells a network that has changed. */
private seenAddresses = new Map<string, string[]>()
+ private networkPreferences: NetworkPreferences = {}
/** The powerSaveBlocker keeping the computer awake while a download runs (see keepAwake). */
private awakeBlocker: number | null = null
/** How many downloads may run at once; the rest wait, queued (see pump). */
@@ -387,6 +389,8 @@ export class DownloadManager {
}
private async configureSettings(settings: AppSettings): Promise<void> {
+ const previousPreferences = this.networkPreferences
+ this.networkPreferences = settings.networkPreferences ?? {}
this.downloadSchedule = settings.downloadSchedule
this.scheduleLoaded = true
const enrollmentChanged: DownloadRuntime[] = []
@@ -407,6 +411,31 @@ export class DownloadManager {
this.limitsChanged()
await Promise.all(enrollmentChanged.map((runtime) => this.persistNow(runtime)))
this.armScheduleTimer()
+
+ // If proxy settings changed, wake and reconnect the affected streams
+ const changedProxies = new Set<string>()
+ for (const [id, pref] of Object.entries(this.networkPreferences)) {
+ const prev = previousPreferences[id]?.proxy
+ const curr = pref.proxy
+ if (JSON.stringify(prev) !== JSON.stringify(curr)) {
+ changedProxies.add(id)
+ }
+ }
+ for (const [id, pref] of Object.entries(previousPreferences)) {
+ if (!this.networkPreferences[id] && pref.proxy) {
+ changedProxies.add(id)
+ }
+ }
+ if (changedProxies.size > 0) {
+ for (const runtime of this.runtimes.values()) {
+ if (runtime.state.status === 'downloading') {
+ runtime.transfer.wake(
+ (id) => changedProxies.has(id),
+ (id) => changedProxies.has(id)
+ )
+ }
+ }
+ }
}
/** A network ran out of data, or a limit changed: each download's networks are looked at
@@ -571,7 +600,8 @@ export class DownloadManager {
reconcile: () => this.reconcile(runtime),
failDownload: (message, discard) => this.failDownload(runtime, message, discard),
failNetwork: (network, message) => this.failNetwork(runtime, network, message),
- scheduleUpdate: () => this.scheduleUpdate(runtime)
+ scheduleUpdate: () => this.scheduleUpdate(runtime),
+ getProxyForInterface: (networkId) => this.networkPreferences[networkId]?.proxy
}
const runtime: HttpDownloadRuntime = Object.assign(target, this.runtimeFields(), {
kind: 'http' as const,
@@ -1166,7 +1196,8 @@ export class DownloadManager {
if (!network) return 'unknown'
const connection = new StreamConnection(() => network, {
timeoutMs: testKnobs.stallTimeoutMs,
- connectTimeoutMs: testKnobs.connectTimeoutMs
+ connectTimeoutMs: testKnobs.connectTimeoutMs,
+ proxy: () => this.networkPreferences[network.id]?.proxy
})
try {
return await compareSamples(runtime, url, browser, connection)
diff --git a/src/main/download/httpTransfer.ts b/src/main/download/httpTransfer.ts
index 4981d39..3cc1697 100644
--- a/src/main/download/httpTransfer.ts
+++ b/src/main/download/httpTransfer.ts
@@ -1103,7 +1103,8 @@ export class HttpTransfer implements Transfer {
nudge: new AbortController(),
connection: new StreamConnection(() => this.host.networks.find(chunk.interfaceId), {
timeoutMs: testKnobs.stallTimeoutMs,
- connectTimeoutMs: testKnobs.connectTimeoutMs
+ connectTimeoutMs: testKnobs.connectTimeoutMs,
+ proxy: () => this.host.getProxyForInterface?.(chunk.interfaceId)
}),
attempt: null,
warmSince: Date.now(),
diff --git a/src/main/download/transfer.ts b/src/main/download/transfer.ts
index 4bbecef..974a375 100644
--- a/src/main/download/transfer.ts
+++ b/src/main/download/transfer.ts
@@ -4,6 +4,7 @@ import type {
DownloadUnitState,
HttpBlockState,
HttpDownloadState,
+ ProxyConfig,
StartHttpDownloadRequest,
StartTorrentDownloadRequest,
TorrentDownloadState,
@@ -80,6 +81,7 @@ export interface TransferHost {
failDownload(message: string, discard?: boolean): void
failNetwork(network: DownloadNetwork, message: string): void
scheduleUpdate(): void
+ getProxyForInterface?(networkId: string): ProxyConfig | undefined
}
// Raw per-event deltas are too noisy to display (socket buffers flush in
diff --git a/src/main/network/deviceBinding.ts b/src/main/network/deviceBinding.ts
index 9c70983..81bcedf 100644
--- a/src/main/network/deviceBinding.ts
+++ b/src/main/network/deviceBinding.ts
@@ -1,4 +1,5 @@
import { connect, Socket, type SocketConstructorOpts } from 'node:net'
+import { networkInterfaces } from 'node:os'
import type { NetworkRoute } from './routes'
// Linux picks a socket's outgoing interface from the routing table alone: binding to an
@@ -89,3 +90,47 @@ export function connectRoute(route: NetworkRoute, port: number): Socket {
family
})
}
+
+function deviceFor(localAddress: string, host: string): string | undefined {
+ if (host === 'localhost' || host.startsWith('127.') || host === '::1') return undefined
+ for (const [device, addresses] of Object.entries(networkInterfaces())) {
+ if (addresses?.some((addr) => addr.address === localAddress)) return device
+ }
+ return undefined
+}
+
+/** A TCP connection to host:port that leaves through the interface owning `localAddress` or `device`. */
+export function connectFrom(
+ localAddress: string | undefined,
+ host: string,
+ port: number,
+ deviceName?: string
+): Socket {
+ const isLoopback = host === 'localhost' || host.startsWith('127.') || host === '::1'
+ if (isLoopback) {
+ return connect({ host, port })
+ }
+
+ const device = deviceName ?? (libc && localAddress ? deviceFor(localAddress, host) : undefined)
+ if (!libc || !device) {
+ return connect({ host, port, localAddress: localAddress || undefined })
+ }
+
+ const isIpv6 = Boolean(localAddress?.includes(':') || host.includes(':'))
+ const family = isIpv6 ? 6 : 4
+ let fd: number
+ try {
+ fd = openOnDevice(libc, device, family)
+ } catch (error) {
+ // The interface vanished since it was listed — surface it like any other connect error.
+ const socket = new Socket()
+ process.nextTick(() => socket.destroy(error as Error))
+ return socket
+ }
+ return new Socket({ fd, manualStart: true } as SocketConstructorOpts).connect({
+ host,
+ port,
+ localAddress: localAddress || undefined,
+ family
+ })
+}
diff --git a/src/main/network/interfaces.ts b/src/main/network/interfaces.ts
index d57360e..efc1bb9 100644
--- a/src/main/network/interfaces.ts
+++ b/src/main/network/interfaces.ts
@@ -1,4 +1,6 @@
import { execFile } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { readdir, readlink } from 'node:fs/promises'
import { networkInterfaces } from 'node:os'
import { promisify } from 'node:util'
import type { NetworkAddress, NetworkInterfaceInfo, NetworkInterfaceKind } from '../../shared/types'
@@ -13,6 +15,11 @@ interface WindowsAdapter {
NdisPhysicalMedium: number
}
+interface LinuxAdapter {
+ displayName: string
+ kind: NetworkInterfaceKind
+}
+
/**
* macOS device names (en0, en1, ...) don't say what they are. `networksetup`
* knows the human-readable "Hardware Port" for each device (Wi-Fi, iPhone USB,
@@ -95,6 +102,98 @@ async function getWindowsAdapters(): Promise<Map<string, WindowsAdapter>> {
}
}
+/**
+ * Queries Linux sysfs and udev to detect hardware interfaces (PCI, USB, Wi-Fi, Ethernet)
+ * and filter out virtual host/container bridges (e.g. docker0, br-*, veth*).
+ */
+async function getLinuxAdapters(): Promise<Map<string, LinuxAdapter>> {
+ const adapters = new Map<string, LinuxAdapter>()
+ if (process.platform !== 'linux') return adapters
+
+ let devices: string[]
+ try {
+ devices = await readdir('/sys/class/net')
+ } catch {
+ return adapters
+ }
+
+ await Promise.all(
+ devices.map(async (device) => {
+ if (device === 'lo') return
+ // Filter out internal container, hypervisor, and dummy bridges/interfaces
+ if (/^(docker|br-|veth|virbr|vboxnet|vmnet|cni|flannel|cbr|dummy)/i.test(device)) return
+
+ const sysPath = `/sys/class/net/${device}`
+ let isVirtual = false
+ try {
+ const link = await readlink(sysPath)
+ isVirtual = link.includes('/devices/virtual/')
+ } catch {
+ /* ignore */
+ }
+
+ // Pure virtual devices with no hardware backing and no wireless/phy capabilities
+ if (
+ isVirtual &&
+ !existsSync(`${sysPath}/device`) &&
+ !existsSync(`${sysPath}/wireless`) &&
+ !existsSync(`${sysPath}/phy80211`)
+ ) {
+ return
+ }
+
+ let isWireless =
+ existsSync(`${sysPath}/wireless`) ||
+ existsSync(`${sysPath}/phy80211`) ||
+ /^wl/i.test(device)
+
+ let isUsb = /^usb|^rndis/i.test(device)
+ try {
+ const link = await readlink(sysPath)
+ if (link.includes('/usb')) isUsb = true
+ } catch {
+ /* ignore */
+ }
+
+ let udevModel = ''
+ try {
+ const { stdout } = await execFileAsync('udevadm', ['info', '-q', 'property', sysPath], {
+ timeout: 1000
+ })
+ for (const line of stdout.split('\n')) {
+ if (line.startsWith('ID_BUS=usb')) isUsb = true
+ if (line.startsWith('DEVTYPE=wlan')) isWireless = true
+ if (line.startsWith('ID_MODEL_FROM_DATABASE=')) {
+ udevModel = line.slice('ID_MODEL_FROM_DATABASE='.length).trim()
+ }
+ }
+ } catch {
+ /* ignore */
+ }
+
+ let kind: NetworkInterfaceKind = 'other'
+ if (isWireless) kind = 'wifi'
+ else if (isUsb) kind = 'usb'
+ else if (/^(eth|en)/i.test(device)) kind = 'ethernet'
+ else kind = classifyInterface(device)
+
+ const displayName =
+ udevModel ||
+ (kind === 'wifi'
+ ? 'Wi-Fi'
+ : kind === 'ethernet'
+ ? 'Ethernet'
+ : kind === 'usb'
+ ? 'USB Network'
+ : device)
+
+ adapters.set(device, { displayName, kind })
+ })
+ )
+
+ return adapters
+}
+
/** Computes the CIDR subnet (e.g. "192.168.1.0/24") from an IPv4 address and netmask. */
export function ipv4Subnet(address: string, netmask: string): string | null {
const ipParts = address.split('.').map(Number)
@@ -119,7 +218,7 @@ export function ipv4Subnet(address: string, netmask: string): string | null {
* takes a child process, while the addresses themselves are one cheap system call. */
let labels: {
devices: string
- lookup: Promise<[Map<string, string>, Map<string, WindowsAdapter>]>
+ lookup: Promise<[Map<string, string>, Map<string, WindowsAdapter>, Map<string, LinuxAdapter>]>
} | null = null
/**
@@ -132,9 +231,12 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {
const all = networkInterfaces()
const devices = Object.keys(all).sort().join('\n')
if (labels?.devices !== devices) {
- labels = { devices, lookup: Promise.all([getMacHardwarePortNames(), getWindowsAdapters()]) }
+ labels = {
+ devices,
+ lookup: Promise.all([getMacHardwarePortNames(), getWindowsAdapters(), getLinuxAdapters()])
+ }
}
- const [hardwarePorts, windowsAdapters] = await labels.lookup
+ const [hardwarePorts, windowsAdapters, linuxAdapters] = await labels.lookup
const result: NetworkInterfaceInfo[] = []
for (const [device, addresses] of Object.entries(all)) {
@@ -158,21 +260,30 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {
}))
if (usable.length === 0) continue
+ // On Linux, skip internal/virtual bridge adapters that aren't recognized hardware/adapters
+ if (process.platform === 'linux' && linuxAdapters.size > 0 && !linuxAdapters.has(device)) {
+ continue
+ }
+
const hardwareName = hardwarePorts.get(device)
const adapter = windowsAdapters.get(device)
+ const linuxAdapter = linuxAdapters.get(device)
+
let kind =
- process.platform === 'linux'
+ linuxAdapter?.kind ??
+ (process.platform === 'linux'
? classifyLinuxDevice(device)
- : classifyInterface(adapter?.InterfaceDescription ?? hardwareName ?? device)
+ : classifyInterface(adapter?.InterfaceDescription ?? hardwareName ?? device))
// NDIS media: 1 = wireless LAN, 9 = native 802.11, 14 = Ethernet (802.3).
if (adapter?.NdisPhysicalMedium === 1 || adapter?.NdisPhysicalMedium === 9) kind = 'wifi'
else if (kind === 'other' && adapter?.NdisPhysicalMedium === 14) kind = 'ethernet'
+
+ const displayName = linuxAdapter?.displayName ?? hardwareName ?? device
+
result.push({
id: device,
device,
- // What the OS shows people: macOS's hardware port ("Wi-Fi", "iPhone USB"), else the device —
- // on Windows its alias ("Wi-Fi", "Ethernet 2"), on Linux its name (wlp2s0).
- displayName: hardwareName ?? device,
+ displayName,
addresses: usable,
kind,
mac: addresses.find((addr) => addr.mac && addr.mac !== '00:00:00:00:00:00')?.mac
diff --git a/src/main/network/proxyTunnel.ts b/src/main/network/proxyTunnel.ts
new file mode 100644
index 0000000..5ee444a
--- /dev/null
+++ b/src/main/network/proxyTunnel.ts
@@ -0,0 +1,617 @@
+import { isIP, Socket } from 'node:net'
+import { connect as tlsConnect, type TLSSocket } from 'node:tls'
+import type { ProxyConfig } from '../../shared/types'
+import { connectFrom } from './deviceBinding'
+
+const PROXY_CONNECT_TIMEOUT_MS = 15_000
+
+const abortError = (): DOMException => new DOMException('Aborted', 'AbortError')
+
+/** Reads exactly `length` bytes from a socket, or rejects on error, close, timeout, or abort. */
+function readExactBytes(
+ socket: Socket | TLSSocket,
+ length: number,
+ signal?: AbortSignal
+): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ let buffer = Buffer.alloc(0)
+
+ const cleanup = (): void => {
+ socket.removeListener('data', onData)
+ socket.removeListener('error', onError)
+ socket.removeListener('close', onClose)
+ socket.removeListener('timeout', onTimeout)
+ signal?.removeEventListener('abort', onAbort)
+ }
+
+ const onData = (chunk: Buffer): void => {
+ buffer = Buffer.concat([buffer, chunk])
+ if (buffer.length >= length) {
+ cleanup()
+ const result = buffer.subarray(0, length)
+ const remainder = buffer.subarray(length)
+ if (remainder.length > 0) {
+ socket.unshift(remainder)
+ }
+ resolve(result)
+ }
+ }
+
+ const onError = (error: Error): void => {
+ cleanup()
+ reject(error)
+ }
+
+ const onClose = (): void => {
+ cleanup()
+ reject(new Error('Proxy connection closed unexpectedly'))
+ }
+
+ const onTimeout = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(new Error('Proxy connection timed out while reading response'))
+ }
+
+ const onAbort = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ socket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ socket.on('data', onData)
+ socket.once('error', onError)
+ socket.once('close', onClose)
+ socket.once('timeout', onTimeout)
+ })
+}
+
+/** Reads data until `\r\n\r\n` HTTP header delimiter is reached. */
+function readHttpHeaders(
+ socket: Socket | TLSSocket,
+ signal?: AbortSignal
+): Promise<{ headers: string; status: number }> {
+ return new Promise((resolve, reject) => {
+ let buffer = Buffer.alloc(0)
+
+ const cleanup = (): void => {
+ socket.removeListener('data', onData)
+ socket.removeListener('error', onError)
+ socket.removeListener('close', onClose)
+ socket.removeListener('timeout', onTimeout)
+ signal?.removeEventListener('abort', onAbort)
+ }
+
+ const onData = (chunk: Buffer): void => {
+ buffer = Buffer.concat([buffer, chunk])
+ const delimiterIndex = buffer.indexOf('\r\n\r\n')
+ if (delimiterIndex !== -1) {
+ cleanup()
+ const headerText = buffer.subarray(0, delimiterIndex).toString('utf-8')
+ const remainder = buffer.subarray(delimiterIndex + 4)
+ if (remainder.length > 0) {
+ socket.unshift(remainder)
+ }
+ const statusMatch = /^HTTP\/\d\.\d\s+(\d+)/i.exec(headerText)
+ const status = statusMatch ? parseInt(statusMatch[1], 10) : 0
+ resolve({ headers: headerText, status })
+ }
+ }
+
+ const onError = (error: Error): void => {
+ cleanup()
+ reject(error)
+ }
+
+ const onClose = (): void => {
+ cleanup()
+ reject(new Error('Proxy connection closed while reading response headers'))
+ }
+
+ const onTimeout = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(new Error('Proxy connection timed out while waiting for HTTP response'))
+ }
+
+ const onAbort = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ socket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ socket.on('data', onData)
+ socket.once('error', onError)
+ socket.once('close', onClose)
+ socket.once('timeout', onTimeout)
+ })
+}
+
+/** Establishes an HTTP CONNECT tunnel through an HTTP or HTTPS proxy. */
+async function connectHttpTunnel(
+ localAddress: string | undefined,
+ targetHost: string,
+ targetPort: number,
+ proxy: ProxyConfig,
+ device?: string,
+ signal?: AbortSignal
+): Promise<Socket | TLSSocket> {
+ if (signal?.aborted) throw abortError()
+ const isHttpsProxy = proxy.type === 'https'
+
+ // 1. Connect TCP socket bound to interface
+ const rawSocket: Socket = connectFrom(localAddress, proxy.host, proxy.port, device)
+
+ await new Promise<void>((resolve, reject) => {
+ const cleanup = (): void => {
+ rawSocket.off('connect', onConnect)
+ rawSocket.off('error', onError)
+ rawSocket.off('timeout', onTimeout)
+ signal?.removeEventListener('abort', onAbort)
+ }
+ const onConnect = (): void => {
+ cleanup()
+ resolve()
+ }
+ const onError = (err: Error): void => {
+ cleanup()
+ rawSocket.destroy()
+ reject(err)
+ }
+ const onTimeout = (): void => {
+ cleanup()
+ rawSocket.destroy()
+ reject(new Error(`Connecting to proxy ${proxy.host}:${proxy.port} timed out`))
+ }
+ const onAbort = (): void => {
+ cleanup()
+ rawSocket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ rawSocket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ rawSocket.once('connect', onConnect)
+ rawSocket.once('error', onError)
+ rawSocket.once('timeout', onTimeout)
+ rawSocket.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+ })
+
+ // 2. If HTTPS proxy, wrap in TLS to proxy first
+ let proxySocket: Socket | TLSSocket = rawSocket
+ if (isHttpsProxy) {
+ proxySocket = await new Promise<TLSSocket>((resolve, reject) => {
+ const tls = tlsConnect({
+ socket: rawSocket,
+ servername: isIP(proxy.host) ? undefined : proxy.host
+ })
+ const cleanup = (): void => {
+ tls.off('secureConnect', onSecure)
+ tls.off('error', onError)
+ tls.off('timeout', onTimeout)
+ signal?.removeEventListener('abort', onAbort)
+ }
+ const onSecure = (): void => {
+ cleanup()
+ resolve(tls)
+ }
+ const onError = (err: Error): void => {
+ cleanup()
+ tls.destroy()
+ rawSocket.destroy()
+ reject(err)
+ }
+ const onTimeout = (): void => {
+ cleanup()
+ tls.destroy()
+ rawSocket.destroy()
+ reject(new Error(`TLS handshake to proxy ${proxy.host}:${proxy.port} timed out`))
+ }
+ const onAbort = (): void => {
+ cleanup()
+ tls.destroy()
+ rawSocket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ tls.destroy()
+ rawSocket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ tls.once('secureConnect', onSecure)
+ tls.once('error', onError)
+ tls.once('timeout', onTimeout)
+ tls.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+ })
+ }
+
+ proxySocket.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+
+ // 3. Send HTTP CONNECT request
+ let connectRequest = `CONNECT ${targetHost}:${targetPort} HTTP/1.1\r\nHost: ${targetHost}:${targetPort}\r\n`
+ if (proxy.username) {
+ const credentials = Buffer.from(`${proxy.username}:${proxy.password ?? ''}`).toString('base64')
+ connectRequest += `Proxy-Authorization: Basic ${credentials}\r\n`
+ }
+ connectRequest += `User-Agent: Plexo/1.0\r\nProxy-Connection: Keep-Alive\r\n\r\n`
+
+ proxySocket.write(connectRequest)
+
+ // 4. Read HTTP 200 response
+ const { status, headers } = await readHttpHeaders(proxySocket, signal)
+ if (status < 200 || status >= 300) {
+ proxySocket.destroy()
+ if (status === 407) {
+ throw new Error(`Proxy authentication required (HTTP 407) on ${proxy.host}:${proxy.port}`)
+ }
+ const firstLine = headers.split('\r\n')[0] || `HTTP ${status}`
+ throw new Error(`Proxy CONNECT failed: ${firstLine}`)
+ }
+
+ proxySocket.setTimeout(0)
+ return proxySocket
+}
+
+/** Establishes a SOCKS5 tunnel with optional username/password authentication (RFC 1928 / RFC 1929). */
+async function connectSocks5Tunnel(
+ localAddress: string | undefined,
+ targetHost: string,
+ targetPort: number,
+ proxy: ProxyConfig,
+ device?: string,
+ signal?: AbortSignal
+): Promise<Socket> {
+ if (signal?.aborted) throw abortError()
+ const socket = connectFrom(localAddress, proxy.host, proxy.port, device)
+
+ await new Promise<void>((resolve, reject) => {
+ const cleanup = (): void => {
+ socket.off('connect', onConnect)
+ socket.off('error', onError)
+ socket.off('timeout', onTimeout)
+ signal?.removeEventListener('abort', onAbort)
+ }
+ const onConnect = (): void => {
+ cleanup()
+ resolve()
+ }
+ const onError = (err: Error): void => {
+ cleanup()
+ socket.destroy()
+ reject(err)
+ }
+ const onTimeout = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(new Error(`Connecting to SOCKS5 proxy ${proxy.host}:${proxy.port} timed out`))
+ }
+ const onAbort = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ socket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ socket.once('connect', onConnect)
+ socket.once('error', onError)
+ socket.once('timeout', onTimeout)
+ socket.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+ })
+
+ socket.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+
+ const hasAuth = Boolean(proxy.username)
+ // Handshake greeting: [VER=0x05, NMETHODS, METHODS...]
+ const greeting = hasAuth
+ ? Buffer.from([0x05, 0x02, 0x00, 0x02]) // No Auth (0x00) & User/Password (0x02)
+ : Buffer.from([0x05, 0x01, 0x00]) // No Auth (0x00)
+ socket.write(greeting)
+
+ const methodResponse = await readExactBytes(socket, 2, signal)
+ if (methodResponse[0] !== 0x05) {
+ socket.destroy()
+ throw new Error(`Invalid SOCKS5 version response (${methodResponse[0]})`)
+ }
+
+ const selectedMethod = methodResponse[1]
+ if (selectedMethod === 0xff) {
+ socket.destroy()
+ throw new Error('SOCKS5 proxy rejected authentication methods')
+ }
+
+ // Handle Username/Password sub-negotiation (RFC 1929)
+ if (selectedMethod === 0x02) {
+ const user = Buffer.from(proxy.username ?? '', 'utf-8')
+ const pass = Buffer.from(proxy.password ?? '', 'utf-8')
+ const authRequest = Buffer.concat([
+ Buffer.from([0x01, user.length]),
+ user,
+ Buffer.from([pass.length]),
+ pass
+ ])
+ socket.write(authRequest)
+
+ const authResponse = await readExactBytes(socket, 2, signal)
+ if (authResponse[1] !== 0x00) {
+ socket.destroy()
+ throw new Error(`SOCKS5 authentication failed on ${proxy.host}:${proxy.port}`)
+ }
+ }
+
+ // Connect command: [VER=0x05, CMD=0x01 (CONNECT), RSV=0x00, ATYP, ADDR, PORT]
+ let addrBuf: Buffer
+ const ipType = isIP(targetHost)
+ if (ipType === 4) {
+ const parts = targetHost.split('.').map(Number)
+ addrBuf = Buffer.from([0x01, ...parts])
+ } else if (ipType === 6) {
+ socket.destroy()
+ throw new Error('IPv6 addresses are not supported through SOCKS5 in this version')
+ } else {
+ // SOCKS5h Domain name address (0x03)
+ const hostBuf = Buffer.from(targetHost, 'utf-8')
+ addrBuf = Buffer.concat([Buffer.from([0x03, hostBuf.length]), hostBuf])
+ }
+
+ const portBuf = Buffer.alloc(2)
+ portBuf.writeUInt16BE(targetPort, 0)
+
+ const connectBuf = Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), addrBuf, portBuf])
+ socket.write(connectBuf)
+
+ // Read response: [VER, REP, RSV, ATYP, BND.ADDR, BND.PORT]
+ const header = await readExactBytes(socket, 4, signal)
+ const rep = header[1]
+ if (rep !== 0x00) {
+ socket.destroy()
+ const errorMessages: Record<number, string> = {
+ 0x01: 'General SOCKS server failure',
+ 0x02: 'Connection not allowed by ruleset',
+ 0x03: 'Network unreachable',
+ 0x04: 'Host unreachable',
+ 0x05: 'Connection refused',
+ 0x06: 'TTL expired',
+ 0x07: 'Command not supported',
+ 0x08: 'Address type not supported'
+ }
+ throw new Error(
+ `SOCKS5 connection to ${targetHost}:${targetPort} failed: ${errorMessages[rep] || `Error code 0x${rep.toString(16)}`}`
+ )
+ }
+
+ // Read remaining bound address and port to clean socket buffer
+ const atyp = header[3]
+ if (atyp === 0x01) {
+ await readExactBytes(socket, 4 + 2, signal) // 4 bytes IPv4 + 2 bytes port
+ } else if (atyp === 0x03) {
+ const lenBuf = await readExactBytes(socket, 1, signal)
+ await readExactBytes(socket, lenBuf[0] + 2, signal)
+ } else if (atyp === 0x04) {
+ await readExactBytes(socket, 16 + 2, signal)
+ }
+
+ socket.setTimeout(0)
+ return socket
+}
+
+/** Establishes a SOCKS4 / SOCKS4a tunnel. */
+async function connectSocks4Tunnel(
+ localAddress: string | undefined,
+ targetHost: string,
+ targetPort: number,
+ proxy: ProxyConfig,
+ device?: string,
+ signal?: AbortSignal
+): Promise<Socket> {
+ if (signal?.aborted) throw abortError()
+ const socket = connectFrom(localAddress, proxy.host, proxy.port, device)
+
+ await new Promise<void>((resolve, reject) => {
+ const cleanup = (): void => {
+ socket.off('connect', onConnect)
+ socket.off('error', onError)
+ socket.off('timeout', onTimeout)
+ signal?.removeEventListener('abort', onAbort)
+ }
+ const onConnect = (): void => {
+ cleanup()
+ resolve()
+ }
+ const onError = (err: Error): void => {
+ cleanup()
+ socket.destroy()
+ reject(err)
+ }
+ const onTimeout = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(new Error(`Connecting to SOCKS4 proxy ${proxy.host}:${proxy.port} timed out`))
+ }
+ const onAbort = (): void => {
+ cleanup()
+ socket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ socket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ socket.once('connect', onConnect)
+ socket.once('error', onError)
+ socket.once('timeout', onTimeout)
+ socket.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+ })
+
+ socket.setTimeout(PROXY_CONNECT_TIMEOUT_MS)
+
+ const isIpv4 = isIP(targetHost) === 4
+ const userId = Buffer.from(proxy.username ?? '', 'utf-8')
+ const portBuf = Buffer.alloc(2)
+ portBuf.writeUInt16BE(targetPort, 0)
+
+ let requestBuf: Buffer
+ if (isIpv4) {
+ const parts = targetHost.split('.').map(Number)
+ requestBuf = Buffer.concat([
+ Buffer.from([0x04, 0x01]),
+ portBuf,
+ Buffer.from(parts),
+ userId,
+ Buffer.from([0x00])
+ ])
+ } else {
+ // SOCKS4a: IP is set to 0.0.0.x with non-zero x, followed by host string
+ const hostBuf = Buffer.from(targetHost, 'utf-8')
+ requestBuf = Buffer.concat([
+ Buffer.from([0x04, 0x01]),
+ portBuf,
+ Buffer.from([0x00, 0x00, 0x00, 0x01]),
+ userId,
+ Buffer.from([0x00]),
+ hostBuf,
+ Buffer.from([0x00])
+ ])
+ }
+
+ socket.write(requestBuf)
+
+ const response = await readExactBytes(socket, 8, signal)
+ const status = response[1]
+ if (status !== 0x5a) {
+ socket.destroy()
+ const errorMessages: Record<number, string> = {
+ 0x5b: 'Request rejected or failed',
+ 0x5c: 'Request failed: client not running identd',
+ 0x5d: 'Request failed: identd reported different user-id'
+ }
+ throw new Error(
+ `SOCKS4 connection to ${targetHost}:${targetPort} failed: ${errorMessages[status] || `Error code 0x${status.toString(16)}`}`
+ )
+ }
+
+ socket.setTimeout(0)
+ return socket
+}
+
+/**
+ * Creates an outbound socket connected to `targetHost:targetPort` through the specified `proxy`,
+ * bound to the physical network interface owning `localAddress` or `device`. If `secure` is true, performs
+ * end-to-end TLS handshake with SNI through the established tunnel.
+ */
+export async function createProxyConnection(
+ localAddress: string | undefined,
+ targetHost: string,
+ targetPort: number,
+ secure: boolean,
+ proxy: ProxyConfig,
+ device?: string,
+ signal?: AbortSignal
+): Promise<Socket | TLSSocket> {
+ if (signal?.aborted) throw abortError()
+ let tunnelSocket: Socket | TLSSocket
+
+ switch (proxy.type) {
+ case 'http':
+ case 'https':
+ tunnelSocket = await connectHttpTunnel(
+ localAddress,
+ targetHost,
+ targetPort,
+ proxy,
+ device,
+ signal
+ )
+ break
+ case 'socks5':
+ tunnelSocket = await connectSocks5Tunnel(
+ localAddress,
+ targetHost,
+ targetPort,
+ proxy,
+ device,
+ signal
+ )
+ break
+ case 'socks4':
+ tunnelSocket = await connectSocks4Tunnel(
+ localAddress,
+ targetHost,
+ targetPort,
+ proxy,
+ device,
+ signal
+ )
+ break
+ default:
+ throw new Error(`Unsupported proxy type: ${String(proxy.type)}`)
+ }
+
+ if (secure) {
+ return new Promise<TLSSocket>((resolve, reject) => {
+ const tls = tlsConnect({
+ socket: tunnelSocket,
+ servername: isIP(targetHost) ? undefined : targetHost
+ })
+ const cleanup = (): void => {
+ tls.off('secureConnect', onSecure)
+ tls.off('error', onError)
+ signal?.removeEventListener('abort', onAbort)
+ }
+ const onSecure = (): void => {
+ cleanup()
+ resolve(tls)
+ }
+ const onError = (err: Error): void => {
+ cleanup()
+ tls.destroy()
+ tunnelSocket.destroy()
+ reject(err)
+ }
+ const onAbort = (): void => {
+ cleanup()
+ tls.destroy()
+ tunnelSocket.destroy()
+ reject(abortError())
+ }
+
+ if (signal?.aborted) {
+ tls.destroy()
+ tunnelSocket.destroy()
+ return reject(abortError())
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+
+ tls.once('secureConnect', onSecure)
+ tls.once('error', onError)
+ })
+ }
+
+ return tunnelSocket
+}
diff --git a/src/main/network/routes.ts b/src/main/network/routes.ts
index f40e784..7efc6f8 100644
--- a/src/main/network/routes.ts
+++ b/src/main/network/routes.ts
@@ -9,8 +9,9 @@ import {
import { Agent as HttpsAgent, request as httpsRequest } from 'node:https'
import { isIP, type Socket } from 'node:net'
import type { Duplex } from 'node:stream'
-import type { IpFamily, NetworkInterfaceInfo } from '../../shared/types'
+import type { IpFamily, NetworkInterfaceInfo, ProxyConfig } from '../../shared/types'
import { connectRoute } from './deviceBinding'
+import { createProxyConnection } from './proxyTunnel'
export interface NetworkRoute {
device: string
@@ -142,6 +143,106 @@ function attemptOrder(routes: NetworkRoute[], preferred: string | undefined): Ne
return ordered
}
+async function connectThroughProxy(
+ iface: NetworkInterfaceInfo,
+ host: string,
+ port: number,
+ secure: ((socket: Socket) => Socket) | null,
+ timeoutMs: number,
+ signal: AbortSignal,
+ proxy: ProxyConfig
+): Promise<Socket> {
+ if (signal.aborted) throw abortError()
+
+ const isProxyIpv6 = proxy.host.includes(':')
+ const localAddress = isProxyIpv6
+ ? (iface.addresses.find((a) => a.family === 6)?.address ?? iface.addresses[0]?.address)
+ : (iface.addresses.find((a) => a.family === 4)?.address ?? iface.addresses[0]?.address)
+
+ const abortController = new AbortController()
+ const onSignalAbort = (): void => abortController.abort()
+ signal.addEventListener('abort', onSignalAbort, { once: true })
+
+ const timer = setTimeout(() => {
+ abortController.abort()
+ }, timeoutMs)
+
+ let rawSocket: Socket | undefined
+ try {
+ const tunnel = await createProxyConnection(
+ localAddress,
+ host,
+ port,
+ false,
+ proxy,
+ iface.device,
+ abortController.signal
+ )
+ rawSocket = tunnel as Socket
+
+ if (signal.aborted) {
+ rawSocket.destroy()
+ throw abortError()
+ }
+
+ if (!secure) {
+ clearTimeout(timer)
+ signal.removeEventListener('abort', onSignalAbort)
+ return rawSocket
+ }
+
+ return await new Promise<Socket>((resolve, reject) => {
+ const socket = secure(rawSocket!)
+ let settled = false
+
+ const finish = (error: Error | null, winner?: Socket): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ signal.removeEventListener('abort', onSignalAbort)
+ abortController.signal.removeEventListener('abort', onTimeoutOrAbort)
+ socket.off('secureConnect', onConnected)
+ socket.off('error', onError)
+ rawSocket?.off('error', onError)
+ if (error) {
+ socket.destroy()
+ rawSocket?.destroy()
+ reject(error)
+ } else {
+ resolve(winner!)
+ }
+ }
+
+ const onConnected = (): void => finish(null, socket)
+ const onError = (err: Error): void => finish(asConnectionError(err))
+ const onTimeoutOrAbort = (): void => {
+ finish(
+ signal.aborted ? abortError() : new Error('Connection stalled: TLS handshake timed out')
+ )
+ }
+
+ if (abortController.signal.aborted) {
+ onTimeoutOrAbort()
+ return
+ }
+ abortController.signal.addEventListener('abort', onTimeoutOrAbort, { once: true })
+
+ socket.once('secureConnect', onConnected)
+ socket.once('error', onError)
+ rawSocket!.once('error', onError)
+ })
+ } catch (error) {
+ rawSocket?.destroy()
+ clearTimeout(timer)
+ signal.removeEventListener('abort', onSignalAbort)
+ if (signal.aborted) throw abortError()
+ if (abortController.signal.aborted && !signal.aborted) {
+ throw asConnectionError(new Error('Connection stalled: proxy connection timed out'))
+ }
+ throw asConnectionError(error)
+ }
+}
+
/**
* A socket to `host` through `iface`, racing its compatible routes as RFC 8305 does: whichever
* completes its handshake first is kept, and the others are dropped. `secure` wraps the TCP
@@ -155,8 +256,19 @@ async function connectOnInterface(
secure: ((socket: Socket) => Socket) | null,
timeoutMs: number,
signal: AbortSignal,
- resolveHost?: ResolveHost
+ resolveHost?: ResolveHost,
+ proxy?: ProxyConfig
): Promise<Socket> {
+ if (proxy && proxy.enabled) {
+ if (!proxy.host || !proxy.host.trim()) {
+ throw asConnectionError(new Error('Proxy is enabled but no proxy host is configured'))
+ }
+ if (!proxy.port || proxy.port <= 0 || proxy.port > 65535) {
+ throw asConnectionError(new Error(`Invalid proxy port: ${proxy.port}`))
+ }
+ return connectThroughProxy(iface, host, port, secure, timeoutMs, signal, proxy)
+ }
+
const deadline = Date.now() + timeoutMs
const found = routesFor(iface, await resolveTargetWithin(host, timeoutMs, signal, resolveHost))
if (found.length === 0) throw new NoCompatibleRouteError(host)
@@ -310,7 +422,8 @@ export class StreamConnection {
{
timeoutMs,
connectTimeoutMs = timeoutMs,
- resolveHost
+ resolveHost,
+ proxy
}: {
/** How long a request may take to get its response headers, connecting included. */
timeoutMs: number
@@ -318,12 +431,14 @@ export class StreamConnection {
* network that can't get through is found out before a slow server would be. */
connectTimeoutMs?: number
resolveHost?: ResolveHost
+ proxy?: () => ProxyConfig | undefined
}
) {
this.timeoutMs = timeoutMs
const open: Open = async (options, secure) => {
const iface = network()
if (!iface) throw new Error('The network is not connected')
+ const proxyConfig = proxy?.()
return connectOnInterface(
iface,
options.host ?? '',
@@ -335,7 +450,8 @@ export class StreamConnection {
options.connectSignal
? AbortSignal.any([this.lifetime.signal, options.connectSignal])
: this.lifetime.signal,
- resolveHost
+ resolveHost,
+ proxyConfig
)
}
this.http = new RoutedHttpAgent(open)
diff --git a/src/main/settings.ts b/src/main/settings.ts
index fa12346..0310e33 100644
--- a/src/main/settings.ts
+++ b/src/main/settings.ts
@@ -6,6 +6,8 @@ import {
type AppSettings,
type NetworkPreference,
type NetworkPreferences,
+ type ProxyConfig,
+ type ProxyType,
type ThemeSource
} from '../shared/types'
import { readJson, updateJson } from './jsonFile'
@@ -19,6 +21,38 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
+const VALID_PROXY_TYPES: readonly ProxyType[] = ['http', 'https', 'socks4', 'socks5']
+
+function sanitizeProxyConfig(value: unknown): ProxyConfig | undefined {
+ if (!isRecord(value)) return undefined
+ const enabled = typeof value.enabled === 'boolean' ? value.enabled : false
+ const type =
+ typeof value.type === 'string' && (VALID_PROXY_TYPES as readonly string[]).includes(value.type)
+ ? (value.type as ProxyType)
+ : 'http'
+ const host = typeof value.host === 'string' ? value.host.trim() : ''
+ const port =
+ typeof value.port === 'number' &&
+ Number.isInteger(value.port) &&
+ value.port >= 1 &&
+ value.port <= 65535
+ ? value.port
+ : 8080
+ const username =
+ typeof value.username === 'string' && value.username.length > 0 ? value.username : undefined
+ const password =
+ typeof value.password === 'string' && value.password.length > 0 ? value.password : undefined
+
+ return {
+ enabled,
+ type,
+ host,
+ port,
+ ...(username ? { username } : {}),
+ ...(password ? { password } : {})
+ }
+}
+
/** A rate or an amount of bytes: a positive whole number, or nothing. */
function byteCount(value: unknown): number | undefined {
return Number.isSafeInteger(value) && (value as number) > 0 ? (value as number) : undefined
@@ -37,6 +71,8 @@ function sanitizeNetworkPreferences(parsed: unknown): NetworkPreferences {
const preference: NetworkPreference = {}
if (typeof value.customName === 'string') preference.customName = value.customName
if (typeof value.colorId === 'string') preference.colorId = value.colorId
+ const proxy = sanitizeProxyConfig(value.proxy)
+ if (proxy) preference.proxy = proxy
if (value.off === true) preference.off = true
preference.speedLimit = byteCount(value.speedLimit)
preference.dataLimit = byteCount(value.dataLimit)
diff --git a/src/renderer/src/components/NetworkEditPopover.tsx b/src/renderer/src/components/NetworkEditPopover.tsx
index 1752a74..41ad4ce 100644
--- a/src/renderer/src/components/NetworkEditPopover.tsx
+++ b/src/renderer/src/components/NetworkEditPopover.tsx
@@ -1,10 +1,12 @@
-import type { NetworkInterfaceKind } from '@shared/types'
+import type { NetworkInterfaceKind, ProxyConfig, ProxyType } from '@shared/types'
+import { cn } from 'cn'
import { Pencil } from 'lucide-react'
import { useState } from 'react'
import { useNetworkVisuals } from '../hooks/useNetworkVisuals'
import { useAppStore } from '../store/useAppStore'
import { NETWORK_COLOR_SWATCHES, type NetworkColorId } from '../theme'
import { Button } from './ui/button'
+import { Checkbox } from './ui/checkbox'
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover'
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
@@ -12,6 +14,10 @@ interface NetworkEditPopoverProps {
interfaceId: string
interfaceKind: NetworkInterfaceKind
osName: string
+ trigger?: React.ReactElement
+ tooltip?: string
+ defaultFocusProxy?: boolean
+ className?: string
}
const fieldLabelClass =
@@ -19,12 +25,23 @@ const fieldLabelClass =
const MAX_NETWORK_NAME_LENGTH = 40
-/** Rename/recolor one network. Edits are a draft that's saved when the popover closes — Done,
- * Enter or clicking away — and thrown away on Escape, like renaming a file in Finder. */
+const PROXY_TYPES: { id: ProxyType; label: string }[] = [
+ { id: 'http', label: 'HTTP' },
+ { id: 'https', label: 'HTTPS' },
+ { id: 'socks5', label: 'SOCKS5' },
+ { id: 'socks4', label: 'SOCKS4' }
+]
+
+/** Rename/recolor one network and configure per-interface proxy settings. Edits are a draft
+ * that's saved when the popover closes — Done, Enter or clicking away — and thrown away on Escape. */
export function NetworkEditPopover({
interfaceId,
interfaceKind,
- osName
+ osName,
+ trigger,
+ tooltip,
+ defaultFocusProxy,
+ className
}: NetworkEditPopoverProps): React.JSX.Element {
const [open, setOpen] = useState(false)
const preference = useAppStore((store) => store.networkPreferences[interfaceId])
@@ -34,13 +51,41 @@ export function NetworkEditPopover({
const [draftName, setDraftName] = useState('')
const [draftColorId, setDraftColorId] = useState<NetworkColorId>(visual.colorId)
+ // Proxy draft state
+ const [proxyEnabled, setProxyEnabled] = useState(false)
+ const [proxyType, setProxyType] = useState<ProxyType>('http')
+ const [proxyHost, setProxyHost] = useState('')
+ const [proxyPort, setProxyPort] = useState('')
+ const [proxyUsername, setProxyUsername] = useState('')
+ const [proxyPassword, setProxyPassword] = useState('')
+
function save(): void {
const trimmed = draftName.trim().slice(0, MAX_NETWORK_NAME_LENGTH)
const customName = trimmed && trimmed !== osName ? trimmed : undefined
// Re-picking the color it already had keeps it automatic instead of pinning it.
const colorId = draftColorId === visual.colorId ? preference?.colorId : draftColorId
- if (customName !== preference?.customName || colorId !== preference?.colorId) {
- setNetworkPreference(interfaceId, { customName, colorId })
+
+ const hostTrimmed = proxyHost.trim()
+ const parsedPort = parseInt(proxyPort.trim(), 10)
+ const defaultPort = proxyType.startsWith('socks') ? 1080 : 8080
+ const port =
+ !isNaN(parsedPort) && parsedPort >= 1 && parsedPort <= 65535 ? parsedPort : defaultPort
+
+ const hasProxyConfig = proxyEnabled || hostTrimmed.length > 0 || preference?.proxy != null
+ const proxy: ProxyConfig | undefined = hasProxyConfig
+ ? {
+ enabled: proxyEnabled,
+ type: proxyType,
+ host: hostTrimmed,
+ port,
+ username: proxyUsername.trim() || undefined,
+ password: proxyPassword || undefined
+ }
+ : undefined
+
+ const proxyChanged = JSON.stringify(preference?.proxy ?? null) !== JSON.stringify(proxy ?? null)
+ if (customName !== preference?.customName || colorId !== preference?.colorId || proxyChanged) {
+ setNetworkPreference(interfaceId, { customName, colorId, proxy })
}
}
@@ -56,6 +101,13 @@ export function NetworkEditPopover({
if (next) {
setDraftName(visual.name)
setDraftColorId(visual.colorId)
+ const p = preference?.proxy
+ setProxyEnabled(Boolean(p?.enabled))
+ setProxyType(p?.type ?? 'http')
+ setProxyHost(p?.host ?? '')
+ setProxyPort(p?.port ? String(p.port) : '')
+ setProxyUsername(p?.username ?? '')
+ setProxyPassword(p?.password ?? '')
} else if (details.reason !== 'escape-key') {
save()
}
@@ -67,22 +119,29 @@ export function NetworkEditPopover({
render={
<PopoverTrigger
render={
- <Button
- type="button"
- variant="ghost"
- size="icon-xs"
- aria-label="Edit network"
- className="shrink-0 text-muted-foreground"
- >
- <Pencil className="size-3" />
- </Button>
+ trigger ?? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={`Edit ${visual.name}`}
+ className={cn('shrink-0 text-muted-foreground', className)}
+ >
+ <Pencil className="size-3" />
+ </Button>
+ )
}
/>
}
/>
- <TooltipContent>Edit network</TooltipContent>
+ <TooltipContent>
+ {tooltip ??
+ (preference?.proxy?.enabled && preference?.proxy?.host
+ ? `Proxy active (${preference!.proxy!.type.toUpperCase()}) — click to configure`
+ : `Configure proxy or edit ${visual.name}`)}
+ </TooltipContent>
</Tooltip>
- <PopoverContent aria-label={`Edit ${visual.name}`} className="gap-3 p-3">
+ <PopoverContent aria-label={`Edit ${visual.name}`} className="w-[320px] gap-3 p-3">
<div className="flex flex-col gap-[6px]">
<label htmlFor={`network-name-${interfaceId}`} className={fieldLabelClass}>
Name
@@ -98,7 +157,7 @@ export function NetworkEditPopover({
}}
placeholder={osName}
maxLength={MAX_NETWORK_NAME_LENGTH}
- autoFocus
+ autoFocus={!defaultFocusProxy}
className="rounded-[6px] border border-input bg-background px-[9px] py-1.5 font-sans text-[12px] leading-[1.3] font-medium text-foreground outline-none focus-visible:border-ring"
/>
</div>
@@ -112,8 +171,6 @@ export function NetworkEditPopover({
<Tooltip key={swatch.id}>
<TooltipTrigger
render={
- // The 24px button is the WCAG 2.5.8 hit target; the visible 20px dot lives
- // in the padding-shrunk inner span so the swatch itself doesn't grow.
<button
type="button"
onClick={() => setDraftColorId(swatch.id)}
@@ -125,7 +182,6 @@ export function NetworkEditPopover({
className="block size-full rounded-full"
style={{
background: swatch.solid,
- // Popover-colored gap, then a ring in the swatch's own hue — reads in both themes.
boxShadow: isSelected
? `0 0 0 2px var(--color-popover), 0 0 0 4px ${swatch.solid}`
: undefined
@@ -141,7 +197,131 @@ export function NetworkEditPopover({
</div>
</div>
- <div className="flex justify-end">
+ <div className="h-px bg-border/60" />
+
+ {/* Proxy configuration section */}
+ <div className="flex flex-col gap-2.5">
+ <div className="flex items-center justify-between">
+ <span className={fieldLabelClass}>Proxy</span>
+ <label className="group flex cursor-pointer items-center gap-1.5 select-none">
+ <Checkbox
+ checked={proxyEnabled}
+ onCheckedChange={(checked) => setProxyEnabled(Boolean(checked))}
+ />
+ <span className="font-sans text-[11px] font-medium text-muted-foreground group-hover:text-foreground">
+ Enable proxy
+ </span>
+ </label>
+ </div>
+
+ {proxyEnabled && (
+ <div className="flex flex-col gap-2.5 pt-0.5">
+ {/* Proxy Type Segmented Control */}
+ <div className="flex flex-col gap-1">
+ <span className={fieldLabelClass}>Protocol</span>
+ <div className="grid grid-cols-4 gap-1 rounded-md bg-muted/50 p-0.5">
+ {PROXY_TYPES.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ onClick={() => setProxyType(t.id)}
+ className={cn(
+ 'rounded-[4px] py-1 text-center font-mono text-[10px] font-semibold transition-all',
+ proxyType === t.id
+ ? 'bg-background text-foreground shadow-xs'
+ : 'text-muted-foreground hover:text-foreground'
+ )}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Host and Port */}
+ <div className="grid grid-cols-[1fr_80px] gap-2">
+ <div className="flex flex-col gap-1">
+ <label htmlFor={`proxy-host-${interfaceId}`} className={fieldLabelClass}>
+ Host / IP
+ </label>
+ <input
+ id={`proxy-host-${interfaceId}`}
+ type="text"
+ value={proxyHost}
+ onChange={(event) => setProxyHost(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') close()
+ }}
+ placeholder="127.0.0.1"
+ className="rounded-[6px] border border-input bg-background px-[9px] py-1.5 font-mono text-[11px] leading-[1.3] text-foreground outline-none focus-visible:border-ring placeholder:text-muted-foreground/50"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label htmlFor={`proxy-port-${interfaceId}`} className={fieldLabelClass}>
+ Port
+ </label>
+ <input
+ id={`proxy-port-${interfaceId}`}
+ type="text"
+ inputMode="numeric"
+ value={proxyPort}
+ onChange={(event) => setProxyPort(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') close()
+ }}
+ placeholder={proxyType.startsWith('socks') ? '1080' : '8080'}
+ className="rounded-[6px] border border-input bg-background px-[9px] py-1.5 font-mono text-[11px] leading-[1.3] text-foreground outline-none focus-visible:border-ring placeholder:text-muted-foreground/50"
+ />
+ </div>
+ </div>
+
+ {/* Authentication */}
+ <div className="grid grid-cols-2 gap-2">
+ <div className="flex flex-col gap-1">
+ <label htmlFor={`proxy-user-${interfaceId}`} className={fieldLabelClass}>
+ User <span className="text-[8px] font-normal lowercase opacity-70">(opt)</span>
+ </label>
+ <input
+ id={`proxy-user-${interfaceId}`}
+ type="text"
+ value={proxyUsername}
+ onChange={(event) => setProxyUsername(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') close()
+ }}
+ placeholder="username"
+ autoComplete="off"
+ className="rounded-[6px] border border-input bg-background px-[9px] py-1.5 font-sans text-[11px] leading-[1.3] text-foreground outline-none focus-visible:border-ring placeholder:text-muted-foreground/50"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label htmlFor={`proxy-pass-${interfaceId}`} className={fieldLabelClass}>
+ Password{' '}
+ <span className="text-[8px] font-normal lowercase opacity-70">(opt)</span>
+ </label>
+ <input
+ id={`proxy-pass-${interfaceId}`}
+ type="password"
+ value={proxyPassword}
+ onChange={(event) => setProxyPassword(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') close()
+ }}
+ placeholder={proxyType === 'socks4' ? 'N/A' : '••••••••'}
+ autoComplete="off"
+ disabled={proxyType === 'socks4'}
+ className={cn(
+ 'rounded-[6px] border border-input bg-background px-[9px] py-1.5 font-sans text-[11px] leading-[1.3] text-foreground outline-none focus-visible:border-ring placeholder:text-muted-foreground/50',
+ proxyType === 'socks4' && 'cursor-not-allowed bg-muted/40 opacity-50'
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="flex justify-end pt-1">
<Button type="button" size="xs" onClick={close}>
Done
</Button>
diff --git a/src/renderer/src/components/NetworkRow.tsx b/src/renderer/src/components/NetworkRow.tsx
index 35a1d12..502dd10 100644
--- a/src/renderer/src/components/NetworkRow.tsx
+++ b/src/renderer/src/components/NetworkRow.tsx
@@ -1,10 +1,10 @@
import type { HttpBlockState, HttpStreamState, NetworkStatus, SpeedUnit } from '@shared/types'
import { useState } from 'react'
+import { useAppStore } from '../store/useAppStore'
import { DANGER, type NetworkVisual } from '../theme'
import type { HttpNetworkGroup, NetworkGroup, TorrentNetworkGroup } from '../utils/format'
import { describeError, formatBytes, formatSpeedOfLimit, networkActive } from '../utils/format'
import { useFormatSpeed } from '../hooks/useFormatSpeed'
-import { useAppStore } from '../store/useAppStore'
import { ColorBadge } from './ColorBadge'
import { NetworkEditPopover } from './NetworkEditPopover'
import { TruncatedText } from './TruncatedText'
@@ -380,6 +380,9 @@ export function NetworkRow({
const connections = group.transfer === 'http' ? group.streams : group.peers
const isActive = networkActive(group)
const hasError = group.status === 'failed'
+ const preference = useAppStore((store) => store.networkPreferences[group.id])
+ const proxy = preference?.proxy
+ const isProxyActive = Boolean(proxy?.enabled && proxy.host)
const rounded = Math.round(sharePercent)
const shareLabel = group.bytesDownloaded === 0 ? '0%' : rounded === 0 ? '<1%' : `${rounded}%`
const noun = group.transfer === 'http' ? 'stream' : 'peer'
@@ -416,6 +419,16 @@ export function NetworkRow({
interfaceKind={group.kind}
osName={group.label}
/>
+ {isProxyActive && (
+ <ColorBadge
+ bg={visual.bg}
+ border={visual.border}
+ text={visual.text}
+ className="h-[15px] rounded-[3px] px-[5px] py-px font-mono text-[8.5px] font-semibold tracking-[0.06em] uppercase"
+ >
+ PROXY · {proxy!.type}
+ </ColorBadge>
+ )}
{connections.length > 0 && (
<Button
type="button"
diff --git a/src/renderer/src/components/NewDownloadDialog.tsx b/src/renderer/src/components/NewDownloadDialog.tsx
index 430f7d1..b770403 100644
--- a/src/renderer/src/components/NewDownloadDialog.tsx
+++ b/src/renderer/src/components/NewDownloadDialog.tsx
@@ -1,6 +1,15 @@
import type { ProbeResult } from '@shared/types'
import { cn } from 'cn'
-import { AlertTriangle, ChevronLeft, ChevronRight, FolderOpen, Globe, Lock, X } from 'lucide-react'
+import {
+ AlertTriangle,
+ ChevronLeft,
+ ChevronRight,
+ FolderOpen,
+ Globe,
+ Lock,
+ Pencil,
+ X
+} from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'
import { useNetworkUsage } from '../hooks/useNetworks'
@@ -20,6 +29,7 @@ import { Dialog, DialogContent, DialogTitle } from './ui/dialog'
import { ToggleGroup, ToggleGroupItem } from './ui/toggle-group'
import { TorrentFileList } from './TorrentFiles'
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'
+import { NetworkEditPopover } from './NetworkEditPopover'
type ProbeState =
| { status: 'idle' }
@@ -539,43 +549,102 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element
const visual = networkVisual(iface.id, iface.kind, iface.displayName)
const selected = selectedInterfaceIds.includes(iface.id)
const reached = isReached(iface.id)
- const speedLimit = networkPreferences[iface.id]?.speedLimit
+ const preference = networkPreferences[iface.id]
+ const speedLimit = preference?.speedLimit
+ const proxy = preference?.proxy
+ const isProxyActive = Boolean(proxy?.enabled && proxy.host)
// What's worth knowing before it's picked: it can't be, or it's capped.
const note = reached
? 'Data limit reached'
: speedLimit !== undefined
? `Limited to ${formatSpeedLimit(speedLimit)}`
: null
- const chip = (
+
+ const toggleButton = (
<button
- key={iface.id}
type="button"
aria-pressed={selected}
// Not `disabled`: a disabled button never gets the hover that says why.
aria-disabled={reached || undefined}
onClick={() => handleToggleInterface(iface.id)}
className={cn(
- 'flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-[12.5px] transition-colors',
+ 'flex items-center gap-1.5 focus-visible:outline-none cursor-pointer select-none py-1',
+ reached && 'cursor-not-allowed line-through'
+ )}
+ >
+ <span
+ className="size-2 rounded-full shrink-0"
+ style={{ background: visual.solid }}
+ />
+ <span className="truncate">{visual.name}</span>
+ </button>
+ )
+
+ return (
+ <div
+ key={iface.id}
+ className={cn(
+ 'group/chip inline-flex h-7 items-center rounded-full border text-[12.5px] transition-colors pl-2.5 pr-1 gap-1',
selected
? 'border-transparent'
: 'border-border text-[var(--text-secondary)] opacity-70',
- reached && 'cursor-not-allowed line-through opacity-50'
+ reached && 'opacity-50'
)}
style={
selected ? { background: visual.bg, borderColor: visual.border } : undefined
}
>
- <span className="size-2 rounded-full" style={{ background: visual.solid }} />
- {visual.name}
- </button>
- )
- return note === null ? (
- chip
- ) : (
- <Tooltip key={iface.id}>
- <TooltipTrigger render={chip} />
- <TooltipContent>{note}</TooltipContent>
- </Tooltip>
+ {note === null ? (
+ toggleButton
+ ) : (
+ <Tooltip>
+ <TooltipTrigger render={toggleButton} />
+ <TooltipContent>{note}</TooltipContent>
+ </Tooltip>
+ )}
+
+ <NetworkEditPopover
+ interfaceId={iface.id}
+ interfaceKind={iface.kind}
+ osName={iface.displayName}
+ defaultFocusProxy={true}
+ trigger={
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ aria-label={
+ isProxyActive
+ ? `Configure proxy (${proxy!.type.toUpperCase()}) or edit ${visual.name}`
+ : `Configure proxy or edit ${visual.name}`
+ }
+ className={cn(
+ 'h-5 px-1.5 rounded-full text-muted-foreground hover:text-foreground shrink-0 gap-1 flex items-center font-mono text-[9px] uppercase tracking-[0.04em]',
+ isProxyActive
+ ? 'font-semibold text-foreground bg-foreground/10 hover:bg-foreground/15'
+ : 'hover:bg-foreground/10'
+ )}
+ >
+ {isProxyActive ? (
+ <>
+ <span>PROXY · {proxy!.type}</span>
+ <Pencil className="size-2.5 opacity-70" />
+ </>
+ ) : (
+ <>
+ <Pencil className="size-2.5 opacity-70" />
+ <span className="capitalize font-sans text-[10.5px]">Proxy</span>
+ </>
+ )}
+ </Button>
+ }
+ tooltip={
+ isProxyActive
+ ? `Proxy active (${proxy!.type.toUpperCase()} · ${proxy!.host}:${proxy!.port}) — click to configure`
+ : `Configure proxy or edit ${visual.name}`
+ }
+ />
+ </div>
)
})}
</div>
diff --git a/src/renderer/src/components/ui/popover.tsx b/src/renderer/src/components/ui/popover.tsx
index bba7f81..4251168 100644
--- a/src/renderer/src/components/ui/popover.tsx
+++ b/src/renderer/src/components/ui/popover.tsx
@@ -31,12 +31,12 @@ function PopoverContent({
side={side}
sideOffset={sideOffset}
collisionPadding={collisionPadding}
- className="isolate z-50"
+ className="isolate z-[60]"
>
<PopoverPrimitive.Popup
data-slot="popover-content"
className={cn(
- 'z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ 'z-[60] flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className
)}
{...props}
diff --git a/src/renderer/src/components/ui/tooltip.tsx b/src/renderer/src/components/ui/tooltip.tsx
index 852fd2e..551cf97 100644
--- a/src/renderer/src/components/ui/tooltip.tsx
+++ b/src/renderer/src/components/ui/tooltip.tsx
@@ -39,12 +39,12 @@ function TooltipContent({
sideOffset={sideOffset}
// Flips below rather than open under the title bar and its window controls.
collisionPadding={{ top: TITLE_BAR_HEIGHT + 4, right: 5, bottom: 5, left: 5 }}
- className="isolate z-50"
+ className="isolate z-[70]"
>
<TooltipPrimitive.Popup
data-slot="tooltip-content"
className={cn(
- 'z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ 'z-[70] inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className
)}
{...props}
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index e1a525e..342aa7d 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -42,6 +42,26 @@ const ERROR_HINTS: Array<{ pattern: RegExp; message: string }> = [
message:
'The downloaded file has an unexpected size. Plexo couldn’t save the completed file. Try downloading again.'
},
+ {
+ pattern: /Proxy authentication required|HTTP 407/i,
+ message: 'Proxy authentication failed — check your proxy username and password.'
+ },
+ {
+ pattern: /SOCKS5 authentication failed/i,
+ message: 'SOCKS5 proxy authentication failed — check your username and password.'
+ },
+ {
+ pattern: /Connecting to proxy .* timed out/i,
+ message: 'Connecting to proxy timed out — check the proxy host, port, and your network.'
+ },
+ {
+ pattern: /Proxy CONNECT failed/i,
+ message: 'The HTTP proxy rejected the connection request.'
+ },
+ {
+ pattern: /SOCKS[45] connection (?:rejected|failed)/i,
+ message: 'The SOCKS proxy rejected the connection — check your proxy settings.'
+ },
{
pattern: /ENOTFOUND|EAI_AGAIN/,
message: 'Plexo couldn’t find the server. Check the link and your connection.'
diff --git a/src/shared/types.ts b/src/shared/types.ts
index ab0eff2..60580a2 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -298,6 +298,17 @@ export type DownloadUpdate = HttpDownloadUpdate | TorrentDownloadUpdate
/** User customization for one physical network, keyed by NetworkInterfaceInfo.id — lets a
* cryptic OS device name (e.g. "feth0") get a real label, and a color distinct from its
* kind's default. Persisted in the main process, independent of any single download. */
+export type ProxyType = 'http' | 'https' | 'socks4' | 'socks5'
+
+export interface ProxyConfig {
+ enabled: boolean
+ type: ProxyType
+ host: string
+ port: number
+ username?: string
+ password?: string
+}
+
export type DataLimitPeriod = 'day' | 'week' | 'month'
export interface NetworkPreference {
@@ -305,6 +316,8 @@ export interface NetworkPreference {
/** One of the app's curated swatch ids (see NETWORK_COLOR_SWATCHES) — not a raw hex, so every
* swatch is guaranteed to have a legible on-solid text color already picked out for it. */
colorId?: string
+ /** Optional per-interface proxy configuration. */
+ proxy?: ProxyConfig
/** Left out of the last download started, so New download starts without it too (it remembers
* the last pick, like the folder). A click there puts it back. */
off?: boolean