Skip to content

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

TypeScript fluxerfluxerapp

feat(desktop): host the account engine from the main process

Hampusaaae0a612755
diff --git a/fluxer_desktop/src/main/AccountEngineAccounts.ts b/fluxer_desktop/src/main/AccountEngineAccounts.ts
new file mode 100644
index 000000000..1cdd266e1
--- /dev/null
+++ b/fluxer_desktop/src/main/AccountEngineAccounts.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {type EngineAccountRecord, parseEngineAccountRecord} from '@electron/engine/HostProtocol';
+import type {DesktopAccountRecord} from '@fluxer/desktop_ipc/src/AccountContract';
+import {ACCOUNT_ENGINE_LIMITS, accountEngineInstanceKey} from '@fluxer/desktop_ipc/src/AccountEngineContract';
+
+export interface AccountEngineAccountLabel {
+ readonly accountKey: string;
+ readonly displayName: string;
+ readonly instanceHost: string;
+ readonly switcherPosition: number | null;
+}
+
+export interface AccountEngineAccountEntry {
+ readonly record: EngineAccountRecord;
+ readonly label: AccountEngineAccountLabel;
+ readonly apiCodeVersion: number;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+function nonEmptyString(value: unknown): string | null {
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
+}
+
+function hostOf(endpoint: string): string {
+ try {
+ return new URL(endpoint).host;
+ } catch {
+ return endpoint;
+ }
+}
+
+function parseAccountEngineEntry(stored: DesktopAccountRecord): AccountEngineAccountEntry | null {
+ const record = asRecord(stored.record);
+ const instance = asRecord(record?.instance);
+ const instanceKey = accountEngineInstanceKey(stored.storageKey);
+ if (record === null || instance === null || instanceKey === null) {
+ return null;
+ }
+ const apiCodeVersion = instance.apiCodeVersion;
+ if (typeof apiCodeVersion !== 'number' || !Number.isSafeInteger(apiCodeVersion) || apiCodeVersion <= 0) {
+ return null;
+ }
+ const engineRecord = parseEngineAccountRecord({
+ accountKey: stored.storageKey,
+ userId: record.userId,
+ instanceKey,
+ token: record.token,
+ gatewayEndpoint: instance.gatewayEndpoint,
+ apiEndpoint: instance.apiEndpoint,
+ isValid: record.isValid !== false,
+ lastActive: typeof record.lastActive === 'number' && Number.isFinite(record.lastActive) ? record.lastActive : 0,
+ });
+ if (engineRecord === null) {
+ return null;
+ }
+ const userData = asRecord(record.userData);
+ const displayName =
+ nonEmptyString(userData?.global_name) ??
+ nonEmptyString(userData?.globalName) ??
+ nonEmptyString(userData?.username) ??
+ engineRecord.userId;
+ return {
+ record: engineRecord,
+ label: {
+ accountKey: engineRecord.accountKey,
+ displayName,
+ instanceHost: hostOf(nonEmptyString(instance.webAppEndpoint) ?? engineRecord.apiEndpoint),
+ switcherPosition:
+ typeof record.switcherPosition === 'number' && Number.isSafeInteger(record.switcherPosition)
+ ? record.switcherPosition
+ : null,
+ },
+ apiCodeVersion,
+ };
+}
+
+export function parseAccountEngineEntries(
+ stored: ReadonlyArray<DesktopAccountRecord>,
+): Array<AccountEngineAccountEntry> {
+ const entries: Array<AccountEngineAccountEntry> = [];
+ for (const record of stored) {
+ const entry = parseAccountEngineEntry(record);
+ if (entry !== null) {
+ entries.push(entry);
+ }
+ }
+ return entries;
+}
+
+export function parseProvidedAccountEngineEntries(value: unknown): Array<AccountEngineAccountEntry> | null {
+ if (!Array.isArray(value) || value.length > ACCOUNT_ENGINE_LIMITS.providedAccountsMax) {
+ return null;
+ }
+ const records: Array<DesktopAccountRecord> = [];
+ for (const entry of value) {
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
+ return null;
+ }
+ const {storageKey, record} = entry as {storageKey?: unknown; record?: unknown};
+ if (typeof storageKey !== 'string' || typeof record !== 'object' || record === null || Array.isArray(record)) {
+ return null;
+ }
+ records.push({storageKey, record: record as DesktopAccountRecord['record']});
+ }
+ return parseAccountEngineEntries(records);
+}
+
+export function rotateStoredAccountToken(
+ stored: DesktopAccountRecord,
+ previousToken: string,
+ token: string,
+): DesktopAccountRecord | null {
+ const record = asRecord(stored.record);
+ if (record === null || record.token !== previousToken) {
+ return null;
+ }
+ return {storageKey: stored.storageKey, record: {...stored.record, token}};
+}
+
+export function rendererHoldsAccount(provided: ReadonlyArray<AccountEngineAccountEntry>, accountKey: string): boolean {
+ return provided.some((entry) => entry.record.accountKey === accountKey);
+}
diff --git a/fluxer_desktop/src/main/AccountEngineHost.ts b/fluxer_desktop/src/main/AccountEngineHost.ts
new file mode 100644
index 000000000..bdc37e8d9
--- /dev/null
+++ b/fluxer_desktop/src/main/AccountEngineHost.ts
@@ -0,0 +1,499 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {errorMessage} from '@electron/common/ErrorMessage';
+
+import {
+ ACCOUNT_ENGINE_HOST_PROTOCOL_VERSION,
+ type EngineAccountRecord,
+ type EnginePowerEvent,
+ type EngineToHostMessage,
+ type EngineTokenPersistOutcome,
+ type HostToEngineMessage,
+} from '@electron/engine/HostProtocol';
+import type {AccountEngineAccountEntry, AccountEngineAccountLabel} from '@electron/main/AccountEngineAccounts';
+import {
+ type AccountEngineAccountSummary,
+ AccountEngineConnectionState,
+} from '@fluxer/desktop_ipc/src/AccountEngineContract';
+
+const ACCOUNT_ENGINE_RESTART_DELAYS_MS = Object.freeze([1_000, 2_000, 5_000, 10_000, 30_000]);
+const ACCOUNT_ENGINE_CRASH_WINDOW_MS = 10 * 60 * 1000;
+const ACCOUNT_ENGINE_CRASH_LIMIT = 5;
+const ACCOUNT_ENGINE_ACCOUNTS_DEBOUNCE_MS = 100;
+const ACCOUNT_ENGINE_ACCOUNTS_RETRY_MS = 5_000;
+const ACCOUNT_ENGINE_SHUTDOWN_TIMEOUT_MS = 3_000;
+
+export interface AccountEngineProcess {
+ postMessage(message: HostToEngineMessage, transfer?: ReadonlyArray<unknown>): void;
+ onMessage(listener: (message: EngineToHostMessage) => void): void;
+ onExit(listener: (code: number) => void): void;
+ kill(): void;
+}
+
+export interface AccountEngineRendererLink {
+ createPortPair(): {readonly engine: unknown; readonly renderer: unknown};
+ deliver(port: unknown): boolean;
+ isCurrent(): boolean;
+}
+
+export interface AccountEngineHttpResult {
+ readonly ok: boolean;
+ readonly status: number;
+ readonly body: string | null;
+}
+
+export interface AccountEngineHostDependencies {
+ readonly fork: () => AccountEngineProcess;
+ readonly readAccounts: () => Promise<ReadonlyArray<AccountEngineAccountEntry>>;
+ readonly admit: (entry: AccountEngineAccountEntry, url: string) => Promise<{url: string; address: string | null}>;
+ readonly http: (
+ entry: AccountEngineAccountEntry,
+ method: 'POST',
+ path: string,
+ body: string | null,
+ ) => Promise<AccountEngineHttpResult>;
+ readonly persistRotatedToken: (
+ accountKey: string,
+ previousToken: string,
+ token: string,
+ ) => Promise<EngineTokenPersistOutcome>;
+ readonly log: (level: 'debug' | 'info' | 'warn' | 'error', message: string, detail?: unknown) => void;
+ readonly now: () => number;
+ readonly setTimeout: (callback: () => void, delayMs: number) => unknown;
+ readonly clearTimeout: (timer: unknown) => void;
+ readonly cachePath: string;
+ readonly preferWebSocket: boolean;
+ readonly trustedCertificates: () => ReadonlyArray<string>;
+}
+
+export interface AccountEngineLabel extends AccountEngineAccountLabel {
+ readonly isForeground: boolean;
+}
+
+const ENGINE_HTTP_ROUTES: ReadonlyArray<{readonly method: 'POST'; readonly path: RegExp}> = [
+ {method: 'POST', path: /^\/channels\/\d{1,20}\/messages\/\d{1,20}\/ack$/u},
+];
+
+function isAllowedEngineHttpRequest(method: string, path: string): boolean {
+ return ENGINE_HTTP_ROUTES.some((route) => route.method === method && route.path.test(path));
+}
+
+type SummaryListener = (summaries: ReadonlyArray<AccountEngineAccountSummary>) => void;
+
+function foregroundHint(entries: ReadonlyArray<AccountEngineAccountEntry>): string | null {
+ let best: EngineAccountRecord | null = null;
+ for (const {record} of entries) {
+ if (record.isValid && (best === null || record.lastActive > best.lastActive)) {
+ best = record;
+ }
+ }
+ return best?.accountKey ?? null;
+}
+
+export class AccountEngineHostController {
+ private readonly deps: AccountEngineHostDependencies;
+ private process: AccountEngineProcess | null = null;
+ private entries = new Map<string, AccountEngineAccountEntry>();
+ private readonly summaries = new Map<string, AccountEngineAccountSummary>();
+ private readonly listeners = new Set<SummaryListener>();
+ private readonly crashes: Array<number> = [];
+ private renderer: AccountEngineRendererLink | null = null;
+ private restartTimer: unknown = null;
+ private accountsTimer: unknown = null;
+ private readonly accountsRetryTimers = new Set<unknown>();
+ private stopping = false;
+ private available = true;
+ private started = false;
+ private shutdownResolve: (() => void) | null = null;
+
+ constructor(deps: AccountEngineHostDependencies) {
+ this.deps = deps;
+ }
+
+ get isAvailable(): boolean {
+ return this.available;
+ }
+
+ async start(): Promise<void> {
+ if (this.started) {
+ return;
+ }
+ this.started = true;
+ await this.spawn();
+ }
+
+ accountsChanged(): void {
+ if (!this.started || this.stopping || this.accountsTimer !== null) {
+ return;
+ }
+ this.accountsTimer = this.deps.setTimeout(() => {
+ this.accountsTimer = null;
+ void this.pushAccounts();
+ }, ACCOUNT_ENGINE_ACCOUNTS_DEBOUNCE_MS);
+ }
+
+ attachRenderer(link: AccountEngineRendererLink): boolean {
+ if (!this.available || this.process === null || this.stopping) {
+ return false;
+ }
+ this.renderer = link;
+ return this.connectRenderer(link);
+ }
+
+ detachRenderer(link: AccountEngineRendererLink): void {
+ if (this.renderer !== link) {
+ return;
+ }
+ this.renderer = null;
+ this.process?.postMessage({type: 'detachRenderer'});
+ }
+
+ power(event: EnginePowerEvent): void {
+ this.process?.postMessage({type: 'power', event});
+ }
+
+ getSummaries(): ReadonlyArray<AccountEngineAccountSummary> {
+ return Array.from(this.summaries.values());
+ }
+
+ getLabels(): ReadonlyArray<AccountEngineLabel> {
+ return Array.from(this.entries.values(), ({label}) => ({
+ ...label,
+ isForeground: this.summaries.get(label.accountKey)?.state === AccountEngineConnectionState.FOREGROUND,
+ }));
+ }
+
+ onSummaries(listener: SummaryListener): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+
+ shutdown(): Promise<void> {
+ this.stopping = true;
+ if (this.restartTimer !== null) {
+ this.deps.clearTimeout(this.restartTimer);
+ this.restartTimer = null;
+ }
+ if (this.accountsTimer !== null) {
+ this.deps.clearTimeout(this.accountsTimer);
+ this.accountsTimer = null;
+ }
+ for (const timer of this.accountsRetryTimers) {
+ this.deps.clearTimeout(timer);
+ }
+ this.accountsRetryTimers.clear();
+ const engine = this.process;
+ if (engine === null) {
+ return Promise.resolve();
+ }
+ return new Promise<void>((resolve) => {
+ const timer = this.deps.setTimeout(() => {
+ this.deps.log('warn', 'The account engine did not exit in time, killing it');
+ engine.kill();
+ finish();
+ }, ACCOUNT_ENGINE_SHUTDOWN_TIMEOUT_MS);
+ const finish = (): void => {
+ this.deps.clearTimeout(timer);
+ this.shutdownResolve = null;
+ resolve();
+ };
+ this.shutdownResolve = finish;
+ engine.postMessage({type: 'shutdown'});
+ });
+ }
+
+ private async spawn(): Promise<void> {
+ let entries: ReadonlyArray<AccountEngineAccountEntry> = Array.from(this.entries.values());
+ let accountsComplete = true;
+ try {
+ entries = await this.deps.readAccounts();
+ } catch (error) {
+ accountsComplete = false;
+ this.deps.log('warn', 'Account engine could not read accounts', error);
+ }
+ if (this.stopping) {
+ return;
+ }
+ this.entries = new Map(entries.map((entry) => [entry.record.accountKey, entry]));
+ let engine: AccountEngineProcess;
+ try {
+ engine = this.deps.fork();
+ } catch (error) {
+ this.deps.log('error', 'Account engine could not start', error);
+ this.handleExit(null, -1);
+ return;
+ }
+ this.process = engine;
+ engine.onMessage((message) => this.handleMessage(engine, message));
+ engine.onExit((code) => this.handleExit(engine, code));
+ engine.postMessage({
+ type: 'init',
+ protocol: ACCOUNT_ENGINE_HOST_PROTOCOL_VERSION,
+ cachePath: this.deps.cachePath,
+ foregroundHint: this.currentForeground() ?? foregroundHint(entries),
+ accounts: entries.map((entry) => entry.record),
+ accountsComplete,
+ preferWebSocket: this.deps.preferWebSocket,
+ trustedCertificates: this.deps.trustedCertificates(),
+ });
+ if (!accountsComplete) {
+ this.accountsChanged();
+ }
+ const renderer = this.renderer;
+ if (renderer?.isCurrent()) {
+ this.connectRenderer(renderer);
+ }
+ }
+
+ private currentForeground(): string | null {
+ for (const summary of this.summaries.values()) {
+ if (summary.state === AccountEngineConnectionState.FOREGROUND && this.entries.has(summary.accountKey)) {
+ return summary.accountKey;
+ }
+ }
+ return null;
+ }
+
+ private connectRenderer(link: AccountEngineRendererLink): boolean {
+ const engine = this.process;
+ if (engine === null) {
+ return false;
+ }
+ const pair = link.createPortPair();
+ engine.postMessage({type: 'attachRenderer'}, [pair.engine]);
+ return link.deliver(pair.renderer);
+ }
+
+ private async pushAccounts(): Promise<void> {
+ let entries: ReadonlyArray<AccountEngineAccountEntry>;
+ try {
+ entries = await this.deps.readAccounts();
+ } catch (error) {
+ this.deps.log('warn', 'Account engine could not read accounts', error);
+ if (this.stopping) {
+ return;
+ }
+ const timer = this.deps.setTimeout(() => {
+ this.accountsRetryTimers.delete(timer);
+ this.accountsChanged();
+ }, ACCOUNT_ENGINE_ACCOUNTS_RETRY_MS);
+ this.accountsRetryTimers.add(timer);
+ return;
+ }
+ this.entries = new Map(entries.map((entry) => [entry.record.accountKey, entry]));
+ for (const accountKey of Array.from(this.summaries.keys())) {
+ if (!this.entries.has(accountKey)) {
+ this.summaries.delete(accountKey);
+ }
+ }
+ this.process?.postMessage({type: 'accounts', accounts: entries.map((entry) => entry.record)});
+ }
+
+ private handleMessage(engine: AccountEngineProcess, message: EngineToHostMessage): void {
+ if (engine !== this.process || typeof message !== 'object' || message === null) {
+ return;
+ }
+ switch (message.type) {
+ case 'ready':
+ this.deps.log('info', 'Account engine gateway transport', {transport: message.transport});
+ if (message.transportError !== null) {
+ this.deps.log('warn', 'Account engine uses the WebSocket fallback transport', message.transportError);
+ }
+ return;
+ case 'admit':
+ void this.answerAdmit(engine, message.requestId, message.accountKey, message.url);
+ return;
+ case 'http':
+ void this.answerHttp(engine, message);
+ return;
+ case 'tokenRotated':
+ void this.persistToken(engine, message.accountKey, message.previousToken, message.token);
+ return;
+ case 'summaries':
+ this.storeSummaries(message.summaries);
+ return;
+ case 'removed':
+ for (const accountKey of message.accountKeys) {
+ this.summaries.delete(accountKey);
+ }
+ this.notify();
+ return;
+ case 'health':
+ this.deps.log('info', 'Account engine health', {
+ rss: message.rss,
+ heapUsed: message.heapUsed,
+ sessions: message.sessions,
+ });
+ return;
+ case 'log':
+ this.deps.log(message.level, `[AccountEngine] ${message.message}`, message.detail ?? undefined);
+ return;
+ case 'shutdownComplete':
+ return;
+ }
+ }
+
+ private storeSummaries(summaries: ReadonlyArray<AccountEngineAccountSummary>): void {
+ for (const summary of summaries) {
+ if (this.entries.has(summary.accountKey)) {
+ this.summaries.set(summary.accountKey, summary);
+ }
+ }
+ this.notify();
+ }
+
+ private notify(): void {
+ const summaries = this.getSummaries();
+ for (const listener of Array.from(this.listeners)) {
+ try {
+ listener(summaries);
+ } catch (error) {
+ this.deps.log('warn', 'Account engine summary listener failed', error);
+ }
+ }
+ }
+
+ private async answerAdmit(
+ engine: AccountEngineProcess,
+ requestId: number,
+ accountKey: string,
+ url: string,
+ ): Promise<void> {
+ const entry = this.entries.get(accountKey);
+ try {
+ if (entry === undefined) {
+ throw new Error('Unknown account');
+ }
+ if (url !== entry.record.gatewayEndpoint) {
+ throw new Error('The gateway does not match the account record');
+ }
+ const admitted = await this.deps.admit(entry, url);
+ engine.postMessage({
+ type: 'admitResult',
+ requestId,
+ ok: true,
+ url: admitted.url,
+ address: admitted.address,
+ error: null,
+ });
+ } catch (error) {
+ engine.postMessage({
+ type: 'admitResult',
+ requestId,
+ ok: false,
+ url: null,
+ address: null,
+ error: errorMessage(error),
+ });
+ }
+ }
+
+ private async answerHttp(
+ engine: AccountEngineProcess,
+ message: Extract<EngineToHostMessage, {type: 'http'}>,
+ ): Promise<void> {
+ const entry = this.entries.get(message.accountKey);
+ try {
+ if (entry === undefined) {
+ throw new Error('Unknown account');
+ }
+ if (!isAllowedEngineHttpRequest(message.method, message.path)) {
+ throw new Error('Invalid request path');
+ }
+ const result = await this.deps.http(entry, message.method, message.path, message.body);
+ engine.postMessage({
+ type: 'httpResult',
+ requestId: message.requestId,
+ ok: result.ok,
+ status: result.status,
+ body: result.body,
+ error: null,
+ });
+ } catch (error) {
+ engine.postMessage({
+ type: 'httpResult',
+ requestId: message.requestId,
+ ok: false,
+ status: 0,
+ body: null,
+ error: errorMessage(error),
+ });
+ }
+ }
+
+ private async persistToken(
+ engine: AccountEngineProcess,
+ accountKey: string,
+ previousToken: string,
+ token: string,
+ ): Promise<void> {
+ let outcome: EngineTokenPersistOutcome = 'rejected';
+ try {
+ outcome = await this.deps.persistRotatedToken(accountKey, previousToken, token);
+ } catch (error) {
+ this.deps.log('warn', 'Account engine token rotation could not be persisted', error);
+ }
+ if (engine === this.process) {
+ engine.postMessage({type: 'tokenPersisted', accountKey, previousToken, token, outcome});
+ }
+ if (outcome === 'persisted') {
+ this.accountsChanged();
+ }
+ }
+
+ private handleExit(engine: AccountEngineProcess | null, code: number): void {
+ if (engine !== null && engine !== this.process) {
+ return;
+ }
+ this.process = null;
+ if (this.stopping) {
+ this.shutdownResolve?.();
+ return;
+ }
+ const now = this.deps.now();
+ this.crashes.push(now);
+ while (this.crashes.length > 0 && now - this.crashes[0] > ACCOUNT_ENGINE_CRASH_WINDOW_MS) {
+ this.crashes.shift();
+ }
+ this.deps.log('warn', 'The account engine exited unexpectedly', {code, recentCrashes: this.crashes.length});
+ if (this.crashes.length >= ACCOUNT_ENGINE_CRASH_LIMIT) {
+ this.available = false;
+ this.deps.log('error', 'The account engine keeps crashing and stays off for this session');
+ return;
+ }
+ const delay =
+ ACCOUNT_ENGINE_RESTART_DELAYS_MS[Math.min(this.crashes.length - 1, ACCOUNT_ENGINE_RESTART_DELAYS_MS.length - 1)];
+ this.restartTimer = this.deps.setTimeout(() => {
+ this.restartTimer = null;
+ void this.spawn();
+ }, delay);
+ }
+}
+
+let host: AccountEngineHostController | null = null;
+
+export function installAccountEngineHost(controller: AccountEngineHostController | null): void {
+ host = controller;
+}
+
+export function isAccountEngineAvailable(): boolean {
+ return host?.isAvailable === true;
+}
+
+export function notifyAccountEngineAccountsChanged(): void {
+ host?.accountsChanged();
+}
+
+export function getAccountEngineSummaries(): ReadonlyArray<AccountEngineAccountSummary> {
+ return host?.getSummaries() ?? [];
+}
+
+export function onAccountEngineSummaries(listener: SummaryListener): () => void {
+ return host?.onSummaries(listener) ?? (() => undefined);
+}
+
+export function getAccountEngineLabels(): ReadonlyArray<AccountEngineLabel> {
+ return host?.getLabels() ?? [];
+}
diff --git a/fluxer_desktop/src/main/DesktopAppStorageIpc.ts b/fluxer_desktop/src/main/DesktopAppStorageIpc.ts
index 8bd58fa88..4bec054f1 100644
--- a/fluxer_desktop/src/main/DesktopAppStorageIpc.ts
+++ b/fluxer_desktop/src/main/DesktopAppStorageIpc.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {notifyAccountEngineAccountsChanged} from '@electron/main/AccountEngineHost';
import type {DesktopAppStorage} from '@electron/main/DesktopAppStorage';
import {DESKTOP_ACCOUNT_CHANNELS} from '@fluxer/desktop_ipc/src/AccountContract';
import {DESKTOP_KNOWN_INSTANCE_CHANNELS} from '@fluxer/desktop_ipc/src/KnownInstanceContract';
@@ -7,15 +8,29 @@ import {DESKTOP_STORAGE_CHANNELS} from '@fluxer/desktop_ipc/src/StorageContract'
type DesktopAppStorageIpcRoutes = Readonly<Record<string, (...args: Array<unknown>) => Promise<unknown>>>;
-export function createDesktopAppStorageIpcRoutes(storage: DesktopAppStorage): DesktopAppStorageIpcRoutes {
+async function afterAccountWrite<T>(write: Promise<T>, onAccountsChanged: () => void): Promise<T> {
+ const result = await write;
+ onAccountsChanged();
+ return result;
+}
+
+export function createDesktopAppStorageIpcRoutes(
+ storage: DesktopAppStorage,
+ onAccountsChanged: () => void = notifyAccountEngineAccountsChanged,
+): DesktopAppStorageIpcRoutes {
return Object.freeze({
[DESKTOP_ACCOUNT_CHANNELS.getAll]: () => storage.getAllAccounts(),
[DESKTOP_ACCOUNT_CHANNELS.get]: (storageKey: unknown) => storage.getAccount(storageKey),
- [DESKTOP_ACCOUNT_CHANNELS.upsert]: (account: unknown) => storage.upsertAccount(account),
- [DESKTOP_ACCOUNT_CHANNELS.compareAndSwap]: (request: unknown) => storage.compareAndSwapAccount(request),
- [DESKTOP_ACCOUNT_CHANNELS.delete]: (storageKey: unknown) => storage.deleteAccount(storageKey),
- [DESKTOP_ACCOUNT_CHANNELS.import]: (request: unknown) => storage.importAccounts(request),
- [DESKTOP_ACCOUNT_CHANNELS.prune]: (request: unknown) => storage.pruneAccounts(request),
+ [DESKTOP_ACCOUNT_CHANNELS.upsert]: (account: unknown) =>
+ afterAccountWrite(storage.upsertAccount(account), onAccountsChanged),
+ [DESKTOP_ACCOUNT_CHANNELS.compareAndSwap]: (request: unknown) =>
+ afterAccountWrite(storage.compareAndSwapAccount(request), onAccountsChanged),
+ [DESKTOP_ACCOUNT_CHANNELS.delete]: (storageKey: unknown) =>
+ afterAccountWrite(storage.deleteAccount(storageKey), onAccountsChanged),
+ [DESKTOP_ACCOUNT_CHANNELS.import]: (request: unknown) =>
+ afterAccountWrite(storage.importAccounts(request), onAccountsChanged),
+ [DESKTOP_ACCOUNT_CHANNELS.prune]: (request: unknown) =>
+ afterAccountWrite(storage.pruneAccounts(request), onAccountsChanged),
[DESKTOP_STORAGE_CHANNELS.getStatus]: () => storage.getStoreStatus(),
[DESKTOP_STORAGE_CHANNELS.load]: (scope: unknown) => storage.loadEntries(scope),
[DESKTOP_STORAGE_CHANNELS.get]: (scope: unknown, key: unknown) => storage.getEntry(scope, key),
@@ -27,7 +42,8 @@ export function createDesktopAppStorageIpcRoutes(storage: DesktopAppStorage): De
[DESKTOP_STORAGE_CHANNELS.setMany]: (writes: unknown) => storage.setManyEntries(writes),
[DESKTOP_STORAGE_CHANNELS.import]: (request: unknown) => storage.importEntries(request),
[DESKTOP_STORAGE_CHANNELS.getMarker]: (key: unknown) => storage.getMarker(key),
- [DESKTOP_STORAGE_CHANNELS.setMarker]: (key: unknown, value: unknown) => storage.setMarker(key, value),
+ [DESKTOP_STORAGE_CHANNELS.setMarker]: (key: unknown, value: unknown) =>
+ afterAccountWrite(storage.setMarker(key, value), onAccountsChanged),
[DESKTOP_KNOWN_INSTANCE_CHANNELS.getAll]: () => storage.getAllKnownInstances(),
[DESKTOP_KNOWN_INSTANCE_CHANNELS.upsert]: (instance: unknown) => storage.upsertKnownInstance(instance),
[DESKTOP_KNOWN_INSTANCE_CHANNELS.delete]: (instanceKey: unknown) => storage.deleteKnownInstance(instanceKey),
diff --git a/fluxer_desktop/src/main/DesktopSystemTrustVerifier.ts b/fluxer_desktop/src/main/DesktopSystemTrustVerifier.ts
index 23755071d..a3479ef4c 100644
--- a/fluxer_desktop/src/main/DesktopSystemTrustVerifier.ts
+++ b/fluxer_desktop/src/main/DesktopSystemTrustVerifier.ts
@@ -4,7 +4,11 @@ import {createHash, X509Certificate} from 'node:crypto';
import net from 'node:net';
import {createChildLogger} from '@electron/common/Logger';
import {CHROMIUM_SPKI_BLOCKLIST, CHROMIUM_SPKI_BLOCKLIST_SOURCE} from '@electron/main/DesktopChromiumSPKIBlocklist';
-import {resolveDesktopLocallyAddedCertificates} from '@electron/main/DesktopTrustedCertificates';
+import {
+ type DesktopCertificateSource,
+ resolveDesktopLocallyAddedCertificates,
+ resolveDesktopTrustedCertificates,
+} from '@electron/main/DesktopTrustedCertificates';
import {readWindowsIntermediateStoreRoots} from '@electron/main/GatewaySocketNativeBoundary';
import type {Certificate, Session} from 'electron';
@@ -100,7 +104,7 @@ interface DesktopSystemTrustRequest {
readonly errorCode: number;
}
-export type DesktopTrustAnchors = ReadonlyMap<string, ReadonlyArray<ParsedCertificate>>;
+type DesktopTrustAnchors = ReadonlyMap<string, ReadonlyArray<ParsedCertificate>>;
function readNodes(buffer: Buffer): Array<DerNode> {
const nodes: Array<DerNode> = [];
@@ -398,7 +402,7 @@ function chainsToDesktopTrustAnchor(
return buildsPath({intermediates, anchors, now, signatures: new Map(), signatureChecks: 0}, leaf, [leaf]);
}
-export function buildDesktopTrustAnchors(
+function buildDesktopTrustAnchors(
certificates: ReadonlyArray<string | Buffer>,
now: number = Date.now(),
): DesktopTrustAnchors {
@@ -418,7 +422,7 @@ export function buildDesktopTrustAnchors(
return anchors;
}
-export function verifyAgainstDesktopSystemTrust(
+function verifyAgainstDesktopSystemTrust(
request: DesktopSystemTrustRequest,
loadAnchors: () => DesktopTrustAnchors,
): number {
@@ -446,6 +450,26 @@ function resolvePlatformAnchorCertificates(): ReadonlyArray<string | Buffer> {
}
}
+function toPem(certificate: string | Buffer): string | null {
+ try {
+ return new X509Certificate(certificate).toString();
+ } catch {
+ return null;
+ }
+}
+
+export function resolveDesktopGatewayTrustedCertificates(
+ source?: DesktopCertificateSource,
+ platformAnchors: () => ReadonlyArray<string | Buffer> = resolvePlatformAnchorCertificates,
+): ReadonlyArray<string> {
+ const merged = new Set(resolveDesktopTrustedCertificates(source));
+ for (const anchor of platformAnchors()) {
+ const pem = toPem(anchor);
+ if (pem !== null) merged.add(pem);
+ }
+ return [...merged];
+}
+
export function installDesktopSystemTrustVerifier(target: Session): void {
const anchors = buildDesktopTrustAnchors(resolvePlatformAnchorCertificates());
if (anchors.size === 0) return;
diff --git a/fluxer_desktop/src/main/GatewayOriginRegistry.ts b/fluxer_desktop/src/main/GatewayOriginRegistry.ts
index 26f9fc706..8d85e93a7 100644
--- a/fluxer_desktop/src/main/GatewayOriginRegistry.ts
+++ b/fluxer_desktop/src/main/GatewayOriginRegistry.ts
@@ -13,7 +13,7 @@ const GATEWAY_ORIGIN_REGISTRATIONS_PER_WINDOW = 8;
const GATEWAY_ORIGIN_REGISTRATION_WINDOW_MS = 60 * 1000;
const GATEWAY_ORIGIN_REGISTRATIONS_PER_DOCUMENT = 64;
const GATEWAY_ORIGIN_REGISTRATION_MIN_INTERVAL_MS = 1000;
-const GATEWAY_ORIGIN_ANCHOR_LIMIT = 32;
+const GATEWAY_ORIGIN_ANCHOR_LIMIT = 1024;
const GATEWAY_ORIGIN_RESOLUTION_CACHE_LIMIT = 256;
type GatewayOriginResolver = (anchorOrigin: string, signal: AbortSignal | null) => Promise<string | null>;
@@ -24,6 +24,12 @@ interface GatewayOriginRegistryDependencies {
readonly now?: () => number;
}
+interface AnchoredGatewayOriginAdmissionRequest {
+ readonly url: string;
+ readonly anchor: string;
+ readonly signal?: AbortSignal | null;
+}
+
interface GatewayOriginAdmissionRequest {
readonly documentKey: object;
readonly url: string;
@@ -135,6 +141,26 @@ export class GatewayOriginRegistry {
return await admission;
}
+ public async admitAnchored({url, anchor, signal}: AnchoredGatewayOriginAdmissionRequest): Promise<string> {
+ const targetOrigin = websocketOrigin(url);
+ if (targetOrigin == null) {
+ throw new GatewayOriginNotAdmittedError('the target has no WebSocket origin');
+ }
+ const anchorValue = anchorOrigin(anchor);
+ if (anchorValue == null) {
+ throw new GatewayOriginNotAdmittedError('the account has no instance origin');
+ }
+ this.seedAnchorOrigin(anchorValue);
+ const gatewayOrigin = await this.resolveAnchor(anchorValue, signal ?? null);
+ if (gatewayOrigin == null) {
+ throw new GatewayOriginNotAdmittedError('could not reach the account instance to confirm its gateway');
+ }
+ if (gatewayOrigin !== targetOrigin) {
+ throw new GatewayOriginNotAdmittedError('the account instance does not advertise it as its gateway');
+ }
+ return targetOrigin;
+ }
+
private async resolveAdmission(
state: DocumentState,
targetOrigin: string,
diff --git a/fluxer_desktop/src/main/LaunchOptions.ts b/fluxer_desktop/src/main/LaunchOptions.ts
index 75d49093a..44244f8e8 100644
--- a/fluxer_desktop/src/main/LaunchOptions.ts
+++ b/fluxer_desktop/src/main/LaunchOptions.ts
@@ -145,6 +145,10 @@ export function getNativeGatewayDisableReason(argv: ReadonlyArray<string> = proc
return null;
}
+export function prefersAccountEngineWebSocketTransport(argv: ReadonlyArray<string> = process.argv): boolean {
+ return getNativeGatewayDisableReason(argv) !== null || process.env.FLUXER_ACCOUNT_ENGINE_TRANSPORT === 'websocket';
+}
+
function isPortableLaunchFlag(argv: ReadonlyArray<string> = process.argv): boolean {
return hasFlag(argv, PORTABLE_MODE_ARGS);
}