Compare commits

..
12 Commits
Author SHA1 Message Date
MrBlake b94f18d2e2 Version 0.11.1 2026-09-26 00:03:26 +02:00
MrBlakeandClaude Opus 5.5 7cff93419d Android: fix app hanging on the loading screen (Node start only returns when Node exits, wait for whenReady instead), build the native bridge with 16 KB page alignment, show an error instead of an endless spinner
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 00:03:26 +02:00
MrBlake 1980d3044b Version 0.11.0 2026-09-25 23:56:47 +02:00
MrBlakeandClaude Opus 5.5 4542aff75f Add Android app: phone UI for hosts, SSH terminal with extra key row, keys, snippets, LAN sync and app lock (password + fingerprint), reusing the desktop Node modules via capacitor-nodejs; APKs per ABI in releases for Obtainium
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:56:39 +02:00
MrBlake 430c18b84e Version 0.10.3 2026-09-25 23:32:05 +02:00
MrBlakeandClaude Opus 5.5 98c7763c47 README: add screenshots of hosts, terminal, host settings, Docker, firewall, network, VPN and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:32:05 +02:00
MrBlake e4396db3c8 Version 0.10.2 2026-09-25 23:22:21 +02:00
MrBlakeandClaude Opus 5.5 98d8cfa993 Network: confirm a change only after it has been fully applied, keep the session when the old connection times out, and retry reloading so changes show up without reopening the tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:22:16 +02:00
MrBlake 1517764cca Version 0.10.1 2026-09-25 23:15:49 +02:00
MrBlakeandClaude Opus 5.5 eba3e38620 Sync: warn CachyOS/UFW/firewalld users to open the sync ports with copyable commands; ask before sharing newly created SSH keys, passwords and VPN configurations
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:15:49 +02:00
MrBlake 6a63e0e80d Version 0.10.0 2026-09-25 23:05:39 +02:00
MrBlakeandClaude Opus 5.5 41717b2d07 Add encrypted LAN sync between MrTerm devices: UDP discovery, X25519 pairing with short authentication code, mutually authenticated AES-256-GCM sessions, last-writer-wins merge with deletions, and per-item opt-in for SSH keys, passwords and VPN configurations
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:05:39 +02:00
86 changed files with 5633 additions and 35 deletions
+6
View File
@@ -2,3 +2,9 @@ node_modules/
dist/
package.json
.gitea-token
!mobile/package.json
# Android-App: Build-Ausgaben, Plugin-Tarball (lädt build.js), Signaturschlüssel
mobile/vendor/
mobile/www/
mobile/android/keystore.properties
mobile/android/*.jks
+67 -1
View File
@@ -2,8 +2,12 @@
A modern SSH, SFTP and RDP client for Windows and Arch Linux / CachyOS. All your servers live in one place and open in tabs: terminals, file transfers and remote desktops.
[<img src="https://raw.githubusercontent.com/ImranR98/Obtainium/main/assets/graphics/badge_obtainium.png" alt="Get it on Obtainium" height="54">](https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22de.mrterm.app%22%2C%22url%22%3A%22https%3A%2F%2Fgit.mrblake.cc%2FMrBlake%2FMrTerm%22%2C%22author%22%3A%22MrBlake%22%2C%22name%22%3A%22MrTerm%22%2C%22overrideSource%22%3A%22Codeberg%22%7D)
MrTerm is available in **English** and **German**. It follows your system language by default, and you can change it under **Settings → Language**.
![MrTerm host overview with groups](docs/screenshots/hosts.png)
## Download & installation
Get the latest version from the [releases page](https://git.mrblake.cc/MrBlake/MrTerm/releases).
@@ -25,6 +29,23 @@ sudo pacman -S freerdp gnome-keyring # use kwallet instead of gnome-keyring on
```
`freerdp` is needed for RDP connections. `gnome-keyring` or `kwallet` lets MrTerm encrypt your saved passwords and keys.
**Android**
- Install with [Obtainium](https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22de.mrterm.app%22%2C%22url%22%3A%22https%3A%2F%2Fgit.mrblake.cc%2FMrBlake%2FMrTerm%22%2C%22author%22%3A%22MrBlake%22%2C%22name%22%3A%22MrTerm%22%2C%22overrideSource%22%3A%22Codeberg%22%7D): tap the badge above on your phone, or add `https://git.mrblake.cc/MrBlake/MrTerm` in Obtainium and choose **Forgejo (Codeberg)** as the source. Obtainium then keeps MrTerm up to date.
- Or download `MrTerm-<version>.apk` from the releases page and install it directly.
## Android app
The Android app is made for phones and focuses on what you need on the go:
- **Hosts** with groups, search and Quick Connect (`user@host:port`)
- **SSH terminal** in full screen with an extra key row (Esc, Tab, Ctrl, Alt, arrow keys, `|`, `~` …), pinch-to-zoom and several open sessions
- **Keys**: generate or import SSH keys and copy the public key
- **Snippets** you can send to the terminal with one tap
- **LAN sync** with MrTerm on your computer: pair once, and your hosts, groups and snippets appear on the phone. You choose which passwords and keys are shared
- **App lock** with a password and fingerprint unlock. The vault is encrypted with a key kept in the Android Keystore
RDP, SFTP, port forwarding and VPN are only available in the desktop app.
## Features
- **Hosts**: nested groups, tags, colors, search and Quick Connect (`user@host:port`, `rdp://host`)
@@ -42,11 +63,25 @@ sudo pacman -S freerdp gnome-keyring # use kwallet instead of gnome-keyring on
- **History** of recent connections
- **Import** from `~/.ssh/config` and from **Devolutions Remote Desktop Manager** (`.rdm`/XML, JSON or CSV)
- **Backup** export and import
- **LAN sync**: keep several MrTerm devices in sync over your local network, end-to-end encrypted and without a server
- **7 app themes** (Midnight, Navy, Nord, Dracula, Catppuccin, Forest, Light) plus a custom accent color
- **Encrypted vault** using your operating system's keyring (Windows DPAPI, Linux libsecret/KWallet)
- **App lock** with a password and/or a FIDO2 security key such as a YubiKey. The vault is then additionally encrypted, and it can lock automatically when you're inactive
- **Automatic updates**: MrTerm checks for new versions on startup and can install them for you
## Screenshots
| | |
|---|---|
| ![SSH terminal](docs/screenshots/terminal.png) | ![Editing a host](docs/screenshots/edit-host.png) |
| **SSH terminal** with tabs and quick access to SFTP, Docker, Firewall and Network | **Host settings**: authentication, keys, jump hosts and VPN |
| ![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 |
| ![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 |
| ![Settings](docs/screenshots/settings.png) | |
| **Settings**: language, app lock, LAN sync and themes | |
## Getting started
1. Click **New host**, enter the address, username and password or key, and click **Save**.
@@ -70,6 +105,28 @@ For a quick one-off connection, press `Ctrl+Shift+K` and type `user@host` (or `r
`Ctrl+W`, `Ctrl+K` and `Ctrl+T` still reach the terminal, so editors like nano work as usual.
## Synchronization between devices
Under **Settings → Synchronization**, you can keep several MrTerm installations in sync, for example your desktop and laptop. Devices talk to each other directly in your local network. There is no server or cloud involved.
1. Turn on **LAN synchronization** on both devices.
2. Click **Pair new device** on both devices and select the other one.
3. Both devices show a 6-digit code. If the codes match, click **Codes match** on both devices.
4. Choose which **SSH keys, host passwords and VPN configurations** this device may share. Nothing secret is shared unless you select it, and you can change the selection at any time. When you add a new key, password or VPN later, MrTerm asks whether to share it.
From then on, hosts, groups, snippets, port forwards, VPNs and known hosts are synchronized automatically whenever both devices are running on the same network. Deletions are synchronized too. If a change was made on both devices, the newest one wins. Device-specific settings such as theme, language and app lock stay local.
**Security:** pairing uses an X25519 key exchange confirmed by the matching code, so another device on the network can't intercept it. Every sync connection is mutually authenticated and encrypted with AES-256-GCM, using a new key for each session.
**Firewall:** devices find each other on UDP port 47811 and sync on TCP port 47812. **CachyOS enables the UFW firewall by default**, so run this once on CachyOS (and on any other Linux with UFW enabled):
```sh
sudo ufw allow 47811/udp
sudo ufw allow 47812/tcp
```
MrTerm shows these commands automatically when it detects CachyOS, UFW or firewalld. Windows asks for permission the first time. If devices can't find each other, you can also add one by its IP address.
## Docker
Right-click an SSH host and choose **Docker containers**, or click **Docker** in the toolbar of an open terminal. MrTerm connects over SSH and shows all containers on that host, with status, ports, CPU and memory.
@@ -158,7 +215,16 @@ In VS Code terminals, unset `ELECTRON_RUN_AS_NODE` first.
If the build fails with `EACCES: permission denied`, some files in `node_modules` belong to root. Run `sudo chown -R $USER: node_modules` and don't run npm with `sudo`.
**Publishing a release**: `./scripts/release-all.sh` asks for the version and release notes, commits and pushes the version, builds Windows + Arch/CachyOS and uploads everything to Gitea. It reads the token from `GITEA_TOKEN` or from `.gitea-token`, which is not committed.
**Android app** (`mobile/`): Capacitor with [capacitor-nodejs](https://github.com/hampoelz/Capacitor-NodeJS). The phone runs the same Node modules as the desktop app (`src/main/ssh.js`, `store.js`, `sync.js` …), bundled with esbuild; the phone UI lives in `mobile/web/`.
```bash
cd mobile
node build.js --setup # once: downloads the Node.js plugin (checksum-verified) and installs dependencies
node build.js --apk # builds signed APKs into dist/ (needs JDK 21 + Android SDK, see JAVA_HOME / ANDROID_HOME)
../node_modules/.bin/electron dev/electron-dev.js # try the phone UI on the desktop (after node build.js)
```
APKs are signed with `mobile/android/keystore.properties` and the keystore it points to. Both are not committed. Keep a backup, because Android only installs updates signed with the same key.
**Publishing a release**: `./scripts/release-all.sh` asks for the version and release notes, commits and pushes the version, builds Windows + Arch/CachyOS + Android and uploads everything to Gitea. It reads the token from `GITEA_TOKEN` or from `.gitea-token`, which is not committed.
**Translations** live in [`src/i18n.js`](src/i18n.js). The English text in the code is the key. To add a language, add a dictionary and list it in `LANGUAGES`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+82
View File
@@ -0,0 +1,82 @@
apply plugin: 'com.android.application'
android {
namespace = "de.mrterm.app"
compileSdk = rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "de.mrterm.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
// Version kommt aus der package.json des Desktop-Projekts (build.js setzt -PmrtermVersion)
def v = (project.findProperty('mrtermVersion') ?: '0.0.1').toString()
def p = v.tokenize('.-')
versionCode (p[0].toInteger() * 10000 + p[1].toInteger() * 100 + p[2].toInteger())
versionName v
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
// Signatur: keystore.properties (nicht im Repo) mit storeFile, storePassword, keyAlias, keyPassword
def ksFile = rootProject.file('keystore.properties')
signingConfigs {
release {
if (ksFile.exists()) {
def ks = new Properties()
ksFile.withInputStream { ks.load(it) }
storeFile rootProject.file(ks['storeFile'])
storePassword ks['storePassword']
keyAlias ks['keyAlias']
keyPassword ks['keyPassword']
}
}
}
// Eine APK je Prozessorarchitektur (libnode ist groß); Obtainium wählt die passende automatisch
splits {
abi {
enable true
reset()
include 'arm64-v8a', 'armeabi-v7a'
universalApk false
}
}
buildTypes {
release {
if (ksFile.exists()) signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
implementation "androidx.biometric:biometric:1.1.0"
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
+19
View File
@@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-nodejs')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
</manifest>
@@ -0,0 +1,38 @@
package de.mrterm.app;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import androidx.activity.OnBackPressedCallback;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
registerPlugin(MrTermNative.class);
super.onCreate(savedInstanceState);
WebView web = getBridge().getWebView();
// Zurück-Taste an die Oberfläche geben (schließt Dialoge, verlässt das Terminal …)
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
web.evaluateJavascript("window.mrtermBack && window.mrtermBack()", null);
}
});
// Edge-to-Edge: Bei offener Tastatur den WebView um die Tastaturhöhe verkleinern,
// damit Terminal und Zusatztasten sichtbar bleiben
View parent = (View) web.getParent();
ViewCompat.setOnApplyWindowInsetsListener(parent, (v, insets) -> {
int ime = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom;
v.setPadding(0, 0, 0, ime);
web.evaluateJavascript("window.mrtermIme && window.mrtermIme(" + (ime > 0) + ")", null);
return insets;
});
}
}
@@ -0,0 +1,244 @@
package de.mrterm.app;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.util.Base64;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
/**
* Plattformfunktionen für MrTerm:
* - Tresorschlüssel: zufällige 32 Byte, verpackt mit einem nicht exportierbaren AES-Schlüssel im Android Keystore
* - Fingerabdruck: Geheimnis, das nur nach erfolgreicher biometrischer Bestätigung entschlüsselt werden kann
* - Multicast-Lock (sonst verwirft WLAN die UDP-Broadcasts der LAN-Synchronisation), Zwischenablage, Gerätename
*/
@CapacitorPlugin(name = "MrTermNative")
public class MrTermNative extends Plugin {
private static final String KS = "AndroidKeyStore";
private static final String VAULT_ALIAS = "mrterm_vault";
private static final String BIO_ALIAS = "mrterm_bio";
private WifiManager.MulticastLock multicastLock;
private SharedPreferences prefs() {
return getContext().getSharedPreferences("mrterm", Context.MODE_PRIVATE);
}
private static String b64(byte[] b) { return Base64.encodeToString(b, Base64.NO_WRAP); }
private static byte[] unb64(String s) { return Base64.decode(s, Base64.NO_WRAP); }
private SecretKey keystoreKey(String alias, boolean userAuth) throws Exception {
KeyStore ks = KeyStore.getInstance(KS);
ks.load(null);
if (ks.containsAlias(alias)) return (SecretKey) ks.getKey(alias, null);
KeyGenerator kg = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KS);
KeyGenParameterSpec.Builder spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256);
if (userAuth) {
spec.setUserAuthenticationRequired(true).setInvalidatedByBiometricEnrollment(true);
if (Build.VERSION.SDK_INT >= 30) spec.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
}
kg.init(spec.build());
return kg.generateKey();
}
private static void deleteKey(String alias) {
try { KeyStore ks = KeyStore.getInstance(KS); ks.load(null); ks.deleteEntry(alias); } catch (Exception ignored) {}
}
// ---------- Tresorschlüssel ----------
@PluginMethod
public void vaultKey(PluginCall call) {
try {
SecretKey k = keystoreKey(VAULT_ALIAS, false);
String stored = prefs().getString("vaultKey", null);
byte[] plain;
if (stored == null) {
plain = new byte[32];
new SecureRandom().nextBytes(plain);
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k);
prefs().edit().putString("vaultKey", b64(c.getIV()) + ":" + b64(c.doFinal(plain))).apply();
} else {
String[] p = stored.split(":");
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, k, new GCMParameterSpec(128, unb64(p[0])));
plain = c.doFinal(unb64(p[1]));
}
JSObject r = new JSObject();
r.put("key", b64(plain));
call.resolve(r);
} catch (Exception e) {
call.reject("Keystore: " + e.getMessage());
}
}
// ---------- Fingerabdruck ----------
@PluginMethod
public void bioAvailable(PluginCall call) {
int s = BiometricManager.from(getContext()).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG);
JSObject r = new JSObject();
r.put("available", s == BiometricManager.BIOMETRIC_SUCCESS);
r.put("enrolled", prefs().getString("bio", null) != null);
call.resolve(r);
}
@PluginMethod
public void bioEnroll(PluginCall call) {
try {
deleteKey(BIO_ALIAS);
SecretKey k = keystoreKey(BIO_ALIAS, true);
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k);
prompt(call, c, call.getString("title", "MrTerm"), call.getString("cancel", "Cancel"), (cipher) -> {
byte[] secret = new byte[32];
new SecureRandom().nextBytes(secret);
byte[] ct = cipher.doFinal(secret);
prefs().edit().putString("bio", b64(cipher.getIV()) + ":" + b64(ct)).apply();
JSObject r = new JSObject();
r.put("secret", b64(secret));
call.resolve(r);
});
} catch (Exception e) {
call.reject(e.getMessage());
}
}
@PluginMethod
public void bioUnlock(PluginCall call) {
String stored = prefs().getString("bio", null);
if (stored == null) { call.reject("not-enrolled"); return; }
try {
String[] p = stored.split(":");
SecretKey k = keystoreKey(BIO_ALIAS, true);
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, k, new GCMParameterSpec(128, unb64(p[0])));
prompt(call, c, call.getString("title", "MrTerm"), call.getString("cancel", "Cancel"), (cipher) -> {
JSObject r = new JSObject();
r.put("secret", b64(cipher.doFinal(unb64(p[1]))));
call.resolve(r);
});
} catch (KeyPermanentlyInvalidatedException e) {
// Neuer Fingerabdruck registriert → Schlüssel ungültig, Nutzer muss neu einrichten
prefs().edit().remove("bio").apply();
deleteKey(BIO_ALIAS);
call.reject("invalidated");
} catch (Exception e) {
call.reject(e.getMessage());
}
}
@PluginMethod
public void bioDisable(PluginCall call) {
prefs().edit().remove("bio").apply();
deleteKey(BIO_ALIAS);
call.resolve();
}
private interface CipherUse { void run(Cipher c) throws Exception; }
private void prompt(PluginCall call, Cipher cipher, String title, String cancel, CipherUse use) {
FragmentActivity act = getActivity();
act.runOnUiThread(() -> {
BiometricPrompt bp = new BiometricPrompt(act, ContextCompat.getMainExecutor(act), new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
try { use.run(result.getCryptoObject().getCipher()); }
catch (Exception e) { call.reject(e.getMessage()); }
}
@Override
public void onAuthenticationError(int code, CharSequence msg) {
call.reject(code == BiometricPrompt.ERROR_USER_CANCELED || code == BiometricPrompt.ERROR_NEGATIVE_BUTTON ? "cancelled" : msg.toString());
}
});
BiometricPrompt.PromptInfo info = new BiometricPrompt.PromptInfo.Builder()
.setTitle(title)
.setNegativeButtonText(cancel)
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
.build();
bp.authenticate(info, new BiometricPrompt.CryptoObject(cipher));
});
}
// ---------- Sonstiges ----------
@PluginMethod
public void info(PluginCall call) {
String name = null;
try { name = Settings.Global.getString(getContext().getContentResolver(), "device_name"); } catch (Exception ignored) {}
if (name == null || name.isEmpty()) name = Build.MANUFACTURER + " " + Build.MODEL;
JSObject r = new JSObject();
r.put("device", name);
r.put("locale", Locale.getDefault().toLanguageTag());
try { r.put("version", getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0).versionName); }
catch (Exception e) { r.put("version", "0.0.0"); }
call.resolve(r);
}
@PluginMethod
public void multicast(PluginCall call) {
boolean on = Boolean.TRUE.equals(call.getBoolean("on", true));
WifiManager wm = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (on && multicastLock == null && wm != null) {
multicastLock = wm.createMulticastLock("mrterm-sync");
multicastLock.setReferenceCounted(false);
multicastLock.acquire();
} else if (!on && multicastLock != null) {
multicastLock.release();
multicastLock = null;
}
call.resolve();
}
@PluginMethod
public void background(PluginCall call) {
getActivity().runOnUiThread(() -> getActivity().moveTaskToBack(true));
call.resolve();
}
@PluginMethod
public void copy(PluginCall call) {
ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText("MrTerm", call.getString("text", "")));
call.resolve();
}
@PluginMethod
public void paste(PluginCall call) {
ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
String text = "";
if (cm.hasPrimaryClip() && cm.getPrimaryClip().getItemCount() > 0) {
CharSequence t = cm.getPrimaryClip().getItemAt(0).coerceToText(getContext());
if (t != null) text = t.toString();
}
JSObject r = new JSObject();
r.put("text", text);
call.resolve(r);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 467 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 798 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 465 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#111728</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">MrTerm</string>
<string name="title_activity_main">MrTerm</string>
<string name="package_name">de.mrterm.app</string>
<string name="custom_url_scheme">de.mrterm.app</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
+29
View File
@@ -0,0 +1,29 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
+6
View File
@@ -0,0 +1,6 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-nodejs'
project(':capacitor-nodejs').projectDir = new File('../node_modules/capacitor-nodejs/android')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
+103
View File
@@ -0,0 +1,103 @@
// Baut die Android-App.
// node build.js --setup Node.js-Plugin herunterladen (Prüfsumme) und Abhängigkeiten installieren
// node build.js Weboberfläche + Node-Backend nach www/ bauen und ins Android-Projekt synchronisieren
// node build.js --apk zusätzlich signierte Release-APK nach ../dist/MrTerm-<version>.apk bauen
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { execFileSync } = require('child_process');
const ROOT = path.join(__dirname, '..');
const WWW = path.join(__dirname, 'www');
const version = require(path.join(ROOT, 'package.json')).version;
const run = (cmd, args, opts = {}) => execFileSync(cmd, args, { stdio: 'inherit', cwd: __dirname, ...opts });
const PLUGIN = {
url: 'https://github.com/hampoelz/capacitor-nodejs/releases/download/v1.0.0-beta.10/capacitor-nodejs.tgz',
file: path.join(__dirname, 'vendor', 'capacitor-nodejs-1.0.0-beta.10.tgz'),
sha256: 'cc47cba4190d5e0ea8e2b33f4e9bd47e159570c01571c51214467e4c21e87bd3',
};
async function setup() {
if (!fs.existsSync(PLUGIN.file)) {
console.log('Lade capacitor-nodejs …');
const res = await fetch(PLUGIN.url);
if (!res.ok) throw new Error(`Download fehlgeschlagen: ${res.status}`);
fs.mkdirSync(path.dirname(PLUGIN.file), { recursive: true });
fs.writeFileSync(PLUGIN.file, Buffer.from(await res.arrayBuffer()));
}
const sum = crypto.createHash('sha256').update(fs.readFileSync(PLUGIN.file)).digest('hex');
if (sum !== PLUGIN.sha256) { fs.rmSync(PLUGIN.file); throw new Error(`Prüfsumme von capacitor-nodejs stimmt nicht (${sum})`); }
run('npm', ['install']);
}
function copy(from, to) {
fs.mkdirSync(path.dirname(to), { recursive: true });
fs.cpSync(from, to, { recursive: true });
}
// capacitor-nodejs baut seine Brückenbibliothek mit 4-KB-Seitenausrichtung; neuere Geräte (z. B. Pixel mit
// 16-KB-Speicherseiten) laden sie dann nicht. Linker-Option einmalig ergänzen.
function patchPlugin() {
const f = path.join(__dirname, 'node_modules', 'capacitor-nodejs', 'android', 'CMakeLists.txt');
const s = fs.readFileSync(f, 'utf8');
if (!s.includes('max-page-size=16384')) fs.writeFileSync(f, `${s}\ntarget_link_options(native-lib PRIVATE "-Wl,-z,max-page-size=16384")\n`);
}
function buildWeb() {
patchPlugin();
fs.rmSync(WWW, { recursive: true, force: true });
copy(path.join(__dirname, 'web'), WWW);
const nm = path.join(ROOT, 'node_modules', '@xterm');
copy(path.join(nm, 'xterm', 'lib', 'xterm.js'), path.join(WWW, 'lib', 'xterm.js'));
copy(path.join(nm, 'xterm', 'css', 'xterm.css'), path.join(WWW, 'lib', 'xterm.css'));
copy(path.join(nm, 'addon-fit', 'lib', 'addon-fit.js'), path.join(WWW, 'lib', 'addon-fit.js'));
copy(path.join(ROOT, 'src', 'i18n.js'), path.join(WWW, 'lib', 'i18n.js'));
copy(path.join(ROOT, 'src', 'renderer', 'themes.js'), path.join(WWW, 'lib', 'themes.js'));
copy(path.join(ROOT, 'src', 'renderer', 'logo.png'), path.join(WWW, 'logo.png'));
// Node-Backend inkl. ssh2 in eine Datei bündeln (nodejs-mobile = Node 18)
require('esbuild').buildSync({
entryPoints: [path.join(__dirname, 'nodejs', 'server.js')],
outfile: path.join(WWW, 'nodejs', 'index.js'),
bundle: true, platform: 'node', target: 'node18', minify: true, legalComments: 'none',
external: ['bridge', 'cpu-features'],
alias: { electron: path.join(__dirname, 'nodejs', 'electron-shim.js') },
logLevel: 'warning',
});
fs.writeFileSync(path.join(WWW, 'nodejs', 'package.json'), JSON.stringify({ name: 'mrterm-backend', main: 'index.js' }));
run('npx', ['cap', 'sync', 'android']);
}
function toolchain() {
const base = path.join(os.homedir(), '.local', 'share', 'android-toolchain');
const env = { ...process.env };
env.JAVA_HOME ||= path.join(base, 'jdk');
env.ANDROID_HOME ||= path.join(base, 'sdk');
if (!fs.existsSync(env.JAVA_HOME) || !fs.existsSync(env.ANDROID_HOME)) throw new Error('JDK/Android-SDK nicht gefunden: JAVA_HOME und ANDROID_HOME setzen');
fs.writeFileSync(path.join(__dirname, 'android', 'local.properties'), `sdk.dir=${env.ANDROID_HOME}\n`);
return env;
}
function buildApk() {
if (!fs.existsSync(path.join(__dirname, 'android', 'keystore.properties'))) {
throw new Error('android/keystore.properties fehlt (Signaturschlüssel). Ohne ihn können Updates nicht installiert werden.');
}
run('./gradlew', ['--no-daemon', '-q', 'assembleRelease', `-PmrtermVersion=${version}`], { cwd: path.join(__dirname, 'android'), env: toolchain() });
const dir = path.join(__dirname, 'android', 'app', 'build', 'outputs', 'apk', 'release');
for (const abi of ['arm64-v8a', 'armeabi-v7a']) {
const out = path.join(ROOT, 'dist', `MrTerm-${version}-${abi}.apk`);
copy(path.join(dir, `app-${abi}-release.apk`), out);
console.log(`APK: ${out}`);
}
}
(async () => {
const args = process.argv.slice(2);
if (args.includes('--setup')) await setup();
else {
buildWeb();
if (args.includes('--apk')) buildApk();
}
})().catch((e) => { console.error(e.message || e); process.exit(1); });
+9
View File
@@ -0,0 +1,9 @@
{
"appId": "de.mrterm.app",
"appName": "MrTerm",
"webDir": "www",
"android": { "backgroundColor": "#14161d" },
"plugins": {
"CapacitorNodeJS": { "nodeDir": "nodejs", "startMode": "manual" }
}
}
+63
View File
@@ -0,0 +1,63 @@
// Entwicklung ohne Handy: startet die gebaute Oberfläche (www/) in einem Fenster in Handygröße
// und das Node-Backend im Electron-Hauptprozess, verbunden über eine nachgebaute Capacitor-Bridge.
// cd mobile && node build.js && ../node_modules/.bin/electron dev/electron-dev.js [--user-data-dir=…]
const { app, BrowserWindow, ipcMain, clipboard } = require('electron');
const path = require('path');
const Module = require('module');
const EventEmitter = require('events');
const crypto = require('crypto');
const WWW = path.join(__dirname, '..', 'www');
const toWeb = new EventEmitter();
const fromWeb = new EventEmitter();
let win;
// require('bridge') im Backend auf diese Nachbildung umleiten
const bridge = {
channel: { send: (name, ...args) => toWeb.emit('msg', name, args), addListener: (name, fn) => fromWeb.on(name, fn) },
getDataPath: () => path.join(app.getPath('userData'), 'mobile-data'),
};
const resolve = Module._resolveFilename;
Module._resolveFilename = function (req, ...rest) { return req === 'bridge' ? 'bridge' : resolve.call(this, req, ...rest); };
require.cache.bridge = { id: 'bridge', filename: 'bridge', loaded: true, exports: bridge };
toWeb.on('msg', (name, args) => { if (win && !win.isDestroyed()) win.webContents.send('dev:node', name, args); });
ipcMain.on('dev:send', (_e, name, args) => fromWeb.emit(name, ...args));
ipcMain.handle('dev:start', (_e, env) => {
Object.assign(process.env, env, { DATADIR: bridge.getDataPath() });
require('fs').mkdirSync(process.env.DATADIR, { recursive: true });
setTimeout(() => { started = true; require(path.join(WWW, 'nodejs', 'index.js')); }, 500);
});
let started;
ipcMain.handle('dev:ready', async () => { while (!started) await new Promise((r) => setTimeout(r, 100)); });
ipcMain.handle('dev:native', (_e, method, arg) => {
if (method === 'vaultKey') return { key: crypto.createHash('sha256').update(app.getPath('userData')).digest('base64') };
if (method === 'info') return { device: 'Dev Phone', locale: process.env.MRTERM_DEV_LOCALE || 'en-US', version: require('../../package.json').version };
if (method === 'bioAvailable') return { available: true, enrolled: false };
if (method === 'bioEnroll' || method === 'bioUnlock') return { secret: Buffer.alloc(32, 1).toString('base64') };
if (method === 'copy') return clipboard.writeText(arg.text);
if (method === 'paste') return { text: clipboard.readText() };
return {};
});
app.whenReady().then(() => {
win = new BrowserWindow({
width: 412, height: 870, backgroundColor: '#14161d',
webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true },
});
win.loadFile(path.join(WWW, 'index.html'));
if (process.env.MRTERM_SHOT) {
const steps = JSON.parse(require('fs').readFileSync(process.env.MRTERM_SHOT, 'utf8'));
win.webContents.on('console-message', (e) => console.log('[r]', e.message));
win.webContents.once('did-finish-load', async () => {
await new Promise((r) => setTimeout(r, 2500));
for (const s of steps) {
if (s.js) await win.webContents.executeJavaScript(`(async()=>{${s.js}})();0`).catch((e) => console.log('js', e.message));
await new Promise((r) => setTimeout(r, s.wait || 900));
if (s.shot) require('fs').writeFileSync(path.join(process.env.MRTERM_SHOT_OUT, s.shot), (await win.webContents.capturePage()).toPNG());
}
app.exit(0);
});
}
});
app.on('window-all-closed', () => app.exit(0));
+16
View File
@@ -0,0 +1,16 @@
const { contextBridge, ipcRenderer } = require('electron');
const listeners = new Map();
ipcRenderer.on('dev:node', (_e, name, args) => listeners.get(name)?.forEach((fn) => fn({ args })));
const native = (m) => (arg) => ipcRenderer.invoke('dev:native', m, arg);
contextBridge.exposeInMainWorld('DevBridge', {
NodeJS: {
// Wie auf Android: start() kehrt erst zurück, wenn Node beendet wird
start: (o) => { ipcRenderer.invoke('dev:start', o.env); return new Promise(() => {}); },
whenReady: () => ipcRenderer.invoke('dev:ready'),
send: ({ eventName, args }) => ipcRenderer.send('dev:send', eventName, args),
addListener: (name, fn) => { if (!listeners.has(name)) listeners.set(name, new Set()); listeners.get(name).add(fn); return { remove: () => listeners.get(name).delete(fn) }; },
},
Native: Object.fromEntries(['vaultKey', 'info', 'bioAvailable', 'bioEnroll', 'bioUnlock', 'bioDisable', 'multicast', 'copy', 'paste', 'background'].map((m) => [m, native(m)])),
});
+30
View File
@@ -0,0 +1,30 @@
// Ersatz für die von store.js genutzten Electron-APIs unter Android.
// safeStorage verschlüsselt mit einem 256-Bit-Schlüssel, den die App im Android Keystore verpackt aufbewahrt
// und beim Start als MRTERM_VAULT_KEY (base64) an den Node-Prozess übergibt.
const crypto = require('crypto');
const dataDir = () => process.env.DATADIR || require('bridge').getDataPath();
const key = () => {
const k = Buffer.from(process.env.MRTERM_VAULT_KEY || '', 'base64');
return k.length === 32 ? k : null;
};
const safeStorage = {
isEncryptionAvailable: () => !!key(),
encryptString(plain) {
const iv = crypto.randomBytes(12);
const c = crypto.createCipheriv('aes-256-gcm', key(), iv);
const ct = Buffer.concat([c.update(String(plain), 'utf8'), c.final()]);
return Buffer.concat([iv, c.getAuthTag(), ct]);
},
decryptString(buf) {
const d = crypto.createDecipheriv('aes-256-gcm', key(), buf.subarray(0, 12));
d.setAuthTag(buf.subarray(12, 28));
return Buffer.concat([d.update(buf.subarray(28)), d.final()]).toString('utf8');
},
};
module.exports = {
app: { getPath: () => dataDir(), getVersion: () => process.env.MRTERM_VERSION || '0.0.0', getLocale: () => process.env.MRTERM_LOCALE || 'en' },
safeStorage,
};
+199
View File
@@ -0,0 +1,199 @@
// Node-Backend der Android-App. Nutzt dieselben Module wie der Electron-Hauptprozess
// (Tresor, SSH, LAN-Sync, Docker, Firewall, Netzwerk) und spricht über die Capacitor-Bridge mit der Oberfläche.
// Protokoll: Oberfläche → 'call' [reqId, Kanal, Argumente] bzw. 'send' [Kanal, Argumente];
// Backend → 'reply' [reqId, ok, Wert|Fehler] und 'evt' [Kanal, Argumente].
const { channel } = require('bridge');
const crypto = require('crypto');
const { utils: sshUtils } = require('ssh2');
const { Store } = require('../../src/main/store');
const { SshManager } = require('../../src/main/ssh');
const { DockerManager } = require('../../src/main/docker');
const { FirewallManager } = require('../../src/main/firewall');
const { NetworkConfigManager } = require('../../src/main/network');
const { SyncService } = require('../../src/main/sync');
const i18n = require('../../src/i18n');
const send = (ch, ...args) => channel.send('evt', ch, args);
process.on('uncaughtException', (e) => { console.error(e); send('toast', e?.message || String(e), 'error'); });
process.on('unhandledRejection', (e) => console.error('Unhandled rejection:', e));
const store = new Store();
const applyLanguage = () => i18n.setLanguage(store.get().settings.language, process.env.MRTERM_LOCALE || 'en');
// Rückfragen an die Oberfläche (Hostschlüssel, Passwörter, Kopplungscode)
const pending = new Map();
function ask(ch, req, timeout = 0) {
return new Promise((resolve) => {
const reqId = crypto.randomUUID();
pending.set(reqId, resolve);
send(ch, { reqId, ...req });
if (timeout) setTimeout(() => { if (pending.delete(reqId)) resolve(null); }, timeout);
});
}
const answer = (reqId, value) => { const r = pending.get(reqId); pending.delete(reqId); r?.(value); };
const confirmHostKey = async (target, fingerprint, known) =>
!!(await ask('hostkey:request', { host: `${target.host}:${target.port}`, fingerprint, previous: known?.fingerprint || '' }));
const askSecret = (sessionId, req) => ask('secret:request', { sessionId, ...req });
const ssh = new SshManager(store, confirmHostKey, askSecret);
const docker = new DockerManager(ssh);
const firewall = new FirewallManager(ssh);
const network = new NetworkConfigManager(ssh);
const sync = new SyncService(store, send, async (req) => !!(await ask('sync:pairPrompt', req, 115000)));
store.onChange = () => sync.schedule();
const handlers = new Map();
const OPEN_WHILE_LOCKED = new Set(['app:version']);
const handle = (ch, fn) => handlers.set(ch, fn);
channel.addListener('call', async (reqId, ch, args = []) => {
try {
const fn = handlers.get(ch);
if (!fn) throw new Error(`Unknown channel ${ch}`);
if (store.locked && !ch.startsWith('lock:') && !OPEN_WHILE_LOCKED.has(ch)) throw new Error(i18n.t('MrTerm is locked.'));
channel.send('reply', reqId, true, await fn(...args));
} catch (e) { channel.send('reply', reqId, false, e?.message || String(e)); }
});
const listeners = {
'ssh:write': (id, d) => ssh.write(id, d),
'ssh:resize': (id, c, r) => ssh.resize(id, c, r),
'ssh:close': (id) => ssh.close(id),
'ask:reply': answer,
};
channel.addListener('send', (ch, args = []) => { try { listeners[ch]?.(...args); } catch (e) { console.error(e); } });
// ---------- App-Sperre: Passwort, zusätzlich Fingerabdruck (Geheimnis aus dem Android Keystore) ----------
const kdf = (pw, salt, N) => new Promise((resolve, reject) =>
crypto.scrypt(String(pw), salt, 32, { N, r: 8, p: 1, maxmem: 256 * N * 8 }, (e, k) => (e ? reject(e) : resolve(k))));
const bioKek = (b64) => Buffer.from(crypto.hkdfSync('sha256', Buffer.from(b64, 'base64'), Buffer.alloc(0), 'mrterm-bio-kek', 32));
function lockStatus() {
const { language, appTheme, accent } = store.get().settings;
return { enabled: store.lockEnabled, locked: store.locked, hasPassword: !!store.lock?.password, bio: !!store.lock?.bio, meta: { language, appTheme, accent } };
}
const requireUnlocked = () => { if (store.locked) throw new Error(i18n.t('MrTerm is locked.')); };
const afterUnlock = () => { applyLanguage(); sync.start().catch(() => {}); };
handle('lock:status', lockStatus);
handle('lock:lock', () => { if (store.lockEnabled) store.locked = true; return lockStatus(); });
handle('lock:unlockPassword', async (pw) => {
const p = store.lock?.password;
if (!p) throw new Error(i18n.t('No password set.'));
const kek = await kdf(pw, Buffer.from(p.salt, 'base64'), p.N);
try { store.unlockWith(kek, p.wrap); } catch { throw new Error(i18n.t('Wrong password.')); }
afterUnlock();
return true;
});
handle('lock:unlockBio', (secret) => {
if (!store.lock?.bio) throw new Error(i18n.t('Fingerprint unlock is not set up.'));
try { store.unlockWith(bioKek(secret), store.lock.bio.wrap); } catch { throw new Error(i18n.t('Fingerprint unlock failed. Use your password.')); }
afterUnlock();
return true;
});
handle('lock:setPassword', async (pw) => {
requireUnlocked();
if (!pw || String(pw).length < 6) throw new Error(i18n.t('The password must be at least 6 characters long.'));
const salt = crypto.randomBytes(16), N = 2 ** 15;
const kek = await kdf(pw, salt, N);
store.lock = store.lock || { password: null, fido: [] };
store.lock.password = { salt: salt.toString('base64'), N, wrap: store.wrapDek(kek) };
store.save();
return lockStatus();
});
handle('lock:removePassword', () => {
requireUnlocked();
if (store.lock) { store.lock.password = null; store.lock.bio = null; } // Fingerabdruck nur zusätzlich zum Passwort
store.dropLockIfEmpty();
store.save();
return lockStatus();
});
handle('lock:setBio', (secret) => {
requireUnlocked();
if (!store.lock?.password) throw new Error(i18n.t('Set a password first.'));
store.lock.bio = secret ? { wrap: store.wrapDek(bioKek(secret)) } : null;
store.save();
return lockStatus();
});
// ---------- Tresor ----------
const publicData = () => { const { sync: _s, tombstones: _t, ...rest } = store.get(); return rest; };
handle('vault:get', () => ({ ...publicData(), encrypted: store.encrypted, platform: 'android' }));
handle('vault:upsert', (col, item) => store.upsert(col, item));
handle('vault:remove', (col, id) => {
if (col === 'vpns') store.get().hosts.forEach((h) => { if (h.vpnId === id) { h.vpnId = null; h.updatedAt = Date.now(); } });
return store.remove(col, id);
});
handle('vault:settings', (s) => { store.setSettings(s); if ('language' in s) applyLanguage(); });
handle('vault:forgetHost', (id) => store.forgetKnownHost(id));
handle('app:version', () => process.env.MRTERM_VERSION || '0.0.0');
// ---------- Schlüssel ----------
handle('key:generate', ({ type, bits, comment, passphrase }) => {
const opts = { comment: comment || 'mrterm@android' };
if (type === 'rsa') opts.bits = Number(bits) || 4096;
if (passphrase) { opts.passphrase = passphrase; opts.cipher = 'aes256-cbc'; }
const k = sshUtils.generateKeyPairSync(type === 'rsa' ? 'rsa' : type === 'ecdsa' ? 'ecdsa' : 'ed25519', opts);
return { privateKey: k.private, publicKey: k.public };
});
handle('key:parse', ({ privateKey, passphrase }) => {
const k = sshUtils.parseKey(privateKey, passphrase || undefined);
if (k instanceof Error) throw k;
const key = Array.isArray(k) ? k[0] : k;
return { type: key.type, publicKey: `${key.type} ${key.getPublicSSH().toString('base64')} ${key.comment || ''}`.trim() };
});
// ---------- SSH-Terminal ----------
function hostWithOverrides(ref) {
if (typeof ref === 'string') {
const h = store.resolveHost(ref);
if (!h) throw new Error(i18n.t('Host not found'));
return h;
}
if (ref?.ref) return { ...hostWithOverrides(ref.ref), execCommand: ref.execCommand, label: ref.label };
return ref;
}
handle('ssh:open', async (sessionId, ref, size) => {
const host = hostWithOverrides(ref);
if (host.id && !host.execCommand) store.addHistory({ hostId: host.id, at: Date.now() });
await ssh.openShell(sessionId, host, size, (type, payload) => send('ssh:event', sessionId, type, payload));
return true;
});
// ---------- Docker / Firewall / Netzwerk (gleiche Module wie am Desktop) ----------
handle('docker:open', (id, ref) => docker.open(id, hostWithOverrides(ref), () => 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('firewall:open', (id, ref) => firewall.open(id, hostWithOverrides(ref), () => 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('network:open', (id, ref) => network.open(id, hostWithOverrides(ref), () => send('network:closed', id)));
handle('network:read', (id) => network.read(id));
handle('network:save', (id, model, verify) => network.saveInterface(id, model, verify));
handle('network:remove', (id, model) => network.removeInterface(id, model));
handle('network:hostname', (id, name) => network.setHostname(id, name));
handle('network:resolv', (id, servers, search) => network.setResolv(id, servers, search));
handle('network:close', (id) => network.close(id));
// ---------- Synchronisation ----------
handle('sync:status', () => sync.status());
handle('sync:enable', (on, name) => sync.setEnabled(on, name));
handle('sync:pairable', (on) => { sync.setPairable(on); return sync.status(); });
handle('sync:pair', (id) => sync.pair(id));
handle('sync:unpair', (id) => sync.unpair(id));
handle('sync:now', () => sync.syncAll());
handle('sync:share', (sel) => sync.setShare(sel));
handle('sync:shareItem', (c, id, yes) => sync.shareItem(c, id, yes));
handle('sync:probe', (address) => sync.probe(address));
// App im Hintergrund: Sync-Sockets schließen, im Vordergrund wieder öffnen
handle('app:pause', () => sync.stop());
handle('app:resume', () => sync.start().catch(() => {}));
store.load();
applyLanguage();
sync.start().catch(() => {});
channel.send('ready');
+1731
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "mrterm-mobile",
"private": true,
"version": "0.0.0",
"description": "MrTerm for Android",
"scripts": {
"build": "node build.js",
"apk": "node build.js --apk"
},
"devDependencies": {
"@capacitor/cli": "^8.5.2",
"esbuild": "^0.28.2"
},
"allowScripts": {
"esbuild@0.28.2": true
},
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
"capacitor-nodejs": "file:vendor/capacitor-nodejs-1.0.0-beta.10.tgz"
}
}
+1037
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<meta name="color-scheme" content="dark" />
<title>MrTerm</title>
<link rel="stylesheet" href="lib/xterm.css" />
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="boot"><img src="logo.png" alt="" /><div class="spinner"></div></div>
<!-- Hauptansicht: Inhalt + untere Navigation -->
<div id="main" hidden>
<main id="view"></main>
<nav id="tabs">
<button data-view="hosts"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/></svg><span data-t>Hosts</span></button>
<button data-view="keys"><svg viewBox="0 0 24 24"><circle cx="8" cy="15" r="4"/><path d="M11 12l9-9M16 7l3 3M14 9l2 2"/></svg><span data-t>Keys</span></button>
<button data-view="snippets"><svg viewBox="0 0 24 24"><path d="M8 7l-5 5 5 5M16 7l5 5-5 5"/></svg><span data-t>Snippets</span></button>
<button data-view="settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></svg><span data-t>Settings</span></button>
</nav>
</div>
<!-- Terminal im Vollbild -->
<div id="termScreen" hidden>
<header class="term-head">
<button class="icon" id="termBack" aria-label="Back"><svg viewBox="0 0 24 24"><path d="M15 18l-6-6 6-6"/></svg></button>
<button class="term-title" id="termTitle"><span class="dot"></span><span class="name"></span><svg viewBox="0 0 24 24"><path d="M6 9l6 6 6-6"/></svg></button>
<button class="icon" id="termKbd" aria-label="Keyboard"><svg viewBox="0 0 24 24"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10"/></svg></button>
<button class="icon" id="termMenu" aria-label="Menu"><svg viewBox="0 0 24 24"><circle cx="12" cy="5" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="19" r="1.5"/></svg></button>
</header>
<div id="terms"></div>
<div id="keybar"></div>
</div>
<div id="lockScreen" hidden></div>
<div id="layer"></div>
<div id="toasts"></div>
<script src="lib/i18n.js"></script>
<script src="lib/themes.js"></script>
<script src="lib/xterm.js"></script>
<script src="lib/addon-fit.js"></script>
<script src="app.js"></script>
</body>
</html>
+190
View File
@@ -0,0 +1,190 @@
:root {
--bg: #14161d;
--surface: #1c1f29;
--surface2: #252936;
--line: #2c3040;
--text: #e6e8ef;
--muted: #9aa0b4;
--faint: #5d6377;
--accent: #6e7bff;
--accent-soft: #6e7bff26;
--green: #3ecf8e;
--red: #ff5f6d;
--orange: #ffb347;
--radius: 14px;
/* Capacitor setzt --safe-area-inset-* bei Edge-to-Edge; env() als Rückfall */
--top: max(env(safe-area-inset-top, 0px), var(--safe-area-inset-top, 0px));
--bottom: max(env(safe-area-inset-bottom, 0px), var(--safe-area-inset-bottom, 0px));
color-scheme: dark;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); overflow: hidden; }
body { font: 15px/1.4 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; -webkit-user-select: none; user-select: none; overscroll-behavior: none; }
[hidden] { display: none !important; }
button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
input, select, textarea { font: inherit; color: var(--text); -webkit-user-select: text; user-select: text; }
svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; flex: none; }
.mono { font-family: ui-monospace, 'JetBrains Mono', 'DejaVu Sans Mono', monospace; }
/* ---------- Start ---------- */
#boot { position: fixed; inset: 0; display: grid; place-content: center; justify-items: center; gap: 28px; }
#boot img { width: 84px; height: 84px; }
.spinner { width: 26px; height: 26px; border-radius: 50%; border: 3px solid var(--surface2); border-top-color: var(--accent); animation: spin .8s linear infinite; }
.spinner.sm { width: 16px; height: 16px; border-width: 2px; }
@keyframes spin { to { transform: rotate(360deg); } }
/* ---------- Grundlayout ---------- */
#main { position: fixed; inset: 0; display: flex; flex-direction: column; }
#view { flex: 1; overflow-y: auto; padding: calc(var(--top) + 8px) 16px 96px; -webkit-overflow-scrolling: touch; }
#tabs { display: flex; background: var(--surface); border-top: 1px solid var(--line); padding-bottom: var(--bottom); }
#tabs button { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 3px; padding: 9px 0 8px; color: var(--faint); font-size: 11.5px; font-weight: 600; }
#tabs button.active { color: var(--accent); }
.top { display: flex; align-items: center; gap: 10px; min-height: 52px; }
.top h1 { font-size: 26px; margin: 0; flex: 1; letter-spacing: -.3px; }
.top h1 .brand { color: var(--green); }
.icon { width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center; color: var(--muted); }
.icon:active { background: var(--surface2); }
.search { display: flex; align-items: center; gap: 10px; background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 0 12px; margin: 6px 0 14px; }
.search svg { color: var(--faint); width: 18px; height: 18px; }
.search input { flex: 1; background: none; border: 0; outline: 0; padding: 12px 0; }
.section { margin: 18px 4px 8px; font-size: 12px; font-weight: 700; letter-spacing: .6px; text-transform: uppercase; color: var(--muted); display: flex; align-items: center; gap: 8px; }
.section .count { background: var(--surface2); border-radius: 8px; padding: 1px 7px; font-size: 11px; color: var(--faint); }
.section svg { width: 16px; height: 16px; }
.list { background: var(--surface); border-radius: var(--radius); overflow: hidden; }
.item { display: flex; align-items: center; gap: 12px; padding: 12px 14px; min-height: 62px; position: relative; }
.item + .item::before { content: ''; position: absolute; top: 0; left: 64px; right: 0; border-top: 1px solid var(--line); }
.item:active { background: var(--surface2); }
.item .meta { flex: 1; min-width: 0; }
.item .title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item .sub { color: var(--muted); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item .more { color: var(--faint); width: 38px; height: 38px; display: grid; place-items: center; border-radius: 10px; margin-right: -6px; }
.item.disabled { opacity: .55; }
.avatar { width: 38px; height: 38px; border-radius: 11px; display: grid; place-items: center; font-weight: 800; color: #fff; flex: none; font-size: 16px; }
.avatar svg { width: 20px; height: 20px; }
.avatar.soft { background: var(--accent-soft); color: var(--accent); }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; }
.dot.on { background: var(--green); }
.dot.err { background: var(--red); }
.sessions { display: flex; gap: 8px; overflow-x: auto; margin: 0 -16px 4px; padding: 2px 16px 8px; scrollbar-width: none; }
.sessions::-webkit-scrollbar { display: none; }
.chip { display: flex; align-items: center; gap: 8px; background: var(--surface); border: 1px solid var(--line); border-radius: 20px; padding: 8px 14px; white-space: nowrap; font-weight: 600; font-size: 14px; }
.empty { text-align: center; padding: 60px 24px; color: var(--muted); }
.empty .avatar { margin: 0 auto 16px; width: 60px; height: 60px; border-radius: 18px; }
.empty .avatar svg { width: 28px; height: 28px; }
.empty h3 { color: var(--text); margin: 0 0 6px; }
.fab { position: fixed; right: 18px; bottom: calc(76px + var(--bottom)); width: 58px; height: 58px; border-radius: 18px; background: var(--accent); color: #fff; display: grid; place-items: center; box-shadow: 0 8px 24px #0008; }
.fab svg { width: 26px; height: 26px; }
/* ---------- Karten / Einstellungen ---------- */
.card { background: var(--surface); border-radius: var(--radius); padding: 14px 16px; margin-bottom: 14px; }
.card h3 { margin: 0 0 4px; font-size: 16px; }
.card p, .hint { color: var(--muted); font-size: 13.5px; margin: 4px 0 10px; }
.row { display: flex; align-items: center; gap: 12px; padding: 10px 0; }
.row + .row { border-top: 1px solid var(--line); }
.row .grow { flex: 1; min-width: 0; }
.row .sub { color: var(--muted); font-size: 13px; }
.btns { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 44px; padding: 0 16px; border-radius: 12px; background: var(--surface2); font-weight: 600; }
.btn svg { width: 18px; height: 18px; }
.btn.primary { background: var(--accent); color: #fff; }
.btn.danger { color: var(--red); }
.btn.block { width: 100%; }
.btn:disabled { opacity: .5; }
.btn:active { filter: brightness(1.15); }
.field { margin-bottom: 14px; }
.field label { display: block; font-size: 12px; font-weight: 700; letter-spacing: .4px; text-transform: uppercase; color: var(--muted); margin: 0 2px 6px; }
.field input, .field select, .field textarea { width: 100%; background: var(--bg); border: 1px solid var(--line); border-radius: 12px; padding: 12px 13px; outline: 0; min-height: 48px; }
.field textarea { min-height: 110px; resize: vertical; font-family: ui-monospace, monospace; font-size: 13px; }
.field input:focus, .field select:focus, .field textarea:focus { border-color: var(--accent); }
.field .hint { margin: 6px 2px 0; font-size: 12.5px; }
.pw { position: relative; }
.pw input { padding-right: 48px; }
.pw button { position: absolute; right: 4px; top: 4px; width: 40px; height: 40px; display: grid; place-items: center; color: var(--faint); }
.two { display: grid; grid-template-columns: 1fr 96px; gap: 10px; }
.switch { position: relative; width: 50px; height: 30px; flex: none; }
.switch input { opacity: 0; width: 0; height: 0; position: absolute; }
.switch span { position: absolute; inset: 0; background: var(--surface2); border-radius: 20px; transition: .2s; }
.switch span::after { content: ''; position: absolute; left: 3px; top: 3px; width: 24px; height: 24px; border-radius: 50%; background: var(--muted); transition: .2s; }
.switch input:checked + span { background: var(--accent); }
.switch input:checked + span::after { transform: translateX(20px); background: #fff; }
.warn-box { border: 1px solid #ffb34755; background: #ffb34712; border-radius: 12px; padding: 10px 12px; color: var(--orange); font-size: 13px; margin: 8px 0; }
/* ---------- Ebenen: Seiten, Sheets, Dialoge ---------- */
#layer > * { position: fixed; inset: 0; z-index: 20; }
.page { background: var(--bg); display: flex; flex-direction: column; animation: slidein .18s ease-out; }
@keyframes slidein { from { transform: translateX(30px); opacity: 0; } }
.page-head { display: flex; align-items: center; gap: 6px; padding: calc(var(--top) + 6px) 8px 6px; border-bottom: 1px solid var(--line); background: var(--surface); }
.page-head h2 { flex: 1; font-size: 18px; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.page-head .btn { min-height: 38px; padding: 0 14px; }
.page-body { flex: 1; overflow-y: auto; padding: 16px 16px calc(24px + var(--bottom)); }
.scrim { background: #0009; display: flex; align-items: flex-end; animation: fade .15s; }
.scrim.center { align-items: center; justify-content: center; padding: 20px; }
@keyframes fade { from { opacity: 0; } }
.sheet { width: 100%; background: var(--surface); border-radius: 20px 20px 0 0; padding: 8px 8px calc(10px + var(--bottom)); max-height: 85vh; overflow-y: auto; animation: up .18s ease-out; }
@keyframes up { from { transform: translateY(40px); } }
.sheet .grab { width: 38px; height: 4px; background: var(--line); border-radius: 4px; margin: 4px auto 8px; }
.sheet .sheet-title { padding: 6px 12px 10px; color: var(--muted); font-size: 13px; font-weight: 600; }
.sheet button.opt { display: flex; align-items: center; gap: 14px; width: 100%; padding: 14px 14px; border-radius: 12px; text-align: left; font-weight: 500; }
.sheet button.opt:active { background: var(--surface2); }
.sheet button.opt.danger { color: var(--red); }
.sheet button.opt svg { color: var(--muted); }
.sheet button.opt.danger svg { color: var(--red); }
.dialog { width: 100%; max-width: 420px; background: var(--surface); border-radius: 20px; padding: 20px; max-height: 88vh; overflow-y: auto; animation: pop .15s ease-out; }
@keyframes pop { from { transform: scale(.96); opacity: 0; } }
.dialog h3 { margin: 0 0 8px; font-size: 18px; }
.dialog p { color: var(--muted); margin: 0 0 14px; }
.dialog .btns { justify-content: flex-end; margin-top: 16px; }
.fp { font-size: 12.5px; background: var(--bg); border-radius: 10px; padding: 10px; word-break: break-all; color: var(--text); -webkit-user-select: text; user-select: text; }
.pair-code { font: 700 38px ui-monospace, monospace; letter-spacing: 6px; text-align: center; padding: 16px; background: var(--bg); border-radius: 14px; color: var(--accent); }
.checks label { display: flex; align-items: center; gap: 12px; padding: 10px 2px; }
.checks input { width: 20px; height: 20px; accent-color: var(--accent); }
.checks h4 { margin: 12px 0 2px; font-size: 13px; color: var(--muted); text-transform: uppercase; letter-spacing: .4px; }
#toasts { position: fixed; left: 16px; right: 16px; bottom: calc(84px + var(--bottom)); z-index: 50; display: flex; flex-direction: column; gap: 8px; pointer-events: none; }
.toast { background: var(--surface2); border-left: 3px solid var(--accent); border-radius: 12px; padding: 12px 14px; box-shadow: 0 8px 24px #0008; animation: up .2s; font-size: 14px; }
.toast.ok { border-color: var(--green); }
.toast.error { border-color: var(--red); }
/* ---------- Sperrbildschirm ---------- */
#lockScreen { position: fixed; inset: 0; z-index: 40; background: var(--bg); display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 24px; gap: 14px; }
#lockScreen img { width: 72px; height: 72px; margin-bottom: 6px; }
#lockScreen h2 { margin: 0; }
#lockScreen p { margin: 0 0 10px; color: var(--muted); text-align: center; }
#lockScreen form { width: 100%; max-width: 340px; display: flex; flex-direction: column; gap: 10px; }
#lockScreen .field { margin: 0; }
.bio-btn { width: 64px; height: 64px; border-radius: 20px; background: var(--accent-soft); color: var(--accent); display: grid; place-items: center; margin-top: 10px; }
.bio-btn svg { width: 32px; height: 32px; }
/* ---------- Terminal ---------- */
#termScreen { position: fixed; left: 0; right: 0; top: 0; height: 100%; display: flex; flex-direction: column; background: var(--term-bg, #13151c); z-index: 10; }
.term-head { display: flex; align-items: center; gap: 2px; padding: calc(var(--top) + 2px) 4px 2px; background: var(--surface); border-bottom: 1px solid var(--line); }
.term-title { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; padding: 8px; font-weight: 700; }
.term-title .name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.term-title svg { width: 16px; height: 16px; color: var(--faint); }
.term-title .count { background: var(--surface2); color: var(--muted); border-radius: 8px; padding: 0 7px; font-size: 12px; }
#terms { flex: 1; position: relative; overflow: hidden; }
.term-wrap { position: absolute; inset: 0; padding: 4px 2px 0 6px; }
.term-wrap .xterm { height: 100%; }
.term-wrap .xterm-viewport { background-color: transparent !important; }
.term-overlay { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; background: var(--term-bg, #13151c); color: var(--muted); padding: 24px; text-align: center; z-index: 5; }
#keybar { display: flex; gap: 6px; overflow-x: auto; padding: 6px 6px calc(6px + var(--bottom)); background: var(--surface); border-top: 1px solid var(--line); scrollbar-width: none; }
#keybar::-webkit-scrollbar { display: none; }
#keybar button { flex: none; min-width: 44px; height: 40px; padding: 0 10px; border-radius: 10px; background: var(--surface2); font: 600 14px ui-monospace, monospace; color: var(--text); display: grid; place-items: center; }
#keybar button svg { width: 18px; height: 18px; }
#keybar button.on { background: var(--accent); color: #fff; }
#keybar button.lock { box-shadow: inset 0 0 0 2px #fff; }
body.kbd-open #keybar { padding-bottom: 6px; }
body.kbd-open #tabs, body.kbd-open .fab { display: none; }
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "mrterm",
"version": "0.9.1",
"version": "0.11.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "mrterm",
"version": "0.9.1",
"version": "0.11.1",
"license": "MIT",
"dependencies": {
"@xterm/addon-fit": "^0.11.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "mrterm",
"productName": "MrTerm",
"version": "0.9.1",
"version": "0.11.1",
"description": "Moderner SSH-, SFTP- und RDP-Client",
"main": "src/main/main.js",
"author": "MrBlake",
+8 -2
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Fragt nach der Version, baut Windows (Setup + Portable, per wine) und Arch/CachyOS (pacman + AppImage)
# und lädt alles als Release v<version> nach Gitea hoch.
# Fragt nach der Version, baut Windows (Setup + Portable, per wine), Arch/CachyOS (pacman + AppImage)
# und Android (APK, signiert mit mobile/android/keystore.properties) und lädt alles als Release v<version> nach Gitea hoch.
# Token: Umgebungsvariable GITEA_TOKEN oder Datei .gitea-token im Projektordner (nicht eingecheckt).
set -euo pipefail
cd "$(dirname "$0")/.."
@@ -31,5 +31,11 @@ git -c http.extraHeader="Authorization: Basic ${auth}" push origin HEAD
rm -rf dist
npm run dist:linux
npm run dist:win
if [[ -f mobile/android/keystore.properties ]]; then
[[ -d mobile/node_modules/capacitor-nodejs ]] || (cd mobile && node build.js --setup)
(cd mobile && node build.js --apk)
else
echo "mobile/android/keystore.properties fehlt – Android-APK wird übersprungen"
fi
npm run release -- --notes "$notes" "${prerelease[@]}"
+1 -1
View File
@@ -28,7 +28,7 @@ const arg = (n) => { const i = process.argv.indexOf(n); return i > 0 ? process.a
rel = await res.json();
console.log('Release angelegt:', rel.html_url);
}
const files = fs.readdirSync('dist').filter((f) => f.includes(version) && /\.(exe|AppImage|pacman)$/.test(f));
const files = fs.readdirSync('dist').filter((f) => f.includes(version) && /\.(exe|AppImage|pacman|apk)$/.test(f));
if (!files.length) throw new Error('Keine Pakete für ' + version + ' in dist/ gefunden.');
for (const f of files) {
const old = (rel.assets || []).find((a) => a.name === f);
+107
View File
@@ -543,6 +543,113 @@
'A static IPv6 configuration needs at least one IPv6 address.': 'Eine statische IPv6-Konfiguration braucht mindestens eine IPv6-Adresse.',
'Authentication failed for {user}. Check the username, password or key.': 'Anmeldung für {user} fehlgeschlagen. Prüfe Benutzername, Passwort oder Schlüssel.',
// Synchronisation
'Synchronization': 'Synchronisation',
'Synchronize hosts, groups, snippets, port forwards, VPNs and known hosts directly between MrTerm devices in your local network. The connection is end-to-end encrypted; no server or cloud is involved.': 'Hosts, Gruppen, Snippets, Port-Weiterleitungen, VPNs und Known Hosts direkt zwischen MrTerm-Geräten im lokalen Netz abgleichen. Die Verbindung ist Ende-zu-Ende verschlüsselt, ohne Server oder Cloud.',
'Enable LAN synchronization': 'LAN-Synchronisation aktivieren',
'Device name': 'Gerätename',
'No paired devices yet.': 'Noch keine gekoppelten Geräte.',
'online': 'online',
'offline': 'offline',
'last sync {time}': 'zuletzt {time}',
'Unpair': 'Entkoppeln',
'Unpair device?': 'Gerät entkoppeln?',
'“{name}” will no longer synchronize with this device.': '„{name}“ synchronisiert dann nicht mehr mit diesem Gerät.',
'Shared secrets: {keys} SSH keys, {pw} host passwords, {vpn} VPN configurations': 'Geteilte Geheimnisse: {keys} SSH-Schlüssel, {pw} Host-Passwörter, {vpn} VPN-Konfigurationen',
'Pair new device': 'Neues Gerät koppeln',
'Sync now': 'Jetzt synchronisieren',
'Synchronized with {n} device(s)': 'Mit {n} Gerät(en) synchronisiert',
'Choose shared secrets': 'Geteilte Geheimnisse auswählen',
'Devices find each other via UDP port 47811 and synchronize via TCP port 47812. If a firewall is active, allow these ports in your local network (with UFW: sudo ufw allow 47811/udp and sudo ufw allow 47812/tcp).': 'Geräte finden sich über UDP-Port 47811 und synchronisieren über TCP-Port 47812. Ist eine Firewall aktiv, erlaube diese Ports im lokalen Netz (mit UFW: sudo ufw allow 47811/udp und sudo ufw allow 47812/tcp).',
'Open “Pair new device” on the other device too, then select it here. Both devices show a code that you confirm on both sides.': 'Öffne „Neues Gerät koppeln“ auch auf dem anderen Gerät und wähle es dann hier aus. Beide Geräte zeigen einen Code, den du auf beiden Seiten bestätigst.',
'Or enter an IP address, e.g. 192.168.0.25': 'Oder IP-Adresse eingeben, z. B. 192.168.0.25',
'Searching for devices …': 'Suche nach Geräten …',
'not ready for pairing': 'nicht bereit zum Koppeln',
'Pair': 'Koppeln',
'Pairing …': 'Kopple …',
'Device found': 'Gerät gefunden',
'Choose which secrets this device may send to paired devices. Everything else (hosts, groups, snippets …) is synchronized without passwords and private keys.': 'Wähle, welche Geheimnisse dieses Gerät an gekoppelte Geräte senden darf. Alles andere (Hosts, Gruppen, Snippets …) wird ohne Passwörter und private Schlüssel synchronisiert.',
'SSH keys': 'SSH-Schlüssel',
'Host passwords': 'Host-Passwörter',
'VPN configurations': 'VPN-Konfigurationen',
'There are no secrets on this device yet.': 'Auf diesem Gerät gibt es noch keine Geheimnisse.',
'Share nothing': 'Nichts teilen',
'Select all': 'Alle auswählen',
'Paired with {name}': 'Mit {name} gekoppelt',
'Confirm pairing': 'Kopplung bestätigen',
'Pairing with “{name}”. Does the other device show the same code?': 'Kopplung mit „{name}“. Zeigt das andere Gerät denselben Code?',
'Codes differ': 'Codes unterschiedlich',
'Codes match': 'Codes stimmen überein',
'Pairing was rejected on this device.': 'Die Kopplung wurde auf diesem Gerät abgelehnt.',
'Pairing was rejected on the other device.': 'Die Kopplung wurde auf dem anderen Gerät abgelehnt.',
'Pairing verification failed.': 'Die Überprüfung der Kopplung ist fehlgeschlagen.',
'Device is not ready for pairing': 'Das Gerät ist nicht zum Koppeln bereit',
'CachyOS: allow the sync ports in the firewall': 'CachyOS: Sync-Ports in der Firewall freigeben',
'Firewall active: allow the sync ports': 'Firewall aktiv: Sync-Ports freigeben',
'Otherwise other devices cannot find or reach this device. Run these commands once in a terminal:': 'Sonst können andere Geräte dieses Gerät weder finden noch erreichen. Führe diese Befehle einmal in einem Terminal aus:',
'Copy commands': 'Befehle kopieren',
'Already done, hide': 'Erledigt, ausblenden',
'CachyOS enables the UFW firewall by default. It blocks the ports MrTerm needs to find and reach other devices (UDP 47811, TCP 47812). Run these commands once in a terminal:': 'CachyOS aktiviert standardmäßig die Firewall UFW. Sie blockiert die Ports, über die MrTerm andere Geräte findet und erreicht (UDP 47811, TCP 47812). Führe diese Befehle einmal in einem Terminal aus:',
'No devices found? The firewall on this device may block them:': 'Keine Geräte gefunden? Die Firewall dieses Geräts blockiert sie eventuell:',
'Host password': 'Host-Passwort',
'Share with paired devices?': 'Mit gekoppelten Geräten teilen?',
'Should this secret be synchronized to your paired devices ({names})? You can change this later under Settings → Synchronization.': 'Soll dieses Geheimnis mit deinen gekoppelten Geräten ({names}) synchronisiert werden? Du kannst das später unter Einstellungen → Synchronisation ändern.',
'Don\'t share': 'Nicht teilen',
'Share': 'Teilen',
// Android-App
'Lock': 'Sperren',
'Add your first server or pair this phone with MrTerm on your computer to take over your hosts.': 'Lege deinen ersten Server an oder kopple dieses Handy mit MrTerm auf deinem Computer, um deine Hosts zu übernehmen.',
'No matching hosts. Press Enter to connect to “{q}”.': 'Keine passenden Hosts. Drücke Enter, um dich mit „{q}“ zu verbinden.',
'RDP is not available on Android': 'RDP ist unter Android nicht verfügbar',
'Please enter a name.': 'Bitte einen Namen eingeben.',
'Sessions': 'Sitzungen',
'New connection': 'Neue Verbindung',
'Paste': 'Einfügen',
'Copy selection': 'Auswahl kopieren',
'Nothing selected. Long-press the terminal to select text.': 'Nichts ausgewählt. Halte das Terminal gedrückt, um Text auszuwählen.',
'Larger font': 'Schrift größer',
'Smaller font': 'Schrift kleiner',
'Close session': 'Sitzung schließen',
'Generate a new SSH key or import an existing one.': 'Erzeuge einen neuen SSH-Schlüssel oder importiere einen vorhandenen.',
'Key created': 'Schlüssel erstellt',
'Add the public key to ~/.ssh/authorized_keys on your servers.': 'Trage den öffentlichen Schlüssel auf deinen Servern in ~/.ssh/authorized_keys ein.',
'Save frequently used commands and send them to a terminal with one tap.': 'Speichere häufig genutzte Befehle und sende sie mit einem Tippen an ein Terminal.',
'Run in terminal': 'Im Terminal ausführen',
'Command': 'Befehl',
'End the command with a line break to run it immediately.': 'Endet der Befehl mit einem Zeilenumbruch, wird er sofort ausgeführt.',
'Please enter a command.': 'Bitte einen Befehl eingeben.',
'General': 'Allgemein',
'System language': 'Systemsprache',
'Known hosts': 'Bekannte Hosts',
'{n} saved host keys': '{n} gespeicherte Hostschlüssel',
'Show': 'Anzeigen',
'Version {v}': 'Version {v}',
'Updates are installed with Obtainium.': 'Updates werden mit Obtainium installiert.',
'No known hosts yet.': 'Noch keine bekannten Hosts.',
'Remove host key?': 'Hostschlüssel entfernen?',
'Immediately': 'Sofort',
'After 1 minute': 'Nach 1 Minute',
'After 5 minutes': 'Nach 5 Minuten',
'Protect MrTerm with a password and optionally your fingerprint. The vault is then additionally encrypted.': 'Schütze MrTerm mit einem Passwort und optional deinem Fingerabdruck. Der Tresor wird dann zusätzlich verschlüsselt.',
'Remove app lock': 'App-Sperre entfernen',
'Remove app lock?': 'App-Sperre entfernen?',
'MrTerm will open without a password.': 'MrTerm öffnet sich dann ohne Passwort.',
'Unlock with fingerprint': 'Mit Fingerabdruck entsperren',
'Uses the fingerprint or face unlock of this phone.': 'Nutzt den Fingerabdruck- oder Gesichtsscanner dieses Handys.',
'Confirm fingerprint': 'Fingerabdruck bestätigen',
'Lock when leaving the app': 'Sperren beim Verlassen der App',
'Enter your password to unlock.': 'Gib dein Passwort ein, um zu entsperren.',
'Unlock MrTerm': 'MrTerm entsperren',
'Use password': 'Passwort verwenden',
'Your fingerprints have changed. Unlock with your password and set up fingerprint unlock again.': 'Deine Fingerabdrücke haben sich geändert. Entsperre mit deinem Passwort und richte das Entsperren per Fingerabdruck neu ein.',
'Take over hosts, groups, snippets and known hosts from MrTerm on your computer. The connection is end-to-end encrypted and stays in your local network.': 'Übernimm Hosts, Gruppen, Snippets und bekannte Hosts von MrTerm auf deinem Computer. Die Verbindung ist Ende-zu-Ende verschlüsselt und bleibt in deinem lokalen Netzwerk.',
'Both devices must be in the same Wi-Fi. If nothing is found, allow UDP port 47811 and TCP port 47812 in the firewall of your computer.': 'Beide Geräte müssen im selben WLAN sein. Wird nichts gefunden, gib in der Firewall deines Computers UDP-Port 47811 und TCP-Port 47812 frei.',
'Or enter an IP address': 'Oder IP-Adresse eingeben',
'Copy failed': 'Kopieren fehlgeschlagen',
'Fingerprint unlock is not set up.': 'Entsperren per Fingerabdruck ist nicht eingerichtet.',
'Fingerprint unlock failed. Use your password.': 'Entsperren per Fingerabdruck fehlgeschlagen. Verwende dein Passwort.',
'Set a password first.': 'Lege zuerst ein Passwort fest.',
// Main-Prozess
'Host key has changed!': 'Host-Schlüssel hat sich geändert!',
'Unknown host': 'Unbekannter Host',
+33 -7
View File
@@ -15,6 +15,7 @@ const { VpnManager } = require('./vpn');
const { DockerManager } = require('./docker');
const { FirewallManager } = require('./firewall');
const { NetworkConfigManager } = require('./network');
const { SyncService } = require('./sync');
const applyLanguage = () => i18n.setLanguage(store.get().settings.language, app.getLocale());
let win;
@@ -75,6 +76,17 @@ const docker = new DockerManager(ssh);
const firewall = new FirewallManager(ssh);
const network = new NetworkConfigManager(ssh);
// LAN-Synchronisation; Vergleichscode beim Koppeln bestätigt der Nutzer in der Oberfläche
const pairReplies = new Map();
const sync = new SyncService(store, send, (req) => new Promise((resolve) => {
const reqId = crypto.randomUUID();
pairReplies.set(reqId, resolve);
send('sync:pairPrompt', { reqId, ...req });
setTimeout(() => { if (pairReplies.delete(reqId)) resolve(false); }, 115000);
}));
ipcMain.on('sync:pairReply', (_e, reqId, ok) => { const r = pairReplies.get(reqId); pairReplies.delete(reqId); r?.(!!ok); });
store.onChange = () => sync.schedule();
function createWindow() {
win = new BrowserWindow({
width: 1360,
@@ -134,7 +146,7 @@ function lockStatus() {
}
function requireUnlocked() { if (store.locked) throw new Error(i18n.t('MrTerm is locked.')); }
const ensureLock = () => (store.lock = store.lock || { password: null, fido: [] });
function afterUnlock() { applyLanguage(); scheduleUpdateCheck(); }
function afterUnlock() { applyLanguage(); scheduleUpdateCheck(); sync.start().catch(() => {}); }
handle('lock:status', lockStatus);
handle('lock:lock', () => { if (store.lockEnabled) store.locked = true; return lockStatus(); });
@@ -190,7 +202,9 @@ handle('lock:removeFido', (id) => {
});
// ---------- Vault ----------
handle('vault:get', () => ({ ...store.get(), encrypted: store.encrypted, platform: process.platform }));
// Kopplungsschlüssel und Löschvermerke bleiben im Hauptprozess
const publicData = () => { const { sync: _s, tombstones: _t, ...rest } = store.get(); return rest; };
handle('vault:get', () => ({ ...publicData(), encrypted: store.encrypted, platform: process.platform }));
handle('vault:upsert', async (col, item) => {
// Geänderte VPN-Konfiguration: alte Systemverbindung entfernen, beim nächsten Verbinden neu importieren
if (col === 'vpns' && item.id) {
@@ -202,7 +216,7 @@ handle('vault:upsert', async (col, item) => {
handle('vault:remove', async (col, id) => {
if (col === 'vpns') {
await vpn.forget(store.get().vpns.find((v) => v.id === id));
store.get().hosts.forEach((h) => { if (h.vpnId === id) h.vpnId = null; });
store.get().hosts.forEach((h) => { if (h.vpnId === id) { h.vpnId = null; h.updatedAt = Date.now(); } });
}
return store.remove(col, id);
});
@@ -245,6 +259,17 @@ 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));
// ---------- Synchronisation ----------
handle('sync:status', () => sync.status());
handle('sync:enable', (on, name) => sync.setEnabled(on, name));
handle('sync:pairable', (on) => { sync.setPairable(on); return sync.status(); });
handle('sync:pair', (id) => sync.pair(id));
handle('sync:unpair', (id) => sync.unpair(id));
handle('sync:now', () => sync.syncAll());
handle('sync:share', (sel) => sync.setShare(sel));
handle('sync:shareItem', (c, id, yes) => sync.shareItem(c, id, yes));
handle('sync:probe', (address) => sync.probe(address));
// ---------- VPN ----------
handle('vpn:status', () => vpn.status());
handle('vpn:up', (id) => vpn.up(id));
@@ -254,18 +279,18 @@ handle('vault:settings', (s) => {
if ('language' in s) applyLanguage();
if ('rdpEmbed' in s) fs.writeFileSync(launchFile, JSON.stringify({ ...readLaunch(), x11: s.rdpEmbed !== false }));
});
handle('vault:forgetHost', (id) => { delete store.get().knownHosts[id]; store.save(); });
handle('vault:forgetHost', (id) => store.forgetKnownHost(id));
handle('vault:export', async () => {
const r = await dialog.showSaveDialog(win, { defaultPath: 'mrterm-backup.json', filters: [{ name: 'JSON', extensions: ['json'] }] });
if (r.canceled) return false;
fs.writeFileSync(r.filePath, JSON.stringify(store.get(), null, 2), { mode: 0o600 });
fs.writeFileSync(r.filePath, JSON.stringify(publicData(), null, 2), { mode: 0o600 });
return r.filePath;
});
handle('vault:import', async () => {
const r = await dialog.showOpenDialog(win, { filters: [{ name: 'JSON', extensions: ['json'] }], properties: ['openFile'] });
if (r.canceled) return false;
const data = JSON.parse(fs.readFileSync(r.filePaths[0], 'utf8'));
for (const col of ['groups', 'hosts', 'keys', 'snippets', 'forwards'])
for (const col of ['groups', 'hosts', 'keys', 'snippets', 'forwards', 'vpns'])
for (const item of data[col] || []) store.upsert(col, item);
return true;
});
@@ -525,6 +550,7 @@ app.whenReady().then(() => {
store.load();
applyLanguage();
createWindow();
sync.start().catch(() => {});
scheduleUpdateCheck();
});
@@ -535,7 +561,7 @@ function scheduleUpdateCheck() {
updateScheduled = true;
setTimeout(() => updater.check().then((r) => { if (r.available) send('update:available', r); }).catch(() => {}), 6000);
}
app.on('window-all-closed', async () => { ssh.closeAll(); await vpn.downOnQuit(); app.quit(); });
app.on('window-all-closed', async () => { ssh.closeAll(); sync.stop(); await vpn.downOnQuit(); app.quit(); });
// Smoke-Test: MRTERM_SMOKE=<pfad.png> startet, loggt Renderer-Meldungen, speichert einen Screenshot und beendet.
if (process.env.MRTERM_SMOKE) {
+13 -10
View File
@@ -149,8 +149,10 @@ class NetworkConfigManager {
}
watch(id, s) {
s.conn.on('close', () => { if (this.sessions.get(id) === s && !s.replacing) { this.close(id); s.onClose(); } });
s.conn.on('error', () => {});
const conn = s.conn;
// Nur die aktuelle Verbindung darf die Sitzung beenden (nach apply wird sie ersetzt)
conn.on('close', () => { if (this.sessions.get(id) === s && s.conn === conn) { this.close(id); s.onClose(); } });
conn.on('error', () => {});
}
async read(id) {
@@ -226,7 +228,7 @@ class NetworkConfigManager {
const be = BACKENDS[backendName || s.backend];
if (!be) throw new Error(i18n.t('Editing is not supported for this network configuration ({backend}).', { backend: s.backend }));
const script = `export PATH=$PATH:/usr/sbin:/sbin
mkdir -p ${STATE} || exit 1; rm -f ${STATE}/pending ${STATE}/rolled-back
mkdir -p ${STATE} || exit 1; rm -f ${STATE}/pending ${STATE}/applied ${STATE}/rolled-back
cd / && tar czf ${STATE}/backup.tgz $(for p in ${be.paths.join(' ')}; do [ -e "$p" ] && echo "$p"; done) || exit 1
# Schreiben in einer Subshell: bei einem Fehler sofort den alten Stand wiederherstellen
if ! ( set -e
@@ -234,7 +236,7 @@ ${writes.join('\n')}
) >${STATE}/write.log 2>&1; then ${be.restore}; cat ${STATE}/write.log >&2; exit 5; fi
if ! (${be.validate}) >${STATE}/validate.log 2>&1; then ${be.restore}; cat ${STATE}/validate.log >&2; exit 4; fi
touch ${STATE}/pending
nohup setsid sh -c 'export PATH=$PATH:/usr/sbin:/sbin; sleep 2; (${be.apply}) >${STATE}/apply.log 2>&1; sleep ${ROLLBACK_SECONDS}; if [ -f ${STATE}/pending ]; then ${be.restore}; (${be.apply}) >>${STATE}/apply.log 2>&1; rm -f ${STATE}/pending; date "+%Y-%m-%d %H:%M:%S" > ${STATE}/rolled-back; fi' >/dev/null 2>&1 &
nohup setsid sh -c 'export PATH=$PATH:/usr/sbin:/sbin; sleep 2; (${be.apply}) >${STATE}/apply.log 2>&1; touch ${STATE}/applied; sleep ${ROLLBACK_SECONDS}; if [ -f ${STATE}/pending ]; then ${be.restore}; (${be.apply}) >>${STATE}/apply.log 2>&1; rm -f ${STATE}/pending; date "+%Y-%m-%d %H:%M:%S" > ${STATE}/rolled-back; fi' >/dev/null 2>&1 &
echo started`;
const r = await this.root(s, script);
if (r.code === 4) throw new Error(i18n.t('The new configuration is invalid and was not applied: {err}', { err: lastLine(r.err) }));
@@ -245,13 +247,14 @@ echo started`;
while (Date.now() < deadline) {
try {
const { conn, jumps } = await this.ssh.connect(target, id);
const c = await this.root(s, `rm -f ${STATE}/pending`, conn);
if (c.code) { conn.end(); throw new Error(lastLine(c.err)); }
// Erst bestätigen, wenn das Anwenden fertig ist: sonst reißt z. B. ein Bond-Neustart die neue Verbindung wieder ab
const c = await this.root(s, `[ -f ${STATE}/applied ] || exit 7; rm -f ${STATE}/pending`, conn);
if (c.code) { conn.on('error', () => {}); conn.end(); jumps?.forEach((x) => { try { x.end(); } catch {} }); throw new Error(lastLine(c.err) || 'not applied yet'); }
// Neue Verbindung übernimmt die Sitzung
s.replacing = true;
try { s.conn.end(); } catch {}
s.jumps?.forEach((x) => { try { x.end(); } catch {} });
Object.assign(s, { conn, jumps, replacing: false });
const old = { conn: s.conn, jumps: s.jumps };
Object.assign(s, { conn, jumps });
// Alte Verbindung ist nach dem IP-Wechsel meist tot: Fehler (z. B. Keepalive-Timeout) still verwerfen
for (const c of [old.conn, ...(old.jumps || [])]) { c.on('error', () => {}); try { c.end(); } catch {} }
if (verifyAddress) s.host = target;
this.watch(id, s);
return { confirmed: true };
+1 -1
View File
@@ -35,7 +35,7 @@ class SshManager {
const cfg = {
host: host.address,
port: Number(host.port) || 22,
username: host.username || os.userInfo().username,
username: host.username || (() => { try { return os.userInfo().username; } catch { return 'root'; } })(),
readyTimeout: 20000,
keepaliveInterval: (this.store.get().settings.keepAlive || 0) * 1000,
tryKeyboard: true,
+19 -1
View File
@@ -15,6 +15,10 @@ const DEFAULTS = {
vpns: [],
knownHosts: {},
history: [],
// Löschvermerke für die Synchronisation: { c: Collection, id, at }
tombstones: [],
// LAN-Synchronisation (gerätebezogen, wird selbst nicht synchronisiert)
sync: { enabled: false, deviceId: '', deviceName: '', peers: [], share: { keys: [], hosts: [], vpns: [] }, asked: false },
settings: {
terminalTheme: 'mrterm',
fontFamily: 'Cascadia Code, JetBrains Mono, Fira Code, Consolas, monospace',
@@ -124,6 +128,7 @@ class Store {
save() {
if (this.sealed) return; // Inhalt noch nicht entschlüsselt – nichts überschreiben
if (!this.muted) this.onChange?.();
let json = JSON.stringify(this.data, null, 2);
if (this.lockEnabled && this.dek) {
const { language, appTheme, accent } = this.data.settings;
@@ -156,7 +161,20 @@ class Store {
remove(collection, id) {
this.data[collection] = this.data[collection].filter((x) => x.id !== id);
if (collection === 'groups') this.data.hosts.forEach((h) => { if (h.groupId === id) h.groupId = null; });
if (collection === 'groups') this.data.hosts.forEach((h) => { if (h.groupId === id) { h.groupId = null; h.updatedAt = Date.now(); } });
this.tombstone(collection, id);
this.save();
}
// Löschung für andere Geräte vermerken (180 Tage aufbewahren)
tombstone(c, id) {
const now = Date.now();
this.data.tombstones = [...(this.data.tombstones || []).filter((t) => !(t.c === c && t.id === id) && now - t.at < 180 * 864e5), { c, id, at: now }];
}
forgetKnownHost(id) {
delete this.data.knownHosts[id];
this.tombstone('knownHosts', id);
this.save();
}
+504
View File
@@ -0,0 +1,504 @@
// LAN-Synchronisation zwischen MrTerm-Clients (Peer-to-Peer, Ende-zu-Ende verschlüsselt).
//
// Finden: UDP-Broadcast auf Port 47811 ("Beacon" mit Geräte-ID, Name, TCP-Port, koppelbar ja/nein).
// Koppeln: X25519-Schlüsselaustausch mit Commitment (der Initiator legt sich per Hash auf seinen Schlüssel fest,
// bevor er den des anderen kennt). Beide Geräte zeigen denselben 6-stelligen Vergleichscode (SAS);
// der Nutzer bestätigt auf beiden Geräten. Ergebnis: dauerhafter Kopplungsschlüssel (32 Byte).
// Sitzung: Gegenseitige Authentisierung per HMAC mit dem Kopplungsschlüssel, frische X25519-Schlüssel je Sitzung
// (Forward Secrecy), danach alle Nachrichten AES-256-GCM-verschlüsselt.
// Abgleich: Beide Seiten senden einen Schnappschuss; pro Eintrag gewinnt die neueste Änderung (updatedAt),
// Löschvermerke (tombstones) entfernen Einträge. Geheimnisse (SSH-Schlüssel, Passwörter, VPN-Konfigurationen)
// werden nur übertragen, wenn der Nutzer sie freigegeben hat.
const dgram = require('dgram');
const net = require('net');
const os = require('os');
const crypto = require('crypto');
const i18n = require('../i18n');
const fs = require('fs');
const { execFileSync } = require('child_process');
// Lokale Firewall erkennen, die Broadcasts/eingehende Verbindungen blockieren könnte (Linux).
// Ob die Ports bereits freigegeben sind, lässt sich ohne root nicht prüfen (UFW-Regeln sind nur für root lesbar).
function localFirewall() {
if (process.platform !== 'linux') return null;
const read = (f) => { try { return fs.readFileSync(f, 'utf8'); } catch { return ''; } };
const active = (unit) => { try { return execFileSync('systemctl', ['is-active', unit], { timeout: 3000 }).toString().trim() === 'active'; } catch { return false; } };
const os = (read('/etc/os-release').match(/^ID=(.*)$/m) || [])[1]?.replace(/"/g, '') || '';
const ufw = /^ENABLED=yes/m.test(read('/etc/ufw/ufw.conf')) || active('ufw');
const firewalld = active('firewalld');
if (!ufw && !firewalld && os !== 'cachyos') return null;
return { os, ufw, firewalld };
}
const UDP_PORT = 47811;
const TCP_PORT = 47812;
const PROTO = 1;
const COLLECTIONS = ['groups', 'hosts', 'keys', 'snippets', 'forwards', 'vpns'];
const SECRETS = { keys: ['privateKey', 'passphrase'], hosts: ['password'], vpns: ['config', 'password'] };
const SPKI_X25519 = Buffer.from('302a300506032b656e032100', 'hex');
const MAX_FRAME = 32 * 1024 * 1024;
const sha = (...parts) => crypto.createHash('sha256').update(Buffer.concat(parts.map((p) => Buffer.from(p)))).digest();
const hmac = (key, ...parts) => crypto.createHmac('sha256', key).update(Buffer.concat(parts.map((p) => Buffer.from(p)))).digest();
const hkdf = (ikm, salt, info) => Buffer.from(crypto.hkdfSync('sha256', ikm, salt, info, 32));
const ts = (x) => x?.updatedAt || x?.createdAt || 0;
function x25519() {
const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519');
return { privateKey, pub: publicKey.export({ type: 'spki', format: 'der' }).subarray(-32) };
}
function dh(privateKey, peerPub) {
const pk = crypto.createPublicKey({ key: Buffer.concat([SPKI_X25519, Buffer.from(peerPub)]), format: 'der', type: 'spki' });
return crypto.diffieHellman({ privateKey, publicKey: pk });
}
// ---------------------------------------------------------------- Framing (4 Byte Länge + Nutzlast)
class Channel {
constructor(sock) {
this.sock = sock;
this.buf = Buffer.alloc(0);
this.queue = [];
this.waiters = [];
this.keys = null; // { send, recv } nach dem Handshake
sock.on('data', (d) => this.onData(d));
const fail = (e) => { this.closed = e || new Error('closed'); this.waiters.splice(0).forEach((w) => w.reject(this.closed)); };
sock.on('close', () => fail());
sock.on('error', (e) => fail(e));
sock.setTimeout(180000, () => sock.destroy(new Error('timeout')));
}
onData(d) {
this.buf = Buffer.concat([this.buf, d]);
while (this.buf.length >= 4) {
const len = this.buf.readUInt32BE(0);
if (len > MAX_FRAME) { this.sock.destroy(new Error('frame too large')); return; }
if (this.buf.length < 4 + len) break;
const frame = this.buf.subarray(4, 4 + len);
this.buf = this.buf.subarray(4 + len);
let msg;
try { msg = this.decode(frame); } catch (e) { this.sock.destroy(e); return; }
const w = this.waiters.shift();
if (w) w.resolve(msg); else this.queue.push(msg);
}
}
encode(obj) {
const plain = Buffer.from(JSON.stringify(obj));
if (!this.keys) return plain;
const iv = crypto.randomBytes(12);
const c = crypto.createCipheriv('aes-256-gcm', this.keys.send, iv);
return Buffer.concat([iv, c.update(plain), c.final(), c.getAuthTag()]);
}
decode(frame) {
if (!this.keys) return JSON.parse(frame.toString('utf8'));
const d = crypto.createDecipheriv('aes-256-gcm', this.keys.recv, frame.subarray(0, 12));
d.setAuthTag(frame.subarray(frame.length - 16));
return JSON.parse(Buffer.concat([d.update(frame.subarray(12, frame.length - 16)), d.final()]).toString('utf8'));
}
send(obj) {
const p = this.encode(obj);
const h = Buffer.alloc(4); h.writeUInt32BE(p.length);
this.sock.write(Buffer.concat([h, p]));
}
recv(type, timeout = 30000) {
const msg = this.queue.length ? Promise.resolve(this.queue.shift()) : this.closed ? Promise.reject(this.closed) : new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
let t;
const to = new Promise((_, rej) => { t = setTimeout(() => rej(new Error('timeout')), timeout); });
return Promise.race([msg, to]).finally(() => clearTimeout(t)).then((m) => {
if (m?.t === 'error') throw new Error(m.msg || 'remote error');
if (type && m?.t !== type) throw new Error(`unexpected message ${m?.t}`);
return m;
});
}
close() { try { this.sock.end(); } catch {} }
}
// ---------------------------------------------------------------- Zusammenführen
// Schnappschuss für ein Gerät; nicht freigegebene Geheimnisse werden entfernt
function snapshot(data) {
const share = data.sync?.share || {};
const out = { tombstones: data.tombstones || [], knownHosts: data.knownHosts || {} };
for (const c of COLLECTIONS) {
out[c] = (data[c] || []).map((x) => {
const fields = SECRETS[c];
if (!fields || (share[c] || []).includes(x.id)) return x;
const y = { ...x, _noSecret: true };
fields.forEach((f) => delete y[f]);
return y;
});
}
return out;
}
// Eingehenden Schnappschuss übernehmen; liefert true, wenn sich etwas geändert hat
function merge(data, incoming) {
let changed = false;
const tombs = new Map((data.tombstones || []).map((t) => [`${t.c}|${t.id}`, t]));
for (const t of incoming.tombstones || []) {
const k = `${t.c}|${t.id}`;
if (!tombs.has(k) || tombs.get(k).at < t.at) { tombs.set(k, t); changed = true; }
}
data.tombstones = [...tombs.values()];
for (const c of COLLECTIONS) {
const list = data[c] || (data[c] = []);
for (const inc of incoming[c] || []) {
if (!inc?.id) continue;
const tomb = tombs.get(`${c}|${inc.id}`);
if (tomb && tomb.at >= ts(inc)) continue;
const i = list.findIndex((x) => x.id === inc.id);
const local = list[i];
if (local && ts(local) >= ts(inc)) continue;
const { _noSecret, ...item } = inc;
// Nicht freigegebene Geheimnisse: lokale Werte behalten
if (_noSecret && local) (SECRETS[c] || []).forEach((f) => { if (local[f] !== undefined) item[f] = local[f]; });
if (i >= 0) list[i] = item; else list.push(item);
changed = true;
}
// Löschvermerke anwenden
const before = list.length;
data[c] = list.filter((x) => { const t = tombs.get(`${c}|${x.id}`); return !t || t.at < ts(x); });
if (data[c].length !== before) changed = true;
}
for (const [id, kh] of Object.entries(incoming.knownHosts || {})) {
const t = tombs.get(`knownHosts|${id}`);
if (t && t.at >= (kh.addedAt || 0)) continue;
const local = data.knownHosts[id];
if (!local || (kh.addedAt || 0) > (local.addedAt || 0)) { data.knownHosts[id] = kh; changed = true; }
}
for (const t of tombs.values()) {
if (t.c === 'knownHosts' && data.knownHosts[t.id] && (data.knownHosts[t.id].addedAt || 0) <= t.at) { delete data.knownHosts[t.id]; changed = true; }
}
return changed;
}
// ---------------------------------------------------------------- Dienst
class SyncService {
/**
* @param {import('./store').Store} store
* @param {(event: string, payload?: any) => void} emit Ereignisse an die Oberfläche
* @param {(req: { code, name, id }) => Promise<boolean>} confirmPair Vergleichscode anzeigen und Bestätigung abwarten
*/
constructor(store, emit, confirmPair) {
this.store = store;
this.emit = emit;
this.confirmPair = confirmPair;
this.seen = new Map(); // id -> { id, name, address, port, pairable, at }
this.pairable = false;
this.running = false;
this.lastError = '';
this.syncing = new Set();
this.firewall = localFirewall();
}
get cfg() {
const d = this.store.get();
d.sync ||= { enabled: false, peers: [], share: { keys: [], hosts: [], vpns: [] } };
const s = d.sync;
if (!s.deviceId) s.deviceId = crypto.randomUUID();
if (!s.deviceName) s.deviceName = process.env.MRTERM_DEVICE || os.hostname();
s.peers ||= []; s.share ||= { keys: [], hosts: [], vpns: [] };
return s;
}
// ------------------------------------------------ Start/Stop
async start() {
if (this.running || this.store.sealed || !this.cfg.enabled) return;
this.running = true;
this.server = net.createServer((sock) => this.accept(sock).catch(() => sock.destroy()));
this.server.on('error', () => {});
await new Promise((res) => {
this.server.once('error', () => this.server.listen(0, res));
this.server.listen(TCP_PORT, res);
});
this.port = this.server.address().port;
this.udp = dgram.createSocket({ type: 'udp4', reuseAddr: true });
this.udp.on('error', () => {});
this.udp.on('message', (msg, rinfo) => this.onBeacon(msg, rinfo));
await new Promise((res) => this.udp.bind(UDP_PORT, () => { try { this.udp.setBroadcast(true); } catch {} res(); }));
this.beaconTimer = setInterval(() => this.beacon(), 5000);
this.syncTimer = setInterval(() => this.syncAll(), 120000);
this.beacon();
this.emitState();
}
stop() {
if (!this.running) return;
this.running = false;
clearInterval(this.beaconTimer); clearInterval(this.syncTimer); clearTimeout(this.debounce);
try { this.server.close(); } catch {}
try { this.udp.close(); } catch {}
this.seen.clear();
this.emitState();
}
setEnabled(on, name) {
const c = this.cfg;
c.enabled = !!on;
if (name) c.deviceName = String(name).slice(0, 60);
this.store.save();
if (on) this.start(); else this.stop();
return this.status();
}
// ------------------------------------------------ Finden
broadcastAddrs() {
const out = new Set(['255.255.255.255']);
let ifaces = {};
try { ifaces = os.networkInterfaces(); } catch {} // Android: je nach Version eingeschränkt
for (const list of Object.values(ifaces)) {
for (const a of list || []) {
if (a.family !== 'IPv4' || a.internal) continue;
const ip = a.address.split('.').map(Number), mask = a.netmask.split('.').map(Number);
out.add(ip.map((o, i) => (o & mask[i]) | (~mask[i] & 255)).join('.'));
}
}
return [...out];
}
beacon() {
if (!this.running) return;
const c = this.cfg;
const msg = Buffer.from(JSON.stringify({ mrterm: PROTO, id: c.deviceId, name: c.deviceName, port: this.port, pairable: this.pairable }));
for (const addr of this.broadcastAddrs()) this.udp.send(msg, UDP_PORT, addr, () => {});
// Einträge älter als 20 s gelten als offline
for (const [id, p] of this.seen) if (Date.now() - p.at > 20000) { this.seen.delete(id); this.emitState(); }
}
onBeacon(buf, rinfo) {
let b;
try { b = JSON.parse(buf.toString('utf8')); } catch { return; }
if (b?.mrterm !== PROTO || !b.id || b.id === this.cfg.deviceId || !Number.isInteger(b.port)) return;
const known = this.seen.get(b.id);
this.seen.set(b.id, { id: b.id, name: String(b.name || '').slice(0, 60), address: rinfo.address, port: b.port, pairable: !!b.pairable, at: Date.now() });
const peer = this.cfg.peers.find((p) => p.id === b.id);
if (peer && peer.address !== rinfo.address) { peer.address = rinfo.address; peer.port = b.port; }
if (!known) { this.emitState(); if (peer) this.syncWith(peer).catch(() => {}); }
else if (known.pairable !== !!b.pairable) this.emitState();
}
setPairable(on) {
this.pairable = !!on;
clearTimeout(this.pairTimer);
if (on) this.pairTimer = setTimeout(() => this.setPairable(false), 180000);
this.beacon();
this.emitState();
}
// ------------------------------------------------ Status für die Oberfläche
status() {
const c = this.cfg;
return {
enabled: c.enabled, running: this.running, deviceId: c.deviceId, deviceName: c.deviceName, pairable: this.pairable, port: this.port,
peers: c.peers.map((p) => ({ id: p.id, name: p.name, lastSync: p.lastSync || 0, online: this.seen.has(p.id), address: p.address, error: p.error || '' })),
nearby: [...this.seen.values()].filter((p) => !c.peers.some((x) => x.id === p.id)).map(({ id, name, address, pairable }) => ({ id, name, address, pairable })),
share: c.share, asked: !!c.asked, sealed: !!this.store.sealed, firewall: this.firewall,
};
}
emitState() { this.emit('sync:state', this.status()); }
// ------------------------------------------------ Verbindungen
connect(address, port) {
return new Promise((resolve, reject) => {
const sock = net.connect({ host: address, port, timeout: 8000 });
sock.once('connect', () => { sock.setTimeout(0); resolve(new Channel(sock)); });
sock.once('timeout', () => { sock.destroy(); reject(new Error('timeout')); });
sock.once('error', reject);
});
}
// Eingehende Verbindung: Kopplung oder Synchronisation
async accept(sock) {
const ch = new Channel(sock);
try {
const first = await ch.recv(null, 10000);
if (first.t === 'pair') await this.pairResponder(ch, first);
else if (first.t === 'hello') await this.sessionResponder(ch, first);
} catch (e) {
try { ch.send({ t: 'error', msg: e.message }); } catch {}
} finally { ch.close(); }
}
// ------------------------------------------------ Kopplung
// Initiator (Gerät, auf dem der Nutzer ein anderes Gerät ausgewählt hat)
async pair(id) {
const target = this.seen.get(id);
if (!target) throw new Error('Device not found');
const ch = await this.connect(target.address, target.port);
try {
const me = x25519();
const nonce = crypto.randomBytes(16);
const c = this.cfg;
ch.send({ t: 'pair', v: PROTO, id: c.deviceId, name: c.deviceName, commit: sha(me.pub, nonce).toString('base64') });
const r = await ch.recv('pair-pub');
ch.send({ t: 'pair-reveal', pub: me.pub.toString('base64'), nonce: nonce.toString('base64') });
const peerPub = Buffer.from(r.pub, 'base64');
const { code, key } = this.derivePair(dh(me.privateKey, peerPub), peerPub, me.pub, r.id, c.deviceId);
return await this.finishPair(ch, { id: r.id, name: r.name, address: target.address, port: target.port }, code, key, 'initiator');
} finally { ch.close(); }
}
// Gegenseite: nur solange "koppelbar" aktiv ist
async pairResponder(ch, msg) {
if (!this.pairable) throw new Error(i18n.t('Device is not ready for pairing'));
const me = x25519();
const c = this.cfg;
ch.send({ t: 'pair-pub', id: c.deviceId, name: c.deviceName, pub: me.pub.toString('base64') });
const rev = await ch.recv('pair-reveal');
const peerPub = Buffer.from(rev.pub, 'base64');
if (!sha(peerPub, Buffer.from(rev.nonce, 'base64')).equals(Buffer.from(msg.commit, 'base64'))) throw new Error('Commitment mismatch');
const { code, key } = this.derivePair(dh(me.privateKey, peerPub), me.pub, peerPub, c.deviceId, msg.id);
const addr = ch.sock.remoteAddress?.replace(/^::ffff:/, '');
await this.finishPair(ch, { id: msg.id, name: String(msg.name || '').slice(0, 60), address: addr, port: this.seen.get(msg.id)?.port || TCP_PORT }, code, key, 'responder');
}
// Vergleichscode und Kopplungsschlüssel aus dem Schlüsselaustausch (Reihenfolge: Responder, Initiator)
derivePair(shared, pubR, pubI, idR, idI) {
const transcript = Buffer.concat([pubR, pubI, Buffer.from(`${idR}|${idI}`)]);
const code = String(sha('mrterm-sas', transcript).readUInt32BE(0) % 1000000).padStart(6, '0');
const key = hkdf(shared, transcript, 'mrterm-pair-key');
return { code, key };
}
async finishPair(ch, peer, code, key, role) {
const ok = await this.confirmPair({ code, name: peer.name, id: peer.id, role });
ch.send({ t: 'pair-confirm', ok, mac: ok ? hmac(key, 'confirm', role).toString('base64') : '' });
const r = await ch.recv('pair-confirm', 120000);
const other = role === 'initiator' ? 'responder' : 'initiator';
if (!ok) throw new Error(i18n.t('Pairing was rejected on this device.'));
if (!r.ok) throw new Error(i18n.t('Pairing was rejected on the other device.'));
if (!crypto.timingSafeEqual(Buffer.from(r.mac, 'base64'), hmac(key, 'confirm', other))) throw new Error(i18n.t('Pairing verification failed.'));
const c = this.cfg;
c.peers = [...c.peers.filter((p) => p.id !== peer.id), { ...peer, key: key.toString('base64'), pairedAt: Date.now() }];
this.store.save();
this.setPairable(false);
this.emit('sync:paired', { id: peer.id, name: peer.name });
this.emitState();
if (role === 'initiator') setTimeout(() => this.syncWith(c.peers.find((p) => p.id === peer.id)).catch(() => {}), 1500);
return true;
}
unpair(id) {
const c = this.cfg;
c.peers = c.peers.filter((p) => p.id !== id);
this.store.save();
this.emitState();
return this.status();
}
// ------------------------------------------------ Sitzung (authentisiert + verschlüsselt)
sessionKeys(pairKey, shared, transcript, initiator) {
const k1 = hkdf(Buffer.concat([pairKey, shared]), transcript, 'mrterm-i2r');
const k2 = hkdf(Buffer.concat([pairKey, shared]), transcript, 'mrterm-r2i');
return initiator ? { send: k1, recv: k2 } : { send: k2, recv: k1 };
}
async syncWith(peer) {
if (!peer || !this.running || this.store.sealed || this.syncing.has(peer.id)) return;
const live = this.seen.get(peer.id);
const address = live?.address || peer.address;
const port = live?.port || peer.port || TCP_PORT;
if (!address) return;
this.syncing.add(peer.id);
let ch;
try {
ch = await this.connect(address, port);
const key = Buffer.from(peer.key, 'base64');
const me = x25519();
const nI = crypto.randomBytes(16);
const c = this.cfg;
ch.send({ t: 'hello', v: PROTO, id: c.deviceId, eph: me.pub.toString('base64'), nonce: nI.toString('base64') });
const r = await ch.recv('hello');
if (r.id !== peer.id) throw new Error('Unexpected device');
const transcript = Buffer.concat([Buffer.from(c.deviceId), Buffer.from(peer.id), me.pub, Buffer.from(r.eph, 'base64'), nI, Buffer.from(r.nonce, 'base64')]);
if (!crypto.timingSafeEqual(Buffer.from(r.mac, 'base64'), hmac(key, 'responder', transcript))) throw new Error('Authentication failed');
ch.send({ t: 'auth', mac: hmac(key, 'initiator', transcript).toString('base64') });
ch.keys = this.sessionKeys(key, dh(me.privateKey, Buffer.from(r.eph, 'base64')), transcript, true);
ch.send({ t: 'state', data: snapshot(this.store.get()) });
const theirs = await ch.recv('state');
this.applyRemote(theirs.data);
Object.assign(peer, { lastSync: Date.now(), error: '', address, port });
this.store.muted = true; this.store.save(); this.store.muted = false;
} catch (e) {
peer.error = e.message;
throw e;
} finally {
this.syncing.delete(peer.id);
ch?.close();
this.emitState();
}
}
async sessionResponder(ch, msg) {
const c = this.cfg;
const peer = c.peers.find((p) => p.id === msg.id);
if (!peer || this.store.sealed) throw new Error('Unknown device');
const key = Buffer.from(peer.key, 'base64');
const me = x25519();
const nR = crypto.randomBytes(16);
const transcript = Buffer.concat([Buffer.from(msg.id), Buffer.from(c.deviceId), Buffer.from(msg.eph, 'base64'), me.pub, Buffer.from(msg.nonce, 'base64'), nR]);
ch.send({ t: 'hello', id: c.deviceId, eph: me.pub.toString('base64'), nonce: nR.toString('base64'), mac: hmac(key, 'responder', transcript).toString('base64') });
const a = await ch.recv('auth');
if (!crypto.timingSafeEqual(Buffer.from(a.mac, 'base64'), hmac(key, 'initiator', transcript))) throw new Error('Authentication failed');
ch.keys = this.sessionKeys(key, dh(me.privateKey, Buffer.from(msg.eph, 'base64')), transcript, false);
const theirs = await ch.recv('state');
ch.send({ t: 'state', data: snapshot(this.store.get()) });
this.applyRemote(theirs.data);
Object.assign(peer, { lastSync: Date.now(), error: '', address: ch.sock.remoteAddress?.replace(/^::ffff:/, '') || peer.address });
this.store.muted = true; this.store.save(); this.store.muted = false;
this.emitState();
}
applyRemote(data) {
if (merge(this.store.get(), data || {})) {
this.store.muted = true; this.store.save(); this.store.muted = false;
this.emit('sync:changed');
// Änderungen an weitere gekoppelte Geräte weitergeben
this.schedule(3000);
}
}
// Nach lokalen Änderungen (entprellt) mit allen erreichbaren Geräten abgleichen
schedule(delay = 2000) {
if (!this.running) return;
clearTimeout(this.debounce);
this.debounce = setTimeout(() => this.syncAll(), delay);
}
async syncAll() {
const results = await Promise.allSettled(this.cfg.peers.filter((p) => this.seen.has(p.id) || p.address).map((p) => this.syncWith(p)));
return results.filter((r) => r.status === 'fulfilled').length;
}
setShare(share) {
const clean = (a) => (Array.isArray(a) ? a.filter((x) => typeof x === 'string') : []);
const c = this.cfg;
c.share = { keys: clean(share?.keys), hosts: clean(share?.hosts), vpns: clean(share?.vpns), declined: { keys: [], hosts: [], vpns: [] } };
c.asked = true;
this.store.save();
return this.status();
}
// Einzelnes neues Geheimnis teilen oder ablehnen (Ablehnung wird gemerkt, damit nicht erneut gefragt wird)
shareItem(c, id, yes) {
if (!SECRETS[c] || typeof id !== 'string') throw new Error('Invalid');
const sh = this.cfg.share;
sh.declined ||= { keys: [], hosts: [], vpns: [] };
sh[c] = (sh[c] || []).filter((x) => x !== id);
sh.declined[c] = (sh.declined[c] || []).filter((x) => x !== id);
(yes ? sh[c] : sh.declined[c]).push(id);
this.store.save();
if (yes) this.schedule(500);
return this.status();
}
// Gerät per IP hinzufügen (wenn Broadcasts im Netz blockiert sind)
async probe(address, port = TCP_PORT) {
if (!/^[\w.:-]+$/.test(address)) throw new Error('Invalid address');
// Kurzer Test, ob dort ein MrTerm lauscht; das Gerät erscheint danach unter "In der Nähe"
const ch = await this.connect(address, Number(port) || TCP_PORT);
ch.close();
this.seen.set(`manual:${address}`, { id: `manual:${address}`, name: address, address, port: Number(port) || TCP_PORT, pairable: true, at: Date.now() + 600000 });
this.emitState();
return true;
}
}
module.exports = { SyncService, snapshot, merge, Channel };
+1
View File
@@ -34,4 +34,5 @@ contextBridge.exposeInMainWorld('api', {
close: (id) => ipcRenderer.send('rdp:close', id),
},
replySecret: (reqId, v) => ipcRenderer.send('secret:reply', reqId, v),
pairReply: (reqId, ok) => ipcRenderer.send('sync:pairReply', reqId, ok),
});
+162 -9
View File
@@ -83,7 +83,7 @@ async function call(ch, ...a) {
}
// ---------- Modals
function modal({ title, text = '', body = '', buttons = [] }) {
function modal({ title, text = '', body = '', buttons = [], noEnter = false }) {
return new Promise((resolve) => {
const bg = h(`<div class="modal-bg"><div class="modal"><div class="mbody"><h3>${esc(title)}</h3>${text ? `<p>${esc(text)}</p>` : ''}${body}</div><div class="mfoot"></div></div></div>`);
const foot = $('.mfoot', bg);
@@ -96,7 +96,7 @@ function modal({ title, text = '', body = '', buttons = [] }) {
bg.addEventListener('mousedown', (e) => { if (e.target === bg) done(null); });
bg.addEventListener('keydown', (e) => {
if (e.key === 'Escape') done(null);
if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') { e.preventDefault(); foot.lastElementChild.click(); }
if (e.key === 'Enter' && !noEnter && e.target.tagName !== 'TEXTAREA') { e.preventDefault(); foot.lastElementChild.click(); }
});
$('#modalRoot').append(bg);
($('input,select,textarea', bg) || foot.lastElementChild).focus();
@@ -556,7 +556,8 @@ function editHost(hst = {}) {
tags: v.tags.split(',').map((t) => t.trim()).filter(Boolean),
groupId: v.groupId || null, keyId: v.keyId || null, jumpHostId: v.jumpHostId || null, vpnId: v.vpnId || null,
};
await call('vault:upsert', 'hosts', item);
const savedHost = await call('vault:upsert', 'hosts', item);
if (item.password) askShareSecret('hosts', savedHost, item.label || item.address);
reload();
}, isNew ? null : (() => { const b = h(`<button class="btn danger">${ICONS.trash}</button>`); b.title = T('Delete'); b.onclick = async () => { if (await confirmBox(T('Delete host?'), T('“{name}” will be permanently removed.', { name: hst.label || hst.address }))) { await call('vault:remove', 'hosts', hst.id); closeDrawer(); reload(); } }; return b; })());
setProto(proto);
@@ -617,7 +618,8 @@ async function generateKey() {
});
if (!r) return;
const k = await call('key:generate', { type: r.type, passphrase: r.passphrase, comment: r.label });
await call('vault:upsert', 'keys', { label: r.label, privateKey: k.privateKey, publicKey: k.publicKey, passphrase: r.passphrase || undefined });
const newKey = await call('vault:upsert', 'keys', { label: r.label, privateKey: k.privateKey, publicKey: k.publicKey, passphrase: r.passphrase || undefined });
askShareSecret('keys', newKey, r.label);
await call('clipboard:write', k.publicKey);
toast(T('Key generated – public key copied to clipboard'), 'ok');
reload();
@@ -633,7 +635,8 @@ function editKey(k = {}, pick = false) {
const v = formValues(form);
if (!v.privateKey.trim()) throw new Error(T('Private key is missing.'));
const parsed = await call('key:parse', { privateKey: v.privateKey, passphrase: v.passphrase });
await call('vault:upsert', 'keys', { ...k, ...v, label: v.label || parsed.type, publicKey: v.publicKey.trim() || parsed.publicKey });
const savedKey = await call('vault:upsert', 'keys', { ...k, ...v, label: v.label || parsed.type, publicKey: v.publicKey.trim() || parsed.publicKey });
askShareSecret('keys', savedKey, savedKey.label);
reload();
}, (() => { const b = h(`<button class="btn">${ICONS.folder}${T('File…')}</button>`); b.onclick = loadFile; return b; })());
async function loadFile() {
@@ -811,6 +814,7 @@ function editVpn(v = {}, pick = false) {
const item = { ...v, type, label: f.label.trim() || VPN_TYPES[type], config: f.config, disconnectOnQuit: f.disconnectOnQuit,
username: type === 'openvpn' ? f.username : '', password: type === 'openvpn' ? f.password : '' };
const saved = await call('vault:upsert', 'vpns', item);
askShareSecret('vpns', saved, saved.label);
for (const cb of $$('[data-host]', hostBox)) {
const hst = S.vault.hosts.find((x) => x.id === cb.dataset.host);
const want = cb.checked ? saved.id : (hst.vpnId === saved.id ? null : hst.vpnId || null);
@@ -945,6 +949,10 @@ async function viewSettings(page) {
const secCard = h(`<div class="settings-card"><h3>${T('App lock')}</h3><p style="color:var(--muted);margin-top:0">${T('Lock MrTerm with a password and/or a FIDO2 security key (e.g. YubiKey). The vault is then additionally encrypted and can only be opened with one of these methods.')}</p><div class="lock-rows"></div></div>`);
renderLockSettings($('.lock-rows', secCard));
// ---- LAN-Synchronisation
const syncCard = h('<div class="settings-card sync-card"></div>');
renderSyncCard(syncCard);
// ---- Updates
const updCard = h(`<div class="settings-card"><h3>Updates</h3><p class="upd-info" style="color:var(--muted);margin-top:0">${T('Installed version: {v}', { v: '…' })}</p></div>`);
api.call('app:version').then((v) => { $('.upd-info', updCard).textContent = T('Installed version: {v}', { v }); });
@@ -977,7 +985,7 @@ 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, designCard, themeCard, termCard, rdpCard, importCard, dataCard, updCard, keysCard);
c.append(langCard, secCard, syncCard, designCard, themeCard, termCard, rdpCard, importCard, dataCard, updCard, keysCard);
}
// ============================================================ App-Sperre
@@ -1092,6 +1100,146 @@ function renderLockSettings(box) {
}
}
// ============================================================ LAN-Synchronisation
S.syncStatus = null;
async function renderSyncCard(card) {
if (!S.syncStatus) { try { S.syncStatus = await api.call('sync:status'); } catch { return; } }
const st = S.syncStatus;
card.innerHTML = `<h3>${T('Synchronization')}</h3><p style="color:var(--muted);margin-top:0">${T('Synchronize hosts, groups, snippets, port forwards, VPNs and known hosts directly between MrTerm devices in your local network. The connection is end-to-end encrypted; no server or cloud is involved.')}</p>`;
const en = check(T('Enable LAN synchronization'), 'syncOn', st.enabled);
$('input', en).onchange = async (e) => {
S.syncStatus = await call('sync:enable', e.target.checked);
renderSyncCard(card);
if (e.target.checked && S.syncStatus.firewall) showFirewallHint();
};
card.append(en);
if (!st.enabled) return;
if (st.firewall && !syncFwDismissed()) card.append(firewallHintBox(() => renderSyncCard(card)));
const name = field(T('Device name'), 'devName', st.deviceName);
$('input', name).onchange = async (e) => { S.syncStatus = await call('sync:enable', true, e.target.value.trim()); };
card.append(name);
const list = h('<div class="sync-peers"></div>');
if (!st.peers.length) list.append(h(`<div class="hint" style="color:var(--faint);padding:6px 0">${T('No paired devices yet.')}</div>`));
for (const p of st.peers) {
const row = h(`<div class="lock-row"><span class="dot ${p.online ? 'on' : ''}"></span><div class="grow"><b>${esc(p.name)}</b><div class="sub">${p.online ? T('online') : T('offline')}${p.lastSync ? ` · ${T('last sync {time}', { time: relTime(p.lastSync) })}` : ''}${p.error ? ` · <span style="color:var(--red)">${esc(p.error)}</span>` : ''}</div></div></div>`);
const rm = h(`<button class="btn ghost" title="${esc(T('Unpair'))}">${ICONS.trash}</button>`);
rm.onclick = async () => { if (await confirmBox(T('Unpair device?'), T('“{name}” will no longer synchronize with this device.', { name: p.name }), T('Unpair'))) { S.syncStatus = await call('sync:unpair', p.id); renderSyncCard(card); } };
row.append(rm);
list.append(row);
}
card.append(list);
const shared = (c, arr, pred = () => true) => `${(st.share[c] || []).filter((id) => arr.some((x) => x.id === id)).length}/${arr.filter(pred).length}`;
card.append(h(`<div class="hint" style="color:var(--muted);font-size:12px;margin-top:10px">${T('Shared secrets: {keys} SSH keys, {pw} host passwords, {vpn} VPN configurations', { keys: shared('keys', S.vault.keys), pw: shared('hosts', S.vault.hosts, (x) => x.password), vpn: shared('vpns', S.vault.vpns) })}</div>`));
const acts = h('<div class="row" style="flex-wrap:wrap;margin-top:12px"></div>');
const pair = h(`<button class="btn primary">${ICONS.plus}${T('Pair new device')}</button>`); pair.onclick = openPairing;
const now = h(`<button class="btn">${ICONS.refresh}${T('Sync now')}</button>`);
now.onclick = async () => { now.disabled = true; try { const n = await call('sync:now'); toast(T('Synchronized with {n} device(s)', { n }), 'ok'); } catch {} now.disabled = false; };
const sec = h(`<button class="btn">${ICONS.key}${T('Choose shared secrets')}</button>`); sec.onclick = chooseSharedSecrets;
acts.append(pair, now, sec);
card.append(acts);
if (!st.firewall || syncFwDismissed()) card.append(h(`<div class="hint" style="color:var(--faint);font-size:11px;margin-top:10px">${T('Devices find each other via UDP port 47811 and synchronize via TCP port 47812. If a firewall is active, allow these ports in your local network (with UFW: sudo ufw allow 47811/udp and sudo ufw allow 47812/tcp).')}</div>`));
}
// Neues Geheimnis bei aktiver Synchronisation: fragen, ob es geteilt werden soll (Antwort wird gemerkt)
async function askShareSecret(c, item, label) {
try {
const st = S.syncStatus || (S.syncStatus = await api.call('sync:status'));
if (!st.enabled || !st.peers.length || !item?.id) return;
if ((st.share[c] || []).includes(item.id) || (st.share.declined?.[c] || []).includes(item.id)) return;
const what = { keys: T('SSH key'), hosts: T('Host password'), vpns: T('VPN configuration') }[c];
const r = await modal({ title: T('Share with paired devices?'), text: `${what}: ${label || ''}`,
body: `<p style="margin-top:0">${T('Should this secret be synchronized to your paired devices ({names})? You can change this later under Settings → Synchronization.', { names: st.peers.map((p) => p.name).join(', ') })}</p>`,
buttons: [{ label: T("Don't share"), value: 'no', cls: 'ghost' }, { label: T('Share'), value: 'yes', cls: 'primary' }], noEnter: true });
if (!r) return; // Dialog geschlossen: beim nächsten Speichern erneut fragen
S.syncStatus = await api.call('sync:shareItem', c, item.id, r === 'yes');
} catch {}
}
// Firewall-Hinweis (CachyOS / aktive UFW bzw. firewalld): Ports für die Synchronisation freigeben
const FW_CMDS = { ufw: 'sudo ufw allow 47811/udp\nsudo ufw allow 47812/tcp', firewalld: 'sudo firewall-cmd --permanent --add-port=47811/udp --add-port=47812/tcp\nsudo firewall-cmd --reload' };
const fwCmds = (f) => (f.firewalld && !f.ufw ? FW_CMDS.firewalld : FW_CMDS.ufw);
const syncFwDismissed = () => { try { return localStorage.getItem('mrterm.sync.fwHint') === '1'; } catch { return false; } };
function firewallHintBox(onDismiss) {
const f = S.syncStatus.firewall;
const box = h(`<div class="net-banner warn fw-hint"><div>${ICONS.wall}</div><div class="grow"><b>${f.os === 'cachyos' ? T('CachyOS: allow the sync ports in the firewall') : T('Firewall active: allow the sync ports')}</b>
<p>${T('Otherwise other devices cannot find or reach this device. Run these commands once in a terminal:')}</p><pre class="mono">${esc(fwCmds(f))}</pre>
<div class="row"><button class="btn sm" data-f="copy">${ICONS.copy}${T('Copy commands')}</button><button class="btn sm ghost" data-f="hide">${T('Already done, hide')}</button></div></div></div>`);
box.onclick = (e) => {
const a = e.target.closest('[data-f]')?.dataset.f;
if (a === 'copy') { api.call('clipboard:write', fwCmds(f)); toast(T('Copied'), 'ok'); }
if (a === 'hide') { try { localStorage.setItem('mrterm.sync.fwHint', '1'); } catch {} onDismiss?.(); }
};
return box;
}
async function showFirewallHint() {
const f = S.syncStatus.firewall;
const r = await modal({ title: f.os === 'cachyos' ? T('CachyOS: allow the sync ports in the firewall') : T('Firewall active: allow the sync ports'),
body: `<p style="margin-top:0">${T('CachyOS enables the UFW firewall by default. It blocks the ports MrTerm needs to find and reach other devices (UDP 47811, TCP 47812). Run these commands once in a terminal:')}</p><pre class="mono fw-pre">${esc(fwCmds(f))}</pre>`,
buttons: [{ label: T('Close'), value: null, cls: 'ghost' }, { label: T('Copy commands'), value: 'copy', cls: 'primary' }] });
if (r === 'copy') { await api.call('clipboard:write', fwCmds(f)); toast(T('Copied'), 'ok'); }
}
// Kopplungsdialog: dieses Gerät ist sichtbar, gefundene Geräte können gekoppelt werden
async function openPairing() {
S.syncStatus = await call('sync:pairable', true);
const body = `<p style="margin-top:0">${T('Open “Pair new device” on the other device too, then select it here. Both devices show a code that you confirm on both sides.')}</p><div class="pair-list list"></div>
<div class="row" style="margin-top:12px"><div class="field" style="flex:1;margin:0"><input name="ip" placeholder="${esc(T('Or enter an IP address, e.g. 192.168.0.25'))}"/></div><button class="btn" data-probe type="button">${T('Search')}</button></div>`;
let timer;
const draw = () => {
const box = $('.pair-list');
if (!box) return clearInterval(timer);
const near = S.syncStatus?.nearby || [];
box.innerHTML = near.length ? '' : `<div class="hint" style="color:var(--muted);display:flex;gap:10px;align-items:center"><span class="spinner sm"></span>${T('Searching for devices …')}</div>${S.syncStatus?.firewall ? `<div class="hint" style="color:var(--orange);margin-top:10px;font-size:12px">${T('No devices found? The firewall on this device may block them:')}<pre class="mono fw-pre">${esc(fwCmds(S.syncStatus.firewall))}</pre></div>` : ''}`;
for (const d of near) {
const row = h(`<div class="card" style="padding:10px 12px;cursor:default"><div class="avatar" style="background:var(--icon-bg);color:var(--accent)">${ICONS.screen}</div><div class="meta"><div class="title">${esc(d.name)}</div><div class="sub">${esc(d.address)}${d.pairable ? '' : ` · ${T('not ready for pairing')}`}</div></div></div>`);
const b = h(`<button class="btn sm primary" ${d.pairable ? '' : 'disabled'}>${T('Pair')}</button>`);
b.onclick = async () => {
b.disabled = true; b.innerHTML = `<span class="spinner sm"></span>${T('Pairing …')}`;
try { await call('sync:pair', d.id); $('.pair-list')?.closest('.modal-bg')?.remove(); } catch {}
b.disabled = false; b.textContent = T('Pair');
};
row.append(b);
box.append(row);
}
};
setTimeout(() => {
draw();
timer = setInterval(draw, 1500);
const probe = $('[data-probe]');
if (probe) probe.onclick = async () => { const ip = $('[name=ip]', probe.closest('.modal')).value.trim(); if (ip) { try { await call('sync:probe', ip); toast(T('Device found'), 'ok'); } catch {} } };
}, 0);
await modal({ title: T('Pair new device'), body, buttons: [{ label: T('Close'), value: null, cls: 'ghost' }] });
clearInterval(timer);
S.syncStatus = await call('sync:pairable', false).catch(() => S.syncStatus);
}
// Auswahl, welche Geheimnisse dieses Gerät an gekoppelte Geräte weitergibt
async function chooseSharedSecrets() {
const sh = S.syncStatus?.share || { keys: [], hosts: [], vpns: [] };
const sect = (title, c, items, label) => items.length ? `<h4>${title}</h4>${items.map((x) => `<label class="check"><input type="checkbox" name="${c}|${esc(x.id)}" ${(sh[c] || []).includes(x.id) ? 'checked' : ''}/>${esc(label(x))}</label>`).join('')}` : '';
const hostsPw = S.vault.hosts.filter((x) => x.password);
const body = `<p style="margin-top:0">${T('Choose which secrets this device may send to paired devices. Everything else (hosts, groups, snippets …) is synchronized without passwords and private keys.')}</p>
<div class="share-list">${sect(T('SSH keys'), 'keys', S.vault.keys, (x) => x.label)}${sect(T('Host passwords'), 'hosts', hostsPw, (x) => `${x.label || x.address} (${x.username || '?'}@${x.address})`)}${sect(T('VPN configurations'), 'vpns', S.vault.vpns, (x) => x.label)}
${!S.vault.keys.length && !hostsPw.length && !S.vault.vpns.length ? `<div class="hint">${T('There are no secrets on this device yet.')}</div>` : ''}</div>`;
const r = await modal({ title: T('Choose shared secrets'), body, buttons: [{ label: T('Share nothing'), value: 'none', cls: 'ghost' }, { label: T('Select all'), value: 'all', cls: '' }, { label: T('Save'), value: 'form', cls: 'primary' }] });
if (!r) return;
const picked = { keys: [], hosts: [], vpns: [] };
if (typeof r === 'object') for (const [k, on] of Object.entries(r)) { const [c, id] = k.split('|'); if (on && picked[c]) picked[c].push(id); }
const sel = r === 'none' ? { keys: [], hosts: [], vpns: [] } : r === 'all' ? { keys: S.vault.keys.map((x) => x.id), hosts: hostsPw.map((x) => x.id), vpns: S.vault.vpns.map((x) => x.id) } : picked;
S.syncStatus = await call('sync:share', sel);
toast(T('Saved'), 'ok');
const card = $('.sync-card'); if (card) renderSyncCard(card);
}
api.on('sync:state', (st) => { S.syncStatus = st; const card = $('.sync-card'); if (card && !card.contains(document.activeElement)) renderSyncCard(card); });
api.on('sync:changed', () => { if (!S.lock?.locked && !$('.lock-screen')) reload(); });
api.on('sync:paired', async (p) => { toast(T('Paired with {name}', { name: p.name }), 'ok'); chooseSharedSecrets(); });
api.on('sync:pairPrompt', async (req) => {
const r = await modal({ title: T('Confirm pairing'), body: `<p style="margin-top:0">${esc(T('Pairing with “{name}”. Does the other device show the same code?', { name: req.name }))}</p><div class="pair-code">${req.code.slice(0, 3)} ${req.code.slice(3)}</div>`,
buttons: [{ label: T('Codes differ'), value: false, cls: 'danger' }, { label: T('Codes match'), value: true, cls: 'primary' }], noEnter: true });
api.pairReply(req.reqId, r === true);
});
// ============================================================ Design
function termTheme() {
const id = settings().terminalTheme;
@@ -2037,8 +2185,13 @@ class NetworkSession {
this.draw();
}
async refresh() {
try { this.apply(await api.call('network:read', this.id)); } catch (e) { toast(e.message, 'error'); }
async refresh(tries = 1) {
for (let i = 1; ; i++) {
try { return this.apply(await api.call('network:read', this.id)); } catch (e) {
if (i >= tries) return toast(e.message, 'error');
await new Promise((r) => setTimeout(r, 3000));
}
}
}
cfg(name) { return this.data.config.find((c) => c.name === name); }
@@ -2110,7 +2263,7 @@ class NetworkSession {
try {
const r = await fn();
ov.remove();
if (r?.confirmed) { toast(r.direct ? T('Saved') : T('Network change applied and confirmed'), 'ok'); await this.refresh(); }
if (r?.confirmed) { toast(r.direct ? T('Saved') : T('Network change applied and confirmed'), 'ok'); await this.refresh(4); }
else {
setTabState(this, 'err');
this.body.innerHTML = `<div class="pane-empty"><div style="color:var(--orange);max-width:560px;text-align:center">${T('MrTerm could not reconnect after the change. The server restores the previous configuration automatically within 90 seconds.')}</div></div>`;
+14
View File
@@ -429,3 +429,17 @@ kbd { background: var(--card); border: 1px solid var(--border); border-bottom-wi
.net-card .dot.on { background: var(--green); }
.net-card .dot.err { background: var(--red); }
.flabel { display: block; font-size: 11px; text-transform: uppercase; letter-spacing: .4px; color: var(--muted); font-weight: 600; margin: 4px 0 6px; }
/* Synchronisation */
.sync-peers .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; }
.sync-peers .dot.on { background: var(--green); }
.pair-code { font-size: 34px; font-weight: 700; letter-spacing: 6px; text-align: center; padding: 14px 0 6px; font-variant-numeric: tabular-nums; color: var(--accent); }
.pair-list { max-height: 260px; overflow: auto; }
.share-list { max-height: 380px; overflow: auto; }
.share-list h4 { margin: 12px 0 6px; }
.fw-hint { align-items: flex-start; margin: 4px 0 14px; }
.fw-hint svg { width: 22px; height: 22px; }
.fw-hint .grow { flex: 1; min-width: 0; }
.fw-hint b { color: var(--text); }
.fw-hint p { margin: 4px 0 8px; color: var(--muted); }
.fw-hint pre, .fw-pre { background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; margin: 0 0 10px; color: var(--text); white-space: pre-wrap; user-select: text; }