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

This commit is contained in:
evgenykei committed 2026-10-29 11:21:39 +03:00
1 parent 66cba1a228
commit 9b554bb93b
11 files changed
+353 -37

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="3000" />
</label>
</div>
<label class="check">
+1
View File
@@ -1,4 +1,5 @@
export const IPC = {
STATE: 'joiner:state',
START: 'joiner:start',
STOP: 'joiner:stop',
LOG: 'joiner:log',
+83 -32
View File
@@ -1,8 +1,10 @@
import { app, BrowserWindow, ipcMain } 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 { 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.
@@ -14,6 +16,37 @@ 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 readSettings(): JoinerSettings {
try {
const settings = { ...DEFAULT_SETTINGS, ...JSON.parse(readFileSync(settingsFile, 'utf8')), socksPass: '' };
validateSettings(settings);
return settings;
}
catch { return { ...DEFAULT_SETTINGS }; }
}
function saveSettings(settings: JoinerSettings) {
const tempFile = settingsFile + '.tmp';
writeFileSync(tempFile, JSON.stringify({ ...settings, 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()) {
@@ -60,6 +93,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);
}
@@ -67,8 +106,10 @@ function send(channel: string, payload: unknown) {
function createWindow() {
mainWindow = new BrowserWindow({
width: 900,
height: 600,
width: 1060,
height: 780,
minWidth: 850,
minHeight: 650,
title: 'WhitelistBypass Joiner',
icon: join(__dirname, '..', '..', 'resources', 'icon.png'),
webPreferences: {
@@ -83,6 +124,7 @@ function createWindow() {
}
app.whenReady().then(() => {
if (!gotLock) return;
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
@@ -90,11 +132,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}` };
@@ -105,26 +149,15 @@ 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')) {
args.push('--dual-track');
}
if (settings.reliable && (settings.platform === 'wbstream' || settings.platform === 'bitrix' || settings.platform === 'telemost')) {
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 &&
@@ -145,12 +178,12 @@ function spawnJoiner(settings: JoinerSettings): { ok: boolean; error?: string }
send(IPC.LOG, `[main] spawn error: ${err.message}\n`);
send(IPC.STATUS, 'stopped');
send(IPC.RUNNING, false);
joinerProcess = null;
// Keep ownership until close so an old child cannot clear a newer start.
});
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;
}
@@ -163,7 +196,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.LOG, `\n[main] joiner exited code=${code} signal=${signal}\n`);
send(IPC.STATUS, 'stopped');
@@ -178,25 +211,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 = 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));
});
});
}
+49
View File
@@ -0,0 +1,49 @@
import { JoinerSettings } 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 (!['telemost', 'wbstream', 'vk', 'dion', 'bitrix'].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, 3000]] 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 && ['vk', 'wbstream', 'bitrix'].includes(settings.platform)) args.push('--dual-track');
if (settings.reliable && ['telemost', 'wbstream', 'bitrix'].includes(settings.platform)) args.push('--reliable');
return args;
}
export function redactLog(text: string, settings: JoinerSettings | null): string {
for (const secret of [settings?.link, settings?.socksPass]) {
if (secret) text = text.split(secret).join('[redacted]');
}
return text;
}
+1
View File
@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from 'electron';
import { IPC, JoinerSettings } 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
@@ -22,6 +22,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;
@@ -43,6 +44,7 @@ const platformHint = $('platformHint');
const linkInput = input('link');
stopBtn.disabled = true;
startBtn.disabled = true;
downloadLogsBtn.addEventListener('click', () => {
const blob = new Blob([logEl.textContent || ''], { type: 'text/plain' });
@@ -81,9 +83,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;
});
startBtn.addEventListener('click', async () => {
@@ -114,8 +139,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; }
.log-download-btn { width: 14px; height: 14px; margin-left: auto; cursor: pointer; filter: invert(0.55); }
@@ -0,0 +1,75 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const vm = require('node:vm');
const fs = require('node:fs');
const path = require('node:path');
const { EventEmitter } = require('node:events');
const { DEFAULT_SETTINGS } = require('../dist/main/settings');
function harness(portCheck = async () => true) {
const app = new EventEmitter();
app.getPath = () => '/mock-profile';
app.requestSingleInstanceLock = () => true;
app.whenReady = () => Promise.resolve();
app.quit = () => {};
const handlers = new Map(), sent = [], children = [], timers = [], writes = [];
class Window {
constructor() { this.webContents = { send: (...args) => sent.push(args) }; }
isDestroyed() { return false; }
setMenuBarVisibility() {}
loadFile() {}
}
const sandbox = {
exports: {}, __dirname: path.resolve(__dirname, '../dist/main'),
process: { platform: 'win32', arch: 'x64', resourcesPath: '/mock-bin' },
setTimeout: callback => { timers.push(callback); return callback; },
clearTimeout: callback => { const i = timers.indexOf(callback); if (i >= 0) timers.splice(i, 1); },
require: name => {
if (name === 'electron') return { app, BrowserWindow: Window, ipcMain: { handle: (key, fn) => handlers.set(key, fn) } };
if (name === 'node:fs') return {
existsSync: () => true, mkdirSync() {}, renameSync() {},
readFileSync: () => { throw new Error('No saved settings'); },
writeFileSync: (_p, value) => writes.push(value),
};
if (name === './port') return { portIsAvailable: portCheck };
if (name === 'node:child_process') return { spawn: () => {
const child = new EventEmitter();
child.stdout = new EventEmitter(); child.stderr = new EventEmitter();
child.stdin = { write() {}, end() {} }; child.kill = () => {};
children.push(child); return child;
} };
if (name.startsWith('.')) return require(path.resolve(__dirname, '../dist/main', name));
return require(name);
},
};
vm.runInNewContext(fs.readFileSync(path.resolve(__dirname, '../dist/main/index.js'), 'utf8'), sandbox);
return { app, sent, children, timers, writes, call: (key, settings) => handlers.get('joiner:' + key)(null, settings) };
}
const settings = { ...DEFAULT_SETTINGS, link: 'https://telemost.yandex.ru/j/example', socksPass: 'private-test-password' };
test('busy port refuses startup without spawning or persisting settings', async () => {
const h = harness(async () => false);
assert.equal((await h.call('start', settings)).ok, false);
assert.equal(h.children.length, 0);
assert.equal(h.writes.length, 0);
});
test('Stop during asynchronous port check cancels pending startup', async () => {
let resolve;
const h = harness(() => new Promise(r => { resolve = r; }));
const pending = h.call('start', settings);
await h.call('stop'); resolve(true);
assert.equal((await pending).ok, false);
assert.equal(h.children.length, 0);
});
test('connected status recognizes underscore, persists no password and closing cancels reconnect', async () => {
const h = harness();
assert.equal((await h.call('start', settings)).ok, true);
assert.equal(JSON.parse(h.writes[0]).socksPass, '');
h.children[0].stdout.emit('data', Buffer.from('TUNNEL_CONNECTED\n'));
assert.ok(h.sent.some(([channel, value]) => channel === 'joiner:status' && value === 'connected'));
assert.ok(!h.sent.filter(([channel]) => channel === 'joiner:log').some(([, value]) => value.includes(settings.link) || value.includes(settings.socksPass)));
h.children[0].emit('close', 1, null);
assert.equal(h.timers.length, 1);
h.app.emit('window-all-closed');
assert.equal(h.timers.length, 0);
});
+50
View File
@@ -0,0 +1,50 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const net = require('node:net');
const { DEFAULT_SETTINGS, buildJoinerArgs, redactLog } = require('../dist/main/settings');
const { portIsAvailable } = require('../dist/main/port');
const base = { ...DEFAULT_SETTINGS, socksPort: 10809, vp8Batch: 300, dns: '1.1.1.1', noTun: true, reliable: true, link: 'https://telemost.yandex.ru/j/test-placeholder' };
test('Telemost GUI launches the agreed SOCKS-only reliable video configuration', () => {
const args = buildJoinerArgs(base);
for (const [key, value] of Object.entries({
'--platform': 'telemost', '--socks-port': '10809', '--vp8-fps': '24',
'--vp8-batch': '300', '--tunnel-mode': 'video', '--dns': '1.1.1.1',
})) assert.equal(args[args.indexOf(key) + 1], value);
assert.ok(args.includes('--reliable'));
assert.ok(args.includes('--no-tun'));
assert.ok(!args.includes('--debug'));
});
test('KCP checkbox controls the Telemost flag and WB Stream keeps its flag', () => {
assert.ok(!buildJoinerArgs({ ...base, reliable: false }).includes('--reliable'));
assert.ok(buildJoinerArgs({ ...base, platform: 'wbstream' }).includes('--reliable'));
const bitrix = buildJoinerArgs({ ...base, platform: 'bitrix', dualTrack: true });
assert.ok(bitrix.includes('--reliable'));
assert.ok(bitrix.includes('--dual-track'));
});
test('invalid ports and malformed settings fail before spawning a child', () => {
for (const socksPort of [0, 65536, 10809.5, NaN]) assert.throws(() => buildJoinerArgs({ ...base, socksPort }));
assert.throws(() => buildJoinerArgs({ ...base, noTun: 'true' }));
assert.throws(() => buildJoinerArgs({ ...base, link: '' }));
});
test('log output does not expose the conference link or SOCKS password', () => {
const settings = { ...base, socksPass: 'test-secret' };
const result = redactLog('run --link ' + settings.link + ' --socks-pass test-secret', settings);
assert.ok(!result.includes(settings.link));
assert.ok(!result.includes('test-secret'));
});
test('a live listener is rejected without interrupting it, then the released port is usable', async () => {
const server = net.createServer((socket) => socket.end('still-alive'));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
try {
assert.equal(await portIsAvailable(port), false);
const data = await new Promise((resolve, reject) => {
const socket = net.connect(port, '127.0.0.1');
socket.on('data', (chunk) => resolve(chunk.toString()));
socket.on('error', reject);
});
assert.equal(data, 'still-alive');
} finally { await new Promise((resolve) => server.close(resolve)); }
assert.equal(await portIsAvailable(port), true);
});