fix(joiner): persist GUI state and guard backend startup (#192)

* fix(joiner): persist GUI state and guard backend startup

* encrypt/decrypt password for desktop joiner local proxy

* hide socks password in desktop joiner logs, restore window size

---------

Co-authored-by: kulikov0 <19497634+kulikov0@users.noreply.github.com>
This commit is contained in:
evgenykeiandkulikov0 authored and GitHub committed 2026-11-04 12:34:17 +01:00
1 parent a46e58d060
commit 7a23110232
11 files changed
+205 -46

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@
</label>
<label>
VP8 batch
<input id="vp8Batch" type="number" value="30" min="1" max="200" />
<input id="vp8Batch" type="number" value="30" min="1" max="256" />
</label>
</div>
<label class="check">
+5 -1
View File
@@ -1,4 +1,5 @@
export const IPC = {
STATE: 'joiner:state',
START: 'joiner:start',
STOP: 'joiner:stop',
LOG: 'joiner:log',
@@ -7,7 +8,10 @@ export const IPC = {
LOGIN_LINK: 'joiner:login-link',
} as const;
export type JoinerPlatform = 'wbstream' | 'telemost' | 'vk' | 'dion' | 'bitrix' | 'blink';
export const JOINER_PLATFORMS = ['wbstream', 'telemost', 'vk', 'dion', 'bitrix', 'blink'] as const;
export type JoinerPlatform = typeof JOINER_PLATFORMS[number];
export const DUAL_TRACK_PLATFORMS: readonly JoinerPlatform[] = ['vk', 'wbstream', 'bitrix', 'blink'];
export const RELIABLE_PLATFORMS: readonly JoinerPlatform[] = ['vk', 'telemost', 'wbstream', 'bitrix', 'blink'];
export interface LoginLink {
link: string;
+100 -35
View File
@@ -1,9 +1,11 @@
import { app, BrowserWindow, ipcMain } from 'electron';
import { app, BrowserWindow, ipcMain, safeStorage } from 'electron';
import { spawn, ChildProcess } from 'node:child_process';
import { existsSync } from 'node:fs';
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
import { join } from 'node:path';
import * as QRCode from 'qrcode';
import { IPC, JoinerSettings } from '../constants';
import { DEFAULT_SETTINGS, buildJoinerArgs, redactLog, validateSettings } from './settings';
import { portIsAvailable } from './port';
// Single global joiner process. We never run two tunnels at once: the
// wintun adapter and the route table are exclusive resources.
@@ -15,6 +17,50 @@ let reconnectTimer: NodeJS.Timeout | null = null;
let retryCount = 0;
let lastSettings: JoinerSettings | null = null;
const MAX_RETRIES = 8;
let startInProgress = false;
let currentStatus = 'idle';
let running = false;
let logBuffer = '';
const profileDir = app.getPath('userData');
mkdirSync(profileDir, { recursive: true });
const settingsFile = join(profileDir, 'settings.json');
function encryptPassword(password: string): string | undefined {
if (!password || !safeStorage.isEncryptionAvailable()) return undefined;
if (process.platform === 'linux' && safeStorage.getSelectedStorageBackend() === 'basic_text') return undefined;
try { return safeStorage.encryptString(password).toString('base64'); }
catch { return undefined; }
}
function decryptPassword(encrypted: unknown): string {
if (typeof encrypted !== 'string' || !encrypted || !safeStorage.isEncryptionAvailable()) return '';
try { return safeStorage.decryptString(Buffer.from(encrypted, 'base64')); }
catch { return ''; }
}
function readSettings(): JoinerSettings {
try {
const { socksPassEncrypted, ...saved } = JSON.parse(readFileSync(settingsFile, 'utf8'));
const settings = { ...DEFAULT_SETTINGS, ...saved, socksPass: decryptPassword(socksPassEncrypted) };
validateSettings(settings);
return settings;
}
catch { return { ...DEFAULT_SETTINGS }; }
}
function saveSettings(settings: JoinerSettings) {
const { socksPass, ...saved } = settings;
const tempFile = settingsFile + '.tmp';
writeFileSync(tempFile, JSON.stringify({ ...saved, socksPassEncrypted: encryptPassword(socksPass) }, null, 2), { mode: 0o600 });
renameSync(tempFile, settingsFile);
}
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) app.quit();
app.on('second-instance', () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
}
});
function openCaptchaWindow(url: string) {
if (captchaWindow && !captchaWindow.isDestroyed()) {
@@ -72,6 +118,12 @@ function resolveJoinerExe(): string {
}
function send(channel: string, payload: unknown) {
if (channel === IPC.LOG) {
payload = redactLog(String(payload), lastSettings);
logBuffer = (logBuffer + payload).slice(-200000);
}
if (channel === IPC.STATUS) currentStatus = String(payload);
if (channel === IPC.RUNNING) running = Boolean(payload);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send(channel, payload);
}
@@ -95,6 +147,7 @@ function createWindow() {
}
app.whenReady().then(() => {
if (!gotLock) return;
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
@@ -102,11 +155,13 @@ app.whenReady().then(() => {
});
app.on('window-all-closed', () => {
userRequestedStop = true;
if (reconnectTimer) clearTimeout(reconnectTimer);
stopJoiner();
if (process.platform !== 'darwin') app.quit();
});
function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string } {
async function spawnJoiner(settings: JoinerSettings): Promise<{ ok: boolean; error?: string }> {
const exe = resolveJoinerExe();
if (!existsSync(exe)) {
return { ok: false, error: `desktop-joiner binary not found at ${exe}` };
@@ -117,33 +172,24 @@ function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string }
if (process.platform !== 'win32' && !noTun && process.getuid && process.getuid() !== 0) {
send(IPC.LOG, `[main] WARNING: ${process.platform} TUN routing needs root; relaunch with sudo or untick the TUN option\n`);
}
const args = [
'--platform', settings.platform,
'--link', settings.link,
'--name', settings.displayName,
'--socks-port', String(settings.socksPort),
'--tunnel-mode', settings.tunnelMode,
'--vp8-fps', String(settings.vp8Fps),
'--vp8-batch', String(settings.vp8Batch),
'--resources', settings.resources,
'--dns', settings.dns,
];
if (settings.socksUser) args.push('--socks-user', settings.socksUser);
if (settings.socksPass) args.push('--socks-pass', settings.socksPass);
if (noTun) args.push('--no-tun');
if (settings.dualTrack && (settings.platform === 'vk' || settings.platform === 'wbstream' || settings.platform === 'bitrix' || settings.platform === 'blink')) {
args.push('--dual-track');
}
if (settings.reliable && (settings.platform === 'vk' || settings.platform === 'wbstream' || settings.platform === 'bitrix' || settings.platform === 'telemost' || settings.platform === 'blink')) {
args.push('--reliable');
let args: string[];
try { args = buildJoinerArgs({ ...settings, noTun }); }
catch (err) { return { ok: false, error: (err as Error).message }; }
if (!(await portIsAvailable(settings.socksPort))) {
return { ok: false, error: 'SOCKS port is already in use. Stop the other client first; no process was changed.' };
}
if (userRequestedStop) return { ok: false, error: 'Start cancelled' };
try { saveSettings(settings); }
catch { return { ok: false, error: 'Cannot save GUI settings' }; }
const elevateOnLinux =
process.platform === 'linux' && !noTun &&
process.getuid && process.getuid() !== 0;
const spawnCmd = elevateOnLinux ? 'pkexec' : exe;
const spawnArgs = elevateOnLinux ? [exe, ...args] : args;
const commandLine = [spawnCmd, ...spawnArgs].map((s) => (/\s/.test(s) ? `"${s}"` : s)).join(' ');
const commandLine = [spawnCmd, ...spawnArgs]
.map((s, index, all) => (all[index - 1] === '--socks-pass' ? '[redacted]' : s))
.map((s) => (/\s/.test(s) ? `"${s}"` : s)).join(' ');
send(IPC.LOG, `[main] spawning: ${commandLine}\n`);
try {
joinerProcess = spawn(spawnCmd, spawnArgs, { windowsHide: true });
@@ -153,16 +199,17 @@ function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string }
send(IPC.RUNNING, true);
send(IPC.STATUS, 'starting');
let spawned = false;
joinerProcess.once('spawn', () => { spawned = true; });
joinerProcess.on('error', (err) => {
send(IPC.LOG, `[main] spawn error: ${err.message}\n`);
send(IPC.STATUS, 'stopped');
send(IPC.RUNNING, false);
joinerProcess = null;
// close also follows a failed spawn. Keep ownership until then and
// emit the terminal state only once, from the close handler.
});
const handleOutput = (text: string) => {
send(IPC.LOG, text);
if (text.includes('TUNNEL ACTIVE')) send(IPC.STATUS, 'active');
if (text.includes('TUNNEL CONNECTED')) {
if (/TUNNEL[ _]ACTIVE/.test(text)) send(IPC.STATUS, 'active');
if (/TUNNEL[ _]CONNECTED/.test(text)) {
send(IPC.STATUS, 'connected');
retryCount = 0;
}
@@ -182,7 +229,7 @@ function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string }
};
joinerProcess.stdout?.on('data', (b: Buffer) => handleOutput(b.toString()));
joinerProcess.stderr?.on('data', (b: Buffer) => handleOutput(b.toString()));
joinerProcess.on('exit', (code, signal) => {
joinerProcess.on('close', (code, signal) => {
closeCaptchaWindow();
send(IPC.LOGIN_LINK, null);
send(IPC.LOG, `\n[main] joiner exited code=${code} signal=${signal}\n`);
@@ -190,7 +237,7 @@ function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string }
send(IPC.RUNNING, false);
joinerProcess = null;
if (userRequestedStop || !lastSettings) return;
if (!spawned || userRequestedStop || !lastSettings) return;
if (retryCount >= MAX_RETRIES) {
send(IPC.LOG, `[main] auto-reconnect: giving up after ${MAX_RETRIES} attempts\n`);
return;
@@ -198,25 +245,43 @@ function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string }
retryCount++;
const delayMs = Math.min(30_000, 2_000 * 2 ** (retryCount - 1));
send(IPC.LOG, `[main] auto-reconnect attempt ${retryCount}/${MAX_RETRIES} in ${Math.round(delayMs / 1000)}s\n`);
reconnectTimer = setTimeout(() => {
send(IPC.STATUS, 'reconnecting');
reconnectTimer = setTimeout(async () => {
reconnectTimer = null;
if (userRequestedStop || !lastSettings) return;
const r = spawnJoiner(lastSettings);
if (!r.ok) send(IPC.LOG, `[main] auto-reconnect spawn failed: ${r.error}\n`);
startInProgress = true;
const r = await spawnJoiner(lastSettings).finally(() => { startInProgress = false; });
if (!r.ok) {
send(IPC.STATUS, 'stopped');
send(IPC.LOG, `[main] auto-reconnect spawn failed: ${r.error}\n`);
}
}, delayMs);
});
return { ok: true };
}
ipcMain.handle(IPC.START, async (_e, settings: JoinerSettings) => {
if (joinerProcess) {
if (joinerProcess || startInProgress) {
return { ok: false, error: 'joiner already running' };
}
userRequestedStop = false;
retryCount = 0;
lastSettings = settings;
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
return spawnJoiner(settings);
startInProgress = true;
try {
const result = await spawnJoiner(settings);
if (!result.ok) send(IPC.STATUS, 'stopped');
return result;
} finally {
startInProgress = false;
}
});
ipcMain.handle(IPC.STATE, async () => {
const settings = lastSettings ?? readSettings();
const occupied = !running && !startInProgress && !(await portIsAvailable(settings.socksPort));
return { settings, running, status: occupied ? 'port in use' : currentStatus, log: logBuffer };
});
ipcMain.handle(IPC.STOP, async () => {
+11
View File
@@ -0,0 +1,11 @@
import { createServer } from 'node:net';
export function portIsAvailable(port: number): Promise<boolean> {
return new Promise((resolve) => {
const server = createServer();
server.once('error', () => resolve(false));
server.listen({ host: '127.0.0.1', port, exclusive: true }, () => {
server.close(() => resolve(true));
});
});
}
+47
View File
@@ -0,0 +1,47 @@
import { DUAL_TRACK_PLATFORMS, JOINER_PLATFORMS, JoinerSettings, RELIABLE_PLATFORMS } from '../constants';
export const DEFAULT_SETTINGS: JoinerSettings = {
platform: 'telemost', link: '', displayName: 'Joiner', socksPort: 1080,
socksUser: '', socksPass: '', tunnelMode: 'video', vp8Fps: 24,
vp8Batch: 30, resources: 'default', dns: '1.1.1.1,8.8.8.8', noTun: false,
dualTrack: false, reliable: false,
};
export function validateSettings(value: JoinerSettings): void {
if (!value || typeof value !== 'object') throw new Error('Invalid settings');
for (const key of ['link', 'displayName', 'socksUser', 'socksPass', 'dns'] as const) {
if (typeof value[key] !== 'string') throw new Error(`Invalid ${key}`);
}
if (!value.link.trim()) throw new Error('Join link is required');
if (!JOINER_PLATFORMS.includes(value.platform)) throw new Error('Invalid platform');
if (!['video', 'dc'].includes(value.tunnelMode)) throw new Error('Invalid tunnel mode');
if (!['moderate', 'default', 'unlimited'].includes(value.resources)) throw new Error('Invalid resources');
for (const [key, min, max] of [['socksPort', 1, 65535], ['vp8Fps', 1, 60], ['vp8Batch', 1, 256]] as const) {
if (!Number.isInteger(value[key]) || value[key] < min || value[key] > max) throw new Error(`Invalid ${key}`);
}
for (const key of ['noTun', 'dualTrack', 'reliable'] as const) {
if (typeof value[key] !== 'boolean') throw new Error(`Invalid ${key}`);
}
}
export function buildJoinerArgs(settings: JoinerSettings): string[] {
validateSettings(settings);
const args = [
'--platform', settings.platform, '--link', settings.link,
'--name', settings.displayName, '--socks-port', String(settings.socksPort),
'--tunnel-mode', settings.tunnelMode, '--vp8-fps', String(settings.vp8Fps),
'--vp8-batch', String(settings.vp8Batch), '--resources', settings.resources,
'--dns', settings.dns,
];
if (settings.socksUser) args.push('--socks-user', settings.socksUser);
if (settings.socksPass) args.push('--socks-pass', settings.socksPass);
if (settings.noTun) args.push('--no-tun');
if (settings.dualTrack && DUAL_TRACK_PLATFORMS.includes(settings.platform)) args.push('--dual-track');
if (settings.reliable && RELIABLE_PLATFORMS.includes(settings.platform)) args.push('--reliable');
return args;
}
export function redactLog(text: string, settings: JoinerSettings | null): string {
if (settings?.link) text = text.split(settings.link).join('[redacted]');
return text;
}
+1
View File
@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from 'electron';
import { IPC, JoinerSettings, LoginLink } from '../constants';
contextBridge.exposeInMainWorld('bridge', {
state: () => ipcRenderer.invoke(IPC.STATE),
start: (settings: JoinerSettings) => ipcRenderer.invoke(IPC.START, settings),
stop: () => ipcRenderer.invoke(IPC.STOP),
onLog(cb: (text: string) => void) {
+34 -3
View File
@@ -25,6 +25,7 @@ function platformLabel(p: JoinerPlatform | null): string {
}
interface Bridge {
state(): Promise<{ settings: any; running: boolean; status: string; log: string }>;
start(settings: any): Promise<{ ok: boolean; error?: string }>;
stop(): Promise<{ ok: boolean }>;
onLog(cb: (text: string) => void): void;
@@ -51,6 +52,7 @@ const loginLinkEl = $('loginLink');
const copyLoginLinkBtn = $('copyLoginLink') as HTMLButtonElement;
stopBtn.disabled = true;
startBtn.disabled = true;
downloadLogsBtn.addEventListener('click', () => {
const blob = new Blob([logEl.textContent || ''], { type: 'text/plain' });
@@ -89,9 +91,32 @@ bridge.onStatus((s) => {
statusEl.textContent = s;
statusEl.dataset.state = s;
});
bridge.onRunning((running) => {
function setRunning(running: boolean) {
startBtn.disabled = running;
stopBtn.disabled = !running;
document.querySelectorAll<HTMLInputElement | HTMLSelectElement>('.form input, .form select')
.forEach((element) => { element.disabled = running; });
}
bridge.onRunning(setRunning);
bridge.state().then((state) => {
const settings = state.settings;
const fields: Record<string, string> = {
link: 'link', name: 'displayName', socksPort: 'socksPort',
socksUser: 'socksUser', socksPass: 'socksPass', tunnelMode: 'tunnelMode',
vp8Fps: 'vp8Fps', vp8Batch: 'vp8Batch', resources: 'resources', dns: 'dns',
};
for (const [id, key] of Object.entries(fields)) {
(document.getElementById(id) as HTMLInputElement).value = String(settings[key] ?? '');
}
for (const key of ['noTun', 'dualTrack', 'reliable']) input(key).checked = Boolean(settings[key]);
refreshPlatformHint();
statusEl.textContent = state.status;
statusEl.dataset.state = state.status;
appendLog(state.log);
setRunning(state.running);
}).catch(() => {
appendLog('[ui] Could not load saved settings.\n');
startBtn.disabled = false;
});
bridge.onLoginLink((login) => {
loginCard.hidden = !login;
@@ -133,8 +158,14 @@ startBtn.addEventListener('click', async () => {
dualTrack: input('dualTrack').checked,
reliable: input('reliable').checked,
};
const r = await bridge.start(settings);
if (!r.ok) appendLog(`[ui] start failed: ${r.error}\n`);
startBtn.disabled = true;
try {
const r = await bridge.start(settings);
if (!r.ok) { appendLog(`[ui] start failed: ${r.error}\n`); setRunning(false); }
} catch {
appendLog('[ui] Could not start the client.\n');
setRunning(false);
}
});
stopBtn.addEventListener('click', async () => {
+1 -1
View File
@@ -27,7 +27,7 @@ h1 { font-size: 14px; margin: 0; }
.status[data-state="active"], .status[data-state="connected"] { background: var(--ok); color: #fff; }
.status[data-state="stopped"] { background: #4a3030; color: #ffb4a8; }
main { flex: 1; display: grid; grid-template-columns: 1fr 1fr; gap: 12px; padding: 12px; min-height: 0; }
section.form { display: flex; flex-direction: column; gap: 10px; }
section.form { overflow-y: auto; padding-right: 4px; display: flex; flex-direction: column; gap: 10px; }
section.log-wrap { display: flex; flex-direction: column; min-height: 0; }
section.log-wrap h2 { font-size: 12px; margin: 0 0 6px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; display: flex; align-items: center; }
.login-card {
+1 -1
View File
@@ -103,7 +103,7 @@ func (t *Tunnel) Start() error {
Device: "tun://" + dev,
MTU: t.cfg.MTU,
}
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=%s", dev, t.cfg.MTU, proxy)
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=socks5://%s:%d", dev, t.cfg.MTU, t.cfg.SocksHost, t.cfg.SocksPort)
engine.Insert(key)
engine.Start()
+2 -2
View File
@@ -98,8 +98,8 @@ func (t *Tunnel) Start() error {
Device: "tun://" + t.cfg.AdapterName,
MTU: t.cfg.MTU,
}
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=%s",
t.cfg.AdapterName, t.cfg.MTU, proxy)
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=socks5://%s:%d",
t.cfg.AdapterName, t.cfg.MTU, t.cfg.SocksHost, t.cfg.SocksPort)
engine.Insert(key)
engine.Start()
+2 -2
View File
@@ -117,8 +117,8 @@ func (t *Tunnel) Start() error {
Device: "tun://" + t.cfg.AdapterName,
MTU: t.cfg.MTU,
}
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=%s",
t.cfg.AdapterName, t.cfg.MTU, proxy)
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=socks5://%s:%d",
t.cfg.AdapterName, t.cfg.MTU, t.cfg.SocksHost, t.cfg.SocksPort)
engine.Insert(key)
engine.Start()