mirror of
https://github.com/db9979/sshtermy.git
synced 2026-12-06 12:44:08 +01:00
Gesamtsicherung/Umzug und KI-Datenschutz (#85)
* Debug-Protokoll für Fehlerberichte, Barrierearm-Modus und Farbenblind-Themes - internal/debuglog: Ereignisse (SSH-Aufbau, Abbrüche, Updates, KI-Anfragen, Sync), Rotation 4 MiB - Schalter in Einstellungen, --debug, bereinigte Kopie (crash.Clean) nach Downloads - Barrierearm: keine Animationen, × für nicht erreichbar, Startanimation aus; geht mit dem Sync - Themes Farbenblind dunkel/hell (Okabe-Ito) - README, README.de, Webseite, Kurzreferenz Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * Release-Signatur: Schlüssel tolerant lesen, klare Fehlermeldung, Abgleich mit UPDATE_PUBKEY Der Release-Lauf nach #81 brach mit „UPDATE_SIGNING_KEY fehlt oder ist ungültig“ ab. sshtermy-sign ignoriert jetzt Zeilenumbrüche, Leerzeichen, Anführungszeichen und die keygen-Überschrift, nennt bei Fehlern die gefundene Länge (nie den Schlüssel) und prüft, dass der private Schlüssel zu UPDATE_PUBKEY passt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * Gesamtsicherung/Umzug und KI-Datenschutz - Gesamtsicherung: ganzer Datenordner als eine mit dem Master-Passwort verschlüsselte Datei (.sshtbak, Argon2id + AES-256-GCM in Blöcken); Einstellungen › Import / Export oder sshtermy backup / restore. Einspielen nach Rückfrage beim Neustart, der alte Ordner bleibt als <ordner>.vorher-<zeit> - KI-Datenschutz (Einstellungen › KI): alle Anbieter / nur lokale KI / KI aus, pro Verbindung per Tag ki-lokal / ki-aus (no-ai, ai-local); strengere Stufe gilt - „Letzte KI-Anfrage ansehen“: was zuletzt an welchen Host/welches Modell ging - Doku: README DE/EN, Webseite, Handout Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
5b029c5164
commit
7ed6b32d9d
33 files changed
+1310
-32
No files matched your search
@@ -118,6 +118,10 @@ sshTermy ist eine schlanke Terminal-Anwendung (TUI, eine einzige Datei, ~9 MB, k
|
||||
(OneDrive, Dropbox, iCloud, Syncthing) oder direkt über dein NAS (Synology, QNAP, Nextcloud, jeder WebDAV-Server)
|
||||
- **Import** bestehender Verbindungen aus `~/.ssh/config`, PuTTY (Registry oder `.reg`-Export), MobaXterm
|
||||
(`MobaXterm.ini`, `.mxtsessions`), Ansible-Inventaren (INI oder YAML) und CSV (auch der Geräte-Export von NetBox), mit Jump-Hosts und Ordnern, ein Tastendruck (i im Manager). `e` dort exportiert alle Verbindungen als CSV (ohne Passwörter)
|
||||
- **Gesamtsicherung / Umzug auf einen neuen Rechner** (Einstellungen › Import / Export oder `sshtermy backup`): der
|
||||
ganze Datenordner (Verbindungen, Schlüssel, Protokolle, Switch-Sicherungen, known_hosts, Einstellungen) als eine
|
||||
mit dem Master-Passwort verschlüsselte Datei (Argon2id + AES-256-GCM). Einspielen ersetzt nach Rückfrage und
|
||||
Neustart alles; der bisherige Stand bleibt daneben als `….vorher-<Datum>`
|
||||
- **Themes** Dunkel, Hell, Hochkontrast, Farbenblind (dunkel und hell), Matrix, Bernstein und Neon (a im Manager), **eigene Farben** und einheitliche Menüsymbole (Text-Tags oder Nerd Font) und **frei belegbare Tastenkürzel** (b im Manager)
|
||||
- **Deutsch und Englisch**: Sprache in der Palette („Sprache“/„Language“) oder im Über-Dialog (F12 → `l`) umschalten;
|
||||
die Wahl wird gespeichert und mit dem Sync übernommen. Beim ersten Start richtet sich sshTermy nach der Systemsprache
|
||||
@@ -187,6 +191,8 @@ sshtermy --version # Version, Commit, Build-Datum
|
||||
sshtermy --update # auf die neueste Version aktualisieren
|
||||
sshtermy --no-intro # ohne Startanimation (dauerhaft: Palette „Startanimation aus“)
|
||||
sshtermy --debug # Debug-Protokoll für diesen Start (debug.log im Konfigurationsordner)
|
||||
sshtermy backup [datei] # Gesamtsicherung aller Daten (fragt das Master-Passwort)
|
||||
sshtermy restore <datei> # Gesamtsicherung einspielen (ersetzt alles, alter Ordner bleibt)
|
||||
```
|
||||
|
||||
## Bedienung
|
||||
@@ -441,6 +447,11 @@ Windows-Anmeldung ──DPAPI CryptProtectData───────────
|
||||
- **Geheimnisse** (Private Keys, AWS/GitHub/OpenAI-Keys, Bearer-Token, `password=…`, `user:pass@`) werden vor dem
|
||||
Senden entfernt; an einer Passwortabfrage gibt es keinen Ghost-Text.
|
||||
- API-Key geht nie per `http://` an einen fremden Host (außer bewusst erlaubt).
|
||||
- **KI-Datenschutz** (Einstellungen › KI): „alle Anbieter“, „nur lokale KI“ (nur Endpunkte im eigenen Netz:
|
||||
localhost, private IPs, Namen auf `.local`/`.lan`/`.internal`; Cloud-Ersatz wird übersprungen) oder „KI aus“.
|
||||
Pro Verbindung wirken die Tags `ki-lokal` bzw. `ki-aus` (auch `ai-local`, `no-ai`) genauso; die strengere
|
||||
Einstellung gilt. Im selben Ordner zeigt „Letzte KI-Anfrage ansehen“ genau, was zuletzt an welchen Host und
|
||||
welches Modell ging.
|
||||
- Ratenlimit im Ziel-Modus (Standard 6 Schritte/min, max. 40 Schritte pro Ziel).
|
||||
|
||||
### KI-Anbieter und Ersatz
|
||||
|
||||
@@ -117,6 +117,10 @@ sshTermy is a lean terminal application (TUI, a single file, ~9 MB, no installer
|
||||
(OneDrive, Dropbox, iCloud, Syncthing) or directly via your NAS (Synology, QNAP, Nextcloud, any WebDAV server)
|
||||
- **Import** of existing connections from `~/.ssh/config`, PuTTY (registry or `.reg` export), MobaXterm
|
||||
(`MobaXterm.ini`, `.mxtsessions`), Ansible inventories (INI or YAML) and CSV (also the NetBox device export), with jump hosts and folders, one key press (i in the manager). `e` there exports all connections as CSV (without passwords)
|
||||
- **Full backup / move to a new computer** (Settings › Import / Export or `sshtermy backup`): the whole data folder
|
||||
(connections, keys, logs, switch backups, known_hosts, settings) as one file encrypted with the master password
|
||||
(Argon2id + AES-256-GCM). Restoring replaces everything after a confirmation and a restart; the previous state stays
|
||||
next to it as `….vorher-<date>`
|
||||
- **Themes** dark, light, high contrast, color-blind (dark and light), Matrix, Amber and Neon (a in the manager), **custom colors** and consistent menu icons (text tags or Nerd Font) and **freely assignable keyboard shortcuts** (b in the manager)
|
||||
- **English and German**: switch the language in the palette (“Language”/“Sprache”) or in the About dialog (F12 → `l`);
|
||||
the choice is saved and synced. On first start sshTermy follows the system language
|
||||
@@ -186,6 +190,8 @@ sshtermy --version # version, commit, build date
|
||||
sshtermy --update # update to the newest version
|
||||
sshtermy --no-intro # without the start animation (permanently: palette “Start animation off”)
|
||||
sshtermy --debug # write a debug log for this run (debug.log in the config folder)
|
||||
sshtermy backup [file] # full backup of all data (asks for the master password)
|
||||
sshtermy restore <file> # restore a full backup (replaces all data, keeps the old folder)
|
||||
```
|
||||
|
||||
## Usage
|
||||
@@ -442,6 +448,10 @@ Windows login ──DPAPI CryptProtectData────────────
|
||||
- **Secrets** (private keys, AWS/GitHub/OpenAI keys, bearer tokens, `password=…`, `user:pass@`) are removed before
|
||||
sending; there is no ghost text at a password prompt.
|
||||
- The API key is never sent via `http://` to a foreign host (unless explicitly allowed).
|
||||
- **AI privacy** (Settings › AI): “all providers”, “local AI only” (only endpoints on your own network: localhost,
|
||||
private IPs, `.local`/`.lan`/`.internal` names; cloud fallbacks are skipped) or “AI off”. Per connection the tags
|
||||
`ai-local` or `no-ai` (also `ki-lokal`, `ki-aus`) do the same; the stricter setting wins. In the same folder
|
||||
“Show last AI request” shows exactly what was last sent, to which host and model.
|
||||
- Rate limit in goal mode (default 6 steps/min, at most 40 steps per goal).
|
||||
|
||||
### AI providers and fallback
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/x/term"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/fullbackup"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/store"
|
||||
"github.com/db9979/sshtermy/internal/vault"
|
||||
"github.com/db9979/sshtermy/internal/version"
|
||||
)
|
||||
|
||||
// sshtermy backup [datei] → Gesamtsicherung des Datenordners
|
||||
// sshtermy restore <datei> → beim nächsten Start einspielen
|
||||
// Beide fragen das Master-Passwort ab (kein Schalter, nichts in der Shell-History).
|
||||
|
||||
func readPass(prompt string) ([]byte, error) {
|
||||
fmt.Fprint(os.Stderr, prompt)
|
||||
pw, err := term.ReadPassword(os.Stdin.Fd())
|
||||
fmt.Fprintln(os.Stderr)
|
||||
return pw, err
|
||||
}
|
||||
|
||||
func runBackup(args []string) int {
|
||||
dir, err := store.Dir()
|
||||
if err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
file := "sshtermy-sicherung-" + time.Now().Format("2006-01-02") + fullbackup.Ext
|
||||
if len(args) > 0 {
|
||||
file = args[0]
|
||||
}
|
||||
v, err := vault.Open(filepath.Join(dir, "store.vault"))
|
||||
if err != nil || !v.Exists() {
|
||||
return cliErr(errors.New(i18n.T("Kein Store in ") + dir))
|
||||
}
|
||||
pw, err := readPass(i18n.T("Master-Passwort: "))
|
||||
if err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
defer vault.Wipe(pw)
|
||||
if err := v.CheckPassword(pw); err != nil {
|
||||
return cliErr(errors.New(i18n.T("Master-Passwort stimmt nicht")))
|
||||
}
|
||||
tmp := file + ".tmp"
|
||||
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
m, err := fullbackup.Create(dir, pw, version.Version, out)
|
||||
if cerr := out.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, file)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp)
|
||||
return cliErr(err)
|
||||
}
|
||||
fmt.Printf(i18n.T("Gesamtsicherung gespeichert: %s (%d Dateien)")+"\n", file, m.Files)
|
||||
return 0
|
||||
}
|
||||
|
||||
func runRestore(args []string) int {
|
||||
if len(args) != 1 {
|
||||
return cliErr(errors.New(i18n.T("Aufruf: sshtermy restore <datei>")))
|
||||
}
|
||||
dir, err := store.Dir()
|
||||
if err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
pw, err := readPass(i18n.T("Master-Passwort der Sicherung: "))
|
||||
if err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
defer vault.Wipe(pw)
|
||||
check := func(vp string) error {
|
||||
v, err := vault.Open(vp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return v.CheckPassword(pw)
|
||||
}
|
||||
stage, m, err := fullbackup.Prepare(dir, args[0], pw, check)
|
||||
switch {
|
||||
case errors.Is(err, fullbackup.ErrWrongPassword), errors.Is(err, vault.ErrWrongPassword):
|
||||
return cliErr(errors.New(i18n.T("Passwort stimmt nicht oder die Datei ist beschädigt")))
|
||||
case errors.Is(err, fullbackup.ErrNotBackup):
|
||||
return cliErr(errors.New(i18n.T("Keine sshTermy-Sicherung")))
|
||||
case err != nil:
|
||||
return cliErr(err)
|
||||
}
|
||||
fmt.Printf(i18n.T("Sicherung vom %s (v%s, %s, %d Dateien).")+"\n", m.Created.Local().Format("02.01.2006 15:04"), m.Version, m.OS, m.Files)
|
||||
fmt.Printf(i18n.T("Alle Daten in %s ersetzen? [j/N] "), dir)
|
||||
var ans string
|
||||
fmt.Scanln(&ans)
|
||||
if a := strings.ToLower(strings.TrimSpace(ans)); a != "j" && a != "y" && a != "ja" && a != "yes" {
|
||||
os.RemoveAll(stage)
|
||||
fmt.Println(i18n.T("Abgebrochen."))
|
||||
return 1
|
||||
}
|
||||
if err := fullbackup.MarkPending(dir, stage); err != nil {
|
||||
os.RemoveAll(stage)
|
||||
return cliErr(err)
|
||||
}
|
||||
old, err := fullbackup.ApplyPending(dir)
|
||||
if err != nil {
|
||||
return cliErr(err)
|
||||
}
|
||||
fmt.Printf(i18n.T("Eingespielt. Bisheriger Stand: %s")+"\n", old)
|
||||
return 0
|
||||
}
|
||||
|
||||
func cliErr(err error) int {
|
||||
fmt.Fprintln(os.Stderr, "sshtermy:", err)
|
||||
return 1
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/charmbracelet/x/term"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/crash"
|
||||
"github.com/db9979/sshtermy/internal/fullbackup"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/sshx"
|
||||
"github.com/db9979/sshtermy/internal/store"
|
||||
@@ -33,6 +34,12 @@ func main() {
|
||||
// Sprache vor allem anderen: auch Hilfe zu den Schaltern und der
|
||||
// Entsperr-Bildschirm sollen sie schon haben.
|
||||
dir, _ := store.Dir()
|
||||
// Gesamtsicherung aus dem letzten Lauf einspielen, bevor irgendetwas
|
||||
// den Datenordner öffnet (internal/fullbackup).
|
||||
restoredFrom, restoreErr := "", error(nil)
|
||||
if dir != "" {
|
||||
restoredFrom, restoreErr = fullbackup.ApplyPending(dir)
|
||||
}
|
||||
i18n.Load(dir)
|
||||
|
||||
// Unterbefehle ohne Oberfläche (eigener Vermittler, Anker auf Servern)
|
||||
@@ -42,6 +49,10 @@ func main() {
|
||||
os.Exit(runRelay(os.Args[2:]))
|
||||
case "anker", "anchor":
|
||||
os.Exit(runAnchor(os.Args[2:]))
|
||||
case "backup", "sicherung":
|
||||
os.Exit(runBackup(os.Args[2:]))
|
||||
case "restore", "einspielen":
|
||||
os.Exit(runRestore(os.Args[2:]))
|
||||
case "attach":
|
||||
// neues Fenster eines abgetrennten Tabs (⇧F10), siehe internal/detach
|
||||
if len(os.Args) != 3 {
|
||||
@@ -93,6 +104,11 @@ func main() {
|
||||
if *noIntro {
|
||||
app.SkipIntro()
|
||||
}
|
||||
if restoreErr != nil {
|
||||
app.StartNotice(false, i18n.T("Gesamtsicherung nicht eingespielt: ")+restoreErr.Error())
|
||||
} else if restoredFrom != "" {
|
||||
app.StartNotice(true, i18n.T("Gesamtsicherung eingespielt. Bisheriger Stand: ")+restoredFrom)
|
||||
}
|
||||
app.CrashTest(*crashTest)
|
||||
if *debug {
|
||||
app.ForceDebug()
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -427,6 +427,11 @@ type LLMConfig struct {
|
||||
GoalStepsMin int `json:"goal_steps_min"` // Ratenlimit Ziel-Modus pro Minute
|
||||
AllowInsecure bool `json:"allow_insecure"` // http:// zu Nicht-Localhost erlauben
|
||||
|
||||
// Privacy: "" alle Anbieter, "lokal" nur Endpunkte im eigenen Netz,
|
||||
// "aus" keine KI. Verbindungen können per Tag strenger sein
|
||||
// (ki-lokal / ki-aus), nie lockerer.
|
||||
Privacy string `json:"privacy,omitempty"`
|
||||
|
||||
// Fallbacks: der Reihe nach, wenn der Endpunkt oben nicht antwortet.
|
||||
Fallbacks []LLMBackup `json:"fallbacks,omitempty"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
// Package fullbackup: Gesamtsicherung des Datenordners in eine einzige
|
||||
// verschlüsselte Datei, zum Sichern und für den Umzug auf einen neuen Rechner.
|
||||
//
|
||||
// Inhalt ist ein ZIP aller Dateien im Datenordner (Store, gesicherte
|
||||
// Switch-Configs, Sitzungsprotokolle, known_hosts, Sprache …) ohne Absturz-
|
||||
// und Debug-Berichte. Das ZIP wird mit einem Schlüssel aus dem Passwort
|
||||
// (Argon2id) in Blöcken mit AES-256-GCM verschlüsselt; jeder Block trägt
|
||||
// seine Nummer und ob er der letzte ist, so fällt Kürzen, Umsortieren oder
|
||||
// Ändern auf. Das Passwort ist das Master-Passwort: die Oberfläche prüft es
|
||||
// beim Erstellen, und der Store in der Sicherung öffnet sich damit.
|
||||
//
|
||||
// Einspielen geschieht in zwei Schritten: Prepare entschlüsselt in einen
|
||||
// Ordner neben dem Datenordner und merkt ihn vor; ApplyPending tauscht beim
|
||||
// nächsten Start (bevor der Store geöffnet wird) die Ordner. Der bisherige
|
||||
// Datenordner bleibt als <ordner>.vorher-<zeit> liegen.
|
||||
package fullbackup
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
magic = "SSHTERMY-SICHERUNG\x01"
|
||||
chunkSize = 1 << 20
|
||||
manifestName = "sshtermy-sicherung.json"
|
||||
pendingName = "restore-pending"
|
||||
// Ext: Dateiendung der Sicherung.
|
||||
Ext = ".sshtbak"
|
||||
// Schutz beim Einspielen: höchstens so viel entpacken.
|
||||
maxTotal = 8 << 30
|
||||
maxFiles = 200000
|
||||
)
|
||||
|
||||
// skip: was nicht in die Sicherung gehört (rechnerbezogen oder Diagnose).
|
||||
func skip(rel string, d fs.DirEntry) bool {
|
||||
top := strings.SplitN(filepath.ToSlash(rel), "/", 2)[0]
|
||||
switch top {
|
||||
case "crash", pendingName, "restore-tabs.json":
|
||||
return true
|
||||
}
|
||||
n := d.Name()
|
||||
return strings.HasPrefix(n, "debug.log") || strings.HasSuffix(n, ".lock") || strings.HasSuffix(n, ".tmp")
|
||||
}
|
||||
|
||||
// Manifest steht unverschlüsselt im ZIP (also verschlüsselt in der Datei).
|
||||
type Manifest struct {
|
||||
Format int `json:"format"`
|
||||
Created time.Time `json:"created"`
|
||||
Version string `json:"version"`
|
||||
OS string `json:"os"`
|
||||
Files int `json:"files"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
func deriveKey(pass, salt []byte) []byte {
|
||||
return argon2.IDKey(pass, salt, 3, 64*1024, 4, 32)
|
||||
}
|
||||
|
||||
// Create schreibt die Sicherung von dir nach w.
|
||||
func Create(dir string, pass []byte, version string, w io.Writer) (Manifest, error) {
|
||||
if len(pass) == 0 {
|
||||
return Manifest{}, errors.New("fullbackup: Passwort fehlt")
|
||||
}
|
||||
var zbuf bytes.Buffer
|
||||
zw := zip.NewWriter(&zbuf)
|
||||
m := Manifest{Format: 1, Created: time.Now().UTC().Truncate(time.Second), Version: version, OS: runtime.GOOS}
|
||||
err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(dir, p)
|
||||
if rel == "." {
|
||||
return nil
|
||||
}
|
||||
if skip(rel, d) {
|
||||
if d.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !d.Type().IsRegular() {
|
||||
return nil // Ordner entstehen beim Entpacken, Links bleiben draußen
|
||||
}
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, err := zip.FileInfoHeader(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.Name, h.Method = filepath.ToSlash(rel), zip.Deflate
|
||||
fw, err := zw.CreateHeader(h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.Open(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := io.Copy(fw, f)
|
||||
f.Close()
|
||||
m.Files++
|
||||
m.Bytes += n
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
if m.Files == 0 {
|
||||
return Manifest{}, errors.New("fullbackup: Datenordner ist leer")
|
||||
}
|
||||
mj, _ := json.MarshalIndent(m, "", " ")
|
||||
fw, err := zw.Create(manifestName)
|
||||
if err == nil {
|
||||
_, err = fw.Write(mj)
|
||||
}
|
||||
if err == nil {
|
||||
err = zw.Close()
|
||||
}
|
||||
if err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
return m, seal(w, pass, zbuf.Bytes())
|
||||
}
|
||||
|
||||
func seal(w io.Writer, pass, plain []byte) error {
|
||||
salt := make([]byte, 16)
|
||||
base := make([]byte, 7)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := rand.Read(base); err != nil {
|
||||
return err
|
||||
}
|
||||
aead, err := newAEAD(deriveKey(pass, salt))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bw := bufio.NewWriter(w)
|
||||
bw.WriteString(magic)
|
||||
bw.Write(salt)
|
||||
bw.Write(base)
|
||||
for i := 0; ; i++ {
|
||||
n := min(chunkSize, len(plain))
|
||||
chunk, rest := plain[:n], plain[n:]
|
||||
ct := aead.Seal(nil, nonce(base, i, len(rest) == 0), chunk, []byte(magic))
|
||||
var l [4]byte
|
||||
binary.BigEndian.PutUint32(l[:], uint32(len(ct)))
|
||||
bw.Write(l[:])
|
||||
if _, err := bw.Write(ct); err != nil {
|
||||
return err
|
||||
}
|
||||
plain = rest
|
||||
if len(rest) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return bw.Flush()
|
||||
}
|
||||
|
||||
func newAEAD(key []byte) (cipher.AEAD, error) {
|
||||
b, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(b)
|
||||
}
|
||||
|
||||
func nonce(base []byte, i int, last bool) []byte {
|
||||
n := make([]byte, 12)
|
||||
copy(n, base)
|
||||
binary.BigEndian.PutUint32(n[7:11], uint32(i))
|
||||
if last {
|
||||
n[11] = 1
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// ErrWrongPassword: Passwort falsch oder Datei verändert.
|
||||
var ErrWrongPassword = errors.New("fullbackup: Passwort falsch oder Datei beschädigt")
|
||||
|
||||
// ErrNotBackup: keine sshTermy-Sicherung.
|
||||
var ErrNotBackup = errors.New("fullbackup: keine sshTermy-Sicherung")
|
||||
|
||||
// open entschlüsselt die ganze Datei.
|
||||
func open(r io.Reader, pass []byte) ([]byte, error) {
|
||||
br := bufio.NewReader(r)
|
||||
head := make([]byte, len(magic)+16+7)
|
||||
if _, err := io.ReadFull(br, head); err != nil || string(head[:len(magic)]) != magic {
|
||||
return nil, ErrNotBackup
|
||||
}
|
||||
salt, base := head[len(magic):len(magic)+16], head[len(magic)+16:]
|
||||
aead, err := newAEAD(deriveKey(pass, salt))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []byte
|
||||
for i := 0; ; i++ {
|
||||
var l [4]byte
|
||||
if _, err := io.ReadFull(br, l[:]); err != nil {
|
||||
return nil, ErrWrongPassword // abgeschnitten
|
||||
}
|
||||
n := binary.BigEndian.Uint32(l[:])
|
||||
if n > chunkSize+uint32(aead.Overhead()) {
|
||||
return nil, ErrWrongPassword
|
||||
}
|
||||
ct := make([]byte, n)
|
||||
if _, err := io.ReadFull(br, ct); err != nil {
|
||||
return nil, ErrWrongPassword
|
||||
}
|
||||
_, peekErr := br.Peek(1)
|
||||
last := peekErr == io.EOF
|
||||
pt, err := aead.Open(nil, nonce(base, i, last), ct, []byte(magic))
|
||||
if err != nil {
|
||||
return nil, ErrWrongPassword
|
||||
}
|
||||
out = append(out, pt...)
|
||||
if int64(len(out)) > maxTotal {
|
||||
return nil, errors.New("fullbackup: Sicherung zu groß")
|
||||
}
|
||||
if last {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare entschlüsselt die Sicherung in einen neuen Ordner neben dir und
|
||||
// prüft, dass ein Store darin liegt. check bekommt den Pfad der Vault-Datei
|
||||
// (die Oberfläche prüft damit das Passwort). Rückgabe: Ordner und Manifest.
|
||||
func Prepare(dir, file string, pass []byte, check func(vaultPath string) error) (string, Manifest, error) {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return "", Manifest{}, err
|
||||
}
|
||||
defer f.Close()
|
||||
plain, err := open(f, pass)
|
||||
if err != nil {
|
||||
return "", Manifest{}, err
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(plain), int64(len(plain)))
|
||||
if err != nil {
|
||||
return "", Manifest{}, ErrNotBackup
|
||||
}
|
||||
if len(zr.File) > maxFiles {
|
||||
return "", Manifest{}, errors.New("fullbackup: zu viele Dateien")
|
||||
}
|
||||
stage := fmt.Sprintf("%s.neu-%s", filepath.Clean(dir), time.Now().Format("20060102-150405"))
|
||||
if err := os.MkdirAll(stage, 0o700); err != nil {
|
||||
return "", Manifest{}, err
|
||||
}
|
||||
var m Manifest
|
||||
fail := func(err error) (string, Manifest, error) { os.RemoveAll(stage); return "", Manifest{}, err }
|
||||
for _, zf := range zr.File {
|
||||
name := filepath.FromSlash(zf.Name)
|
||||
// nur relative Pfade innerhalb des Ordners (kein ../, kein C:\)
|
||||
if !filepath.IsLocal(name) || strings.HasSuffix(zf.Name, "/") {
|
||||
continue
|
||||
}
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(rc, maxTotal))
|
||||
rc.Close()
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if zf.Name == manifestName {
|
||||
_ = json.Unmarshal(data, &m)
|
||||
continue
|
||||
}
|
||||
dst := filepath.Join(stage, name)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if err := os.WriteFile(dst, data, 0o600); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
vp := filepath.Join(stage, "store.vault")
|
||||
if _, err := os.Stat(vp); err != nil {
|
||||
return fail(errors.New("fullbackup: kein Store in der Sicherung"))
|
||||
}
|
||||
if check != nil {
|
||||
if err := check(vp); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
return stage, m, nil
|
||||
}
|
||||
|
||||
// MarkPending: beim nächsten Start stage einspielen.
|
||||
func MarkPending(dir, stage string) error {
|
||||
return os.WriteFile(filepath.Join(dir, pendingName), []byte(stage), 0o600)
|
||||
}
|
||||
|
||||
// ApplyPending tauscht den Datenordner gegen die vorbereitete Sicherung
|
||||
// (vor dem Öffnen des Stores aufrufen). Rückgabe: Ordner mit dem bisherigen
|
||||
// Stand ("" = nichts zu tun).
|
||||
func ApplyPending(dir string) (string, error) {
|
||||
b, err := os.ReadFile(filepath.Join(dir, pendingName))
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
stage := strings.TrimSpace(string(b))
|
||||
// nur ein Ordner, den Prepare neben dir angelegt hat
|
||||
if filepath.Dir(stage) != filepath.Dir(filepath.Clean(dir)) || !strings.HasPrefix(filepath.Base(stage), filepath.Base(filepath.Clean(dir))+".neu-") {
|
||||
os.Remove(filepath.Join(dir, pendingName))
|
||||
return "", errors.New("fullbackup: vorgemerkter Ordner ungültig")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(stage, "store.vault")); err != nil {
|
||||
os.Remove(filepath.Join(dir, pendingName))
|
||||
return "", errors.New("fullbackup: vorgemerkte Sicherung fehlt")
|
||||
}
|
||||
os.Remove(filepath.Join(dir, pendingName))
|
||||
old := fmt.Sprintf("%s.vorher-%s", filepath.Clean(dir), time.Now().Format("20060102-150405"))
|
||||
if err := os.Rename(dir, old); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := os.Rename(stage, dir); err != nil {
|
||||
_ = os.Rename(old, dir) // zurück, nichts verloren
|
||||
return "", err
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package fullbackup
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func write(t *testing.T, p, s string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoundTripAndSwap(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
src := filepath.Join(root, "alt", "sshtermy")
|
||||
write(t, filepath.Join(src, "store.vault"), "VAULT")
|
||||
write(t, filepath.Join(src, "logs", "a.log.enc"), strings.Repeat("x", 3<<20)) // mehrere Blöcke
|
||||
write(t, filepath.Join(src, "known_hosts"), "h ssh-ed25519 AAAA")
|
||||
write(t, filepath.Join(src, "crash", "c.txt"), "nicht mitnehmen")
|
||||
write(t, filepath.Join(src, "debug.log"), "nicht mitnehmen")
|
||||
|
||||
var buf bytes.Buffer
|
||||
m, err := Create(src, []byte("pw"), "1.0.1", &buf)
|
||||
if err != nil || m.Files != 3 {
|
||||
t.Fatalf("Create: %+v %v", m, err)
|
||||
}
|
||||
if bytes.Contains(buf.Bytes(), []byte("VAULT")) || bytes.Contains(buf.Bytes(), []byte("ssh-ed25519")) {
|
||||
t.Fatal("Inhalt unverschlüsselt")
|
||||
}
|
||||
file := filepath.Join(root, "s"+Ext)
|
||||
write(t, file, buf.String())
|
||||
|
||||
dst := filepath.Join(root, "neu", "sshtermy")
|
||||
write(t, filepath.Join(dst, "store.vault"), "ALT")
|
||||
if _, _, err := Prepare(dst, file, []byte("falsch"), nil); !errors.Is(err, ErrWrongPassword) {
|
||||
t.Fatalf("falsches Passwort: %v", err)
|
||||
}
|
||||
checked := ""
|
||||
stage, m2, err := Prepare(dst, file, []byte("pw"), func(vp string) error { checked = vp; return nil })
|
||||
if err != nil || m2.Version != "1.0.1" || checked == "" {
|
||||
t.Fatalf("Prepare: %v %+v", err, m2)
|
||||
}
|
||||
if err := MarkPending(dst, stage); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old, err := ApplyPending(dst)
|
||||
if err != nil || old == "" {
|
||||
t.Fatalf("Apply: %v", err)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(dst, "store.vault")); string(b) != "VAULT" {
|
||||
t.Fatalf("Store nicht getauscht: %q", b)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(old, "store.vault")); string(b) != "ALT" {
|
||||
t.Fatal("alter Stand weg")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dst, "crash")); !os.IsNotExist(err) {
|
||||
t.Fatal("crash mitgenommen")
|
||||
}
|
||||
if st, err := os.Stat(filepath.Join(dst, "logs", "a.log.enc")); err != nil || st.Size() != 3<<20 {
|
||||
t.Fatal("Protokoll fehlt", err)
|
||||
}
|
||||
if o, err := ApplyPending(dst); o != "" || err != nil {
|
||||
t.Fatal("zweites Apply")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTamperAndTruncate(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
rnd := make([]byte, 2<<20) // zufällig: lässt sich nicht packen, also mehrere Blöcke
|
||||
_, _ = rand.Read(rnd)
|
||||
write(t, filepath.Join(src, "store.vault"), string(rnd))
|
||||
var buf bytes.Buffer
|
||||
if _, err := Create(src, []byte("pw"), "x", &buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := buf.Bytes()
|
||||
for name, bad := range map[string][]byte{
|
||||
"gekürzt": b[:len(b)-(1<<20)],
|
||||
"verändert": append(append([]byte{}, b[:len(b)-5]...), 0, 0, 0, 0, 0),
|
||||
"fremd": []byte("PK\x03\x04 kein Format"),
|
||||
} {
|
||||
p := filepath.Join(t.TempDir(), "x"+Ext)
|
||||
write(t, p, string(bad))
|
||||
if _, _, err := Prepare(t.TempDir(), p, []byte("pw"), nil); err == nil {
|
||||
t.Errorf("%s: kein Fehler", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyPendingRejectsForeignDir(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
dir := filepath.Join(root, "sshtermy")
|
||||
write(t, filepath.Join(dir, "store.vault"), "A")
|
||||
write(t, filepath.Join(root, "woanders", "store.vault"), "B")
|
||||
if err := MarkPending(dir, filepath.Join(root, "woanders")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ApplyPending(dir); err == nil {
|
||||
t.Fatal("fremder Ordner angenommen")
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(dir, "store.vault")); string(b) != "A" {
|
||||
t.Fatal("Store verändert")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package i18n
|
||||
|
||||
// Gesamtsicherung (internal/fullbackup, ui/fullbackup.go, cmd/sshtermy/backupcmd.go)
|
||||
// und KI-Datenschutz (llm/privacy.go, ui/aiprivacy.go).
|
||||
func init() {
|
||||
for k, v := range enBackup {
|
||||
en[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
var enBackup = map[string]string{
|
||||
"Alle Daten in %s ersetzen? [j/N] ": "Replace all data in %s? [y/N] ",
|
||||
"Aufruf: sshtermy restore <datei>": "Usage: sshtermy restore <file>",
|
||||
"Eingespielt. Bisheriger Stand: %s": "Restored. Previous state: %s",
|
||||
"Gesamtsicherung eingespielt. Bisheriger Stand: ": "Full backup restored. Previous state: ",
|
||||
"Gesamtsicherung einspielen": "Restore full backup",
|
||||
"Gesamtsicherung einspielen …": "Restore full backup …",
|
||||
"Gesamtsicherung gespeichert: %s (%d Dateien)": "Full backup saved: %s (%d files)",
|
||||
"Gesamtsicherung nicht eingespielt: ": "Full backup not restored: ",
|
||||
"Gesamtsicherung speichern": "Save full backup",
|
||||
"Gesamtsicherung speichern (für Umzug/Sicherung) …": "Save full backup (to move or back up) …",
|
||||
"KI aus": "AI off",
|
||||
"KI ist ausgeschaltet (Einstellungen › KI › KI-Datenschutz)": "AI is turned off (Settings › AI › AI privacy)",
|
||||
"KI ist für diese Verbindung aus (Tag ki-aus)": "AI is off for this connection (tag no-ai)",
|
||||
"KI-Datenschutz": "AI privacy",
|
||||
"KI-Datenschutz: ": "AI privacy: ",
|
||||
"Kein Store in ": "No store in ",
|
||||
"Keine sshTermy-Sicherung": "Not an sshTermy backup",
|
||||
"Letzte KI-Anfrage": "Last AI request",
|
||||
"Letzte KI-Anfrage ansehen": "Show last AI request",
|
||||
"Master-Passwort der Sicherung": "Master password of the backup",
|
||||
"Master-Passwort der Sicherung: ": "Master password of the backup: ",
|
||||
"Master-Passwort fehlt": "Master password missing",
|
||||
"Master-Passwort stimmt nicht": "Master password is wrong",
|
||||
"Master-Passwort: ": "Master password: ",
|
||||
"Nur lokale KI erlaubt, aber kein Endpunkt im eigenen Netz eingerichtet (z. B. Ollama auf localhost)": "Only local AI allowed, but no endpoint on your own network is set up (e.g. Ollama on localhost)",
|
||||
"Passwort stimmt nicht oder die Datei ist beschädigt": "Wrong password or damaged file",
|
||||
"Passwörter, Keys und Tokens werden vor dem Senden entfernt.": "Passwords, keys and tokens are removed before sending.",
|
||||
"Pfad zur .sshtbak-Datei": "Path to the .sshtbak file",
|
||||
"Seit dem Start ging noch nichts an eine KI.": "Nothing has been sent to an AI since start.",
|
||||
"Sicherung vom %s (v%s, %s, %d Dateien).": "Backup from %s (v%s, %s, %d files).",
|
||||
"Sicherung vom %s (v%s, %s, %d Dateien).\n\nAlle Daten hier werden durch die Sicherung ersetzt. Der bisherige Stand bleibt im Ordner\n%s.vorher-…\n\nsshTermy startet dafür neu, offene Sitzungen werden getrennt.": "Backup from %s (v%s, %s, %d files).\n\nAll data here will be replaced by the backup. The previous state stays in the folder\n%s.vorher-…\n\nsshTermy restarts for this; open sessions will be disconnected.",
|
||||
"alle Anbieter": "all providers",
|
||||
"alles, verschlüsselt": "everything, encrypted",
|
||||
"außerhalb des eigenen Netzes": "outside your own network",
|
||||
"das Passwort, mit dem die Sicherung gespeichert wurde": "the password the backup was saved with",
|
||||
"die Sicherung wird damit verschlüsselt": "the backup is encrypted with it",
|
||||
"enthält alle Verbindungen, Schlüssel, Protokolle und Einstellungen": "contains all connections, keys, logs and settings",
|
||||
"im eigenen Netz": "on your own network",
|
||||
"nur lokale KI": "local AI only",
|
||||
"was ging hinaus": "what was sent",
|
||||
}
|
||||
@@ -422,6 +422,7 @@ func (c *conn) do(ctx context.Context, body any, stream bool) (*http.Response, e
|
||||
cp.Timeout = 0 // Streams dürfen länger dauern; Abbruch über ctx
|
||||
cl = &cp
|
||||
}
|
||||
remember(c.cfg, req.URL.Host, raw)
|
||||
t0 := time.Now()
|
||||
resp, err := cl.Do(req)
|
||||
if debuglog.On() {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
)
|
||||
|
||||
// KI-Datenschutz: welche Endpunkte dürfen Daten bekommen, und was ging
|
||||
// zuletzt hinaus (zum Nachsehen in der Oberfläche).
|
||||
|
||||
// Datenschutz-Stufen (LLMConfig.Privacy und Tags an Verbindungen).
|
||||
const (
|
||||
PrivacyAll = "" // alle eingerichteten Anbieter
|
||||
PrivacyLocal = "lokal" // nur Endpunkte im eigenen Netz
|
||||
PrivacyOff = "aus" // keine KI
|
||||
)
|
||||
|
||||
// Stricter: die strengere von zwei Stufen.
|
||||
func Stricter(a, b string) string {
|
||||
rank := map[string]int{PrivacyAll: 0, PrivacyLocal: 1, PrivacyOff: 2}
|
||||
if rank[b] > rank[a] {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// ErrAIOff: für diese Verbindung (oder überhaupt) ist die KI aus.
|
||||
var ErrAIOff = errors.New("KI aus")
|
||||
|
||||
// IsLocalEndpoint: liegt der Endpunkt im eigenen Netz? Loopback, private und
|
||||
// link-lokale Adressen, Namen ohne Punkt (dgx-spark) und die üblichen
|
||||
// internen Endungen. Kein DNS-Nachschlagen: ein öffentlicher Name zählt
|
||||
// immer als außerhalb, auch wenn er gerade auf eine interne Adresse zeigt.
|
||||
func IsLocalEndpoint(baseURL string) bool {
|
||||
u, err := url.Parse(strings.TrimSpace(baseURL))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
h := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
|
||||
if h == "" {
|
||||
return false
|
||||
}
|
||||
if ip := net.ParseIP(h); ip != nil {
|
||||
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
if h == "localhost" || !strings.Contains(h, ".") {
|
||||
return true
|
||||
}
|
||||
for _, s := range []string{".local", ".lan", ".internal", ".intranet", ".home.arpa", ".localdomain", ".localhost"} {
|
||||
if strings.HasSuffix(h, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NewWithPrivacy wie New, behält aber nur Endpunkte, die die Stufe erlaubt.
|
||||
func NewWithPrivacy(cfg domain.LLMConfig, level string) (*Client, error) {
|
||||
if level == PrivacyOff {
|
||||
return nil, ErrAIOff
|
||||
}
|
||||
c, err := New(cfg)
|
||||
if err != nil || level != PrivacyLocal {
|
||||
return c, err
|
||||
}
|
||||
var keep []*conn
|
||||
for _, k := range c.conns {
|
||||
if IsLocalEndpoint(baseURL(k.cfg)) {
|
||||
keep = append(keep, k)
|
||||
}
|
||||
}
|
||||
if len(keep) == 0 {
|
||||
return nil, errors.New(i18n.T("Nur lokale KI erlaubt, aber kein Endpunkt im eigenen Netz eingerichtet (z. B. Ollama auf localhost)"))
|
||||
}
|
||||
c.conns = keep
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- letzte Anfrage
|
||||
|
||||
// Request: was zuletzt an eine KI ging (nur im Speicher, nie auf Platte).
|
||||
type Request struct {
|
||||
At time.Time
|
||||
Provider domain.LLMProvider
|
||||
Host string
|
||||
Model string
|
||||
Messages []Message
|
||||
}
|
||||
|
||||
var last struct {
|
||||
mu sync.Mutex
|
||||
req *Request
|
||||
}
|
||||
|
||||
// LastRequest: die letzte Anfrage oder nil.
|
||||
func LastRequest() *Request {
|
||||
last.mu.Lock()
|
||||
defer last.mu.Unlock()
|
||||
if last.req == nil {
|
||||
return nil
|
||||
}
|
||||
r := *last.req
|
||||
r.Messages = append([]Message(nil), r.Messages...)
|
||||
return &r
|
||||
}
|
||||
|
||||
// remember: Nachrichten aus dem JSON-Körper (OpenAI und Anthropic haben
|
||||
// beide "messages", Anthropic zusätzlich "system").
|
||||
func remember(cfg domain.LLMConfig, host string, raw []byte) {
|
||||
var b struct {
|
||||
System any `json:"system"`
|
||||
Messages []Message `json:"messages"`
|
||||
}
|
||||
if json.Unmarshal(raw, &b) != nil {
|
||||
return
|
||||
}
|
||||
msgs := b.Messages
|
||||
if s, ok := b.System.(string); ok && s != "" {
|
||||
msgs = append([]Message{{Role: "system", Content: s}}, msgs...)
|
||||
}
|
||||
last.mu.Lock()
|
||||
last.req = &Request{At: time.Now(), Provider: cfg.Provider, Host: host, Model: cfg.Model, Messages: msgs}
|
||||
last.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
)
|
||||
|
||||
func TestIsLocalEndpoint(t *testing.T) {
|
||||
local := []string{"http://localhost:11434/v1", "http://127.0.0.1:8000/v1", "http://10.1.2.3/v1", "http://192.168.0.5:8000",
|
||||
"http://dgx-spark:8000/v1", "http://ki.lan/v1", "https://llm.firma.internal/v1", "http://[::1]:11434", "http://[fd00::5]/v1"}
|
||||
remote := []string{"https://api.openai.com/v1", "https://api.anthropic.com", "http://8.8.8.8/v1", "https://llm.example.com/v1", "kaputt"}
|
||||
for _, u := range local {
|
||||
if !IsLocalEndpoint(u) {
|
||||
t.Errorf("%s sollte lokal sein", u)
|
||||
}
|
||||
}
|
||||
for _, u := range remote {
|
||||
if IsLocalEndpoint(u) {
|
||||
t.Errorf("%s sollte nicht lokal sein", u)
|
||||
}
|
||||
}
|
||||
if Stricter(PrivacyAll, PrivacyLocal) != PrivacyLocal || Stricter(PrivacyOff, PrivacyLocal) != PrivacyOff || Stricter("", "") != "" {
|
||||
t.Error("Stricter")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewWithPrivacy(t *testing.T) {
|
||||
cfg := domain.LLMConfig{Provider: domain.ProviderOpenAI, BaseURL: "https://api.openai.com/v1", APIKey: "sk-x", Model: "gpt",
|
||||
Fallbacks: []domain.LLMBackup{{BaseURL: "http://localhost:11434/v1", Model: "qwen"}}}
|
||||
if _, err := NewWithPrivacy(cfg, PrivacyOff); !errors.Is(err, ErrAIOff) {
|
||||
t.Fatalf("aus: %v", err)
|
||||
}
|
||||
c, err := NewWithPrivacy(cfg, PrivacyLocal)
|
||||
if err != nil || len(c.conns) != 1 || !strings.Contains(c.conns[0].cfg.BaseURL, "localhost") {
|
||||
t.Fatalf("lokal: %v", err)
|
||||
}
|
||||
cfg.Fallbacks = nil
|
||||
if _, err := NewWithPrivacy(cfg, PrivacyLocal); err == nil {
|
||||
t.Fatal("ohne lokalen Endpunkt muss es scheitern")
|
||||
}
|
||||
if c, err := NewWithPrivacy(cfg, PrivacyAll); err != nil || len(c.conns) != 1 {
|
||||
t.Fatalf("alle: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastRequestRemembered(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
c, err := New(domain.LLMConfig{BaseURL: srv.URL + "/v1", Model: "m", MaxTokens: 10, TimeoutSec: 5})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.CompleteResult(context.Background(), []Message{{Role: "system", Content: "sei knapp"}, {Role: "user", Content: "uptime?"}}, Opts{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := LastRequest()
|
||||
if r == nil || r.Model != "m" || len(r.Messages) != 2 || r.Messages[1].Content != "uptime?" {
|
||||
t.Fatalf("letzte Anfrage: %+v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package ui
|
||||
|
||||
// KI-Datenschutz: welche KI eine Verbindung bekommen darf, und was zuletzt
|
||||
// an die KI ging.
|
||||
//
|
||||
// - Einstellung (geht mit dem Sync): alle Anbieter, nur lokale (eigenes
|
||||
// Netz) oder KI aus.
|
||||
// - Tag an einer Verbindung, z. B. für Kundennetze: „ki-lokal“ oder
|
||||
// „ki-aus“ (englisch „local-ai“, „no-ai“). Ein Tag macht strenger, nie
|
||||
// lockerer als die Einstellung.
|
||||
// - Palette: „Letzte KI-Anfrage ansehen“ zeigt genau den Text, der
|
||||
// zuletzt hinausging (nach dem Entfernen von Geheimnissen).
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/agent"
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/llm"
|
||||
"github.com/db9979/sshtermy/internal/sessionlog"
|
||||
)
|
||||
|
||||
// tagPrivacy: Stufe aus den Tags einer Verbindung.
|
||||
func tagPrivacy(c domain.Connection) string {
|
||||
level := llm.PrivacyAll
|
||||
for _, t := range c.Tags {
|
||||
switch strings.ToLower(strings.TrimSpace(t)) {
|
||||
case "ki-aus", "keine-ki", "no-ai", "ai-off":
|
||||
level = llm.Stricter(level, llm.PrivacyOff)
|
||||
case "ki-lokal", "local-ai", "ai-local":
|
||||
level = llm.Stricter(level, llm.PrivacyLocal)
|
||||
}
|
||||
}
|
||||
return level
|
||||
}
|
||||
|
||||
// aiLevel: die strengste Stufe aus Einstellung und allen beteiligten Verbindungen.
|
||||
func (a *App) aiLevel(conns ...domain.Connection) string {
|
||||
level := a.st.LLM().Privacy
|
||||
for _, c := range conns {
|
||||
level = llm.Stricter(level, tagPrivacy(c))
|
||||
}
|
||||
return level
|
||||
}
|
||||
|
||||
// agentClientFor: KI-Zugang unter Beachtung des Datenschutzes.
|
||||
func (a *App) agentClientFor(conns ...domain.Connection) (*agent.Agent, error) {
|
||||
c, err := llm.NewWithPrivacy(a.st.LLM(), a.aiLevel(conns...))
|
||||
if errors.Is(err, llm.ErrAIOff) {
|
||||
if a.st.LLM().Privacy == llm.PrivacyOff {
|
||||
return nil, errors.New(i18n.T("KI ist ausgeschaltet (Einstellungen › KI › KI-Datenschutz)"))
|
||||
}
|
||||
return nil, errors.New(i18n.T("KI ist für diese Verbindung aus (Tag ki-aus)"))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &agent.Agent{C: c}, nil
|
||||
}
|
||||
|
||||
// logConns: Verbindungen zu Protokollen (für die strengste Stufe).
|
||||
func (a *App) logConns(list []*sessionlog.Log) []domain.Connection {
|
||||
var out []domain.Connection
|
||||
for _, l := range list {
|
||||
if c, ok := a.st.Connection(l.ConnID); ok {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func privacyLabel(level string) string {
|
||||
switch level {
|
||||
case llm.PrivacyLocal:
|
||||
return i18n.T("nur lokale KI")
|
||||
case llm.PrivacyOff:
|
||||
return i18n.T("KI aus")
|
||||
}
|
||||
return i18n.T("alle Anbieter")
|
||||
}
|
||||
|
||||
func (a *App) cyclePrivacy(dir int) tea.Cmd {
|
||||
levels := []string{llm.PrivacyAll, llm.PrivacyLocal, llm.PrivacyOff}
|
||||
cur := -1
|
||||
for i, l := range levels {
|
||||
if l == a.st.LLM().Privacy {
|
||||
cur = i
|
||||
}
|
||||
}
|
||||
next := levels[cycleIndex(cur, len(levels), dir)]
|
||||
cfg := a.st.LLM()
|
||||
cfg.Privacy = next
|
||||
if err := a.st.SetLLM(cfg); err != nil {
|
||||
a.flashErr(i18n.T("Einstellung nicht gespeichert: ") + err.Error())
|
||||
return nil
|
||||
}
|
||||
a.flash(i18n.T("KI-Datenschutz: ") + privacyLabel(next))
|
||||
return nil
|
||||
}
|
||||
|
||||
// lastRequestModal: was zuletzt an die KI ging.
|
||||
func (a *App) lastRequestModal() *modal {
|
||||
r := llm.LastRequest()
|
||||
if r == nil {
|
||||
return textModal(i18n.T("Letzte KI-Anfrage"), []string{i18n.T("Seit dem Start ging noch nichts an eine KI.")})
|
||||
}
|
||||
where := i18n.T("im eigenen Netz")
|
||||
if !llm.IsLocalEndpoint("http://" + r.Host) {
|
||||
where = i18n.T("außerhalb des eigenen Netzes")
|
||||
}
|
||||
lines := []string{
|
||||
fmt.Sprintf("%s · %s · %s (%s)", r.At.Format("15:04:05"), r.Model, r.Host, where),
|
||||
i18n.T("Passwörter, Keys und Tokens werden vor dem Senden entfernt."),
|
||||
"",
|
||||
}
|
||||
for _, m := range r.Messages {
|
||||
lines = append(lines, "── "+m.Role+" ──")
|
||||
lines = append(lines, strings.Split(strings.TrimRight(m.Content, "\n"), "\n")...)
|
||||
lines = append(lines, "")
|
||||
}
|
||||
return textModal(i18n.T("Letzte KI-Anfrage"), lines)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/llm"
|
||||
)
|
||||
|
||||
// Tags an Verbindungen machen den KI-Datenschutz strenger, nie lockerer.
|
||||
func TestAIPrivacyTagsAndSetting(t *testing.T) {
|
||||
a := newPaletteTestApp(t)
|
||||
cfg := domain.LLMConfig{Provider: domain.ProviderOpenAI, BaseURL: "https://api.openai.com/v1", APIKey: "sk-x", Model: "gpt", MaxTokens: 10,
|
||||
Fallbacks: []domain.LLMBackup{{BaseURL: "http://localhost:11434/v1", Model: "qwen"}}}
|
||||
if err := a.st.SetLLM(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kunde := domain.Connection{Alias: "kunde", Tags: []string{"KI-Lokal"}}
|
||||
geheim := domain.Connection{Alias: "geheim", Tags: []string{"no-ai"}}
|
||||
if a.aiLevel() != llm.PrivacyAll || a.aiLevel(kunde) != llm.PrivacyLocal || a.aiLevel(kunde, geheim) != llm.PrivacyOff {
|
||||
t.Fatalf("Stufen: %q %q %q", a.aiLevel(), a.aiLevel(kunde), a.aiLevel(kunde, geheim))
|
||||
}
|
||||
if _, err := a.agentClientFor(geheim); err == nil || !strings.Contains(err.Error(), "ki-aus") {
|
||||
t.Fatalf("ki-aus: %v", err)
|
||||
}
|
||||
if _, err := a.agentClientFor(kunde); err != nil {
|
||||
t.Fatalf("lokal mit Ollama-Ersatz: %v", err)
|
||||
}
|
||||
a.cyclePrivacy(1) // alle → lokal
|
||||
if a.st.LLM().Privacy != llm.PrivacyLocal || a.aiLevel() != llm.PrivacyLocal {
|
||||
t.Fatalf("Einstellung: %q", a.st.LLM().Privacy)
|
||||
}
|
||||
a.cyclePrivacy(1) // lokal → aus
|
||||
if _, err := a.agentClientFor(); err == nil || !strings.Contains(err.Error(), "ausgeschaltet") {
|
||||
t.Fatalf("aus: %v", err)
|
||||
}
|
||||
if m := a.lastRequestModal(); m == nil {
|
||||
t.Fatal("Ansicht fehlt")
|
||||
}
|
||||
}
|
||||
+14
-11
@@ -61,6 +61,7 @@ const (
|
||||
scrSSHKeyForm // SSH-Schlüssel erzeugen / übertragen (sshkey.go)
|
||||
scrRelayForm // Vermittler koppeln (relay.go)
|
||||
scrMasterForm // Master-Passwort ändern, DPAPI (master.go)
|
||||
scrBackupForm // Gesamtsicherung speichern/einspielen (fullbackup.go)
|
||||
scrColors // Farben anpassen (colors.go)
|
||||
scrTeam // Team-Freigabe: Auswahl bzw. Vorschau (team.go)
|
||||
scrTeamForm // Team-Freigabe: Passwort, Datei, Optionen
|
||||
@@ -71,14 +72,16 @@ const (
|
||||
|
||||
// App ist das Wurzel-Modell.
|
||||
type App struct {
|
||||
inputLog *os.File // nur mit SSHTERMY_DEBUG=1
|
||||
debugForced bool // --debug: Debug-Protokoll für diesen Start (debugreport.go)
|
||||
st *store.Store
|
||||
hostKeys *sshx.HostKeyStore
|
||||
s Styles
|
||||
w, h int
|
||||
scr screen
|
||||
events chan tea.Msg
|
||||
inputLog *os.File // nur mit SSHTERMY_DEBUG=1
|
||||
debugForced bool // --debug: Debug-Protokoll für diesen Start (debugreport.go)
|
||||
startNotice string // Meldung nach dem Entsperren (fullbackup.go)
|
||||
startNoticeOK bool
|
||||
st *store.Store
|
||||
hostKeys *sshx.HostKeyStore
|
||||
s Styles
|
||||
w, h int
|
||||
scr screen
|
||||
events chan tea.Msg
|
||||
|
||||
unlock unlockState
|
||||
mgr managerState
|
||||
@@ -480,7 +483,7 @@ func (a *App) update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if a.pick != nil {
|
||||
return a, a.pickerKey(k)
|
||||
}
|
||||
if a.keys.is(actHelp, k.String()) && (a.pal != nil || a.scr == scrConnForm || a.scr == scrSettings || a.scr == scrTunnelForm || a.scr == scrImport || a.scr == scrKeys || a.scr == scrBroadcast || a.scr == scrScan || a.scr == scrQuickForm || a.scr == scrMonitorForm || a.scr == scrHighlightForm || a.scr == scrScheduleForm || a.scr == scrRulesForm || a.scr == scrKeyForm || a.scr == scrSSHKeyForm || a.scr == scrRelayForm || a.scr == scrMasterForm) {
|
||||
if a.keys.is(actHelp, k.String()) && (a.pal != nil || a.scr == scrConnForm || a.scr == scrSettings || a.scr == scrTunnelForm || a.scr == scrImport || a.scr == scrKeys || a.scr == scrBroadcast || a.scr == scrScan || a.scr == scrQuickForm || a.scr == scrMonitorForm || a.scr == scrHighlightForm || a.scr == scrScheduleForm || a.scr == scrRulesForm || a.scr == scrKeyForm || a.scr == scrSSHKeyForm || a.scr == scrRelayForm || a.scr == scrMasterForm || a.scr == scrBackupForm) {
|
||||
a.modal = a.helpModal()
|
||||
return a, nil
|
||||
}
|
||||
@@ -521,7 +524,7 @@ func (a *App) update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return a, a.updateUnlock(msg)
|
||||
case scrManager:
|
||||
return a, a.updateManager(msg)
|
||||
case scrConnForm, scrSettings, scrTunnelForm, scrQuickForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrRulesForm, scrKeyForm, scrSSHKeyForm, scrRelayForm, scrMasterForm:
|
||||
case scrConnForm, scrSettings, scrTunnelForm, scrQuickForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrRulesForm, scrKeyForm, scrSSHKeyForm, scrRelayForm, scrMasterForm, scrBackupForm:
|
||||
return a, a.updateForm(msg)
|
||||
case scrTerminal:
|
||||
return a, a.updateTerminal(msg)
|
||||
@@ -633,7 +636,7 @@ func (a *App) View() tea.View {
|
||||
k = append(k, [2]string{"Strg+D", i18n.T("löschen")})
|
||||
}
|
||||
body = a.frame(a.viewForm(), append(k, [2]string{"Esc", i18n.T("abbrechen")}))
|
||||
case scrConnForm, scrKeyForm, scrSSHKeyForm, scrRelayForm, scrMasterForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrRulesForm:
|
||||
case scrConnForm, scrKeyForm, scrSSHKeyForm, scrRelayForm, scrMasterForm, scrBackupForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrRulesForm:
|
||||
body = a.frame(a.viewForm(), [][2]string{{"Tab", i18n.T("weiter")}, {"←/→", i18n.T("wählen")}, {"Strg+S", i18n.T("speichern")}, {"Esc", i18n.T("abbrechen")}})
|
||||
case scrQuickForm:
|
||||
body = a.frame(a.viewForm(), [][2]string{{"Tab", i18n.T("weiter")}, {"Strg+R", i18n.T("Vorbelegung")}, {"Strg+S", i18n.T("speichern")}, {"Esc", i18n.T("abbrechen")}})
|
||||
|
||||
@@ -304,7 +304,7 @@ func hasProfile(c domain.Connection) bool {
|
||||
// bcReview startet die KI-Prüfung für alle gewählten Hosts.
|
||||
func (a *App) bcReview() tea.Cmd {
|
||||
b := a.bc
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(b.chosen()...)
|
||||
if err != nil {
|
||||
a.flashErr(i18n.T("KI-Prüfung: ") + err.Error())
|
||||
return nil
|
||||
|
||||
@@ -201,7 +201,7 @@ func (a *App) explainFailure(s *session) tea.Cmd {
|
||||
a.panelOpened(withPanel(s, panelAsk))
|
||||
a.resize(s)
|
||||
q := &s.ask
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
q.err = err.Error()
|
||||
return nil
|
||||
|
||||
@@ -49,7 +49,7 @@ func (a *App) diagnoseWith(s *session, text, what string) tea.Cmd {
|
||||
a.panelOpened(withPanel(s, panelAsk))
|
||||
a.resize(s)
|
||||
q := &s.ask
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
q.err = err.Error()
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/debuglog"
|
||||
"github.com/db9979/sshtermy/internal/fullbackup"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/vault"
|
||||
"github.com/db9979/sshtermy/internal/version"
|
||||
)
|
||||
|
||||
// Gesamtsicherung: der ganze Datenordner (Store, Protokolle, Sicherungen,
|
||||
// known_hosts, Einstellungen) als eine verschlüsselte Datei, zum Umzug auf
|
||||
// einen neuen Rechner oder als Sicherung. Verschlüsselt wird mit dem
|
||||
// Master-Passwort (internal/fullbackup).
|
||||
|
||||
func defaultBackupPath() string {
|
||||
return filepath.Join(exportDir(), "sshtermy-sicherung-"+time.Now().Format("2006-01-02")+fullbackup.Ext)
|
||||
}
|
||||
|
||||
func (a *App) openBackupForm(restore bool) tea.Cmd {
|
||||
f := &form{title: i18n.T("Gesamtsicherung speichern")}
|
||||
id := "export"
|
||||
if restore {
|
||||
id = "import"
|
||||
f.title = i18n.T("Gesamtsicherung einspielen")
|
||||
f.text("file", i18n.T("Datei"), "", i18n.T("Pfad zur .sshtbak-Datei"))
|
||||
f.secret("pw", i18n.T("Master-Passwort der Sicherung"), "", i18n.T("das Passwort, mit dem die Sicherung gespeichert wurde"))
|
||||
} else {
|
||||
f.text("file", i18n.T("Datei"), defaultBackupPath(), i18n.T("enthält alle Verbindungen, Schlüssel, Protokolle und Einstellungen"))
|
||||
f.secret("pw", i18n.T("Master-Passwort"), "", i18n.T("die Sicherung wird damit verschlüsselt"))
|
||||
}
|
||||
a.returnToTerminal = a.scr == scrTerminal
|
||||
a.form, a.formID, a.scr = f, id, scrBackupForm
|
||||
return f.setFocus(0)
|
||||
}
|
||||
|
||||
func (a *App) saveBackupForm() (tea.Cmd, error) {
|
||||
f := a.form
|
||||
file := expandHome(f.str("file"))
|
||||
pw := []byte(f.raw("pw"))
|
||||
defer vault.Wipe(pw)
|
||||
if file == "" {
|
||||
return nil, errors.New(i18n.T("Datei fehlt"))
|
||||
}
|
||||
if len(pw) == 0 {
|
||||
return nil, errors.New(i18n.T("Master-Passwort fehlt"))
|
||||
}
|
||||
if a.formID == "import" {
|
||||
return a.prepareRestore(file, pw)
|
||||
}
|
||||
if err := a.st.V.CheckPassword(pw); err != nil {
|
||||
return nil, errors.New(i18n.T("Master-Passwort stimmt nicht"))
|
||||
}
|
||||
if !strings.HasSuffix(strings.ToLower(file), fullbackup.Ext) {
|
||||
file += fullbackup.Ext
|
||||
}
|
||||
m, err := writeBackup(a.st.Dir, file, pw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.flashOK(fmt.Sprintf(i18n.T("Gesamtsicherung gespeichert: %s (%d Dateien)"), file, m.Files))
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func writeBackup(dir, file string, pw []byte) (fullbackup.Manifest, error) {
|
||||
tmp := file + ".tmp"
|
||||
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return fullbackup.Manifest{}, err
|
||||
}
|
||||
m, err := fullbackup.Create(dir, pw, version.Version, out)
|
||||
if cerr := out.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, file)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp)
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
// prepareRestore entpackt die Sicherung neben den Datenordner, prüft das
|
||||
// Passwort am enthaltenen Store und fragt dann nach. Erst der Neustart
|
||||
// tauscht die Ordner (fullbackup.ApplyPending in main).
|
||||
func (a *App) prepareRestore(file string, pw []byte) (tea.Cmd, error) {
|
||||
dir := a.st.Dir
|
||||
check := func(vp string) error {
|
||||
v, err := vault.Open(vp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return v.CheckPassword(pw)
|
||||
}
|
||||
stage, m, err := fullbackup.Prepare(dir, file, pw, check)
|
||||
switch {
|
||||
case errors.Is(err, fullbackup.ErrWrongPassword), errors.Is(err, vault.ErrWrongPassword):
|
||||
return nil, errors.New(i18n.T("Passwort stimmt nicht oder die Datei ist beschädigt"))
|
||||
case errors.Is(err, fullbackup.ErrNotBackup):
|
||||
return nil, errors.New(i18n.T("Keine sshTermy-Sicherung"))
|
||||
case err != nil:
|
||||
return nil, err
|
||||
}
|
||||
when := m.Created.Local().Format("02.01.2006 15:04")
|
||||
body := fmt.Sprintf(i18n.T("Sicherung vom %s (v%s, %s, %d Dateien).\n\nAlle Daten hier werden durch die Sicherung ersetzt. Der bisherige Stand bleibt im Ordner\n%s.vorher-…\n\nsshTermy startet dafür neu, offene Sitzungen werden getrennt."), when, m.Version, m.OS, m.Files, dir)
|
||||
a.modal = confirmModal(i18n.T("Gesamtsicherung einspielen"), body, func() tea.Cmd {
|
||||
if err := fullbackup.MarkPending(dir, stage); err != nil {
|
||||
os.RemoveAll(stage)
|
||||
a.flashErr(err.Error())
|
||||
return nil
|
||||
}
|
||||
_ = debuglog.Set(false) // Windows: offene Datei verhindert das Umbenennen
|
||||
return a.doRestart()
|
||||
})
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// StartNotice: Meldung nach dem Entsperren zeigen (z. B. Gesamtsicherung
|
||||
// beim Start eingespielt, cmd/sshtermy).
|
||||
func (a *App) StartNotice(ok bool, s string) { a.startNotice, a.startNoticeOK = s, ok }
|
||||
|
||||
func (a *App) showStartNotice() {
|
||||
if a.startNotice == "" {
|
||||
return
|
||||
}
|
||||
if a.startNoticeOK {
|
||||
a.flashOK(a.startNotice)
|
||||
} else {
|
||||
a.flashErr(a.startNotice)
|
||||
}
|
||||
a.startNotice = ""
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/fullbackup"
|
||||
)
|
||||
|
||||
func TestFullBackupForms(t *testing.T) {
|
||||
a := newPaletteTestApp(t)
|
||||
a.pal = nil
|
||||
out := filepath.Join(t.TempDir(), "sich")
|
||||
open := func(label string) {
|
||||
t.Helper()
|
||||
a.openPalette()
|
||||
a.palEnter("settings/io")
|
||||
it, ok := hasLabel(a.paletteItems(), label)
|
||||
if !ok {
|
||||
t.Fatalf("%q fehlt: %v", label, labels(a.paletteItems()))
|
||||
}
|
||||
a.pal = nil
|
||||
it.run()
|
||||
if a.scr != scrBackupForm || a.form == nil {
|
||||
t.Fatal("Formular nicht offen")
|
||||
}
|
||||
}
|
||||
set := func(k, v string) { a.form.get(k).in.SetValue(v) }
|
||||
|
||||
open("Gesamtsicherung speichern")
|
||||
set("file", out)
|
||||
set("pw", "falsch!!")
|
||||
if _, err := a.saveBackupForm(); err == nil {
|
||||
t.Fatal("falsches Passwort angenommen")
|
||||
}
|
||||
set("pw", "correct horse")
|
||||
if _, err := a.saveBackupForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := out + fullbackup.Ext
|
||||
if st, err := os.Stat(file); err != nil || st.Size() == 0 {
|
||||
t.Fatalf("Sicherung fehlt: %v", err)
|
||||
}
|
||||
|
||||
open("Gesamtsicherung einspielen")
|
||||
set("file", file)
|
||||
set("pw", "falsch!!")
|
||||
if _, err := a.saveBackupForm(); err == nil {
|
||||
t.Fatal("falsches Passwort beim Einspielen angenommen")
|
||||
}
|
||||
set("pw", "correct horse")
|
||||
if _, err := a.saveBackupForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.modal == nil || a.modal.onYes == nil {
|
||||
t.Fatal("keine Rückfrage vor dem Ersetzen")
|
||||
}
|
||||
dir := a.st.Dir
|
||||
a.modal.onYes()
|
||||
if !a.Restart() {
|
||||
t.Fatal("kein Neustart nach dem Einspielen")
|
||||
}
|
||||
old, err := fullbackup.ApplyPending(dir)
|
||||
if err != nil || old == "" {
|
||||
t.Fatalf("ApplyPending: %q %v", old, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "store.vault")); err != nil {
|
||||
t.Fatal("Store fehlt nach dem Einspielen")
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -334,7 +334,7 @@ func (a *App) toggleSessionLog() tea.Cmd {
|
||||
}
|
||||
|
||||
func (a *App) summarizeLogs(list []*sessionlog.Log, id, title, key string) tea.Cmd {
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(a.logConns(list)...)
|
||||
if err != nil {
|
||||
a.flashErr("KI: " + err.Error())
|
||||
return nil
|
||||
|
||||
@@ -863,7 +863,7 @@ func (a *App) updateForm(msg tea.Msg) tea.Cmd {
|
||||
}
|
||||
var err error
|
||||
var next tea.Cmd
|
||||
wasKey := a.scr == scrKeyForm || a.scr == scrSSHKeyForm || a.scr == scrRelayForm
|
||||
wasKey := a.scr == scrKeyForm || a.scr == scrSSHKeyForm || a.scr == scrRelayForm || a.scr == scrBackupForm
|
||||
switch a.scr {
|
||||
case scrKeyForm:
|
||||
next, err = a.saveKeyFix()
|
||||
@@ -873,6 +873,8 @@ func (a *App) updateForm(msg tea.Msg) tea.Cmd {
|
||||
next, err = a.startRelayPair()
|
||||
case scrMasterForm:
|
||||
err = a.saveMasterForm()
|
||||
case scrBackupForm:
|
||||
next, err = a.saveBackupForm()
|
||||
case scrConnForm:
|
||||
err = a.saveConn()
|
||||
case scrTunnelForm:
|
||||
|
||||
+11
-1
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/fullbackup"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/relay"
|
||||
"github.com/db9979/sshtermy/internal/sshx"
|
||||
@@ -434,7 +435,7 @@ var palMenus = []palMenu{
|
||||
var palSubMenus = []palMenu{
|
||||
{"settings/ki", "ai", "KI", "Endpunkt, Ersatz-Anbieter, Status", "ai llm ki"},
|
||||
{"settings/relay", "relay", "Vermittler", "Server hinter NAT/Firewall", "relay vermittler"},
|
||||
{"settings/io", "import", "Import / Export", "ssh-config, PuTTY, Ansible, CSV", "import export csv"},
|
||||
{"settings/io", "import", "Import / Export", "ssh-config, PuTTY, Ansible, CSV, Gesamtsicherung", "import export csv backup sicherung umzug"},
|
||||
}
|
||||
|
||||
// palParent: übergeordnetes Menü ("settings/ki" → "settings", "settings" → "").
|
||||
@@ -503,6 +504,9 @@ func (a *App) palFolder(id string) palItem {
|
||||
return palItem{}
|
||||
}
|
||||
|
||||
// inMenu: Eintrag in ein anderes Untermenü legen.
|
||||
func inMenu(menu string, it palItem) palItem { it.menu = menu; return it }
|
||||
|
||||
// cycleIndex: Position von cur in n Werten, um dir verschoben (rundherum).
|
||||
// Unbekannter Wert: vorwärts beim ersten, rückwärts beim letzten beginnen.
|
||||
func cycleIndex(cur, n, dir int) int {
|
||||
@@ -628,12 +632,18 @@ func (a *App) palMenuItems() []palItem {
|
||||
|
||||
palItem{group: pgSetSetup, menu: "settings/ki", icon: ic("ai"), label: i18n.T("KI-Einstellungen"), hint: "s", keys: "ai llm", run: func() tea.Cmd { return a.openSettings() }},
|
||||
palItem{group: pgSetSetup, menu: "settings/ki", icon: ic("ai"), label: i18n.T("KI-Ersatz-Anbieter (Ollama, OpenAI, Claude)"), keys: "ai llm fallback ollama openai claude", run: func() tea.Cmd { return a.openFallbackForm() }},
|
||||
inMenu("settings/ki", palCycle(pgSetSetup, ic("ai"), i18n.T("KI-Datenschutz"), privacyLabel(a.st.LLM().Privacy),
|
||||
"ki ai datenschutz privacy lokal local cloud aus off kunde", func(dir int) tea.Cmd { return a.cyclePrivacy(dir) })),
|
||||
palItem{group: pgSetSetup, menu: "settings/ki", icon: ic("ai"), label: i18n.T("Letzte KI-Anfrage ansehen"), hint: i18n.T("was ging hinaus"),
|
||||
keys: "ki ai datenschutz privacy anfrage request prompt gesendet", run: func() tea.Cmd { a.modal = a.lastRequestModal(); return nil }},
|
||||
palItem{group: pgSetSetup, menu: "settings/ki", icon: ic("llmcheck"), label: i18n.T("KI-Status: Endpunkt erreichbar? jetzt prüfen"), keys: "ai llm status",
|
||||
run: func() tea.Cmd { a.openLLMStatus(); return a.llmProbeCmd() }},
|
||||
palItem{group: pgSetSetup, menu: "settings/relay", icon: ic("relay"), label: i18n.T("Systeme über Vermittler (Server hinter NAT/Firewall)"), keys: "relay", run: func() tea.Cmd { return a.openRelaySystems() }},
|
||||
palItem{group: pgSetSetup, menu: "settings/relay", icon: ic("relay"), label: i18n.T("Vermittler koppeln / verwalten (eigener oder Speech on DGX Spark)"), keys: "relay", run: func() tea.Cmd { return a.openRelayManage() }},
|
||||
palItem{group: pgSetSetup, menu: "settings/io", icon: ic("import"), label: i18n.T("Verbindungen importieren (ssh-config, PuTTY, MobaXterm, Ansible, CSV)"), hint: a.keys.label(actImport), keys: "import netbox", run: func() tea.Cmd { return a.openImport() }},
|
||||
palItem{group: pgSetSetup, menu: "settings/io", icon: ic("export"), label: i18n.T("Verbindungen als CSV exportieren (ohne Passwörter)"), hint: ".csv", keys: "export csv excel", run: func() tea.Cmd { return a.exportConnsCSV() }},
|
||||
palItem{group: pgSetSetup, menu: "settings/io", icon: ic("export"), label: i18n.T("Gesamtsicherung speichern (für Umzug/Sicherung) …"), hint: i18n.T("alles, verschlüsselt"), keys: "backup sicherung umzug neuer rechner migrate", run: func() tea.Cmd { return a.openBackupForm(false) }},
|
||||
palItem{group: pgSetSetup, menu: "settings/io", icon: ic("import"), label: i18n.T("Gesamtsicherung einspielen …"), hint: fullbackup.Ext, keys: "restore backup sicherung umzug wiederherstellen migrate", run: func() tea.Cmd { return a.openBackupForm(true) }},
|
||||
|
||||
palItem{group: pgHelp, menu: "help", icon: ic("help"), label: i18n.T("Tastenkürzel anzeigen"), hint: a.keys.label(actHelp), keys: "help keys", run: func() tea.Cmd { a.modal = a.helpModal(); return nil }},
|
||||
palItem{group: pgHelp, menu: "help", icon: ic("tour"), label: i18n.T("Einführungstour"), hint: i18n.T("5 Schritte"), keys: "tour", run: func() tea.Cmd { a.modal = a.tourModal(); return nil }},
|
||||
|
||||
@@ -286,7 +286,7 @@ func (a *App) requestStep(s *session) tea.Cmd {
|
||||
g.err = i18n.T("Maximal 40 Schritte pro Ziel. Ziel neu setzen (x).")
|
||||
return nil
|
||||
}
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
g.err = err.Error()
|
||||
return nil
|
||||
@@ -1123,7 +1123,7 @@ func (a *App) startAsk(s *session, text string) tea.Cmd {
|
||||
a.panelOpened(withPanel(s, panelAsk))
|
||||
a.resize(s)
|
||||
q := &s.ask
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
q.err = err.Error()
|
||||
return nil
|
||||
|
||||
@@ -160,7 +160,7 @@ type adaptMsg struct {
|
||||
|
||||
// startAdapt lässt die KI einen Befehl für das System dieser Sitzung umschreiben.
|
||||
func (a *App) startAdapt(s *session, cmd string) tea.Cmd {
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
a.flashErr("KI: " + err.Error())
|
||||
return nil
|
||||
|
||||
@@ -29,7 +29,7 @@ func (a *App) reportLogs(list []*sessionlog.Log, title string) tea.Cmd {
|
||||
if len(list) == 0 {
|
||||
return nil
|
||||
}
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(a.logConns(list)...)
|
||||
if err != nil {
|
||||
a.flashErr("KI: " + err.Error())
|
||||
return nil
|
||||
|
||||
@@ -134,13 +134,8 @@ func (a *App) resize(s *session) {
|
||||
a.shareResized(s)
|
||||
}
|
||||
|
||||
func (a *App) agentClient() (*agent.Agent, error) {
|
||||
c, err := llm.New(a.st.LLM())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &agent.Agent{C: c}, nil
|
||||
}
|
||||
// agentClient: KI ohne Bezug zu einer Verbindung (nur die Einstellung zählt).
|
||||
func (a *App) agentClient() (*agent.Agent, error) { return a.agentClientFor() }
|
||||
|
||||
// ---------------------------------------------------------------- Tasten
|
||||
|
||||
@@ -453,7 +448,7 @@ func (a *App) fireGhost(s *session, seq int) tea.Cmd {
|
||||
if !ok || len(strings.TrimSpace(typed)) < 2 || agent.LooksLikeSecretPrompt(s.term.CursorLine()) {
|
||||
return nil
|
||||
}
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -486,7 +481,7 @@ func (a *App) followTick(s *session) tea.Cmd {
|
||||
if time.Since(s.lastFollow) < 5*time.Second {
|
||||
return nil
|
||||
}
|
||||
ag, err := a.agentClient()
|
||||
ag, err := a.agentClientFor(s.conn)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ func (a *App) updateUnlock(msg tea.Msg) tea.Cmd {
|
||||
a.showWhatsNew(u.setup)
|
||||
a.maybeTour(u.setup)
|
||||
a.checkCrash()
|
||||
a.showStartNotice()
|
||||
return tea.Batch(checkUpdate(), a.runSync(), a.restoreTabs())
|
||||
case tea.KeyPressMsg:
|
||||
if u.busy {
|
||||
|
||||
@@ -147,6 +147,8 @@ sudo apt update && sudo apt install sshtermy</pre></div>
|
||||
<div class="card"><h3>Aussehen & Tasten</h3><p>Neun Themes, darunter Matrix, Bernstein, Neon und zwei für Farbenblinde, eigene Farben, vier Symbol-Stile, jede Taste frei belegbar.</p></div>
|
||||
<div class="card"><h3>Barrierearm & Support</h3><p>Barrierearmer Modus ohne Animationen, mit Formen statt nur Farben. Debug-Protokoll für Fehlerberichte (<code>--debug</code>), bereinigt von Hosts, IPs und Passwörtern.</p></div>
|
||||
<div class="card"><h3>Bildschirmsperre</h3><p>Sofort sperren oder nach 5 bis 60 Minuten Leerlauf; Sitzungen laufen hinter der Sperre weiter. Master-Passwort und Windows-Anmeldung jederzeit änderbar.</p></div>
|
||||
<div class="card"><h3>Umzug auf neuen Rechner</h3><p>Eine verschlüsselte Datei enthält alles: Verbindungen, Schlüssel, Protokolle, Switch-Sicherungen und Einstellungen. Auf dem neuen Rechner einspielen, der alte Stand bleibt als Kopie.</p></div>
|
||||
<div class="card"><h3>KI-Datenschutz</h3><p>Alle Anbieter, nur lokale KI im eigenen Netz oder gar keine KI, global oder pro Verbindung per Tag. Genau sehen, was zuletzt hinausging.</p></div>
|
||||
</div>
|
||||
<div class="shots">
|
||||
<figure><img src="../bilder/02-manager.png" alt="Verbindungsmanager" loading="lazy"><figcaption>Verbindungsmanager</figcaption></figure>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -147,6 +147,8 @@ sudo apt update && sudo apt install sshtermy</pre></div>
|
||||
<div class="card"><h3>Look & keys</h3><p>Nine themes including Matrix, Amber, Neon and two for color blindness, your own colors, four icon styles, every shortcut can be changed.</p></div>
|
||||
<div class="card"><h3>Accessible & supportable</h3><p>Accessible mode without animations and with shapes instead of color only. Debug log for bug reports (<code>--debug</code>), saved cleaned of hosts, IPs and passwords.</p></div>
|
||||
<div class="card"><h3>Screen lock</h3><p>Lock now or after 5 to 60 minutes idle; sessions keep running behind the lock. Change the master password or the Windows sign-in any time.</p></div>
|
||||
<div class="card"><h3>Move to a new computer</h3><p>One encrypted file holds everything: connections, keys, logs, switch backups and settings. Restore it on the new machine, the old state stays as a copy.</p></div>
|
||||
<div class="card"><h3>AI privacy</h3><p>Allow all providers, only local AI on your own network, or no AI at all, globally or per connection by tag. See exactly what was last sent.</p></div>
|
||||
</div>
|
||||
<div class="shots">
|
||||
<figure><img src="bilder/02-manager.png" alt="Connection manager" loading="lazy"><figcaption>Connection manager</figcaption></figure>
|
||||
|
||||
@@ -182,7 +182,7 @@ export const de = {
|
||||
['_Palette_', '„Jetzt sperren“ · „Master-Passwort“ · „Gefahren-Check“'],
|
||||
]},
|
||||
{ t: 'Start & Tipps', ic: '$', rows: [
|
||||
['sshtermy --update', 'auf neueste Version'],
|
||||
['--update · backup', 'Update · alles sichern'],
|
||||
['--no-intro · --debug', 'ohne Startanimation · Debug-Protokoll'],
|
||||
['tsz / trz', 'Datei vom / zum Server (trzsz)'],
|
||||
['_Palette_', '„teilen“: Tab live zeigen'],
|
||||
@@ -368,7 +368,7 @@ export const en = {
|
||||
['_palette_', '“Lock now” · “Master password” · “Danger check”'],
|
||||
]},
|
||||
{ t: 'Start & tips', ic: '$', rows: [
|
||||
['sshtermy --update', 'update to the newest version'],
|
||||
['--update · backup', 'newest version · full backup'],
|
||||
['--no-intro · --debug', 'no start animation · debug log'],
|
||||
['tsz / trz', 'file from / to the server (trzsz)'],
|
||||
['_palette_', '“share”: show a tab live'],
|
||||
|
||||
Reference in new issue
Block a user