fix(desktop): harden capture and release packaging (#2049)

This commit is contained in:
Hampus authored and GitHub committed 2026-08-27 23:54:38 +02:00
1 parent 5ee59c4675
commit 374db9ed2b
25 files changed
+1394 -1317

No files matched your search

-1
View File
@@ -688,7 +688,6 @@ export interface ElectronAPI {
pasteFromClipboard: () => Promise<void>;
onDeepLink: (callback: (url: string) => void) => () => void;
getInitialDeepLink: () => Promise<string | null>;
onRpcNavigate: (callback: (path: string) => void) => () => void;
autostartEnable: () => Promise<void>;
autostartDisable: () => Promise<void>;
autostartIsEnabled: () => Promise<boolean>;
-217
View File
@@ -1,217 +0,0 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import http from 'node:http';
import {BUILD_CHANNEL} from '@electron/common/BuildChannel';
import {CANARY_APP_URL, STABLE_APP_URL} from '@electron/common/Constants';
import {getCustomAppUrl} from '@electron/common/DesktopConfig';
import {getMainWindow, showWindow} from '@electron/main/Window';
import {app} from 'electron';
import log from 'electron-log';
const RPC_PORT = BUILD_CHANNEL === 'canary' ? 21864 : 21863;
const ALLOWED_ORIGINS = [STABLE_APP_URL, CANARY_APP_URL];
const isAllowedOrigin = (origin?: string): boolean => {
if (!origin) return false;
if (ALLOWED_ORIGINS.includes(origin)) return true;
const customUrl = getCustomAppUrl();
return customUrl != null && origin === customUrl;
};
const refererMatchesAllowedOrigin = (referer?: string): boolean => {
if (!referer) return false;
if (ALLOWED_ORIGINS.some((allowed) => referer.startsWith(allowed))) return true;
const customUrl = getCustomAppUrl();
return customUrl != null && referer.startsWith(customUrl);
};
let server: http.Server | null = null;
interface RpcRequest {
method: string;
params?: Record<string, unknown>;
}
interface RpcResponse {
success: boolean;
data?: unknown;
error?: string;
}
const sendJson = (res: http.ServerResponse, status: number, data: RpcResponse) => {
res.writeHead(status, {'Content-Type': 'application/json'});
res.end(JSON.stringify(data));
};
const rejectIfDisallowedPage = (req: http.IncomingMessage, res: http.ServerResponse): boolean => {
const origin = req.headers.origin;
const referer = req.headers.referer;
if (!origin && !referer) {
res.writeHead(403);
res.end();
return true;
}
if (origin && !isAllowedOrigin(origin)) {
res.writeHead(403);
res.end();
return true;
}
if (referer && !refererMatchesAllowedOrigin(referer)) {
res.writeHead(403);
res.end();
return true;
}
if (origin && referer && !referer.startsWith(origin)) {
res.writeHead(403);
res.end();
return true;
}
return false;
};
const handleCors = (req: http.IncomingMessage, res: http.ServerResponse): boolean => {
const origin = req.headers.origin;
if (origin && !isAllowedOrigin(origin)) {
res.writeHead(403);
res.end();
return true;
}
if (origin && isAllowedOrigin(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Max-Age', '86400');
}
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return true;
}
return false;
};
const parseBody = (req: http.IncomingMessage): Promise<RpcRequest | null> => {
return new Promise((resolve) => {
if (req.method !== 'POST') {
resolve(null);
return;
}
let body = '';
req.on('data', (chunk) => {
body += chunk;
if (body.length > 1024 * 1024) {
resolve(null);
}
});
req.on('end', () => {
try {
resolve(JSON.parse(body) as RpcRequest);
} catch {
resolve(null);
}
});
req.on('error', () => resolve(null));
});
};
const handleHealth = (_req: http.IncomingMessage, res: http.ServerResponse) => {
sendJson(res, 200, {
success: true,
data: {
status: 'ok',
channel: BUILD_CHANNEL,
version: app.getVersion(),
platform: process.platform,
},
});
};
const handleNavigate = async (req: http.IncomingMessage, res: http.ServerResponse) => {
const body = await parseBody(req);
if (!body?.params?.path || typeof body.params['path'] !== 'string') {
sendJson(res, 400, {success: false, error: 'Missing or invalid path parameter'});
return;
}
const path = body.params['path'];
const mainWindow = getMainWindow();
if (!mainWindow || mainWindow.isDestroyed()) {
sendJson(res, 503, {success: false, error: 'Main window not available'});
return;
}
mainWindow.webContents.send('rpc-navigate', path);
showWindow();
sendJson(res, 200, {success: true, data: {navigated: true, path}});
};
const handleFocus = (_req: http.IncomingMessage, res: http.ServerResponse) => {
const mainWindow = getMainWindow();
if (!mainWindow || mainWindow.isDestroyed()) {
sendJson(res, 503, {success: false, error: 'Main window not available'});
return;
}
showWindow();
sendJson(res, 200, {success: true, data: {focused: true}});
};
const requestHandler = async (req: http.IncomingMessage, res: http.ServerResponse) => {
const remoteAddress = req.socket.remoteAddress;
if (remoteAddress !== '127.0.0.1' && remoteAddress !== '::1' && remoteAddress !== '::ffff:127.0.0.1') {
res.writeHead(403);
res.end();
return;
}
if (rejectIfDisallowedPage(req, res)) {
return;
}
if (handleCors(req, res)) {
return;
}
const url = req.url ?? '/';
try {
switch (url) {
case '/health':
handleHealth(req, res);
break;
case '/navigate':
await handleNavigate(req, res);
break;
case '/focus':
handleFocus(req, res);
break;
default:
sendJson(res, 404, {success: false, error: 'Not found'});
}
} catch (error) {
log.error('[RPC] Request handler error:', error);
sendJson(res, 500, {success: false, error: 'Internal server error'});
}
};
export const startRpcServer = (): Promise<void> => {
return new Promise((resolve, reject) => {
if (server) {
resolve();
return;
}
server = http.createServer(requestHandler);
server.on('error', (error: NodeJS.ErrnoException) => {
if (error.code === 'EADDRINUSE') {
log.warn(`[RPC] Port ${RPC_PORT} already in use, RPC server disabled`);
server = null;
resolve();
} else {
log.error('[RPC] Server error:', error);
reject(error);
}
});
server.listen(RPC_PORT, '127.0.0.1', () => {
log.info(`[RPC] Server listening on http://127.0.0.1:${RPC_PORT}`);
resolve();
});
});
};
export const stopRpcServer = (): Promise<void> => {
return new Promise((resolve) => {
if (!server) {
resolve();
return;
}
server.close((err) => {
if (err) {
log.error('[RPC] Error closing server:', err);
}
server = null;
resolve();
});
});
};
+1 -5
View File
@@ -68,7 +68,6 @@ import {
import {runNativeModulePreflight} from '@electron/main/NativeModulePreflight';
import {cleanupNativeScreenCapture, registerNativeScreenCaptureHandlers} from '@electron/main/NativeScreenCapture';
import {appendOpenH264Switches} from '@electron/main/OpenH264Manager';
import {startRpcServer, stopRpcServer} from '@electron/main/RpcServer';
import {cleanupLinuxChromiumSpellcheckDictionaries} from '@electron/main/Spellcheck';
import {registerUpdater} from '@electron/main/Updater';
import {
@@ -430,9 +429,6 @@ if (launchConfigurationError) {
showWindow();
}
});
void startRpcServer().catch((error: unknown) => {
log.error('[RPC] Failed to start RPC server:', error);
});
log.info('App initialized successfully');
})
.catch((error: unknown) => {
@@ -478,7 +474,7 @@ if (launchConfigurationError) {
cleanupNativeHardwareEncoderHandlers();
cleanupVirtmic();
destroyDesktopTray();
const asyncCleanups: Array<Promise<unknown>> = [stopRpcServer()];
const asyncCleanups: Array<Promise<unknown>> = [];
if (netLog.currentlyLogging) {
asyncCleanups.push(
netLog.stopLogging().catch((error) => {
-9
View File
@@ -425,15 +425,6 @@ const api: ElectronAPI = {
};
},
getInitialDeepLink: (): Promise<string | null> => ipcRenderer.invoke('get-initial-deep-link'),
onRpcNavigate: (callback: (path: string) => void): (() => void) => {
const handler = (_event: Electron.IpcRendererEvent, path: string): void => {
callback(path);
};
ipcRenderer.on('rpc-navigate', handler);
return () => {
ipcRenderer.removeListener('rpc-navigate', handler);
};
},
autostartEnable: (): Promise<void> => ipcRenderer.invoke('autostart-enable'),
autostartDisable: (): Promise<void> => ipcRenderer.invoke('autostart-disable'),
autostartIsEnabled: (): Promise<boolean> => ipcRenderer.invoke('autostart-is-enabled'),