Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(desktop): proxy background account gateways (#3639)

Hampus1f41d7ea07b5
diff --git a/fluxer_desktop/src/engine/AccountEngine.ts b/fluxer_desktop/src/engine/AccountEngine.ts
index 01cea038d..8a974687f 100644
--- a/fluxer_desktop/src/engine/AccountEngine.ts
+++ b/fluxer_desktop/src/engine/AccountEngine.ts
@@ -1,11 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {
- AccountSession,
- type AdmittedGateway,
- accountTokenTag,
- type PersistedAccountSummary,
-} from '@electron/engine/AccountSession';
+import {AccountSession, accountTokenTag, type PersistedAccountSummary} from '@electron/engine/AccountSession';
import {CacheDatabase} from '@electron/engine/CacheDatabase';
import {DispatchPump} from '@electron/engine/DispatchPump';
import type {EngineClock, EngineTimer} from '@electron/engine/EngineClock';
@@ -14,6 +9,7 @@ import type {GatewayTransportFactory} from '@electron/engine/GatewayTransport';
import type {EngineMessagePort} from '@electron/engine/HostChannel';
import {
ACCOUNT_ENGINE_HOST_PROTOCOL_VERSION,
+ type AdmittedGateway,
type EngineAccountRecord,
type EngineInitMessage,
type EngineLogLevel,
@@ -561,7 +557,7 @@ export class AccountEngine {
if (response.type !== 'admitResult' || !response.ok || response.url === null) {
throw new Error(response.type === 'admitResult' ? (response.error ?? 'Admission refused') : 'Admission refused');
}
- return {url: response.url, address: response.address};
+ return {url: response.url, address: response.address, proxy: response.proxy};
}
private hostRequest(message: Extract<EngineToHostMessage, {type: 'admit' | 'http'}>): Promise<HostToEngineMessage> {
diff --git a/fluxer_desktop/src/engine/AccountSession.ts b/fluxer_desktop/src/engine/AccountSession.ts
index 9358c8560..b1b6b18c6 100644
--- a/fluxer_desktop/src/engine/AccountSession.ts
+++ b/fluxer_desktop/src/engine/AccountSession.ts
@@ -12,7 +12,7 @@ import {
type GatewayResumeState,
} from '@electron/engine/GatewayClient';
import type {GatewayTransportFactory} from '@electron/engine/GatewayTransport';
-import type {EngineAccountRecord, EngineLogLevel} from '@electron/engine/HostProtocol';
+import type {AdmittedGateway, EngineAccountRecord, EngineLogLevel} from '@electron/engine/HostProtocol';
import {SCHEDULER_LIMITS, type SchedulerClient, type SessionScheduler} from '@electron/engine/SessionScheduler';
import {
ACCOUNT_ENGINE_LIMITS,
@@ -46,11 +46,6 @@ const INVALID_SESSION_MAX_DELAY_MS = 5_000;
const DECODE_RETRY_DELAY_MS = 1_000;
const SUBSCRIPTION_RELEASE_SETTLE_MS = 250;
-export interface AdmittedGateway {
- readonly url: string;
- readonly address: string | null;
-}
-
export interface AccountSessionDependencies {
readonly clock: EngineClock;
readonly scheduler: SessionScheduler;
@@ -645,6 +640,7 @@ export class AccountSession implements SchedulerClient, DispatchConsumer {
const client: GatewayClient = new GatewayClient({
gatewayUrl: admitted.url,
address: admitted.address,
+ proxy: admitted.proxy,
token: this.token,
config,
resume,
diff --git a/fluxer_desktop/src/engine/GatewayClient.ts b/fluxer_desktop/src/engine/GatewayClient.ts
index 6777d0ab6..025091f69 100644
--- a/fluxer_desktop/src/engine/GatewayClient.ts
+++ b/fluxer_desktop/src/engine/GatewayClient.ts
@@ -80,6 +80,7 @@ interface GatewayClientHandlers {
export interface GatewayClientOptions {
readonly gatewayUrl: string;
readonly address: string | null;
+ readonly proxy: string | null;
readonly token: string;
readonly config: AccountEngineClientConfig;
readonly resume: GatewayResumeState | null;
@@ -163,6 +164,7 @@ export class GatewayClient {
this.connection = this.options.transport({
url,
address: this.options.address,
+ proxy: this.options.proxy,
onEvent: (event) => this.handleTransportEvent(event),
});
} catch (error) {
diff --git a/fluxer_desktop/src/engine/GatewayTransport.ts b/fluxer_desktop/src/engine/GatewayTransport.ts
index 9322acc09..8647651c9 100644
--- a/fluxer_desktop/src/engine/GatewayTransport.ts
+++ b/fluxer_desktop/src/engine/GatewayTransport.ts
@@ -4,7 +4,7 @@ import type {LookupAddress} from 'node:dns';
import {createRequire} from 'node:module';
import {isIP, type LookupFunction} from 'node:net';
import {errorMessage} from '@electron/common/ErrorMessage';
-import {Agent, WebSocket} from 'undici';
+import {Agent, type Dispatcher, ProxyAgent, WebSocket} from 'undici';
export type GatewayTransportEvent =
| {readonly kind: 'open'}
@@ -22,6 +22,7 @@ export interface GatewayTransportConnection {
interface GatewayTransportConnectRequest {
readonly url: string;
readonly address: string | null;
+ readonly proxy: string | null;
readonly onEvent: (event: GatewayTransportEvent) => void;
}
@@ -112,13 +113,16 @@ interface WebSocketGatewayTransportOptions {
function createWebSocketGatewayTransport(options: WebSocketGatewayTransportOptions = {}): GatewayTransportFactory {
const trustedCertificates = options.trustedCertificates ?? [];
const trust = trustedCertificates.length > 0 ? {ca: [...trustedCertificates]} : {};
- return ({url, address, onEvent}) => {
- const dispatcher = new Agent({
- connect: {
- ...(address === null ? {} : {lookup: pinnedLookup(address)}),
- ...trust,
- },
- });
+ return ({url, address, proxy, onEvent}) => {
+ const dispatcher: Dispatcher =
+ proxy === null
+ ? new Agent({
+ connect: {
+ ...(address === null ? {} : {lookup: pinnedLookup(address)}),
+ ...trust,
+ },
+ })
+ : new ProxyAgent({uri: proxy, proxyTunnel: true, requestTls: trust, proxyTls: trust});
let terminated = false;
const finish = (event: GatewayTransportEvent): void => {
if (terminated) {
@@ -177,24 +181,29 @@ export function resolveGatewayTransport({
preferWebSocket,
trustedCertificates,
}: GatewayTransportPreferences): ResolvedGatewayTransport {
- const fallback = (): GatewayTransportFactory => createWebSocketGatewayTransport({trustedCertificates});
+ const websocket = createWebSocketGatewayTransport({trustedCertificates});
if (preferWebSocket) {
- return {factory: fallback(), kind: 'websocket', loadError: null};
+ return {factory: websocket, kind: 'websocket', loadError: null};
}
try {
const requireModule = typeof require === 'function' ? require : createRequire(import.meta.url);
const addon = requireModule('@fluxer/gateway-socket') as {connect: NativeConnect | null; loadError: Error | null};
if (addon.connect !== null) {
- return {factory: createNativeGatewayTransport(addon.connect), kind: 'native', loadError: null};
+ const native = createNativeGatewayTransport(addon.connect);
+ return {
+ factory: (request) => (request.proxy === null ? native(request) : websocket(request)),
+ kind: 'native',
+ loadError: null,
+ };
}
return {
- factory: fallback(),
+ factory: websocket,
kind: 'websocket',
loadError: addon.loadError?.message ?? 'The gateway socket addon has no connect binding',
};
} catch (error) {
return {
- factory: fallback(),
+ factory: websocket,
kind: 'websocket',
loadError: errorMessage(error),
};
diff --git a/fluxer_desktop/src/engine/HostProtocol.ts b/fluxer_desktop/src/engine/HostProtocol.ts
index e493fd435..b5c238559 100644
--- a/fluxer_desktop/src/engine/HostProtocol.ts
+++ b/fluxer_desktop/src/engine/HostProtocol.ts
@@ -29,6 +29,12 @@ export interface EngineInitMessage {
readonly trustedCertificates: ReadonlyArray<string>;
}
+export interface AdmittedGateway {
+ readonly url: string;
+ readonly address: string | null;
+ readonly proxy: string | null;
+}
+
export type HostToEngineMessage =
| EngineInitMessage
| {readonly type: 'accounts'; readonly accounts: ReadonlyArray<EngineAccountRecord>}
@@ -40,6 +46,7 @@ export type HostToEngineMessage =
readonly ok: boolean;
readonly url: string | null;
readonly address: string | null;
+ readonly proxy: string | null;
readonly error: string | null;
}
| {
diff --git a/fluxer_desktop/src/main/AccountEngineHost.ts b/fluxer_desktop/src/main/AccountEngineHost.ts
index 28a968de9..4bb1b61a6 100644
--- a/fluxer_desktop/src/main/AccountEngineHost.ts
+++ b/fluxer_desktop/src/main/AccountEngineHost.ts
@@ -4,6 +4,7 @@ import {errorMessage} from '@electron/common/ErrorMessage';
import {
ACCOUNT_ENGINE_HOST_PROTOCOL_VERSION,
+ type AdmittedGateway,
type EngineAccountRecord,
type EnginePowerEvent,
type EngineToHostMessage,
@@ -45,7 +46,7 @@ export interface AccountEngineHttpResult {
export interface AccountEngineHostDependencies {
readonly fork: () => AccountEngineProcess;
readonly readAccounts: () => Promise<ReadonlyArray<AccountEngineAccountEntry>>;
- readonly admit: (entry: AccountEngineAccountEntry, url: string) => Promise<{url: string; address: string | null}>;
+ readonly admit: (entry: AccountEngineAccountEntry, url: string) => Promise<AdmittedGateway>;
readonly http: (
entry: AccountEngineAccountEntry,
method: 'POST',
@@ -376,6 +377,7 @@ export class AccountEngineHostController {
ok: true,
url: admitted.url,
address: admitted.address,
+ proxy: admitted.proxy,
error: null,
});
} catch (error) {
@@ -385,6 +387,7 @@ export class AccountEngineHostController {
ok: false,
url: null,
address: null,
+ proxy: null,
error: errorMessage(error),
});
}
diff --git a/fluxer_desktop/src/main/AccountEngineIpc.ts b/fluxer_desktop/src/main/AccountEngineIpc.ts
index 0c7055977..2bb4852f9 100644
--- a/fluxer_desktop/src/main/AccountEngineIpc.ts
+++ b/fluxer_desktop/src/main/AccountEngineIpc.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import path from 'node:path';
-import type {EngineTokenPersistOutcome} from '@electron/engine/HostProtocol';
+import type {AdmittedGateway, EngineTokenPersistOutcome} from '@electron/engine/HostProtocol';
import {
type AccountEngineAccountEntry,
parseAccountEngineEntries,
@@ -24,7 +24,6 @@ import {
readBoundedMessage,
readMessageContentLength,
} from '@electron/main/DesktopOutboundHTTP';
-import {isDirectProxyRoute} from '@electron/main/DesktopSessionHTTP';
import {resolveDesktopGatewayTrustedCertificates} from '@electron/main/DesktopSystemTrustVerifier';
import {getGatewayOriginRegistry} from '@electron/main/GatewayOriginRegistry';
import {prefersAccountEngineWebSocketTransport} from '@electron/main/LaunchOptions';
@@ -103,23 +102,33 @@ async function readEngineAccounts(): Promise<ReadonlyArray<AccountEngineAccountE
return parseAccountEngineEntries(await storage.getAllAccounts());
}
-async function admitEngineGateway(
- entry: AccountEngineAccountEntry,
- url: string,
-): Promise<{url: string; address: string | null}> {
- await getGatewayOriginRegistry().admitAnchored({url, anchor: entry.record.apiEndpoint});
- const route = await session.defaultSession.resolveProxy(url.replace(/^ws/u, 'http'));
- if (!isDirectProxyRoute(route)) {
- throw new Error('The gateway resolves through a proxy');
+function engineGatewayProxy(route: string): string | null {
+ for (const entry of route.split(';')) {
+ const [scheme = '', hostPort = ''] = entry.trim().split(/\s+/u);
+ switch (scheme.toUpperCase()) {
+ case 'DIRECT':
+ return null;
+ case 'PROXY':
+ return `http://${hostPort}`;
+ case 'HTTPS':
+ return `https://${hostPort}`;
+ }
}
+ throw new Error(`The gateway resolves through a proxy the account engine cannot use: ${route}`);
+}
+
+async function admitEngineGateway(entry: AccountEngineAccountEntry, url: string): Promise<AdmittedGateway> {
+ await getGatewayOriginRegistry().admitAnchored({url, anchor: entry.record.apiEndpoint});
+ const proxy = engineGatewayProxy(await session.defaultSession.resolveProxy(url.replace(/^ws/u, 'http')));
if (new URL(url).protocol !== 'ws:') {
- return {url, address: null};
+ return {url, address: null, proxy};
}
const httpOrigin = websocketHTTPOrigin(url);
if (httpOrigin == null) {
throw new Error('The gateway has no HTTP origin');
}
- return {url, address: await getDesktopOutboundHTTP().requireCleartextTransportAddress(httpOrigin)};
+ const address = await getDesktopOutboundHTTP().requireCleartextTransportAddress(httpOrigin);
+ return {url, address: proxy === null ? address : null, proxy};
}
async function engineHttp(