Compare commits

...
6 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 4a617151ce README: refresh screenshots (new title bar, feature toolbar, VPN options) and add SFTP; add scripts/screenshots.js to regenerate them with demo data and simulated connections
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 22:33:49 +02:00
MrBlake 5386e8bdc0 Version 0.24.0 2026-10-21 22:21:01 +02:00
MrBlakeandClaude Opus 5.5 ac7be8e6af 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]>
2026-10-21 22:20:57 +02:00
MrBlake c853d13191 Version 0.23.1 2026-10-21 22:06:05 +02:00
MrBlakeandClaude Opus 5.5 c599c873d4 README: document SFTP auto-refresh and keyboard shortcuts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 21:39:30 +02:00
MrBlakeandClaude Opus 5.5 2dff4a5c47 Snippets panel updates right after adding a snippet; SFTP explorer refreshes reliably: keeps selection and scroll on refresh, refreshes both panes after delete/rename/mkdir, target pane after each transferred file, auto-refresh on tab/window focus and every 10 s while visible, selects new/renamed items, greys out items being deleted, F5/Del/F2 shortcuts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 21:38:33 +02:00
18 changed files with 409 additions and 52 deletions

No files matched your search

+10 -4
View File
@@ -50,7 +50,7 @@ RDP, SFTP, port forwarding and VPN are only available in the desktop app.
- **Hosts**: nested groups, tags, colors, search and Quick Connect (`user@host:port`, `rdp://host`) - **Hosts**: nested groups, tags, colors, search and Quick Connect (`user@host:port`, `rdp://host`)
- **SSH terminal in tabs**: password, key, SSH agent, keyboard-interactive/2FA, jump hosts (ProxyJump chains), startup command, environment variables, search, zoom and several color schemes - **SSH terminal in tabs**: password, key, SSH agent, keyboard-interactive/2FA, jump hosts (ProxyJump chains), startup command, environment variables, search, zoom and several color schemes
- **SFTP**: two-pane file browser (local ↔ remote), drag & drop, recursive folders, rename, delete, chmod and progress display - **SFTP**: two-pane file browser (local ↔ remote), drag & drop, recursive folders, rename, delete, chmod and progress display; refreshes automatically after every change, when you return to the tab and every 10 seconds, and keeps your selection; shortcuts F5 (refresh), Del (delete) and F2 (rename)
- **RDP in a tab** right inside MrTerm (Windows: `mstsc`, Linux: FreeRDP), or in a separate window if you prefer - **RDP in a tab** right inside MrTerm (Windows: `mstsc`, Linux: FreeRDP), or in a separate window if you prefer
- **Keychain**: generate Ed25519/ECDSA/RSA keys, import existing ones and copy the public key - **Keychain**: generate Ed25519/ECDSA/RSA keys, import existing ones and copy the public key
- **Docker & Podman**: list a host's containers, open a shell inside a container, follow logs, and start, stop, restart or remove containers, all over SSH - **Docker & Podman**: list a host's containers, open a shell inside a container, follow logs, and start, stop, restart or remove containers, all over SSH
@@ -79,9 +79,9 @@ RDP, SFTP, port forwarding and VPN are only available in the desktop app.
| ![Docker containers](docs/screenshots/docker.png) | ![UFW firewall rules](docs/screenshots/firewall.png) | | ![Docker containers](docs/screenshots/docker.png) | ![UFW firewall rules](docs/screenshots/firewall.png) |
| **Docker & Podman** containers with CPU and memory usage | **Firewall** rules for UFW and iptables | | **Docker & Podman** containers with CPU and memory usage | **Firewall** rules for UFW and iptables |
| ![Network configuration](docs/screenshots/network.png) | ![VPN configurations](docs/screenshots/vpn.png) | | ![Network configuration](docs/screenshots/network.png) | ![VPN configurations](docs/screenshots/vpn.png) |
| **Network**: interfaces, bonds (LACP), bridges, gateway and DNS | **VPN**: WireGuard and OpenVPN, connected automatically per host | | **Network**: interfaces, bonds (LACP), bridges, gateway and DNS | **VPN**: WireGuard and OpenVPN, connected automatically per host when it isn't reachable directly |
| ![Settings](docs/screenshots/settings.png) | | | ![SFTP file browser](docs/screenshots/sftp.png) | ![Settings](docs/screenshots/settings.png) |
| **Settings**: language, app lock, LAN sync and themes | | | **SFTP**: local and remote side by side, drag & drop between them | **Settings**: language, app lock, LAN sync and themes |
## Web version (Docker) ## Web version (Docker)
@@ -207,6 +207,12 @@ Under **VPN** in the sidebar you can add WireGuard (`.conf`) and OpenVPN (`.ovpn
When you open an assigned host (terminal, SFTP, RDP or port forwarding), MrTerm connects the VPN first if it isn't already connected. You can also connect and disconnect manually. By default, MrTerm disconnects the VPNs it started when you close it. When you open an assigned host (terminal, SFTP, RDP or port forwarding), MrTerm connects the VPN first if it isn't already connected. You can also connect and disconnect manually. By default, MrTerm disconnects the VPNs it started when you close it.
Each VPN has these options:
- **Only connect if the host is not reachable directly** (on by default): before connecting the VPN, MrTerm briefly tries to reach the host's SSH or RDP port. If the host answers, for example because you are in the same network, the VPN is skipped.
- **Disconnect when the last connection using it is closed**: when you close the last tab, SFTP window or port forward that uses the VPN, MrTerm disconnects it. This only applies to VPNs that MrTerm connected itself. VPNs you connected yourself stay connected.
- **Disconnect when MrTerm closes** (on by default).
- **Linux**: uses NetworkManager, so no root password is needed. For OpenVPN, install the plugin with `sudo pacman -S networkmanager-openvpn`. - **Linux**: uses NetworkManager, so no root password is needed. For OpenVPN, install the plugin with `sudo pacman -S networkmanager-openvpn`.
- **Windows**: WireGuard requires [WireGuard for Windows](https://www.wireguard.com/install/) and asks for administrator permission when connecting. OpenVPN requires the [OpenVPN GUI](https://openvpn.net/community-downloads/). - **Windows**: WireGuard requires [WireGuard for Windows](https://www.wireguard.com/install/) and asks for administrator permission when connecting. OpenVPN requires the [OpenVPN GUI](https://openvpn.net/community-downloads/).
- OpenVPN certificates and keys must be embedded in the `.ovpn` file. - OpenVPN certificates and keys must be embedded in the `.ovpn` file.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

After

Width:  |  Height:  |  Size: 655 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 868 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 576 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 647 KiB

+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "mrterm", "name": "mrterm",
"version": "0.23.0", "version": "0.24.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "mrterm", "name": "mrterm",
"version": "0.23.0", "version": "0.24.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@xterm/addon-fit": "^0.11.0", "@xterm/addon-fit": "^0.11.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "mrterm", "name": "mrterm",
"productName": "MrTerm", "productName": "MrTerm",
"version": "0.23.0", "version": "0.24.0",
"description": "Moderner SSH-, SFTP- und RDP-Client", "description": "Moderner SSH-, SFTP- und RDP-Client",
"main": "src/main/main.js", "main": "src/main/main.js",
"author": "MrBlake", "author": "MrBlake",
+264
View File
@@ -0,0 +1,264 @@
// README-Screenshots mit Demo-Daten erzeugen: npx electron scripts/screenshots.js (läuft ca. 20 s im Hintergrund)
// Startet MrTerm mit einem leeren Profil und einem Demo-Tresor. SSH, SFTP, Docker, Firewall und Netzwerk
// werden simuliert (keine echten Verbindungen), die Bilder landen in docs/screenshots/.
const path = require('path');
const fs = require('fs');
const os = require('os');
const { app, ipcMain, BrowserWindow } = require('electron');
const ROOT = path.join(__dirname, '..');
const OUT = path.join(ROOT, 'docs', 'screenshots');
const profile = path.join(os.tmpdir(), 'mrterm-screenshots');
fs.rmSync(profile, { recursive: true, force: true });
fs.mkdirSync(profile);
app.setPath('userData', profile);
process.env.MRTERM_SCREENSHOTS = '1';
// ---------------------------------------------------------------- Demo-Tresor
const now = Date.now();
const G = { home: 'g-homelab', cloud: 'g-cloud' };
const host = (id, label, address, username, color, groupId, extra = {}) => ({ id, label, address, port: 22, username, protocol: 'ssh', groupId, color, auth: 'password', ...extra });
const vault = {
version: 1,
groups: [{ id: G.cloud, label: 'Cloud', parentId: null }, { id: G.home, label: 'Homelab', parentId: null }],
hosts: [
host('h-pve', 'pve', '192.168.0.20', 'root', '#3ecf8e', G.home),
host('h-docker', 'docker-host', '192.168.0.30', 'admin', '#ffb454', G.home),
host('h-ha', 'home-assistant', '192.168.0.40', 'root', '#c792ea', G.home),
host('h-nas', 'nas', '192.168.0.10', 'admin', '#ff6b6b', G.home),
host('h-win', 'win11-workstation', '192.168.0.55', 'louis', '#ff5c7a', G.home, { protocol: 'rdp', port: 3389 }),
host('h-db', 'db-primary', '10.20.0.5', 'deploy', '#8b93a7', G.cloud, { vpnId: 'v-office', jumpHostId: 'h-web1' }),
host('h-web1', 'web-01', '203.0.113.11', 'deploy', '#7c83ff', G.cloud, { auth: 'key', keyId: 'k-deploy' }),
host('h-web2', 'web-02', '203.0.113.12', 'deploy', '#3ecf8e', G.cloud, { auth: 'key', keyId: 'k-deploy' }),
],
keys: [{ id: 'k-deploy', label: 'deploy@ci', type: 'ed25519', publicKey: 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDemoKeyOnlyForScreenshots deploy@ci', privateKey: '' }],
snippets: [
{ id: 's1', label: 'System update', command: 'sudo apt update && sudo apt upgrade -y', autoRun: true },
{ id: 's2', label: 'Disk usage', command: 'df -h -x tmpfs', autoRun: true },
],
forwards: [],
vpns: [
{ id: 'v-office', type: 'wireguard', label: 'Office', config: '[Interface]\nPrivateKey = demo\nAddress = 10.8.0.2/32\n\n[Peer]\nPublicKey = demo\nEndpoint = vpn.example.com:51820\nAllowedIPs = 10.20.0.0/16', disconnectOnQuit: true, onlyIfUnreachable: true, disconnectOnClose: true },
{ id: 'v-hetzner', type: 'openvpn', label: 'Datacenter', config: 'client\ndev tun\nremote vpn.example.net 1194', disconnectOnQuit: true, onlyIfUnreachable: true },
],
knownHosts: {},
history: [{ hostId: 'h-pve', at: now - 60000 }, { hostId: 'h-docker', at: now - 3600000 }],
aiChats: [],
tombstones: [],
settings: { language: 'en', updateAutoCheck: false },
};
fs.writeFileSync(path.join(profile, 'vault.dat'), JSON.stringify(vault));
// ---------------------------------------------------------------- Simulierte Verbindungen
// Anzeige wie mit System-Keyring ("Vault encrypted"), die Demo-Datei bleibt trotzdem lesbar
const { Store } = require('../src/main/store');
const load = Store.prototype.load;
Store.prototype.load = function () { const d = load.call(this); this.encrypted = true; return d; };
Store.prototype.save = function () {};
const { SshManager } = require('../src/main/ssh');
const { DockerManager } = require('../src/main/docker');
const { FirewallManager, parseUfw, parseIptables } = require('../src/main/firewall');
const { NetworkConfigManager } = require('../src/main/network');
const { VpnManager } = require('../src/main/vpn');
const TERM = [
'\x1b[1;32mroot@pve\x1b[0m:\x1b[1;34m~\x1b[0m# fastfetch --logo none',
'\x1b[1;36mroot\x1b[0m@\x1b[1;36mpve\x1b[0m', '---------',
'\x1b[1;36mOS\x1b[0m: Proxmox VE 8.2.4 (Debian 12 bookworm) x86_64',
'\x1b[1;36mKernel\x1b[0m: 6.8.12-1-pve',
'\x1b[1;36mUptime\x1b[0m: 41 days, 3 hours, 12 mins',
'\x1b[1;36mCPU\x1b[0m: AMD Ryzen 9 5950X (32) @ 5.05 GHz',
'\x1b[1;36mMemory\x1b[0m: 38.21 GiB / 125.71 GiB (30%)',
'\x1b[1;36mDisk (/)\x1b[0m: 18.4 GiB / 94.0 GiB (20%) - ext4',
'\x1b[1;36mLocal IP (vmbr0)\x1b[0m: 192.168.0.20/24', '',
'\x1b[1;32mroot@pve\x1b[0m:\x1b[1;34m~\x1b[0m# qm list',
' VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID',
' 100 docker-host \x1b[32mrunning\x1b[0m 16384 64.00 2231',
' 101 home-assistant \x1b[32mrunning\x1b[0m 4096 32.00 2318',
' 102 win11 \x1b[31mstopped\x1b[0m 8192 128.00 0',
' 103 k3s-node-1 \x1b[32mrunning\x1b[0m 8192 40.00 2502', '',
'\x1b[1;32mroot@pve\x1b[0m:\x1b[1;34m~\x1b[0m# systemctl --failed',
' UNIT LOAD ACTIVE SUB DESCRIPTION', '0 loaded units listed.',
'\x1b[1;32mroot@pve\x1b[0m:\x1b[1;34m~\x1b[0m# ',
].join('\r\n');
SshManager.prototype.openShell = async (sid, h, size, send) => { setTimeout(() => send('data', TERM), 300); };
SshManager.prototype.write = () => {};
SshManager.prototype.resize = () => {};
SshManager.prototype.close = () => {};
const day = 86400000;
const file = (name, size, age, isDir = false) => ({ name, size, mtime: now - age, isDir, isLink: false, mode: isDir ? 0o40755 : 0o100644 });
const REMOTE = {
'/root': [file('backups', 4096, 2 * day, true), file('scripts', 4096, 9 * day, true), file('iso', 4096, 30 * day, true),
file('.bashrc', 3526, 200 * day), file('.profile', 161, 200 * day), file('cluster-notes.md', 4812, 3 * day),
file('vzdump-qemu-100.vma.zst', 8455716864, 1 * day), file('pve-backup.sh', 1893, 12 * day), file('interfaces.bak', 702, 40 * day)],
};
SshManager.prototype.openSftp = async () => ({ home: '/root' });
SshManager.prototype.sftpList = async (id, dir) => REMOTE[dir] || [];
const CONTAINERS = [
['gitea', 'gitea/gitea:1.22', 'running', 'Up 3 days', '0.0.0.0:2222->22/tcp', '0.35%', '154.0MiB'],
['nextcloud', 'nextcloud:29-apache', 'running', 'Up 12 days (healthy)', '', '1.84%', '412.7MiB'],
['nextcloud-db', 'mariadb:11', 'running', 'Up 12 days', '3306/tcp', '0.47%', '188.2MiB'],
['traefik', 'traefik:v3.1', 'running', 'Up 12 days', '0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp', '0.21%', '48.3MiB'],
['uptime-kuma', 'louislam/uptime-kuma:1', 'running', 'Up 12 days (healthy)', '3001/tcp', '0.92%', '96.4MiB'],
['vaultwarden', 'vaultwarden/server:latest', 'running', 'Up 5 days (healthy)', '', '0.03%', '22.9MiB'],
['backup-restic', 'restic/restic:0.17', 'exited', 'Exited (0) 6 hours ago', '', '', ''],
].map(([name, image, state, status, ports, cpu, mem], i) => ({ id: `c0ffee00${i}abc`, name, image, state, status, ports, cpu, mem }));
const dockerList = async () => ({ runtime: 'docker', sudo: false, containers: CONTAINERS.map(({ cpu, mem, ...c }) => c) });
DockerManager.prototype.open = dockerList;
DockerManager.prototype.list = dockerList;
DockerManager.prototype.stats = async () => Object.fromEntries(CONTAINERS.filter((c) => c.cpu).map((c) => [c.id, { cpu: c.cpu, mem: `${c.mem} / 125.7GiB` }]));
DockerManager.prototype.close = () => {};
const UFW = `Status: active
To Action From
-- ------ ----
[ 1] 22/tcp ALLOW IN 192.168.0.0/24 # SSH (MrTerm)
[ 2] 8006/tcp ALLOW IN 192.168.0.0/24 # Proxmox web UI
[ 3] 80,443/tcp ALLOW IN Anywhere # traefik
[ 4] 2222/tcp LIMIT IN Anywhere # gitea ssh
[ 5] 3306/tcp DENY IN Anywhere
[ 6] 51820/udp ALLOW IN Anywhere # WireGuard
[ 7] 80,443/tcp (v6) ALLOW IN Anywhere (v6) # traefik
[ 8] 51820/udp (v6) ALLOW IN Anywhere (v6) # WireGuard`;
const IPT = `-P INPUT DROP
-P FORWARD DROP
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -s 192.168.0.0/24 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT`;
FirewallManager.prototype.open = async () => ({ tools: ['ufw', 'iptables', 'ip6tables'], sudo: false });
FirewallManager.prototype.list = async (id, b) => (b === 'ufw' ? { ...parseUfw(UFW), defaults: { incoming: 'deny', outgoing: 'allow', routed: 'disabled' } } : { chains: parseIptables(IPT) });
FirewallManager.prototype.close = () => {};
const link = (ifname, mac, extra = {}) => ({ ifname, address: mac, mtu: 1500, operstate: 'UP', link_type: 'ether', ...extra });
const GATHER = `@@HOSTNAME
pve
@@OS
Debian GNU/Linux 12 (bookworm)
@@BACKEND
ifupdown
@@LINK
${JSON.stringify([
link('lo', '00:00:00:00:00:00', { link_type: 'loopback' }),
link('eno1', 'a4:bf:01:11:22:01', { master: 'bond0', linkinfo: { info_slave_kind: 'bond' } }),
link('eno2', 'a4:bf:01:11:22:02', { master: 'bond0', linkinfo: { info_slave_kind: 'bond' } }),
link('eno3', 'a4:bf:01:11:22:03', { operstate: 'DOWN' }),
link('bond0', 'a4:bf:01:11:22:01', { master: 'vmbr0', linkinfo: { info_kind: 'bond', info_slave_kind: 'bridge' } }),
link('vmbr0', 'a4:bf:01:11:22:01', { linkinfo: { info_kind: 'bridge' } }),
])}
@@ADDR
${JSON.stringify([{ ifname: 'vmbr0', addr_info: [{ family: 'inet', local: '192.168.0.20', prefixlen: 24, scope: 'global' }, { family: 'inet6', local: '2a01:598::20', prefixlen: 64, scope: 'global' }] }])}
@@ROUTE
${JSON.stringify([{ gateway: '192.168.0.1', dev: 'vmbr0' }])}
@@ROUTE6
[]
@@RESOLVTYPE
file
@@RESOLV
search home.lan
nameserver 192.168.0.202
nameserver 1.1.1.1
@@BONDING
== bond0
Bonding Mode: IEEE 802.3ad Dynamic link aggregation
Transmit Hash Policy: layer2+3 (2)
MII Status: up
LACP rate: fast
Slave Interface: eno1
MII Status: up
Speed: 1000 Mbps
Aggregator ID: 1
Slave Interface: eno2
MII Status: up
Speed: 1000 Mbps
Aggregator ID: 1
@@IFUPDOWN
==FILE /etc/network/interfaces
auto lo
iface lo inet loopback
auto eno1
iface eno1 inet manual
auto eno2
iface eno2 inet manual
auto bond0
iface bond0 inet manual
bond-slaves eno1 eno2
bond-miimon 100
bond-mode 802.3ad
bond-xmit-hash-policy layer2+3
bond-lacp-rate fast
auto vmbr0
iface vmbr0 inet static
address 192.168.0.20/24
gateway 192.168.0.1
bridge-ports bond0
bridge-stp off
bridge-fd 0
@@FILES
/etc/network/interfaces
@@PENDING
@@END`;
NetworkConfigManager.prototype.open = async function (id, h) { this.sessions.set(id, { host: h, sudo: false }); return this.read(id); };
NetworkConfigManager.prototype.rootOk = async () => GATHER;
NetworkConfigManager.prototype.close = () => {};
VpnManager.prototype.status = async () => ({ 'v-office': true });
VpnManager.prototype.ensureForHost = async () => false;
// Lokale Dateien nicht vom echten Rechner zeigen
const LOCAL = '/home/louis';
const LOCAL_FILES = [file('Documents', 4096, 1 * day, true), file('Downloads', 4096, 0.1 * day, true), file('Projects', 4096, 2 * day, true),
file('proxmox-ve_8.2-1.iso', 1356732416, 60 * day), file('nextcloud-compose.yml', 2214, 5 * day), file('notes.txt', 912, 1 * day)];
const realHandle = ipcMain.handle.bind(ipcMain);
const MOCK = { 'local:home': () => LOCAL, 'local:list': () => LOCAL_FILES, 'local:roots': () => [] };
ipcMain.handle = (ch, fn) => realHandle(ch, MOCK[ch] ? async () => ({ ok: true, value: MOCK[ch]() }) : fn);
require('../src/main/main.js');
// ---------------------------------------------------------------- Ablauf
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
app.whenReady().then(async () => {
await sleep(2500);
const win = BrowserWindow.getAllWindows()[0];
win.setSize(1360, 860);
win.show(); win.focus();
win.webContents.setBackgroundThrottling(false);
const js = (code) => win.webContents.executeJavaScript(`(async () => { ${code} })()`);
const shot = async (name, code, wait = 1200) => {
await js(code); await sleep(wait);
// Neu zeichnen erzwingen, sonst liefert capturePage gelegentlich das vorige Bild
win.webContents.invalidate();
await js('await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));');
await sleep(300);
fs.writeFileSync(path.join(OUT, name + '.png'), (await win.webContents.capturePage()).toPNG());
console.log('✓', name);
};
const host = (id) => `S.vault.hosts.find((x) => x.id === '${id}')`;
const home = `activateTab('home');`;
const closeDrawer = `document.querySelectorAll('.drawer-bg, .modal-bg').forEach((e) => e.remove());`;
try {
await shot('hosts', `goGroup('${G.home}');`);
await shot('edit-host', `editHost(${host('h-db')});`);
await js(closeDrawer);
await shot('vpn', `${home} $('#sidebar .nav[data-view=vpns]').click(); editVpn(S.vault.vpns[0]);`);
await js(closeDrawer);
await shot('settings', `$('#sidebar .nav[data-view=settings]').click();`);
await js(`$('#sidebar .nav[data-view=hosts]').click();`);
await shot('terminal', `openTerminal(${host('h-pve')});`, 1800);
await shot('sftp', `openSftp(${host('h-pve')});`);
await shot('docker', `openDocker(${host('h-pve')});`);
await shot('firewall', `openFirewall(${host('h-pve')});`);
await shot('network', `openNetwork(${host('h-pve')});`);
} catch (e) { console.error(e); process.exitCode = 1; }
app.exit();
});
+4
View File
@@ -339,6 +339,7 @@
'Move {n} item(s) to the trash: {list}': '{n} Element(e) in den Papierkorb verschieben: {list}', 'Move {n} item(s) to the trash: {list}': '{n} Element(e) in den Papierkorb verschieben: {list}',
'Permanently delete {n} item(s) from the server: {list}': '{n} Element(e) endgültig vom Server löschen: {list}', 'Permanently delete {n} item(s) from the server: {list}': '{n} Element(e) endgültig vom Server löschen: {list}',
'Nothing selected': 'Nichts ausgewählt', 'Nothing selected': 'Nichts ausgewählt',
'{n} item(s) deleted': '{n} Element(e) gelöscht',
'Try again': 'Erneut versuchen', 'Try again': 'Erneut versuchen',
'done': 'fertig', 'done': 'fertig',
'Error': 'Fehler', 'Error': 'Fehler',
@@ -496,6 +497,9 @@
'Edit VPN': 'VPN bearbeiten', 'Edit VPN': 'VPN bearbeiten',
'Office VPN': 'Büro-VPN', 'Office VPN': 'Büro-VPN',
'Disconnect when MrTerm closes': 'Beim Beenden von MrTerm trennen', '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', 'Assigned hosts': 'Zugeordnete Hosts',
'Configuration is missing.': 'Konfiguration fehlt.', 'Configuration is missing.': 'Konfiguration fehlt.',
'This does not look like a WireGuard configuration.': 'Das sieht nicht nach einer WireGuard-Konfiguration aus.', '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) { for (const [id, o] of sessionOwner) {
if (o !== w) continue; if (o !== w) continue;
sessionOwner.delete(id); sessionOwner.delete(id);
vpnRelease(id);
for (const m of [ssh, docker, firewall, network, ...Object.values(admins)]) { try { m.close(id); } catch {} } 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); 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 ---------- // ---------- Docker ----------
handle('docker:open', async (id, hostRef) => { handle('docker:open', async (id, hostRef) => {
const host = hostWithOverrides(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)); return docker.open(id, host, () => send('docker:closed', id));
}); });
handle('docker:list', (id) => docker.list(id)); handle('docker:list', (id) => docker.list(id));
handle('docker:stats', (id) => docker.stats(id)); handle('docker:stats', (id) => docker.stats(id));
handle('docker:action', (id, action, cid) => docker.action(id, action, cid)); handle('docker:action', (id, action, cid) => docker.action(id, action, cid));
handle('docker:command', (id, kind, cid) => docker.command(id, kind, 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:stacks', (id, dir) => docker.stacks(id, dir));
handle('docker:stackRead', (id, file) => docker.readStack(id, file)); handle('docker:stackRead', (id, file) => docker.readStack(id, file));
handle('docker:stackSave', (id, data) => docker.saveStack(id, data)); handle('docker:stackSave', (id, data) => docker.saveStack(id, data));
@@ -303,18 +308,18 @@ handle('docker:template', (index, url) => composeTemplates.build(index, url));
// ---------- Firewall ---------- // ---------- Firewall ----------
handle('firewall:open', async (id, hostRef) => { handle('firewall:open', async (id, hostRef) => {
const host = hostWithOverrides(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)); return firewall.open(id, host, () => send('firewall:closed', id));
}); });
handle('firewall:list', (id, backend) => firewall.list(id, backend)); handle('firewall:list', (id, backend) => firewall.list(id, backend));
handle('firewall:ufw', (id, op, args) => firewall.ufw(id, op, args)); handle('firewall:ufw', (id, op, args) => firewall.ufw(id, op, args));
handle('firewall:ipt', (id, op, args) => firewall.ipt(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 ---------- // ---------- Netzwerk ----------
handle('network:open', async (id, hostRef) => { handle('network:open', async (id, hostRef) => {
const host = hostWithOverrides(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)); return network.open(id, host, () => send('network:closed', id));
}); });
handle('network:read', (id) => network.read(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:resolv', (id, servers, search) => network.setResolv(id, servers, search));
handle('network:readFile', (id, path) => network.readFile(id, path)); handle('network:readFile', (id, path) => network.readFile(id, path));
handle('network:writeFile', (id, path, content, verify) => network.writeFile(id, path, content, verify)); 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 ---------- // ---------- Webserver / Zertifikate / Samba-AD ----------
for (const [p, m] of Object.entries(admins)) { for (const [p, m] of Object.entries(admins)) {
handle(`${p}:open`, async (id, hostRef) => { handle(`${p}:open`, async (id, hostRef) => {
const host = hostWithOverrides(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)); return m.open(id, host, () => send(`${p}:closed`, id));
}); });
handle(`${p}:read`, (id) => m.read(id)); handle(`${p}:read`, (id) => m.read(id));
handle(`${p}:op`, (id, op, ...args) => m.op(id, op, ...args)); 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)); handle('certs:probe', (host, port) => probeTls(host, port));
@@ -458,13 +463,13 @@ handle('ssh:open', async (sessionId, hostRef, size) => {
const host = hostWithOverrides(hostRef); const host = hostWithOverrides(hostRef);
if (host.id && !host.execCommand) store.addHistory({ hostId: host.id, at: Date.now() }); if (host.id && !host.execCommand) store.addHistory({ hostId: host.id, at: Date.now() });
const onEvent = (type, payload) => send('ssh:event', sessionId, type, payload); 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)); await ssh.openShell(sessionId, host, size, (type, payload) => send('ssh:event', sessionId, type, payload));
return true; return true;
}); });
ipcMain.on('ssh:write', (_e, id, data) => ssh.write(id, data)); 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: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) => { ipcMain.on('secret:reply', (_e, reqId, value) => {
pendingSecrets.get(reqId)?.(value); pendingSecrets.get(reqId)?.(value);
pendingSecrets.delete(reqId); pendingSecrets.delete(reqId);
@@ -473,7 +478,7 @@ ipcMain.on('secret:reply', (_e, reqId, value) => {
// ---------- SFTP ---------- // ---------- SFTP ----------
handle('sftp:open', async (sessionId, hostRef) => { handle('sftp:open', async (sessionId, hostRef) => {
const host = hostWithOverrides(hostRef); const host = hostWithOverrides(hostRef);
if (await vpn.ensureForHost(host)) send('vpn:changed'); await vpnFor(host, sessionId);
return ssh.openSftp(sessionId, host); return ssh.openSftp(sessionId, host);
}); });
handle('sftp:list', (id, dir) => ssh.sftpList(id, dir)); handle('sftp:list', (id, dir) => ssh.sftpList(id, dir));
@@ -491,7 +496,7 @@ handle('sftp:transfer', async (id, dir, localPath, remotePath, transferId) => {
}); });
return true; 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) // Lokales Dateisystem (für den Dual-Pane-SFTP-Browser)
handle('local:home', () => os.homedir()); handle('local:home', () => os.homedir());
@@ -517,17 +522,17 @@ handle('local:op', (op, a, b) => {
handle('fw:start', async (id) => { handle('fw:start', async (id) => {
const fw = store.get().forwards.find((f) => f.id === id); const fw = store.get().forwards.find((f) => f.id === id);
if (!fw) throw new Error(i18n.t('Rule not found')); 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)); 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()); handle('fw:active', () => ssh.activeForwards());
// ---------- RDP ---------- // ---------- RDP ----------
handle('rdp:detect', () => rdp.detect(store.get().settings)); handle('rdp:detect', () => rdp.detect(store.get().settings));
handle('rdp:launch', async (hostId) => { handle('rdp:launch', async (hostId) => {
const host = hostWithOverrides(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() }); if (host.id) store.addHistory({ hostId: host.id, at: Date.now() });
const r = rdp.launch(host, store.get().settings); const r = rdp.launch(host, store.get().settings);
if (r.process) { if (r.process) {
@@ -547,7 +552,7 @@ handle('rdp:embedSupported', () => {
handle('rdp:open', async (id, hostRef, bounds) => { handle('rdp:open', async (id, hostRef, bounds) => {
const host = hostWithOverrides(hostRef); const host = hostWithOverrides(hostRef);
if (host.id) store.addHistory({ hostId: host.id, at: Date.now() }); 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 }; const sess = { cancelled: false };
rdpSessions.set(id, sess); rdpSessions.set(id, sess);
return startRdpEmbed(id, sess, host, bounds); 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: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:focus', (_e, id) => { try { rdpSessions.get(id)?.emb.focus(); } catch {} });
ipcMain.on('rdp:close', (_e, id) => { ipcMain.on('rdp:close', (_e, id) => {
vpnRelease(id);
const s = rdpSessions.get(id); const s = rdpSessions.get(id);
if (!s) return; if (!s) return;
s.cancelled = true; s.cancelled = true;
+51 -7
View File
@@ -4,6 +4,7 @@
// Windows: WireGuard als Tunnel-Dienst über wireguard.exe (UAC-Abfrage), OpenVPN über die OpenVPN GUI. // Windows: WireGuard als Tunnel-Dienst über wireguard.exe (UAC-Abfrage), OpenVPN über die OpenVPN GUI.
const { execFile, spawn } = require('child_process'); const { execFile, spawn } = require('child_process');
const fs = require('fs'); const fs = require('fs');
const net = require('net');
const os = require('os'); const os = require('os');
const path = require('path'); const path = require('path');
const i18n = require('../i18n'); 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 lastLine = (s) => s.split('\n').map((l) => l.trim()).filter(Boolean).slice(-1)[0] || '';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); 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 { class VpnManager {
constructor(store, userDir) { constructor(store, userDir) {
@@ -24,6 +37,7 @@ class VpnManager {
this.dir = path.join(userDir, 'vpn'); this.dir = path.join(userDir, 'vpn');
this.busy = new Map(); // id -> laufendes up() (parallele Verbindungen zum selben VPN nur einmal aufbauen) this.busy = new Map(); // id -> laufendes up() (parallele Verbindungen zum selben VPN nur einmal aufbauen)
this.started = new Set(); // von MrTerm aufgebaute VPNs 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); } 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 */ } } catch { /* VPN-Werkzeuge fehlen – nichts aufzuräumen */ }
} }
// Alle VPNs eines Hosts (inkl. Jump-Host-Kette) aufbauen, bevor verbunden wird // Alle VPNs eines Hosts (inkl. Jump-Host-Kette) aufbauen, bevor verbunden wird.
async ensureForHost(host, onStatus = () => {}) { // owner: Sitzungs-ID; mit release(owner) wird das VPN wieder getrennt, sobald keine Sitzung es mehr nutzt.
const ids = []; 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++) { 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); const v = this.get(id);
if (!v) continue; if (!v) continue;
if (await this.isUp(v)) continue; 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 })); onStatus(i18n.t('Connecting VPN “{name}” …', { name: v.label }));
await this.up(id); 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;
} }
} }
+53 -22
View File
@@ -681,7 +681,7 @@ function viewSnippets(page) {
} }
c.append(l, templateList()); c.append(l, templateList());
} }
function editSnippet(s = {}) { function editSnippet(s = {}, onSaved) {
const form = openDrawer(s.id ? T('Edit snippet') : T('New snippet'), [ const form = openDrawer(s.id ? T('Edit snippet') : T('New snippet'), [
field('Name', 'label', s.label, { placeholder: T('System update') }), field('Name', 'label', s.label, { placeholder: T('System update') }),
field(T('Command(s)'), 'command', s.command, { type: 'textarea', placeholder: 'sudo pacman -Syu' }), field(T('Command(s)'), 'command', s.command, { type: 'textarea', placeholder: 'sudo pacman -Syu' }),
@@ -690,7 +690,8 @@ function editSnippet(s = {}) {
const v = formValues(form); const v = formValues(form);
if (!v.command.trim()) throw new Error(T('Command is missing.')); if (!v.command.trim()) throw new Error(T('Command is missing.'));
await call('vault:upsert', 'snippets', { ...s, ...v, label: v.label || v.command.split('\n')[0].slice(0, 40) }); await call('vault:upsert', 'snippets', { ...s, ...v, label: v.label || v.command.split('\n')[0].slice(0, 40) });
reload(); await reload();
onSaved?.();
}); });
} }
// Eingebaute Vorlagen (nicht im Vault). Parameter werden vor dem Ausführen abgefragt; build() liefert eine Zeile. // Eingebaute Vorlagen (nicht im Vault). Parameter werden vor dem Ausführen abgefragt; build() liefert eine Zeile.
@@ -896,6 +897,8 @@ function editVpn(v = {}, pick = false) {
field(T('Name'), 'label', v.label, { placeholder: T('Office VPN') }), field(T('Name'), 'label', v.label, { placeholder: T('Office VPN') }),
cfg, cfg,
ovpnBox, 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), check(T('Disconnect when MrTerm closes'), 'disconnectOnQuit', v.disconnectOnQuit !== false),
heading(T('Assigned hosts')), heading(T('Assigned hosts')),
hostBox, hostBox,
@@ -903,7 +906,7 @@ function editVpn(v = {}, pick = false) {
const f = formValues(form); const f = formValues(form);
if (!f.config.trim()) throw new Error(T('Configuration is missing.')); 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.')); 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 : '' }; username: type === 'openvpn' ? f.username : '', password: type === 'openvpn' ? f.password : '' };
const saved = await call('vault:upsert', 'vpns', item); const saved = await call('vault:upsert', 'vpns', item);
askShareSecret('vpns', saved, saved.label); askShareSecret('vpns', saved, saved.label);
@@ -1768,7 +1771,7 @@ class TerminalSession {
const fid = e.target.closest('[data-feature]')?.dataset.feature; const fid = e.target.closest('[data-feature]')?.dataset.feature;
if (fid) featureOpeners()[fid](this.host); if (fid) featureOpeners()[fid](this.host);
if (a === 'snip') { $('.snip-panel', this.el).classList.toggle('open'); this.renderSnips(); this.doFit(); } if (a === 'snip') { $('.snip-panel', this.el).classList.toggle('open'); this.renderSnips(); this.doFit(); }
if (a === 'snipnew') editSnippet(); if (a === 'snipnew') editSnippet({}, () => this.renderSnips());
if (a === 'find') this.toggleFind(); if (a === 'find') this.toggleFind();
const f = e.target.closest('[data-f]')?.dataset.f; const f = e.target.closest('[data-f]')?.dataset.f;
const inp = $('.findbar input', this.el); const inp = $('.findbar input', this.el);
@@ -2161,14 +2164,21 @@ class FilePane {
const p = e.target.closest('[data-p]')?.dataset.p; const p = e.target.closest('[data-p]')?.dataset.p;
if (p === 'up') this.up(); if (p === 'up') this.up();
if (p === 'home') this.go(this.home); if (p === 'home') this.go(this.home);
if (p === 'refresh') this.go(this.cwd); if (p === 'refresh') this.refresh();
if (p === 'mkdir') this.mkdir(); if (p === 'mkdir') this.mkdir();
if (p === 'xfer') this.transferSelected(); if (p === 'xfer') this.transferSelected();
if (p === 'upload') this.pickUpload(); if (p === 'upload') this.pickUpload();
}); });
$('.path', this.el).addEventListener('keydown', (e) => { if (e.key === 'Enter') this.go(e.target.value); }); $('.path', this.el).addEventListener('keydown', (e) => { if (e.key === 'Enter') this.go(e.target.value); });
const files = $('.files', this.el); const files = $('.files', this.el);
files.addEventListener('contextmenu', (e) => { if (!e.target.closest('tr[data-i]')) { e.preventDefault(); ctxMenu(e.clientX, e.clientY, [{ label: T('New folder'), icon: 'newdir', run: () => this.mkdir() }, { label: T('Refresh'), icon: 'refresh', run: () => this.go(this.cwd) }]); } }); // Tastatur: F5 aktualisieren, Entf löschen, F2 umbenennen
files.tabIndex = 0;
files.addEventListener('keydown', (e) => {
if (e.key === 'F5') { e.preventDefault(); this.refresh(); }
else if (e.key === 'Delete' && this.sel.size) { e.preventDefault(); this.remove(); }
else if (e.key === 'F2' && this.sel.size === 1) { e.preventDefault(); this.rename(this.files.find((x) => this.sel.has(x.name))); }
});
files.addEventListener('contextmenu', (e) => { if (!e.target.closest('tr[data-i]')) { e.preventDefault(); ctxMenu(e.clientX, e.clientY, [{ label: T('New folder'), icon: 'newdir', run: () => this.mkdir() }, { label: T('Refresh'), icon: 'refresh', run: () => this.refresh() }]); } });
// Drag & Drop zwischen den Panes // Drag & Drop zwischen den Panes
// Web-Version: Dateien aus dem Betriebssystem in den Server-Bereich ziehen = hochladen // Web-Version: Dateien aus dem Betriebssystem in den Server-Bereich ziehen = hochladen
const osFiles = (e) => WEB && [...(e.dataTransfer?.types || [])].includes('Files'); const osFiles = (e) => WEB && [...(e.dataTransfer?.types || [])].includes('Files');
@@ -2186,8 +2196,7 @@ class FilePane {
if (!WEB) { if (!WEB) {
// Desktop: Dateiauswahl des Systems, Upload in den aktuellen Server-Ordner // Desktop: Dateiauswahl des Systems, Upload in den aktuellen Server-Ordner
const files = await call('sftp:pickUpload'); const files = await call('sftp:pickUpload');
for (const f of files) await this.sftp.transfer('upload', f.path, await this.join(this.cwd, f.name), f.name); for (const f of files) { await this.sftp.transfer('upload', f.path, await this.join(this.cwd, f.name), f.name); this.refresh(); }
if (files.length) this.go(this.cwd);
return; return;
} }
const inp = h('<input type="file" multiple style="display:none"/>'); const inp = h('<input type="file" multiple style="display:none"/>');
@@ -2196,8 +2205,7 @@ class FilePane {
inp.click(); inp.click();
} }
async uploadFiles(files) { async uploadFiles(files) {
for (const f of files) await this.sftp.webTransfer('upload', f, `${this.cwd.replace(/\/$/, '')}/${f.name}`, f.name); for (const f of files) { await this.sftp.webTransfer('upload', f, `${this.cwd.replace(/\/$/, '')}/${f.name}`, f.name); this.refresh(); }
this.go(this.cwd);
} }
async join(...p) { return this.side === 'local' ? api.call('local:join', ...p) : p.join('/').replace(/\/+/g, '/'); } async join(...p) { return this.side === 'local' ? api.call('local:join', ...p) : p.join('/').replace(/\/+/g, '/'); }
async parent(p) { return this.side === 'local' ? api.call('local:parent', p) : (p.replace(/\/[^/]+\/?$/, '') || '/'); } async parent(p) { return this.side === 'local' ? api.call('local:parent', p) : (p.replace(/\/[^/]+\/?$/, '') || '/'); }
@@ -2212,15 +2220,26 @@ class FilePane {
return this.go(home); return this.go(home);
} }
async up() { this.go(await this.parent(this.cwd)); } async up() { this.go(await this.parent(this.cwd)); }
async go(dir) { // keep: Auswahl und Scrollposition behalten (Aktualisieren im selben Ordner); select: diese Namen danach markieren
async go(dir, { keep = false, select, quiet = false } = {}) {
const seq = (this.seq = (this.seq || 0) + 1);
try { try {
const files = await this.list(dir); const files = await this.list(dir);
this.cwd = dir; this.files = files; this.sel.clear(); if (seq !== this.seq) return; // inzwischen neuer angefordert
$('.path', this.el).value = dir; const box = $('.files', this.el), scroll = keep ? box.scrollTop : 0;
const sel = select ? new Set(select) : keep ? this.sel : new Set();
this.cwd = dir; this.files = files; this.sel = new Set(files.map((f) => f.name).filter((n) => sel.has(n)));
if (!keep) this.lastIdx = null;
const path = $('.path', this.el); if (document.activeElement !== path || !keep) path.value = dir;
const roots = $('.roots', this.el); if (roots) roots.value = dir.slice(0, 2).toUpperCase() + '\\'; const roots = $('.roots', this.el); if (roots) roots.value = dir.slice(0, 2).toUpperCase() + '\\';
this.draw(); this.draw();
} catch (e) { toast(e.message, 'error'); } box.scrollTop = scroll;
if (select) $('tr.sel', box)?.scrollIntoView({ block: 'nearest' });
} catch (e) { if (!quiet) toast(e.message, 'error'); }
} }
refresh(opts = {}) { return this.cwd ? this.go(this.cwd, { keep: true, ...opts }) : Promise.resolve(); }
// Nach Änderungen beide Seiten aktualisieren (die andere zeigt evtl. denselben Ordner)
refreshBoth(opts) { this.other?.refresh({ quiet: true }); return this.refresh(opts); }
sorted() { sorted() {
const { k, dir } = this.sort; const { k, dir } = this.sort;
return [...this.files].filter((f) => f.name !== '.' && f.name !== '..').sort((a, b) => (b.isDir - a.isDir) || (k === 'name' ? a.name.localeCompare(b.name, undefined, { numeric: true }) : (a[k] - b[k])) * dir); return [...this.files].filter((f) => f.name !== '.' && f.name !== '..').sort((a, b) => (b.isDir - a.isDir) || (k === 'name' ? a.name.localeCompare(b.name, undefined, { numeric: true }) : (a[k] - b[k])) * dir);
@@ -2266,29 +2285,34 @@ class FilePane {
async mkdir() { async mkdir() {
const n = await promptBox(T('New folder'), T('Name')); if (!n) return; const n = await promptBox(T('New folder'), T('Name')); if (!n) return;
const p = await this.join(this.cwd, n); const p = await this.join(this.cwd, n);
try { this.side === 'local' ? await api.call('local:op', 'mkdir', p) : await api.call('sftp:op', this.sftp.id, 'mkdir', p); this.go(this.cwd); } catch (e) { toast(e.message, 'error'); } try { this.side === 'local' ? await api.call('local:op', 'mkdir', p) : await api.call('sftp:op', this.sftp.id, 'mkdir', p); this.refreshBoth({ select: [n] }); } catch (e) { toast(e.message, 'error'); }
} }
async rename(f) { async rename(f) {
const n = await promptBox(T('Rename'), T('New name'), f.name); if (!n || n === f.name) return; const n = await promptBox(T('Rename'), T('New name'), f.name); if (!n || n === f.name) return;
const a = await this.join(this.cwd, f.name), b = await this.join(this.cwd, n); const a = await this.join(this.cwd, f.name), b = await this.join(this.cwd, n);
try { this.side === 'local' ? await api.call('local:op', 'rename', a, b) : await api.call('sftp:op', this.sftp.id, 'rename', a, b); this.go(this.cwd); } catch (e) { toast(e.message, 'error'); } try { this.side === 'local' ? await api.call('local:op', 'rename', a, b) : await api.call('sftp:op', this.sftp.id, 'rename', a, b); this.refreshBoth({ select: [n] }); } catch (e) { toast(e.message, 'error'); this.refresh(); }
} }
async chmod(f) { async chmod(f) {
const m = await promptBox(T('Change permissions'), T('Octal (e.g. 644)'), (f.mode & 0o777).toString(8)); if (!m) return; const m = await promptBox(T('Change permissions'), T('Octal (e.g. 644)'), (f.mode & 0o777).toString(8)); if (!m) return;
try { await api.call('sftp:op', this.sftp.id, 'chmod', await this.join(this.cwd, f.name), parseInt(m, 8)); this.go(this.cwd); } catch (e) { toast(e.message, 'error'); } try { await api.call('sftp:op', this.sftp.id, 'chmod', await this.join(this.cwd, f.name), parseInt(m, 8)); this.refresh(); } catch (e) { toast(e.message, 'error'); }
} }
async remove() { async remove() {
const names = [...this.sel]; if (!names.length) return; const names = [...this.sel]; if (!names.length) return;
if (!(await confirmBox(T('Delete?'), T(this.side === 'local' ? 'Move {n} item(s) to the trash: {list}' : 'Permanently delete {n} item(s) from the server: {list}', { n: names.length, list: names.slice(0, 5).join(', ') + (names.length > 5 ? ' …' : '') })))) return; if (!(await confirmBox(T('Delete?'), T(this.side === 'local' ? 'Move {n} item(s) to the trash: {list}' : 'Permanently delete {n} item(s) from the server: {list}', { n: names.length, list: names.slice(0, 5).join(', ') + (names.length > 5 ? ' …' : '') })))) return;
// Sofort ausgrauen, damit man sieht, was gerade gelöscht wird
$$('tr.sel', this.el).forEach((tr) => tr.classList.add('busy'));
let ok = 0;
for (const n of names) { for (const n of names) {
const f = this.files.find((x) => x.name === n); const f = this.files.find((x) => x.name === n);
const p = await this.join(this.cwd, n); const p = await this.join(this.cwd, n);
try { try {
if (this.side === 'local') await api.call('local:op', 'delete', p); if (this.side === 'local') await api.call('local:op', 'delete', p);
else await api.call('sftp:op', this.sftp.id, f.isDir ? 'rmdir' : 'unlink', p); else await api.call('sftp:op', this.sftp.id, f.isDir ? 'rmdir' : 'unlink', p);
ok++;
} catch (e) { toast(`${n}: ${e.message}`, 'error'); } } catch (e) { toast(`${n}: ${e.message}`, 'error'); }
} }
this.go(this.cwd); await this.refreshBoth();
if (ok) toast(T('{n} item(s) deleted', { n: ok }), 'ok');
} }
async transferSelected() { async transferSelected() {
const names = [...this.sel]; const names = [...this.sel];
@@ -2306,8 +2330,8 @@ class FilePane {
const src = await this.join(this.cwd, n), dst = await target.join(target.cwd, n); const src = await this.join(this.cwd, n), dst = await target.join(target.cwd, n);
const dir = this.side === 'local' ? 'upload' : 'download'; const dir = this.side === 'local' ? 'upload' : 'download';
await this.sftp.transfer(dir, dir === 'upload' ? src : dst, dir === 'upload' ? dst : src, n); await this.sftp.transfer(dir, dir === 'upload' ? src : dst, dir === 'upload' ? dst : src, n);
target.refresh({ select: names });
} }
target.go(target.cwd);
} }
} }
@@ -2323,6 +2347,12 @@ class SftpSession {
wrap.append(h(`<div class="pane"><div class="pane-empty"><div class="spinner" style="width:30px;height:30px;border:3px solid var(--border);border-top-color:var(--accent);border-radius:50%;animation:spin .9s linear infinite"></div><div>${esc(T('Connecting to {host} …', { host: host.address }))}</div></div></div>`)); wrap.append(h(`<div class="pane"><div class="pane-empty"><div class="spinner" style="width:30px;height:30px;border:3px solid var(--border);border-top-color:var(--accent);border-radius:50%;animation:spin .9s linear infinite"></div><div>${esc(T('Connecting to {host} …', { host: host.address }))}</div></div></div>`));
this.unsub = api.on('sftp:progress', (tid, done, total) => this.progress(tid, done, total)); this.unsub = api.on('sftp:progress', (tid, done, total) => this.progress(tid, done, total));
this.xfers = new Map(); this.xfers = new Map();
// Automatisch aktualisieren: beim Zurückkehren ins Fenster und alle 10 s, solange der Tab sichtbar ist
const visible = () => this.el.classList.contains('active') && !document.hidden;
this.autoRefresh = () => { if (visible() && !this.xfers.size) { this.local?.refresh({ quiet: true }); this.remote.refresh({ quiet: true }); } };
window.addEventListener('focus', this.autoRefresh);
this.timer = setInterval(this.autoRefresh, 10000);
this.onShow = () => this.autoRefresh();
addTab(this); addTab(this);
this.open(); this.open();
} }
@@ -2355,6 +2385,7 @@ class SftpSession {
row.classList.add('fail'); $('.pct', row).textContent = T('Error'); row.title = e.message; toast(`${name}: ${e.message}`, 'error'); row.classList.add('fail'); $('.pct', row).textContent = T('Error'); row.title = e.message; toast(`${name}: ${e.message}`, 'error');
setTimeout(() => row.remove(), 10000); setTimeout(() => row.remove(), 10000);
} }
this.xfers.delete(tid);
} }
// Web-Version: Upload per HTTP (mit Fortschritt), Download als Browser-Download // Web-Version: Upload per HTTP (mit Fortschritt), Download als Browser-Download
webTransfer(dir, file, remotePath, name) { webTransfer(dir, file, remotePath, name) {
@@ -2376,9 +2407,9 @@ class SftpSession {
x.onload = () => { x.onload = () => {
if (x.status < 300) { row.classList.add('done'); $('.bar i', row).style.width = '100%'; $('.pct', row).textContent = T('done'); setTimeout(() => row.remove(), 5000); } if (x.status < 300) { row.classList.add('done'); $('.bar i', row).style.width = '100%'; $('.pct', row).textContent = T('done'); setTimeout(() => row.remove(), 5000); }
else { row.classList.add('fail'); $('.pct', row).textContent = T('Error'); const m = (() => { try { return JSON.parse(x.responseText).error; } catch { return x.statusText; } })(); toast(`${name}: ${m}`, 'error'); setTimeout(() => row.remove(), 10000); } else { row.classList.add('fail'); $('.pct', row).textContent = T('Error'); const m = (() => { try { return JSON.parse(x.responseText).error; } catch { return x.statusText; } })(); toast(`${name}: ${m}`, 'error'); setTimeout(() => row.remove(), 10000); }
resolve(); this.xfers.delete(tid); resolve();
}; };
x.onerror = () => { row.classList.add('fail'); $('.pct', row).textContent = T('Error'); resolve(); }; x.onerror = () => { row.classList.add('fail'); $('.pct', row).textContent = T('Error'); this.xfers.delete(tid); resolve(); };
x.send(file); x.send(file);
}); });
} }
@@ -2388,7 +2419,7 @@ class SftpSession {
$('.bar i', row).style.width = p + '%'; $('.bar i', row).style.width = p + '%';
$('.pct', row).textContent = `${p}% · ${fmtSize(done)} / ${fmtSize(total)}`; $('.pct', row).textContent = `${p}% · ${fmtSize(done)} / ${fmtSize(total)}`;
} }
dispose() { this.unsub(); api.call('sftp:close', this.id).catch(() => {}); } dispose() { this.unsub(); clearInterval(this.timer); window.removeEventListener('focus', this.autoRefresh); api.call('sftp:close', this.id).catch(() => {}); }
} }
function openSftp(host) { return new SftpSession(host); } function openSftp(host) { return new SftpSession(host); }
+2
View File
@@ -253,6 +253,8 @@ body.in-session #sidebar { display: none; }
.pane td.date { color: var(--muted); } .pane td.date { color: var(--muted); }
.pane tr:hover td { background: rgb(var(--tint) / 0.024); } .pane tr:hover td { background: rgb(var(--tint) / 0.024); }
.pane tr.sel td { background: color-mix(in srgb, var(--accent) 15%, transparent); } .pane tr.sel td { background: color-mix(in srgb, var(--accent) 15%, transparent); }
.pane tr.busy { opacity: .45; pointer-events: none; }
.pane .files:focus { outline: none; }
.pane .ico-dir { color: var(--folder); } .pane .ico-dir { color: var(--folder); }
.pane .ico-file { color: var(--faint); } .pane .ico-file { color: var(--faint); }
.pane-empty { flex: 1; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 14px; color: var(--muted); } .pane-empty { flex: 1; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 14px; color: var(--muted); }