VPN: skip connecting when the host is reachable directly (TCP check of the SSH/RDP port, option per VPN, on by default); optionally disconnect a VPN started by MrTerm when the last session using it is closed by the user (terminal, SFTP, RDP, port forward, admin tabs; 3 s grace for reconnect/duplicate); README

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-21 22:20:57 +02:00
1 parent c853d13191
commit ac7be8e6af
5 files changed
+87 -26

No files matched your search

+3
View File
@@ -497,6 +497,9 @@
'Edit VPN': 'VPN bearbeiten',
'Office VPN': 'Büro-VPN',
'Disconnect when MrTerm closes': 'Beim Beenden von MrTerm trennen',
'Only connect if the host is not reachable directly': 'Nur verbinden, wenn der Host nicht direkt erreichbar ist',
'Disconnect when the last connection using it is closed': 'Trennen, wenn die letzte Verbindung darüber geschlossen wird',
'Checking whether {host} is reachable …': 'Prüfe, ob {host} erreichbar ist …',
'Assigned hosts': 'Zugeordnete Hosts',
'Configuration is missing.': 'Konfiguration fehlt.',
'This does not look like a WireGuard configuration.': 'Das sieht nicht nach einer WireGuard-Konfiguration aus.',
+22 -16
View File
@@ -158,6 +158,7 @@ function openTabWindow(data, pos) {
for (const [id, o] of sessionOwner) {
if (o !== w) continue;
sessionOwner.delete(id);
vpnRelease(id);
for (const m of [ssh, docker, firewall, network, ...Object.values(admins)]) { try { m.close(id); } catch {} }
}
});
@@ -282,17 +283,21 @@ handle('vault:remove', async (col, id) => {
return store.remove(col, id);
});
// VPN vor dem Verbinden aufbauen; owner = Sitzung, die es nutzt (Freigabe beim Schließen)
async function vpnFor(host, owner, onStatus) { if (await vpn.ensureForHost(host, onStatus, owner)) send('vpn:changed'); }
const vpnRelease = (owner) => vpn.release(owner, () => send('vpn:changed'));
// ---------- Docker ----------
handle('docker:open', async (id, hostRef) => {
const host = hostWithOverrides(hostRef);
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host, id);
return docker.open(id, host, () => send('docker:closed', id));
});
handle('docker:list', (id) => docker.list(id));
handle('docker:stats', (id) => docker.stats(id));
handle('docker:action', (id, action, cid) => docker.action(id, action, cid));
handle('docker:command', (id, kind, cid) => docker.command(id, kind, cid));
handle('docker:close', (id) => docker.close(id));
handle('docker:close', (id) => { vpnRelease(id); return docker.close(id); });
handle('docker:stacks', (id, dir) => docker.stacks(id, dir));
handle('docker:stackRead', (id, file) => docker.readStack(id, file));
handle('docker:stackSave', (id, data) => docker.saveStack(id, data));
@@ -303,18 +308,18 @@ handle('docker:template', (index, url) => composeTemplates.build(index, url));
// ---------- Firewall ----------
handle('firewall:open', async (id, hostRef) => {
const host = hostWithOverrides(hostRef);
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host, id);
return firewall.open(id, host, () => send('firewall:closed', id));
});
handle('firewall:list', (id, backend) => firewall.list(id, backend));
handle('firewall:ufw', (id, op, args) => firewall.ufw(id, op, args));
handle('firewall:ipt', (id, op, args) => firewall.ipt(id, op, args));
handle('firewall:close', (id) => firewall.close(id));
handle('firewall:close', (id) => { vpnRelease(id); return firewall.close(id); });
// ---------- Netzwerk ----------
handle('network:open', async (id, hostRef) => {
const host = hostWithOverrides(hostRef);
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host, id);
return network.open(id, host, () => send('network:closed', id));
});
handle('network:read', (id) => network.read(id));
@@ -324,18 +329,18 @@ handle('network:hostname', (id, name) => network.setHostname(id, name));
handle('network:resolv', (id, servers, search) => network.setResolv(id, servers, search));
handle('network:readFile', (id, path) => network.readFile(id, path));
handle('network:writeFile', (id, path, content, verify) => network.writeFile(id, path, content, verify));
handle('network:close', (id) => network.close(id));
handle('network:close', (id) => { vpnRelease(id); return network.close(id); });
// ---------- Webserver / Zertifikate / Samba-AD ----------
for (const [p, m] of Object.entries(admins)) {
handle(`${p}:open`, async (id, hostRef) => {
const host = hostWithOverrides(hostRef);
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host, id);
return m.open(id, host, () => send(`${p}:closed`, id));
});
handle(`${p}:read`, (id) => m.read(id));
handle(`${p}:op`, (id, op, ...args) => m.op(id, op, ...args));
handle(`${p}:close`, (id) => m.close(id));
handle(`${p}:close`, (id) => { vpnRelease(id); return m.close(id); });
}
handle('certs:probe', (host, port) => probeTls(host, port));
@@ -458,13 +463,13 @@ handle('ssh:open', async (sessionId, hostRef, size) => {
const host = hostWithOverrides(hostRef);
if (host.id && !host.execCommand) store.addHistory({ hostId: host.id, at: Date.now() });
const onEvent = (type, payload) => send('ssh:event', sessionId, type, payload);
if (await vpn.ensureForHost(host, (m) => onEvent('status', m))) send('vpn:changed');
await vpnFor(host, sessionId, (m) => onEvent('status', m));
await ssh.openShell(sessionId, host, size, (type, payload) => send('ssh:event', sessionId, type, payload));
return true;
});
ipcMain.on('ssh:write', (_e, id, data) => ssh.write(id, data));
ipcMain.on('ssh:resize', (_e, id, cols, rows) => ssh.resize(id, cols, rows));
ipcMain.on('ssh:close', (_e, id) => ssh.close(id));
ipcMain.on('ssh:close', (_e, id) => { vpnRelease(id); ssh.close(id); });
ipcMain.on('secret:reply', (_e, reqId, value) => {
pendingSecrets.get(reqId)?.(value);
pendingSecrets.delete(reqId);
@@ -473,7 +478,7 @@ ipcMain.on('secret:reply', (_e, reqId, value) => {
// ---------- SFTP ----------
handle('sftp:open', async (sessionId, hostRef) => {
const host = hostWithOverrides(hostRef);
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host, sessionId);
return ssh.openSftp(sessionId, host);
});
handle('sftp:list', (id, dir) => ssh.sftpList(id, dir));
@@ -491,7 +496,7 @@ handle('sftp:transfer', async (id, dir, localPath, remotePath, transferId) => {
});
return true;
});
handle('sftp:close', (id) => ssh.close(id));
handle('sftp:close', (id) => { vpnRelease(id); return ssh.close(id); });
// Lokales Dateisystem (für den Dual-Pane-SFTP-Browser)
handle('local:home', () => os.homedir());
@@ -517,17 +522,17 @@ handle('local:op', (op, a, b) => {
handle('fw:start', async (id) => {
const fw = store.get().forwards.find((f) => f.id === id);
if (!fw) throw new Error(i18n.t('Rule not found'));
if (await vpn.ensureForHost(store.resolveHost(fw.hostId))) send('vpn:changed');
await vpnFor(store.resolveHost(fw.hostId), 'fw:' + id);
return ssh.startForward(fw, (ev) => send('fw:event', id, ev));
});
handle('fw:stop', (id) => ssh.stopForward(id));
handle('fw:stop', (id) => { vpnRelease('fw:' + id); return ssh.stopForward(id); });
handle('fw:active', () => ssh.activeForwards());
// ---------- RDP ----------
handle('rdp:detect', () => rdp.detect(store.get().settings));
handle('rdp:launch', async (hostId) => {
const host = hostWithOverrides(hostId);
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host);
if (host.id) store.addHistory({ hostId: host.id, at: Date.now() });
const r = rdp.launch(host, store.get().settings);
if (r.process) {
@@ -547,7 +552,7 @@ handle('rdp:embedSupported', () => {
handle('rdp:open', async (id, hostRef, bounds) => {
const host = hostWithOverrides(hostRef);
if (host.id) store.addHistory({ hostId: host.id, at: Date.now() });
if (await vpn.ensureForHost(host)) send('vpn:changed');
await vpnFor(host, id);
const sess = { cancelled: false };
rdpSessions.set(id, sess);
return startRdpEmbed(id, sess, host, bounds);
@@ -593,6 +598,7 @@ ipcMain.on('rdp:show', (_e, id) => { const s = rdpSessions.get(id); if (s) { s.h
ipcMain.on('rdp:hide', (_e, id) => { const s = rdpSessions.get(id); if (s) { s.hidden = true; try { s.emb.hide(); } catch {} } });
ipcMain.on('rdp:focus', (_e, id) => { try { rdpSessions.get(id)?.emb.focus(); } catch {} });
ipcMain.on('rdp:close', (_e, id) => {
vpnRelease(id);
const s = rdpSessions.get(id);
if (!s) return;
s.cancelled = true;
+53 -9
View File
@@ -4,6 +4,7 @@
// Windows: WireGuard als Tunnel-Dienst über wireguard.exe (UAC-Abfrage), OpenVPN über die OpenVPN GUI.
const { execFile, spawn } = require('child_process');
const fs = require('fs');
const net = require('net');
const os = require('os');
const path = require('path');
const i18n = require('../i18n');
@@ -17,6 +18,18 @@ function exec(cmd, args) {
}
const lastLine = (s) => s.split('\n').map((l) => l.trim()).filter(Boolean).slice(-1)[0] || '';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Ist der Host ohne VPN erreichbar? (TCP-Verbindung zum SSH-/RDP-Port mit kurzem Timeout)
function reachable(h, timeout = 1500) {
return new Promise((resolve) => {
if (!h.address) return resolve(false);
const port = Number(h.port) || (h.protocol === 'rdp' ? 3389 : 22);
const s = net.connect({ host: h.address, port, timeout });
const done = (ok) => { s.destroy(); resolve(ok); };
s.once('connect', () => done(true));
s.once('timeout', () => done(false));
s.once('error', () => done(false));
});
}
class VpnManager {
constructor(store, userDir) {
@@ -24,6 +37,7 @@ class VpnManager {
this.dir = path.join(userDir, 'vpn');
this.busy = new Map(); // id -> laufendes up() (parallele Verbindungen zum selben VPN nur einmal aufbauen)
this.started = new Set(); // von MrTerm aufgebaute VPNs
this.users = new Map(); // VPN-ID -> Set der Sitzungen, die es gerade nutzen (nur von MrTerm aufgebaute VPNs)
}
get(id) { return this.store.get().vpns.find((v) => v.id === id); }
@@ -163,20 +177,50 @@ class VpnManager {
} catch { /* VPN-Werkzeuge fehlen – nichts aufzuräumen */ }
}
// Alle VPNs eines Hosts (inkl. Jump-Host-Kette) aufbauen, bevor verbunden wird
async ensureForHost(host, onStatus = () => {}) {
const ids = [];
// Alle VPNs eines Hosts (inkl. Jump-Host-Kette) aufbauen, bevor verbunden wird.
// owner: Sitzungs-ID; mit release(owner) wird das VPN wieder getrennt, sobald keine Sitzung es mehr nutzt.
async ensureForHost(host, onStatus = () => {}, owner = null) {
const hops = [];
for (let h = host, n = 0; h && n < 10; h = h.jumpHostId ? this.store.resolveHost(h.jumpHostId) : null, n++) {
if (h.vpnId && !ids.includes(h.vpnId)) ids.push(h.vpnId);
if (h.vpnId && !hops.some((x) => x.id === h.vpnId)) hops.push({ id: h.vpnId, host: h });
}
for (const id of ids.reverse()) {
let changed = false;
for (const { id, host: h } of hops.reverse()) {
const v = this.get(id);
if (!v) continue;
if (await this.isUp(v)) continue;
onStatus(i18n.t('Connecting VPN “{name}” …', { name: v.label }));
await this.up(id);
if (!(await this.isUp(v))) {
// Host direkt erreichbar (z. B. im selben Netz) -> VPN nicht nötig
if (v.onlyIfUnreachable !== false) {
onStatus(i18n.t('Checking whether {host} is reachable …', { host: h.address }));
if (await reachable(h)) continue;
}
onStatus(i18n.t('Connecting VPN “{name}” …', { name: v.label }));
await this.up(id);
changed = true;
}
if (owner && this.started.has(id)) {
if (!this.users.has(id)) this.users.set(id, new Set());
this.users.get(id).add(owner);
}
}
return changed;
}
// Sitzung wurde vom Benutzer geschlossen: VPNs mit "beim Schließen trennen" abbauen, wenn sie niemand mehr nutzt
release(owner, onChange = () => {}) {
for (const [id, set] of this.users) {
if (!set.delete(owner) || set.size) continue;
this.users.delete(id);
const v = this.get(id);
if (!v?.disconnectOnClose) continue;
// kurz warten: "Neu verbinden" oder "Duplizieren" soll das VPN nicht trennen
setTimeout(async () => {
if (this.users.get(id)?.size) return;
await this.down(id).catch(() => {});
this.started.delete(id);
onChange();
}, 3000);
}
return ids.length > 0;
}
}
+3 -1
View File
@@ -897,6 +897,8 @@ function editVpn(v = {}, pick = false) {
field(T('Name'), 'label', v.label, { placeholder: T('Office VPN') }),
cfg,
ovpnBox,
check(T('Only connect if the host is not reachable directly'), 'onlyIfUnreachable', v.onlyIfUnreachable !== false),
check(T('Disconnect when the last connection using it is closed'), 'disconnectOnClose', !!v.disconnectOnClose),
check(T('Disconnect when MrTerm closes'), 'disconnectOnQuit', v.disconnectOnQuit !== false),
heading(T('Assigned hosts')),
hostBox,
@@ -904,7 +906,7 @@ function editVpn(v = {}, pick = false) {
const f = formValues(form);
if (!f.config.trim()) throw new Error(T('Configuration is missing.'));
if (type === 'wireguard' && !/\[Interface\]/i.test(f.config)) throw new Error(T('This does not look like a WireGuard configuration.'));
const item = { ...v, type, label: f.label.trim() || VPN_TYPES[type], config: f.config, disconnectOnQuit: f.disconnectOnQuit,
const item = { ...v, type, label: f.label.trim() || VPN_TYPES[type], config: f.config, disconnectOnQuit: f.disconnectOnQuit, onlyIfUnreachable: f.onlyIfUnreachable, disconnectOnClose: f.disconnectOnClose,
username: type === 'openvpn' ? f.username : '', password: type === 'openvpn' ? f.password : '' };
const saved = await call('vault:upsert', 'vpns', item);
askShareSecret('vpns', saved, saved.label);