Add MrTerm Web: self-hosted browser version (Docker Compose) with user accounts, per-user vaults encrypted by the login password, the desktop UI over WebSocket, SFTP upload/download over HTTP; share backend channels between Android and web (src/core/backend.js)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-26 14:52:26 +02:00
co-authored by Claude Opus 5.5
parent c143053319
commit 45b0be8557
18 changed files with 1567 additions and 187 deletions
+133 -9
View File
@@ -8,6 +8,8 @@ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '
const uid = () => crypto.randomUUID();
function h(html) { const t = document.createElement('template'); t.innerHTML = html.trim(); return t.content.firstElementChild; }
const T = I18N.t;
// Web-Version (Docker, src/web): gleiche Oberfläche im Browser; ohne RDP, VPN, Port-Forwarding und lokale Dateien
const WEB = api.platform === 'web';
const ICONS = {
search: '<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/></svg>',
@@ -407,6 +409,7 @@ function connectHost(hst) {
}
async function openRdp(hst) {
if (WEB) return toast(T('RDP is not available in the web version.'), 'error');
if (settings().rdpEmbed !== false) {
const s = await api.call('rdp:embedSupported').catch((e) => ({ ok: false, reason: e.message }));
if (s.ok) return new RdpSession(hst);
@@ -863,6 +866,60 @@ function viewHistory(page) {
}
// ============================================================ Einstellungen
// ---------- Web-Version: Konto und Benutzerverwaltung (HTTP-API des Web-Servers)
async function webApi(path, body) {
const r = await fetch(path, { method: body === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'X-MrTerm': '1' }, body: body === undefined ? undefined : JSON.stringify(body) });
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(T(j.error || r.statusText));
return j;
}
function webAccountCard() {
const card = h(`<div class="settings-card"><h3>${T('Account')}</h3><div class="acc"></div></div>`);
const draw = async () => {
const box = $('.acc', card);
let me;
try { me = await webApi('/api/me'); } catch (e) { box.textContent = e.message; return; }
box.innerHTML = `<p style="color:var(--muted);margin-top:0">${esc(T('Signed in as {name}', { name: me.name }))}${me.admin ? ` · ${esc(T('Administrator'))}` : ''}</p><div class="row" style="flex-wrap:wrap"></div>`;
const pw = h(`<button class="btn">${esc(T('Change password'))}</button>`);
pw.onclick = async () => {
const r = await modal({ title: T('Change password'), body: `<div class="field"><label>${esc(T('Current password'))}</label><input name="old" type="password"/></div><div class="field"><label>${esc(T('New password'))}</label><input name="a" type="password"/></div><div class="field"><label>${esc(T('Repeat password'))}</label><input name="b" type="password"/></div>`,
buttons: [{ label: T('Cancel'), value: null, cls: 'ghost' }, { label: T('Save'), value: 'form', cls: 'primary' }] });
if (!r) return;
if (r.a !== r.b) return toast(T('The passwords do not match.'), 'error');
try { await webApi('/api/password', { old: r.old, password: r.a }); toast(T('Saved'), 'ok'); } catch (e) { toast(e.message, 'error'); }
};
const out = h(`<button class="btn">${esc(T('Sign out'))}</button>`);
out.onclick = async () => { await webApi('/api/logout', {}).catch(() => {}); location.href = '/'; };
$('.row', box).append(pw, out);
if (!me.admin) return;
const users = await webApi('/api/users').catch(() => ({ users: [] }));
const list = h(`<div style="margin-top:16px"><h4 style="margin:0 0 8px">${esc(T('Users'))}</h4></div>`);
for (const u of users.users) {
const row = h(`<div class="lock-row"><div class="grow"><b>${esc(u.name)}</b><div class="sub">${u.admin ? esc(T('Administrator')) : esc(T('User'))}</div></div></div>`);
if (u.id !== me.id) {
const del = h(`<button class="btn ghost" title="${esc(T('Delete'))}">${ICONS.trash}</button>`);
del.onclick = async () => {
if (!(await confirmBox(T('Delete user?'), T('“{name}” and their vault will be permanently deleted.', { name: u.name })))) return;
try { await webApi('/api/users/delete', { id: u.id }); draw(); } catch (e) { toast(e.message, 'error'); }
};
row.append(del);
}
list.append(row);
}
const add = h(`<button class="btn" style="margin-top:10px">${ICONS.plus}${esc(T('Add user'))}</button>`);
add.onclick = async () => {
const r = await modal({ title: T('Add user'), body: `<div class="field"><label>${esc(T('Username'))}</label><input name="name" autocomplete="off"/></div><div class="field"><label>${esc(T('Password'))}</label><input name="password" type="password" autocomplete="new-password"/></div><label class="check"><input type="checkbox" name="admin"/>${esc(T('Administrator'))}</label>`,
buttons: [{ label: T('Cancel'), value: null, cls: 'ghost' }, { label: T('Add user'), value: 'form', cls: 'primary' }] });
if (!r) return;
try { await webApi('/api/users', r); toast(T('Saved'), 'ok'); draw(); } catch (e) { toast(e.message, 'error'); }
};
list.append(add);
box.append(list);
};
draw();
return card;
}
async function viewSettings(page) {
const st = settings();
page.append(h(`<div class="toolbar"><h2 style="margin:0;font-size:18px">${T('Settings')}</h2></div>`));
@@ -931,9 +988,9 @@ async function viewSettings(page) {
if (!d.available) $('.rdp-info', rdpCard).style.color = 'var(--orange)';
}).catch(() => {});
const dataCard = h(`<div class="settings-card"><h3>${T('Data')}</h3><p style="color:var(--muted);margin-top:0">${S.vault.encrypted ? T('The vault is encrypted with the operating system keyring (Windows DPAPI / libsecret or KWallet).') : T('The vault is not encrypted because no keyring is available. On Arch/CachyOS: install <code>gnome-keyring</code> or <code>kwallet</code>.')}</p><div class="row" style="flex-wrap:wrap"></div></div>`);
const dataCard = h(`<div class="settings-card"><h3>${T('Data')}</h3><p style="color:var(--muted);margin-top:0">${WEB ? T('Your vault is stored on the server, encrypted with a key that only your login password can unlock.') : S.vault.encrypted ? T('The vault is encrypted with the operating system keyring (Windows DPAPI / libsecret or KWallet).') : T('The vault is not encrypted because no keyring is available. On Arch/CachyOS: install <code>gnome-keyring</code> or <code>kwallet</code>.')}</p><div class="row" style="flex-wrap:wrap"></div></div>`);
const btns = [
[T('Import ~/.ssh/config'), importSshConfig],
...(WEB ? [] : [[T('Import ~/.ssh/config'), importSshConfig]]),
[T('Export backup'), async () => { const p = await call('vault:export'); if (p) toast(T('Exported to {path}', { path: p }), 'ok'); }],
[T('Import backup'), async () => { if (await call('vault:import')) { toast(T('Import complete'), 'ok'); reload(); } }],
];
@@ -985,7 +1042,8 @@ async function viewSettings(page) {
<span>${C}+<kbd>Shift</kbd>+<kbd>F</kbd></span><span>${T('Search in terminal')}</span>
<span>${C}+<kbd>+/−/0</kbd></span><span>${T('Font size')}</span>
<span>${C}+<kbd>Shift</kbd>+<kbd>L</kbd></span><span>${T('Lock now')}</span></div></div>`);
c.append(langCard, secCard, syncCard, designCard, themeCard, termCard, rdpCard, importCard, dataCard, updCard, keysCard);
if (WEB) c.append(langCard, webAccountCard(), designCard, themeCard, termCard, importCard, dataCard, keysCard);
else c.append(langCard, secCard, syncCard, designCard, themeCard, termCard, rdpCard, importCard, dataCard, updCard, keysCard);
}
// ============================================================ App-Sperre
@@ -1643,7 +1701,7 @@ class FilePane {
<input class="path" spellcheck="false"/>
<button class="btn ghost sm" data-p="refresh" title="${T('Refresh')}">${ICONS.refresh}</button>
<button class="btn ghost sm" data-p="mkdir" title="${T('New folder')}">${ICONS.newdir}</button>
<button class="btn ghost sm" data-p="xfer" title="${side === 'local' ? T('Upload →') : T('← Download')}">${side === 'local' ? ICONS.arrowR : ICONS.arrowL}</button></div>
${WEB ? `<button class="btn ghost sm" data-p="upload" title="${T('Upload')}">${ICONS.upload}</button><button class="btn ghost sm" data-p="xfer" title="${T('Download')}">${ICONS.download}</button>` : `<button class="btn ghost sm" data-p="xfer" title="${side === 'local' ? T('Upload →') : T('← Download')}">${side === 'local' ? ICONS.arrowR : ICONS.arrowL}</button>`}</div>
<div class="files"></div></div>`);
this.el.addEventListener('click', (e) => {
const p = e.target.closest('[data-p]')?.dataset.p;
@@ -1652,16 +1710,34 @@ class FilePane {
if (p === 'refresh') this.go(this.cwd);
if (p === 'mkdir') this.mkdir();
if (p === 'xfer') this.transferSelected();
if (p === 'upload') this.pickUpload();
});
$('.path', this.el).addEventListener('keydown', (e) => { if (e.key === 'Enter') this.go(e.target.value); });
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) }]); } });
// Drag & Drop zwischen den Panes
this.el.addEventListener('dragover', (e) => { if (S.drag && S.drag.pane !== this) { e.preventDefault(); this.el.classList.add('dragover'); } });
// Web-Version: Dateien aus dem Betriebssystem in den Server-Bereich ziehen = hochladen
const osFiles = (e) => WEB && [...(e.dataTransfer?.types || [])].includes('Files');
this.el.addEventListener('dragover', (e) => { if ((S.drag && S.drag.pane !== this) || osFiles(e)) { e.preventDefault(); this.el.classList.add('dragover'); } });
this.el.addEventListener('dragleave', (e) => { if (!this.el.contains(e.relatedTarget)) this.el.classList.remove('dragover'); });
this.el.addEventListener('drop', (e) => { e.preventDefault(); this.el.classList.remove('dragover'); if (S.drag && S.drag.pane !== this) S.drag.pane.transferSelected(); S.drag = null; });
this.el.addEventListener('drop', (e) => {
e.preventDefault(); this.el.classList.remove('dragover');
if (osFiles(e)) return this.uploadFiles([...e.dataTransfer.files]);
if (S.drag && S.drag.pane !== this) S.drag.pane.transferSelected();
S.drag = null;
});
}
get other() { return this.side === 'local' ? this.sftp.remote : this.sftp.local; }
pickUpload() {
const inp = h('<input type="file" multiple style="display:none"/>');
inp.onchange = () => { this.uploadFiles([...inp.files]); inp.remove(); };
document.body.append(inp);
inp.click();
}
async uploadFiles(files) {
for (const f of files) await this.sftp.webTransfer('upload', f, `${this.cwd.replace(/\/$/, '')}/${f.name}`, f.name);
this.go(this.cwd);
}
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 list(dir) { return this.side === 'local' ? api.call('local:list', dir) : api.call('sftp:list', this.sftp.id, dir); }
@@ -1756,6 +1832,14 @@ class FilePane {
async transferSelected() {
const names = [...this.sel];
if (!names.length) return toast(T('Nothing selected'));
if (WEB) {
for (const n of names) {
const f = this.files.find((x) => x.name === n);
if (f?.isDir) { toast(T('Folders cannot be downloaded in the browser: {name}', { name: n })); continue; }
this.sftp.webTransfer('download', null, await this.join(this.cwd, n), n);
}
return;
}
const target = this.other;
for (const n of names) {
const src = await this.join(this.cwd, n), dst = await target.join(target.cwd, n);
@@ -1771,17 +1855,18 @@ class SftpSession {
this.kind = 'sftp'; this.id = uid(); this.host = host;
this.title = `SFTP · ${host.label || host.address}`;
this.el = h(`<div class="session"><div class="sftp"></div><div class="transfers"></div></div>`);
this.local = new FilePane(this, 'local');
this.local = WEB ? null : new FilePane(this, 'local');
this.remote = new FilePane(this, 'remote');
const wrap = $('.sftp', this.el);
wrap.append(this.local.el, 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>`));
if (this.local) wrap.append(this.local.el);
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.xfers = new Map();
addTab(this);
this.open();
}
async open() {
this.local.init(await api.call('local:home'));
if (this.local) this.local.init(await api.call('local:home'));
try {
const { home } = await api.call('sftp:open', this.id, this.host.id || this.host);
$('.sftp', this.el).lastElementChild.replaceWith(this.remote.el);
@@ -1810,6 +1895,32 @@ class SftpSession {
setTimeout(() => row.remove(), 10000);
}
}
// Web-Version: Upload per HTTP (mit Fortschritt), Download als Browser-Download
webTransfer(dir, file, remotePath, name) {
const q = `sid=${encodeURIComponent(this.id)}&path=${encodeURIComponent(remotePath)}`;
if (dir === 'download') {
const a = h(`<a href="/web/download?${q}" download="${esc(name)}" style="display:none"></a>`);
document.body.append(a); a.click(); a.remove();
return Promise.resolve();
}
const tid = uid();
const row = h(`<div class="transfer"><span>${ICONS.upload}</span><span class="nm">${esc(name)}</span><span class="pct">0%</span><div class="bar"><i></i></div></div>`);
$('.transfers', this.el).prepend(row);
this.xfers.set(tid, row);
return new Promise((resolve) => {
const x = new XMLHttpRequest();
x.open('POST', `/web/upload?${q}`);
x.setRequestHeader('X-MrTerm', '1');
x.upload.onprogress = (e) => this.progress(tid, e.loaded, e.total);
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); }
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();
};
x.onerror = () => { row.classList.add('fail'); $('.pct', row).textContent = T('Error'); resolve(); };
x.send(file);
});
}
progress(tid, done, total) {
const row = this.xfers.get(tid); if (!row) return;
const p = total ? Math.round((done / total) * 100) : 0;
@@ -2466,6 +2577,19 @@ document.addEventListener('keydown', (e) => {
}
});
// Web-Version: Hostschlüssel bestätigen (in Electron zeigt der Hauptprozess dafür einen Systemdialog)
api.on('hostkey:request', async (req) => {
const changed = !!req.previous;
const r = await modal({
title: changed ? T('Host key has changed!') : T('Unknown host'),
body: `<p style="margin-top:0">${esc(changed ? T('WARNING: The host key of {target} has changed. This may indicate a man-in-the-middle attack.', { target: req.host }) : T('The authenticity of {target} cannot be verified.', { target: req.host }))}</p>
<div class="mono" style="word-break:break-all;background:var(--panel);padding:8px 10px;border-radius:8px">${esc(req.fingerprint)}</div>
${changed ? `<p>${esc(T('Previously stored:'))}</p><div class="mono" style="word-break:break-all;background:var(--panel);padding:8px 10px;border-radius:8px">${esc(req.previous)}</div>` : ''}`,
buttons: [{ label: T('Cancel'), value: false, cls: 'ghost' }, { label: changed ? T('Connect anyway & replace') : T('Trust & connect'), value: true, cls: changed ? 'danger' : 'primary' }],
noEnter: changed,
});
api.replySecret(req.reqId, r === true);
});
api.on('secret:request', async (req) => {
const r = await modal({
title: req.title || T('Authentication'),