A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(desktop): refine passkeys, updater and module installs (#3884)
Hampus203258e2e126
diff --git a/fluxer_app/src/features/app/state/Updater.ts b/fluxer_app/src/features/app/state/Updater.tsindex e1adf172f..4977c733e 100644--- a/fluxer_app/src/features/app/state/Updater.ts+++ b/fluxer_app/src/features/app/state/Updater.ts@@ -41,6 +41,7 @@ type UpdaterEvent =context: UpdaterContext;version: string | null;downloadUrl?: string;+ sha256: string | null;}| {type: 'not-available';@@ -117,6 +118,7 @@ function normalizeUpdaterEvent(event: NativeUpdaterEvent): UpdaterEvent | null {context,version: event.version ?? null,downloadUrl: event.downloadUrl,+ sha256: event.sha256 ?? null,};case 'not-available':return {type: 'not-available', context};@@ -188,6 +190,10 @@ class Updater {return this.snapshot.context.nativeManualDownloadUrl;}+ get nativeManualDownloadSha256(): string | null {+ return this.snapshot.context.nativeManualDownloadSha256;+ }+private get nativeCheckFailed(): boolean {return this.snapshot.context.nativeCheckFailed;}@@ -390,6 +396,7 @@ class Updater {type: 'native.available',version: event.version ?? null,downloadUrl: getElectronAPI()?.platform === 'linux' ? DESKTOP_DOWNLOAD_URL : (event.downloadUrl ?? null),+ sha256: getElectronAPI()?.platform === 'linux' ? null : event.sha256,});if (shouldShowImmediateUserResult) {this.showCurrentUpdateState();@@ -630,17 +637,15 @@ class Updater {showUpdaterModal((modals) => modals.pushManagedShellUpdateModal({version, flatpakAppId}));return;}- const url = this.nativeManualDownloadUrl ?? DESKTOP_DOWNLOAD_URL;+ const url = this.nativeManualDownloadUrl;+ const sha256 = url ? this.nativeManualDownloadSha256 : null;+ const downloadUrl = url ?? DESKTOP_DOWNLOAD_URL;showUpdaterModal((modals) =>- modals.pushUpdateAvailableModal(version, () => this.downloadManualNativeUpdateOrOpen(url)),+ modals.pushUpdateAvailableModal(version, () => this.downloadManualNativeUpdateOrOpen(downloadUrl, sha256)),);}- private async downloadManualNativeUpdateOrOpen(- url: string,- suggestedName?: string,- sha256?: string | null,- ): Promise<void> {+ private async downloadManualNativeUpdateOrOpen(url: string, sha256: string | null): Promise<void> {if (this.manualNativeDownloadInFlight) {return;}@@ -648,7 +653,7 @@ class Updater {try {const outcome = await downloadWithNative({url,- suggestedName: suggestedName ?? this.getManualUpdateSuggestedName(url),+ suggestedName: this.getManualUpdateSuggestedName(url),sha256,});if (outcome === 'success' || outcome === 'canceled') {diff --git a/fluxer_app/src/features/updater/state/UpdaterStateMachine.ts b/fluxer_app/src/features/updater/state/UpdaterStateMachine.tsindex 5b21a44b1..ee9388204 100644--- a/fluxer_app/src/features/updater/state/UpdaterStateMachine.ts+++ b/fluxer_app/src/features/updater/state/UpdaterStateMachine.ts@@ -30,6 +30,7 @@ interface UpdaterMachineContext {manualNativeDownloadInFlight: boolean;nativeUnsupported: NativeUnsupportedUpdate | null;nativeManualDownloadUrl: string | null;+ nativeManualDownloadSha256: string | null;}export type UpdaterMachineEvent =@@ -41,6 +42,7 @@ export type UpdaterMachineEvent =type: 'native.available';version: string | null;downloadUrl: string | null;+ sha256: string | null;}| {type: 'native.notAvailable'; now: number}| {type: 'native.error'}@@ -76,6 +78,7 @@ function createInitialUpdaterContext(): UpdaterMachineContext {manualNativeDownloadInFlight: false,nativeUnsupported: null,nativeManualDownloadUrl: null,+ nativeManualDownloadSha256: null,};}@@ -91,6 +94,7 @@ function clearNativeUpdate(context: UpdaterMachineContext): UpdaterMachineContexnative: createEmptyNativeUpdateInfo(),},nativeManualDownloadUrl: null,+ nativeManualDownloadSha256: null,};}@@ -134,6 +138,7 @@ const updaterStateMachine = setup({isChecking: false,nativeUnsupported: null,nativeManualDownloadUrl: event.downloadUrl,+ nativeManualDownloadSha256: event.sha256,};}),applyNativeNotAvailable: assign(({context, event}) => {diff --git a/fluxer_app/src/types/electron.d.ts b/fluxer_app/src/types/electron.d.tsindex 43c85c827..01cf2aeed 100644--- a/fluxer_app/src/types/electron.d.ts+++ b/fluxer_app/src/types/electron.d.ts@@ -211,6 +211,7 @@ export interface UpdaterEvent {message?: string;reason?: 'platform' | 'unpackaged' | 'managed-package';downloadUrl?: string;+ sha256?: string | null;downloadOptions?: Array<UpdaterDownloadOption>;}diff --git a/fluxer_desktop/native/linux-audio-capture/src/pipewire/device_enum.rs b/fluxer_desktop/native/linux-audio-capture/src/pipewire/device_enum.rsindex 4a98cd2a3..6587f73b6 100644--- a/fluxer_desktop/native/linux-audio-capture/src/pipewire/device_enum.rs+++ b/fluxer_desktop/native/linux-audio-capture/src/pipewire/device_enum.rs@@ -167,8 +167,8 @@ fn handle_global_added_metadata(let sink_node_name_owned = ctx.sink_node_name.to_string();let listener = metadata.add_listener_local()- .property(move |_subject, key, _type_, value| {- if key == Some("default.audio.sink") {+ .property(move |subject, key, _type_, value| {+ if is_default && subject == pw::core::PW_ID_CORE && key == Some("default.audio.sink") {let name = value.map(crate::routing::parse_default_sink_name).unwrap_or_default();@@ -329,8 +329,8 @@ fn direct_added_metadata(let st = args.state.clone();let listener = metadata.add_listener_local()- .property(move |_subject, key, _type_, value| {- if key == Some("default.audio.sink") {+ .property(move |subject, key, _type_, value| {+ if is_default && subject == pw::core::PW_ID_CORE && key == Some("default.audio.sink") {let name = value.map(crate::routing::parse_default_sink_name).unwrap_or_default();diff --git a/fluxer_desktop/native/linux-evdev/src/linux.rs b/fluxer_desktop/native/linux-evdev/src/linux.rsindex cfa32c98a..1a716b092 100644--- a/fluxer_desktop/native/linux-evdev/src/linux.rs+++ b/fluxer_desktop/native/linux-evdev/src/linux.rs@@ -47,6 +47,7 @@ const EVENT_NODE_PREFIX: &str = "event";const FLATPAK_INFO_PATH: &str = "/.flatpak-info";const PERMISSION_RETRY_DELAY: Duration = Duration::from_millis(500);const FULL_KEYBOARD_KEY_CODES: std::ops::Range<u16> = 1..32;+const MAX_DEVICE_READS_PER_WAKE: usize = 64;fn poll_key_for_device_fd(fd: RawFd) -> Option<usize> {usize::try_from(fd).ok()?.checked_add(DEVICE_KEY_BASE)@@ -637,7 +638,7 @@ impl Reader {let Some(opened) = self.devices.get_mut(&fd) else {return;};- loop {+ for _ in 0..MAX_DEVICE_READS_PER_WAKE {match opened.device.fetch_events() {Ok(events) => {for ev in events {diff --git a/fluxer_desktop/native/linux-evdev/src/logind.rs b/fluxer_desktop/native/linux-evdev/src/logind.rsindex df773b2bf..0c6bd6913 100644--- a/fluxer_desktop/native/linux-evdev/src/logind.rs+++ b/fluxer_desktop/native/linux-evdev/src/logind.rs@@ -132,14 +132,18 @@ async fn supervise(gate: &SessionGate) {}match &end {WatchEnd::Unreachable(err) if !ever_subscribed => {- eprintln!("[linux-evdev] logind unreachable, session gating disabled: {err}");+ if failures == 0 {+ eprintln!("[linux-evdev] logind unreachable, session gating disabled: {err}");+ }gate.set_active(true);- return;}WatchEnd::NoSession(err) if !ever_subscribed => {- eprintln!("[linux-evdev] no logind session found, session gating disabled: {err}");+ if failures == 0 {+ eprintln!(+ "[linux-evdev] no logind session found, session gating disabled: {err}"+ );+ }gate.set_active(true);- return;}WatchEnd::Unreachable(err) | WatchEnd::NoSession(err) | WatchEnd::Lost(Some(err))if failures == 0 =>diff --git a/fluxer_desktop/native/mac-app-audio/src/audio_source.rs b/fluxer_desktop/native/mac-app-audio/src/audio_source.rsindex 186d95cb0..04b219de0 100644--- a/fluxer_desktop/native/mac-app-audio/src/audio_source.rs+++ b/fluxer_desktop/native/mac-app-audio/src/audio_source.rs@@ -5,8 +5,8 @@use core::ffi::c_void;use core::ptr;use std::sync::{- Mutex, MutexGuard,- atomic::{AtomicPtr, AtomicU64, Ordering},+ Mutex, MutexGuard, RwLock, RwLockReadGuard,+ atomic::{AtomicU64, Ordering},};use objc2::rc::Retained;@@ -104,7 +104,23 @@ unsafe impl Send for Source {}unsafe impl Sync for Source {}pub struct DelegateIvars {- pub source: AtomicPtr<Source>,+ source: RwLock<*mut Source>,+}++impl DelegateIvars {+ fn read_source(&self) -> RwLockReadGuard<'_, *mut Source> {+ self.source+ .read()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ }++ fn set_source(&self, ptr: *mut Source) {+ let mut guard = self+ .source+ .write()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ *guard = ptr;+ }}define_class!(@@ -118,11 +134,11 @@ define_class!(unsafe impl SCStreamDelegate for FluxerSCKAudioSource {#[unsafe(method(stream:didStopWithError:))]unsafe fn did_stop_with_error(&self, _stream: &SCStream, err: &NSError) {- let ptr = self.ivars().source.load(Ordering::Acquire);- if ptr.is_null() {+ let guard = self.ivars().read_source();+ if guard.is_null() {return;}- let src = unsafe { &*ptr };+ let src = unsafe { &**guard };let _ = src.state.request_stop();let _ = src.state.mark_stopped();let (cb, ctx) = {@@ -148,12 +164,12 @@ define_class!(if output_type != SCStreamOutputType::Audio {return;}- let ptr = self.ivars().source.load(Ordering::Acquire);- if ptr.is_null() {+ let guard = self.ivars().read_source();+ if guard.is_null() {return;}unsafe {- handle_audio_sample(&*ptr, sample_buffer);+ handle_audio_sample(&**guard, sample_buffer);}}}@@ -162,7 +178,7 @@ define_class!(impl FluxerSCKAudioSource {pub fn new() -> Retained<Self> {let this = Self::alloc().set_ivars(DelegateIvars {- source: AtomicPtr::new(core::ptr::null_mut()),+ source: RwLock::new(core::ptr::null_mut()),});unsafe { msg_send![super(this), init] }}@@ -372,7 +388,7 @@ impl Source {});let raw: *mut Source = &mut *src;- src.delegate.ivars().source.store(raw, Ordering::Release);+ src.delegate.ivars().set_source(raw);src}@@ -422,9 +438,6 @@ impl Source {impl Drop for Source {fn drop(&mut self) {- self.delegate- .ivars()- .source- .store(ptr::null_mut(), Ordering::Release);+ self.delegate.ivars().set_source(ptr::null_mut());}}diff --git a/fluxer_desktop/native/mac-app-audio/src/napi_surface_macos.rs b/fluxer_desktop/native/mac-app-audio/src/napi_surface_macos.rsindex 63c2cdb62..eaa00d42a 100644--- a/fluxer_desktop/native/mac-app-audio/src/napi_surface_macos.rs+++ b/fluxer_desktop/native/mac-app-audio/src/napi_surface_macos.rs@@ -879,9 +879,12 @@ impl ProcessLoopback {self.inner.running.store(false, std::sync::atomic::Ordering::Release);- let mut state = lock_loopback_state(&self.inner)?;- state.source = None;- state.stream = None;+ let source = {+ let mut state = lock_loopback_state(&self.inner)?;+ state.stream = None;+ state.source.take()+ };+ drop(source);return Err(napi::Error::new(Status::GenericFailure,"SCStream startCapture failed",diff --git a/fluxer_desktop/native/webauthn/src/lib.rs b/fluxer_desktop/native/webauthn/src/lib.rsindex bb2f9b524..fcba812f9 100644--- a/fluxer_desktop/native/webauthn/src/lib.rs+++ b/fluxer_desktop/native/webauthn/src/lib.rs@@ -591,7 +591,7 @@ fn required_alg_array(object: &Object) -> Result<Vec<i32>> {"pubKeyCredParams must not be empty".to_owned(),));}- let mut algs = Vec::with_capacity(len as usize);+ let mut algs = Vec::new();for i in 0..len {let mut elem_raw: napi::sys::napi_value = std::ptr::null_mut();let status = unsafe { napi::sys::napi_get_element(raw_env, raw, i, &mut elem_raw) };@@ -651,7 +651,7 @@ fn optional_descriptor_array(object: &Object, key: &str) -> Result<Vec<Descripto}let arr: Object = unsafe { value.cast::<Object>()? };let len = read_array_length(&arr)?;- let mut out = Vec::with_capacity(len as usize);+ let mut out = Vec::new();for i in 0..len {let mut elem_raw: napi::sys::napi_value = std::ptr::null_mut();let status = unsafe { napi::sys::napi_get_element(raw_env, raw, i, &mut elem_raw) };diff --git a/fluxer_desktop/src/common/Types.ts b/fluxer_desktop/src/common/Types.tsindex f40c435c0..f184ceff0 100644--- a/fluxer_desktop/src/common/Types.ts+++ b/fluxer_desktop/src/common/Types.ts@@ -122,6 +122,7 @@ export type UpdaterEvent =context: UpdaterContext;version: string | null;downloadUrl?: string;+ sha256?: string | null;}| {type: 'not-available';diff --git a/fluxer_desktop/src/engine/AccountSession.ts b/fluxer_desktop/src/engine/AccountSession.tsindex b1b6b18c6..223c5c62f 100644--- a/fluxer_desktop/src/engine/AccountSession.ts+++ b/fluxer_desktop/src/engine/AccountSession.ts@@ -38,6 +38,7 @@ import type {} from '@fluxer/desktop_ipc/src/AccountEngineCoreContract';const INBOUND_QUEUE_MAX_BYTES = 32 * 1024 * 1024;+const INBOUND_QUEUE_COMPACT_AT = 1024;const NOTIFICATION_MAX_AGE_MS = 2 * 60 * 1000;const NOTIFICATION_BURST = 5;const NOTIFICATION_REFILL_MS = 1_000;@@ -514,6 +515,9 @@ export class AccountSession implements SchedulerClient, DispatchConsumer {this.queue = [];this.queueHead = 0;this.queueBytes = 0;+ } else if (this.queueHead >= INBOUND_QUEUE_COMPACT_AT && this.queueHead * 2 >= this.queue.length) {+ this.queue = this.queue.slice(this.queueHead);+ this.queueHead = 0;}if (item.client !== this.client) {return;@@ -668,7 +672,7 @@ export class AccountSession implements SchedulerClient, DispatchConsumer {this.releaseSentAt = this.deps.clock.now();}}- if (this.queueBytes + bytes > INBOUND_QUEUE_MAX_BYTES && type !== 'READY') {+ if (this.queueBytes + bytes > INBOUND_QUEUE_MAX_BYTES && (type !== 'READY' || this.hasPending())) {this.deps.log('warn', 'Account engine inbound queue overflowed, resuming', {accountKey: this.accountKey});this.dropQueue();this.disconnect(GatewayClose.ZOMBIE, 'overflow');diff --git a/fluxer_desktop/src/engine/GatewayTransport.ts b/fluxer_desktop/src/engine/GatewayTransport.tsindex 8647651c9..08c3534a5 100644--- a/fluxer_desktop/src/engine/GatewayTransport.ts+++ b/fluxer_desktop/src/engine/GatewayTransport.ts@@ -2,9 +2,11 @@import type {LookupAddress} from 'node:dns';import {createRequire} from 'node:module';-import {isIP, type LookupFunction} from 'node:net';+import {isIP, type LookupFunction, type Socket} from 'node:net';import {errorMessage} from '@electron/common/ErrorMessage';-import {Agent, type Dispatcher, ProxyAgent, WebSocket} from 'undici';+import {Agent, type buildConnector, Client, type Dispatcher, Pool, ProxyAgent, WebSocket} from 'undici';++const GATEWAY_CLOSE_GRACE_MS = 5_000;export type GatewayTransportEvent =| {readonly kind: 'open'}@@ -106,6 +108,28 @@ function pinnedLookup(address: string): LookupFunction {};}+function socketTrackingFactory(sockets: Set<Socket>): (origin: string | URL, opts: object) => Dispatcher {+ return (origin, opts) =>+ new Pool(origin, {+ ...opts,+ factory: (clientOrigin, clientOpts) => {+ const {connect} = clientOpts as {connect: buildConnector.connector};+ return new Client(clientOrigin, {+ ...clientOpts,+ connect: (connectOpts, callback) =>+ connect(connectOpts, (...args) => {+ const socket = args[1];+ if (socket != null) {+ sockets.add(socket);+ socket.once('close', () => sockets.delete(socket));+ }+ callback(...args);+ }),+ });+ },+ });+}+interface WebSocketGatewayTransportOptions {readonly trustedCertificates?: ReadonlyArray<string>;}@@ -114,25 +138,39 @@ function createWebSocketGatewayTransport(options: WebSocketGatewayTransportOptioconst trustedCertificates = options.trustedCertificates ?? [];const trust = trustedCertificates.length > 0 ? {ca: [...trustedCertificates]} : {};return ({url, address, proxy, onEvent}) => {+ const sockets = new Set<Socket>();+ const factory = socketTrackingFactory(sockets);const dispatcher: Dispatcher =proxy === null? new Agent({+ factory,connect: {...(address === null ? {} : {lookup: pinnedLookup(address)}),...trust,},})- : new ProxyAgent({uri: proxy, proxyTunnel: true, requestTls: trust, proxyTls: trust});+ : new ProxyAgent({uri: proxy, proxyTunnel: true, requestTls: trust, proxyTls: trust, factory});let terminated = false;+ let closeGraceTimer: ReturnType<typeof setTimeout> | null = null;const finish = (event: GatewayTransportEvent): void => {if (terminated) {return;}terminated = true;+ if (closeGraceTimer !== null) {+ clearTimeout(closeGraceTimer);+ closeGraceTimer = null;+ }void dispatcher.close().catch(() => undefined);onEvent(event);};- const socket = new WebSocket(url, {dispatcher});+ let socket: WebSocket;+ try {+ socket = new WebSocket(url, {dispatcher});+ } catch (error) {+ void dispatcher.destroy().catch(() => undefined);+ throw error;+ }socket.binaryType = 'arraybuffer';socket.addEventListener('open', () => {if (!terminated) onEvent({kind: 'open'});@@ -161,6 +199,20 @@ function createWebSocketGatewayTransport(options: WebSocketGatewayTransportOptio} catch {socket.close();}+ if (terminated || closeGraceTimer !== null) {+ return;+ }+ closeGraceTimer = setTimeout(() => {+ closeGraceTimer = null;+ if (terminated) {+ return;+ }+ for (const tracked of sockets) {+ tracked.destroy();+ }+ void dispatcher.destroy().catch(() => undefined);+ }, GATEWAY_CLOSE_GRACE_MS);+ closeGraceTimer.unref?.();},};};diff --git a/fluxer_desktop/src/engine/ZstdStreamCodec.ts b/fluxer_desktop/src/engine/ZstdStreamCodec.tsindex bda1d4a06..85628b43d 100644--- a/fluxer_desktop/src/engine/ZstdStreamCodec.ts+++ b/fluxer_desktop/src/engine/ZstdStreamCodec.ts@@ -11,18 +11,35 @@ class ZstdStreamCodecError extends Error {type ZstdStream = ZstdCompress | ZstdDecompress;+const DECOMPRESSED_FRAME_MAX_BYTES = 128 * 1024 * 1024;+class SerialStream {private readonly stream: ZstdStream;private readonly flushKind: number | null;+ private readonly maxOutputBytes: number | null;private tail: Promise<unknown> = Promise.resolve();private chunks: Array<Buffer> = [];+ private outputBytes = 0;private pendingReject: ((error: Error) => void) | null = null;private failure: Error | null = null;- constructor(stream: ZstdStream, flushKind: number | null) {+ constructor(stream: ZstdStream, flushKind: number | null, maxOutputBytes: number | null = null) {this.stream = stream;this.flushKind = flushKind;+ this.maxOutputBytes = maxOutputBytes;stream.on('data', (chunk: Buffer) => {+ if (this.failure !== null) {+ return;+ }+ this.outputBytes += chunk.length;+ if (this.maxOutputBytes !== null && this.outputBytes > this.maxOutputBytes) {+ this.failure = new ZstdStreamCodecError('Decompressed gateway frame exceeds the size limit');+ this.chunks = [];+ this.pendingReject?.(this.failure);+ this.pendingReject = null;+ this.stream.destroy();+ return;+ }this.chunks.push(chunk);});stream.on('error', (error: Error) => {@@ -51,6 +68,7 @@ class SerialStream {}return new Promise<Buffer>((resolve, reject) => {this.chunks = [];+ this.outputBytes = 0;this.pendingReject = reject;const done = (): void => {if (this.pendingReject !== reject) {@@ -59,6 +77,7 @@ class SerialStream {this.pendingReject = null;const output = Buffer.concat(this.chunks);this.chunks = [];+ this.outputBytes = 0;resolve(output);};this.stream.write(input);@@ -72,7 +91,7 @@ class SerialStream {}export class ZstdStreamCodec {- private readonly decoder = new SerialStream(createZstdDecompress(), null);+ private readonly decoder = new SerialStream(createZstdDecompress(), null, DECOMPRESSED_FRAME_MAX_BYTES);private readonly encoder = new SerialStream(createZstdCompress(), constants.ZSTD_e_flush);private readonly textDecoder = new TextDecoder('utf-8', {fatal: true});diff --git a/fluxer_desktop/src/main/AppImageUpdate.ts b/fluxer_desktop/src/main/AppImageUpdate.tsindex 5b177abed..7d1117d0e 100644--- a/fluxer_desktop/src/main/AppImageUpdate.ts+++ b/fluxer_desktop/src/main/AppImageUpdate.ts@@ -47,6 +47,7 @@ const APPIMAGE_MODE = 0o755;const SHA256_PATTERN = /^[0-9a-f]{64}$/;const STAGING_FREE_SPACE_MARGIN_BYTES = 16 * 1024 * 1024;const APPIMAGE_DOWNLOAD_STALL_MS = 30_000;+const APPIMAGE_MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024;const NON_RETRYABLE_STAGING_ERRNOS = new Set(['ENOSPC','EDQUOT',@@ -213,7 +214,15 @@ async function downloadAndStageAppImage(}const declaredTotal = Number.parseInt(response.headers.get('content-length') ?? '', 10);const total = Number.isFinite(declaredTotal) && declaredTotal > 0 ? declaredTotal : 0;+ const contentEncoding = (response.headers.get('content-encoding') ?? '').trim().toLowerCase();+ const limit =+ total > 0 && (contentEncoding === '' || contentEncoding === 'identity')+ ? Math.min(total, APPIMAGE_MAX_DOWNLOAD_BYTES)+ : APPIMAGE_MAX_DOWNLOAD_BYTES;try {+ if (total > APPIMAGE_MAX_DOWNLOAD_BYTES) {+ throw new Error(`Update download is ${total} bytes, above the ${APPIMAGE_MAX_DOWNLOAD_BYTES} byte limit.`);+ }assertRoomToStage(options.target.directory, total);} catch (error) {await response.body.cancel().catch(() => {});@@ -250,6 +259,9 @@ async function downloadAndStageAppImage(break;}onData();+ if (transferred + value.byteLength > limit) {+ throw new Error(`Update download exceeded ${limit} bytes.`);+ }let written = 0;while (written < value.byteLength) {const result = await handle.write(value, written, value.byteLength - written);diff --git a/fluxer_desktop/src/main/BrowserHandoff.ts b/fluxer_desktop/src/main/BrowserHandoff.tsindex bffa09db8..075991020 100644--- a/fluxer_desktop/src/main/BrowserHandoff.ts+++ b/fluxer_desktop/src/main/BrowserHandoff.ts@@ -37,6 +37,7 @@ const HANDOFF_TOKEN_MAX_LENGTH = 4096;const HANDOFF_API_VERSION_MAX = 1000;const HANDOFF_CODE_PATTERN = /^[A-Za-z0-9-]{1,64}$/u;const HANDOFF_POLL_SECRET_PATTERN = /^[A-Za-z0-9_-]{1,256}$/u;+const HANDOFF_RETURN_GRANT_MAX = 4;const HANDOFF_CODE_SEPARATOR_PATTERN = /[^A-Za-z0-9]/gu;const TRAILING_SLASH_PATTERN = /\/+$/u;@@ -60,7 +61,8 @@ interface ActiveHandoffSession {readonly watcher: RendererDocumentOwnerWatcher;inFlight: Promise<DesktopHandoffStatusResult> | null;pollSecret: string | null;- grant: string | null;+ readonly grants: Array<string>;+ grantPolls: number;}interface HandoffJSONRequest {@@ -226,7 +228,10 @@ export class DesktopBrowserHandoff {);return;}- session.grant = grant;+ if (session.grants.includes(grant) || session.grants.length >= HANDOFF_RETURN_GRANT_MAX) {+ return;+ }+ session.grants.push(grant);}public cleanup(): void {@@ -268,7 +273,7 @@ export class DesktopBrowserHandoff {? DesktopHandoffReturnMethod.DEEP_LINK: DesktopHandoffReturnMethod.CODE;owner.requireCurrent(RENDERER_CONTEXT);- this.rememberSession(owner, {code, expiresAtMs, instance, origin, pollSecret: usablePollSecret, grant: null});+ this.rememberSession(owner, {code, expiresAtMs, instance, origin, pollSecret: usablePollSecret});return {instance, code, expiresAt, returnMethod};}@@ -304,11 +309,9 @@ export class DesktopBrowserHandoff {const path = `/auth/handoff/${encodeURIComponent(session.code)}/status`;let response: HandoffJSONResponse | null = null;if (session.pollSecret != null) {+ const grant = session.grants.length === 0 ? null : session.grants[session.grantPolls++ % session.grants.length];const attempt = await this.requestJSON({- body:- session.grant == null- ? {poll_secret: session.pollSecret}- : {poll_secret: session.pollSecret, grant: session.grant},+ body: grant == null ? {poll_secret: session.pollSecret} : {poll_secret: session.pollSecret, grant},instance: session.instance,method: 'POST',origin: session.origin,@@ -367,12 +370,14 @@ export class DesktopBrowserHandoff {private rememberSession(owner: RendererDocumentOwner,- session: Omit<ActiveHandoffSession, 'inFlight' | 'owner' | 'watcher'>,+ session: Omit<ActiveHandoffSession, 'grantPolls' | 'grants' | 'inFlight' | 'owner' | 'watcher'>,): void {const frame = owner.frame;this.releaseFrame(frame);this.sessions.set(frame, {...session,+ grantPolls: 0,+ grants: [],inFlight: null,owner,watcher: owner.watchInvalidation(() => this.releaseFrame(frame)),diff --git a/fluxer_desktop/src/main/DesktopAccountStoreTelemetry.ts b/fluxer_desktop/src/main/DesktopAccountStoreTelemetry.tsindex 63f9292eb..a7d75e272 100644--- a/fluxer_desktop/src/main/DesktopAccountStoreTelemetry.ts+++ b/fluxer_desktop/src/main/DesktopAccountStoreTelemetry.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {readFileSync, renameSync, statSync, writeFileSync} from 'node:fs';+import {randomBytes} from 'node:crypto';+import {readFileSync, renameSync, rmSync, statSync, writeFileSync} from 'node:fs';import path from 'node:path';import {createChildLogger} from '@electron/common/Logger';@@ -73,15 +74,16 @@ export function recordDesktopAccountStoreEvent(const counts = {...readDesktopAccountStoreTelemetry(userDataPath)};counts[event] = (counts[event] ?? 0) + 1;const file = desktopAccountStoreTelemetryFile(userDataPath);- const pending = `${file}.tmp`;+ const pending = `${file}.${randomBytes(8).toString('hex')}.tmp`;try {writeFileSync(pending,`${JSON.stringify({version: DESKTOP_ACCOUNT_STORE_TELEMETRY_VERSION, counts, updatedAt: Date.now()})}\n`,- {encoding: 'utf8', mode: 0o600},+ {encoding: 'utf8', mode: 0o600, flag: 'wx'},);renameSync(pending, file);} catch (error) {+ rmSync(pending, {force: true});logger.warn('Failed to persist account store telemetry', {file, error});}return counts;diff --git a/fluxer_desktop/src/main/DesktopAppStorage.ts b/fluxer_desktop/src/main/DesktopAppStorage.tsindex e1e63082d..972704390 100644--- a/fluxer_desktop/src/main/DesktopAppStorage.ts+++ b/fluxer_desktop/src/main/DesktopAppStorage.ts@@ -5,6 +5,7 @@ import fsPromises from 'node:fs/promises';import path from 'node:path';import {errorMessage as describeError} from '@electron/common/ErrorMessage';import type {AppStoreBoundary, AppStoreBoundaryFactory} from '@electron/main/AppStoreNativeBoundary';+import {writeFileAtomically} from '@electron/main/AtomicFile';import {desktopAppStoreStateFile} from '@electron/main/DesktopAppStoreHealth';import type {DesktopAccountCompareAndSwapRequest,@@ -614,9 +615,7 @@ export class DesktopAppStorage {}private async writeAuthoritySentinel(): Promise<void> {- const temporary = `${this.authoritySentinelPath}.tmp`;- await fsPromises.writeFile(temporary, '1\n', {encoding: 'utf8', mode: 0o600});- await fsPromises.rename(temporary, this.authoritySentinelPath);+ await writeFileAtomically(this.authoritySentinelPath, '1\n', 0o600);this.authorityExpected = true;this.status = {...this.status, authorityExpected: true};}diff --git a/fluxer_desktop/src/main/DesktopAppStoreHealth.ts b/fluxer_desktop/src/main/DesktopAppStoreHealth.tsindex 14034f8b1..dd0c8430e 100644--- a/fluxer_desktop/src/main/DesktopAppStoreHealth.ts+++ b/fluxer_desktop/src/main/DesktopAppStoreHealth.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {readFileSync, renameSync, writeFileSync} from 'node:fs';+import {randomBytes} from 'node:crypto';+import {readFileSync, renameSync, rmSync, writeFileSync} from 'node:fs';import path from 'node:path';const DESKTOP_APP_STORE_STATE_FILE_NAME = 'account-store-state-v1.json';@@ -73,11 +74,12 @@ export function recordDesktopAppStoreSuccess(options: {lastSchemaVersion: options.schemaVersion,};const file = desktopAppStoreStateFile(options.userDataPath);- const pending = `${file}.tmp`;+ const pending = `${file}.${randomBytes(8).toString('hex')}.tmp`;try {- writeFileSync(pending, `${JSON.stringify(state)}\n`, {encoding: 'utf8', mode: 0o600});+ writeFileSync(pending, `${JSON.stringify(state)}\n`, {encoding: 'utf8', mode: 0o600, flag: 'wx'});renameSync(pending, file);} catch {+ rmSync(pending, {force: true});return null;}return state;diff --git a/fluxer_desktop/src/main/GlobalShortcutsEngine.ts b/fluxer_desktop/src/main/GlobalShortcutsEngine.tsindex f1d33369a..8f51b8e44 100644--- a/fluxer_desktop/src/main/GlobalShortcutsEngine.ts+++ b/fluxer_desktop/src/main/GlobalShortcutsEngine.ts@@ -157,7 +157,7 @@ function sanitizeGlobalShortcutCombo(value: unknown): GlobalShortcutCombo | nullexport function sanitizeGlobalShortcutsSyncPayload(value: unknown): SanitizedSyncPayload | null {if (!isRecord(value) || !Array.isArray(value.bindings) || !Array.isArray(value.actions)) return null;- if (value.bindings.length > MAX_SYNC_BINDINGS) return null;+ if (value.bindings.length > MAX_SYNC_BINDINGS || value.actions.length > MAX_SYNC_BINDINGS) return null;const bindings: Array<SanitizedSyncBinding> = [];for (const entry of value.bindings) {if (!isRecord(entry)) return null;diff --git a/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts b/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.tsindex 353adf22c..4d1484fe8 100644--- a/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts+++ b/fluxer_desktop/src/main/LegacyGlobalKeyHookIpc.ts@@ -15,6 +15,7 @@ import {ipcMain} from 'electron';const MAX_LEGACY_ID_LENGTH = 512;const MAX_LEGACY_KEY_NAME_LENGTH = 64;const MAX_LEGACY_MOUSE_BUTTON = 31;+const MAX_LEGACY_REGISTRATIONS = 256;interface LegacyLinuxEvdevStatus {supported: boolean;@@ -82,6 +83,7 @@ export class LegacyGlobalKeyHookAdapter implements GlobalShortcutsConsumer {register(id: number, binding: ShortcutBinding): void {const client = this.clients.get(id);if (!client) return;+ if (!client.registrations.has(binding.sourceId) && client.registrations.size >= MAX_LEGACY_REGISTRATIONS) return;client.registrations.set(binding.sourceId, binding);this.applyRegistrations(client);}diff --git a/fluxer_desktop/src/main/LinuxDesktopEntry.ts b/fluxer_desktop/src/main/LinuxDesktopEntry.tsindex 1ea4ba593..6e7972966 100644--- a/fluxer_desktop/src/main/LinuxDesktopEntry.ts+++ b/fluxer_desktop/src/main/LinuxDesktopEntry.ts@@ -289,10 +289,10 @@ function removeLegacyGeneratedDesktopEntry(): boolean {}function writeDesktopFileAtomically(filePath: string, contents: string): void {- const tempPath = `${filePath}.${process.pid}.tmp`;+ const tempPath = `${filePath}.${crypto.randomBytes(8).toString('hex')}.tmp`;try {fs.mkdirSync(path.dirname(filePath), {recursive: true});- fs.writeFileSync(tempPath, contents, {encoding: 'utf8', mode: 0o644});+ fs.writeFileSync(tempPath, contents, {encoding: 'utf8', mode: 0o644, flag: 'wx'});fs.renameSync(tempPath, filePath);} catch (error) {try {diff --git a/fluxer_desktop/src/main/MainI18n.ts b/fluxer_desktop/src/main/MainI18n.tsindex 85d1f25c3..33bb948cf 100644--- a/fluxer_desktop/src/main/MainI18n.ts+++ b/fluxer_desktop/src/main/MainI18n.ts@@ -133,6 +133,7 @@ const FALLBACK_STRINGS: Readonly<Record<string, string>> = Object.freeze({'desktop.linuxEntry.comment': 'Instant messaging and VoIP',});const STORAGE_FILE_NAME = 'native-strings.json';+const LOCALE_TAG_PATTERN = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/;interface PersistedStrings {locale: string;@@ -169,13 +170,14 @@ function writePersisted(payload: PersistedStrings): void {export function initializeMainI18n(): void {const persisted = readPersisted();- if (!persisted) return;+ if (!persisted || !LOCALE_TAG_PATTERN.test(persisted.locale)) return;currentLocale = persisted.locale;currentStrings = {...FALLBACK_STRINGS, ...persisted.strings};logger.info('Loaded persisted native strings', {locale: currentLocale, count: Object.keys(persisted.strings).length});}export function setNativeStrings(locale: string, strings: Record<string, string>): void {+ if (!LOCALE_TAG_PATTERN.test(locale)) return;const next = {...FALLBACK_STRINGS, ...strings};if (locale === currentLocale && shallowEqualStrings(currentStrings, next)) {return;diff --git a/fluxer_desktop/src/main/ModuleManifestRepository.ts b/fluxer_desktop/src/main/ModuleManifestRepository.tsindex 3f3f5226a..a616a073c 100644--- a/fluxer_desktop/src/main/ModuleManifestRepository.ts+++ b/fluxer_desktop/src/main/ModuleManifestRepository.ts@@ -178,6 +178,7 @@ export class ModuleManifestRepository {} catch (error) {throw new ModuleManifestFetchError(`failed to reach ${url}`, null, {cause: error});}+ this.requireFeedResponseUrl(response);if (response.status === 304 && known != null) {return known.version;}@@ -244,6 +245,7 @@ export class ModuleManifestRepository {} catch (error) {throw new ModuleManifestFetchError(`failed to reach ${url}`, null, {cause: error});}+ this.requireFeedResponseUrl(response);if (response.status === 304) {return null;}@@ -257,6 +259,17 @@ export class ModuleManifestRepository {return document;}+ private requireFeedResponseUrl(response: Response): void {+ if (response.url.length === 0) {+ return;+ }+ const finalUrl = new URL(response.url);+ if (finalUrl.protocol === 'https:' || finalUrl.origin === new URL(this.packageOrigin).origin) {+ return;+ }+ throw new ModuleManifestFetchError(`feed request was redirected to ${finalUrl.origin}`, response.status);+ }+private async readBoundedBody(response: Response, limit: number, description: string): Promise<Buffer> {const declared = Number.parseInt(response.headers.get('content-length') ?? '', 10);if (Number.isSafeInteger(declared) && declared > limit) {diff --git a/fluxer_desktop/src/main/ModulePackageInstaller.ts b/fluxer_desktop/src/main/ModulePackageInstaller.tsindex b3ec3cb01..248521aa9 100644--- a/fluxer_desktop/src/main/ModulePackageInstaller.ts+++ b/fluxer_desktop/src/main/ModulePackageInstaller.ts@@ -13,6 +13,7 @@ import {ModuleStoreDownloadHashMismatchError,} from '@electron/main/ModuleStore';import type {ModulePlanItem} from '@electron/main/ModuleUpdatePlanner';+import {DESKTOP_PACKAGE_LOOPBACK_HOSTS} from '@electron/main/ShellDownloadFormats';const MODULE_PACKAGE_HASH_MISMATCH_RETRIES = 1;const MODULE_PACKAGE_HEADER_TIMEOUT_MS = 30000;@@ -21,7 +22,6 @@ const MODULE_PACKAGE_PROGRESS_INTERVAL_MS = 250;const TRANSIENT_HTTP_STATUS_FLOOR = 500;const TRANSIENT_PACKAGE_HTTP_STATUSES: ReadonlySet<number> = new Set([408, 425, 429]);const CAUSE_CHAIN_LIMIT = 8;-const MODULE_LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['127.0.0.1', 'localhost']);const DETERMINISTIC_PACKAGE_IO_CODES: ReadonlySet<string> = new Set(['EEXIST', 'EISDIR', 'ENOTDIR']);const HTTP_PARTIAL_CONTENT = 206;const HTTP_RANGE_NOT_SATISFIABLE = 416;@@ -457,7 +457,7 @@ export class ModulePackageInstaller {return url.toString();}const base = new URL(this.packageOrigin);- if (url.protocol === 'http:' && url.origin === base.origin && MODULE_LOOPBACK_HOSTS.has(base.hostname)) {+ if (url.protocol === 'http:' && url.origin === base.origin && DESKTOP_PACKAGE_LOOPBACK_HOSTS.has(base.hostname)) {return url.toString();}throw new ModulePackageUrlPolicyError(item.module, item.entry.url);diff --git a/fluxer_desktop/src/main/NativeAudio.ts b/fluxer_desktop/src/main/NativeAudio.tsindex 7c5c88bb0..7cbea15e1 100644--- a/fluxer_desktop/src/main/NativeAudio.ts+++ b/fluxer_desktop/src/main/NativeAudio.ts@@ -666,7 +666,7 @@ function reconfigureCaptureById(if (session.finalized || session.stopping) return false;if (typeof session.capture.setRoutingRule !== 'function') return false;try {- return session.capture.setRoutingRule({linuxRule});+ return session.capture.setRoutingRule({linuxRule: normalizeLinuxRoutingRule(linuxRule)});} catch (error) {logger.warn('Failed to reconfigure native audio routing in place', {captureId, error});return false;diff --git a/fluxer_desktop/src/main/NotificationsIpc.ts b/fluxer_desktop/src/main/NotificationsIpc.tsindex c7496dd75..d7f2caf50 100644--- a/fluxer_desktop/src/main/NotificationsIpc.ts+++ b/fluxer_desktop/src/main/NotificationsIpc.ts@@ -167,6 +167,7 @@ const activeNotifications = new Map<string, ActiveNotificationHandle>();let notificationIdCounter = 0;let linuxNativeClient: NativeNotificationClient | null = null;+let linuxBodyMarkupSupported: Promise<boolean> | null = null;let linuxNativeWindowGetter: (() => BrowserWindow | null) | null = null;const linuxNativeIdToString = new Map<number, string>();@@ -273,6 +274,24 @@ async function resolveImageDataForLinux(iconSource: string | undefined): Promise}}+function linuxBodyMarkupSupport(client: NativeNotificationClient): Promise<boolean> {+ if (!linuxBodyMarkupSupported) {+ linuxBodyMarkupSupported = client+ .getServerCapabilities()+ .then((capabilities) => capabilities.includes('body-markup'))+ .catch((error) => {+ logger.warn('FreedesktopNotifications.getServerCapabilities failed', {error});+ linuxBodyMarkupSupported = null;+ return false;+ });+ }+ return linuxBodyMarkupSupported;+}++function escapeNotificationMarkup(text: string): string {+ return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');+}+async function showLinuxNativeNotification(id: string,options: NotificationOptions,@@ -282,11 +301,12 @@ async function showLinuxNativeNotification(const previousHandle = activeNotifications.get(id);const replacesId = previousHandle?.type === 'linux-native' ? previousHandle.nativeId : undefined;const imageData = await resolveImageDataForLinux(options.icon);+ const bodyMarkupSupported = await linuxBodyMarkupSupport(client);const payload: NativeNotifyPayload = {appName: DESKTOP_APP_NAME,...(replacesId !== undefined ? {replacesId} : {}),summary: options.title,- body: options.body,+ body: bodyMarkupSupported ? escapeNotificationMarkup(options.body) : options.body,expireTimeoutMs: -1,hints: {urgency: 'normal',diff --git a/fluxer_desktop/src/main/Passkeys.ts b/fluxer_desktop/src/main/Passkeys.tsindex e3779306c..e2a824fe7 100644--- a/fluxer_desktop/src/main/Passkeys.ts+++ b/fluxer_desktop/src/main/Passkeys.ts@@ -51,9 +51,12 @@ const convertDescriptorList = (transports: descriptor.transports,}));const convertRequestOptions = (options: PublicKeyCredentialRequestOptionsJSON): NativeRequestOptionsWithoutOrigin => ({- ...options,- challenge: base64UrlToBuffer(options.challenge),allowCredentials: convertDescriptorList(options.allowCredentials),+ challenge: base64UrlToBuffer(options.challenge),+ extensions: options.extensions,+ rpId: options.rpId,+ timeout: options.timeout,+ userVerification: options.userVerification,});const convertCreationOptions = (options: PublicKeyCredentialCreationOptionsJSON,@@ -166,6 +169,26 @@ const requireOrigin = (origin: string | undefined): string => {return origin;};+const isRpIdAllowedForOrigin = (rpId: string, origin: string): boolean => {+ const hostname = new URL(origin).hostname.toLowerCase();+ const normalizedRpId = rpId.toLowerCase();+ if (hostname === normalizedRpId) {+ return true;+ }+ if (normalizedRpId.includes('.') && hostname.endsWith(`.${normalizedRpId}`)) {+ return true;+ }+ return isOfficialInstanceHost(origin) && isOfficialInstanceHost(`https://${normalizedRpId}`);+};++const requireOriginForRpId = (origin: string | undefined, rpId: string | undefined): string => {+ const ceremonyOrigin = requireOrigin(origin);+ if (rpId && !isRpIdAllowedForOrigin(rpId, ceremonyOrigin)) {+ throw new Error(`Relying party ID ${rpId} is not valid for origin ${ceremonyOrigin}`);+ }+ return ceremonyOrigin;+};+function loadFluxerWebAuthnAddon(): NativeWebAuthnAddon | null {try {const addon = requireModule('@fluxer/webauthn') as NativeWebAuthnAddon;@@ -195,7 +218,7 @@ function createNativePasskeyProviderForAddon(addon: NativeWebAuthnAddon, includeconst requestOptions = convertRequestOptions(options);const credential = await addon.get({...requestOptions,- origin: includeOrigin ? requireOrigin(context.origin) : '',+ origin: includeOrigin ? requireOriginForRpId(context.origin, options.rpId) : '',windowHandle: context.windowHandle,pin: context.pin,});@@ -205,7 +228,7 @@ function createNativePasskeyProviderForAddon(addon: NativeWebAuthnAddon, includeconst creationOptions = convertCreationOptions(options);const credential = await addon.create({...creationOptions,- origin: includeOrigin ? requireOrigin(context.origin) : '',+ origin: includeOrigin ? requireOriginForRpId(context.origin, options.rp?.id) : '',windowHandle: context.windowHandle,pin: context.pin,});diff --git a/fluxer_desktop/src/main/ShellDownloadFormats.ts b/fluxer_desktop/src/main/ShellDownloadFormats.tsindex b4ab99703..98180c443 100644--- a/fluxer_desktop/src/main/ShellDownloadFormats.ts+++ b/fluxer_desktop/src/main/ShellDownloadFormats.ts@@ -13,15 +13,28 @@ const PACKAGE_ORIGIN_ENV = 'FLUXER_DESKTOP_PACKAGE_ORIGIN';const CHANNEL_PACKAGE_ORIGINS: Record<BuildChannel, string> = {stable: 'https://pkgs.fluxer.com',canary: 'https://pkgs.fluxer.com',- development: 'http://localhost:48780',+ development: 'http://127.0.0.1:48780',};+export const DESKTOP_PACKAGE_LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['127.0.0.1', 'localhost', '[::1]']);++function isUsablePackageOrigin(value: string): boolean {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ return false;+ }+ return url.protocol === 'https:' || (url.protocol === 'http:' && DESKTOP_PACKAGE_LOOPBACK_HOSTS.has(url.hostname));+}+export function resolveDesktopPackageOrigin(): string {const override = process.env?.[PACKAGE_ORIGIN_ENV];- if (override == null || override.trim().length === 0) {+ const trimmed = override?.trim() ?? '';+ if (trimmed.length === 0 || !isUsablePackageOrigin(trimmed)) {return CHANNEL_PACKAGE_ORIGINS[BUILD_CHANNEL];}- return override.trim().replace(/\/+$/u, '');+ return trimmed.replace(/\/+$/u, '');}export function getUpdateBaseUrl(platform: NodeJS.Platform = process.platform): string {diff --git a/fluxer_desktop/src/main/ThemeFolderWatch.ts b/fluxer_desktop/src/main/ThemeFolderWatch.tsindex 76828ecd7..421f48c27 100644--- a/fluxer_desktop/src/main/ThemeFolderWatch.ts+++ b/fluxer_desktop/src/main/ThemeFolderWatch.ts@@ -7,6 +7,8 @@ import type {ThemeDirectoryCssFile, ThemeFolderChange, ThemeFolderStatus} from 'import {readThemeCssFile} from '@electron/main/ThemeLinkedFileWatch';const THEME_FOLDER_MAX_CSS_FILES = 200;+const THEME_FOLDER_MAX_ENTRIES = 10_000;+const THEME_FOLDER_MAX_DEPTH = 16;const SKIPPED_DIRECTORY_NAMES: ReadonlySet<string> = new Set(['node_modules']);interface ThemeFolderEntry {@@ -46,12 +48,21 @@ function isMissingError(error: unknown): boolean {export async function listThemeFolderCssFiles(folder: string): Promise<ThemeFolderListing> {const files: Array<string> = [];let truncated = false;- const visit = async (directory: string, root: boolean): Promise<void> => {- let entries: Array<fs.Dirent>;+ let visited = 0;+ const visit = async (directory: string, depth: number): Promise<void> => {+ const entries: Array<fs.Dirent> = [];try {- entries = await fs.promises.readdir(directory, {withFileTypes: true});+ const dir = await fs.promises.opendir(directory);+ for await (const entry of dir) {+ visited += 1;+ if (visited > THEME_FOLDER_MAX_ENTRIES) {+ truncated = true;+ break;+ }+ entries.push(entry);+ }} catch (error) {- if (root) throw error;+ if (depth === 0) throw error;return;}entries.sort((a, b) => a.name.localeCompare(b.name));@@ -60,7 +71,11 @@ export async function listThemeFolderCssFiles(folder: string): Promise<ThemeFoldconst entryPath = path.join(directory, entry.name);if (entry.isDirectory()) {if (entry.name.startsWith('.') || SKIPPED_DIRECTORY_NAMES.has(entry.name)) continue;- await visit(entryPath, false);+ if (depth + 1 > THEME_FOLDER_MAX_DEPTH) {+ truncated = true;+ continue;+ }+ await visit(entryPath, depth + 1);} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.css')) {if (files.length === THEME_FOLDER_MAX_CSS_FILES) {truncated = true;@@ -70,7 +85,7 @@ export async function listThemeFolderCssFiles(folder: string): Promise<ThemeFold}}};- await visit(folder, true);+ await visit(folder, 0);return {files, truncated};}@@ -101,12 +116,6 @@ function diffThemeFolderScan(return {added, changed, removed, renamed};}-function isFlatpakDocumentPortalPath(folder: string): boolean {- const runtimeDir = process.env.XDG_RUNTIME_DIR;- if (runtimeDir && folder.startsWith(`${path.join(runtimeDir, 'doc')}${path.sep}`)) return true;- return /^\/run\/user\/\d+\/doc\//.test(folder);-}-export async function resolveThemeFolderFile(filePath: string, folders: ReadonlyArray<string>): Promise<string | null> {if (folders.length === 0) return null;let realPath: string;@@ -139,7 +148,7 @@ export function createThemeFolderWatch(folder: string,emit: (change: ThemeFolderChange) => void,{- forcePolling = isFlatpakDocumentPortalPath(folder),+ forcePolling = process.platform === 'linux',pollIntervalMs = 2000,debounceMs = 150,reconcileIntervalMs = 30_000,@@ -169,7 +178,9 @@ export function createThemeFolderWatch(const startInterval = (intervalMs: number): void => {clearIntervalTimer();- intervalTimer = setInterval(() => void scan(), intervalMs);+ intervalTimer = setInterval(() => {+ if (!scanning) void scan();+ }, intervalMs);intervalTimer.unref?.();};diff --git a/fluxer_desktop/src/main/Updater.ts b/fluxer_desktop/src/main/Updater.tsindex 0c58e4b83..5bfc65d87 100644--- a/fluxer_desktop/src/main/Updater.ts+++ b/fluxer_desktop/src/main/Updater.ts@@ -9,7 +9,7 @@ import {MANUAL_DESKTOP_FORMATS, type ManualDesktopFormat} from '@electron/main/Simport {resolveShellUpdatePlan, ShellUpdateCapability} from '@electron/main/ShellUpdateCapability';import {DOWNLOAD_PAGE_URL,- getManualDownloadUrl,+ getManualDownloadFile,type ManualLatestFile,type ManualLatestInfo,UPDATE_BASE_URL,@@ -28,6 +28,7 @@ type UpdaterEvent =context: UpdaterContext;version?: string | null;downloadUrl?: string;+ sha256?: string | null;}| {type: 'not-available';@@ -158,11 +159,13 @@ function sendManualUpdateAvailable(context: UpdaterContext,latest: ManualLatestInfo,): void {+ const file = getManualDownloadFile(latest);send(getMainWindow(), {type: 'available',context,version: latest.version,- downloadUrl: getManualDownloadUrl(latest),+ downloadUrl: file.url,+ sha256: file.sha256,});}diff --git a/fluxer_desktop/src/main/UpdaterDownloads.ts b/fluxer_desktop/src/main/UpdaterDownloads.tsindex a860e3c82..85cce0fb3 100644--- a/fluxer_desktop/src/main/UpdaterDownloads.ts+++ b/fluxer_desktop/src/main/UpdaterDownloads.ts@@ -25,12 +25,12 @@ function getManualDownloadFormatPreference(): Array<ManualDesktopFormat> {return [];}-export function getManualDownloadUrl(info: ManualLatestInfo): string {+export function getManualDownloadFile(info: ManualLatestInfo): ManualLatestFile {for (const format of getManualDownloadFormatPreference()) {- const url = info.files[format]?.url;- if (url) {- return url;+ const file = info.files[format];+ if (file?.url) {+ return file;}}- return DOWNLOAD_PAGE_URL;+ return {url: DOWNLOAD_PAGE_URL, sha256: null};}