diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7eaf09..2305b49 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,9 +4,15 @@ name: ci on: pull_request: +# Neuer Push auf denselben PR: den alten Lauf abbrechen (spart Wartezeit) +concurrency: + group: ci-${{ github.head_ref || github.ref }} + cancel-in-progress: true + jobs: test: runs-on: ubuntu-latest + timeout-minutes: 30 # hängender Test bricht ab statt stundenlang zu laufen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 @@ -14,7 +20,9 @@ jobs: # neuester Patch von Go 1.27: Sicherheitskorrekturen der Standardbibliothek go-version: "1.27.x" check-latest: true - - run: go vet ./... && go test ./... + # zufällige Reihenfolge: Tests, die voneinander abhängen, fallen auf + # (bei Fehlern steht „-test.shuffle N“ im Protokoll zum Nachstellen) + - run: go vet ./... && go test -shuffle=on ./... - name: Terminal-Emulator (eigene Kopie in third_party/vt) run: cd third_party/vt && go test ./... - name: ANSI-Parser (eigene Kopie in third_party/ansi) @@ -39,6 +47,7 @@ jobs: # Datenrennen (Terminal-Emulator, Vermittler, SSH) früh finden race: runs-on: ubuntu-latest + timeout-minutes: 30 # hängender Test bricht ab statt stundenlang zu laufen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 @@ -52,6 +61,7 @@ jobs: # wahre Bedingungen. Abweichungen von der Vorgabe in staticcheck.conf. lint: runs-on: ubuntu-latest + timeout-minutes: 15 # hängender Test bricht ab statt stundenlang zu laufen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 @@ -71,6 +81,7 @@ jobs: matrix: os: [windows-latest, macos-latest] runs-on: ${{ matrix.os }} + timeout-minutes: 40 # hängender Test bricht ab statt stundenlang zu laufen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 @@ -90,6 +101,7 @@ jobs: # Bekannte Sicherheitslücken in Go und allen Bibliotheken, die wirklich aufgerufen werden vuln: runs-on: ubuntu-latest + timeout-minutes: 10 # hängender Test bricht ab statt stundenlang zu laufen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 @@ -101,6 +113,7 @@ jobs: # Parser für Daten von fremden Geräten kurz mit Zufallsdaten beschießen fuzz: runs-on: ubuntu-latest + timeout-minutes: 20 # hängender Test bricht ab statt stundenlang zu laufen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 @@ -121,6 +134,7 @@ jobs: # ubuntu-latest (26.04) holte apt-utils am 2026-11-11 stundenlang nur von # security.ubuntu.com, das der Runner nicht auflösen konnte. runs-on: ubuntu-24.04 + timeout-minutes: 15 # Paketquellen können hängen steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # Paketquellen können kurz nicht erreichbar sein (DNS beim Runner): diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000..6882f22 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,41 @@ +# Nachts: Dauerlauf (Lecks über lange Zeit) und längere Zufallstests als im +# PR. Fehler kommen als rote Markierung in Actions und per Mail von GitHub. +name: nightly + +on: + schedule: + - cron: "17 2 * * *" # 2:17 UTC, außerhalb der Stoßzeiten + workflow_dispatch: + inputs: + soak: + description: "Dauer des Dauerlaufs" + default: "45m" + +jobs: + soak: + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: "1.27.x" + check-latest: true + - run: make soak SOAK=${{ github.event.inputs.soak || '45m' }} + + fuzz-long: + runs-on: ubuntu-latest + timeout-minutes: 120 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: "1.27.x" + check-latest: true + - run: FUZZTIME=3m tools/fuzz/run.sh + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: failure() + with: + name: fuzz-funde-nachts + path: internal/**/testdata/fuzz/ + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index fdc7fb3..6f29f9b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ tools/dev/gifs/out/ *.test *.out /internal/ui/testdata/golden-actual/ +/cmd/sshtermy/sshtermy diff --git a/Makefile b/Makefile index 04500f6..ca6dd32 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ PKG := github.com/db9979/sshtermy/internal/version LDFLAGS := -s -w -X $(PKG).Version=$(VERSION) -X $(PKG).Commit=$(COMMIT) -X $(PKG).Date=$(DATE) -X $(PKG).UpdatePubKey=$(UPDATE_PUBKEY) TARGETS := windows/arm64 windows/386 windows/amd64 darwin/arm64 darwin/amd64 linux/amd64 linux/arm64 linux/arm linux/riscv64 -.PHONY: build test bench loadtest dist clean run golden handout fuzz vuln icon zusehen +.PHONY: build test check soak bench loadtest dist clean run golden handout fuzz vuln icon zusehen build: CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/sshtermy ./cmd/sshtermy @@ -15,6 +15,17 @@ test: cd third_party/vt && go test ./... cd third_party/ansi && go test ./... +# Vor dem Push: dasselbe wie die CI-Jobs test + lint (Format, vet, staticcheck, +# Tests in zufälliger Reihenfolge). Spart den Umweg über einen roten CI-Lauf. +check: + tools/check-fmt.sh + go vet ./... + # staticcheck mit dem Go dieses Projekts bauen (sonst versteht es neuere Sprachstände nicht) + GOTOOLCHAIN=$$(go env GOVERSION) go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 ./... + go test -shuffle=on ./... + cd third_party/vt && go test ./... + cd third_party/ansi && go test ./... + # Leistung: Terminal-Durchsatz, Speicher pro Tab, Manager mit 500 Verbindungen bench: go test -run '^$$' -bench . -benchtime 2s ./internal/termemu ./internal/ui ./internal/store @@ -23,6 +34,11 @@ bench: loadtest: SSHTERMY_LOAD=1 go test -run TestLoad1000 -v -count=1 ./internal/ui +# Dauerlauf: Tabs öffnen/schließen, Verbindungen abreißen, Lecks messen (nachts in CI) +SOAK ?= 10m +soak: + SSHTERMY_SOAK=$(SOAK) go test -run TestSoak -v -count=1 -timeout 0 ./internal/ui + # Fuzz-Tests (Parser für Daten von fremden Geräten), je FUZZTIME lang FUZZTIME ?= 20s fuzz: diff --git a/README.de.md b/README.de.md index f90f126..9000f3d 100644 --- a/README.de.md +++ b/README.de.md @@ -260,6 +260,8 @@ nicht als Beweis. Die Liste: Palette *Logwache: Meldungen* oder `w` im Log-Blick Schlüssel aus dem Store signiert; geänderte, gelöschte oder umsortierte Zeilen fallen auf. „Audit-Protokoll prüfen und speichern“ legt Prüfergebnis und lesbare Fassung in Downloads. Befehle mit führendem Leerzeichen erscheinen nur als „(privat)“ +- **Läuft nach Fehlern weiter:** Ein Fehler an einer Stelle (KI-Antwort, Geräteausgabe, Dateiansicht) wird abgefangen, + statt sshTermy samt allen Verbindungen zu beenden; **Selbstprüfung** mit `sshtermy doctor` oder Palette › Hilfe › Fehlersuche. - **Debug-Protokoll für Fehlerberichte** (Einstellungen oder `sshtermy --debug`): Verbindungsversuche, Abbrüche, Updates, KI-Anfragen und Sync als Ereignisse, nie Passwörter oder Bildschirminhalte. Hilfe › „Debug-Protokoll bereinigt speichern“ legt eine Kopie ohne Hosts, IPs und Benutzernamen in Downloads, fertig für ein GitHub-Issue. @@ -338,6 +340,7 @@ sshtermy --debug # Debug-Protokoll für diesen Start (debug.log im Konfigur sshtermy backup [datei] # Gesamtsicherung aller Daten (fragt das Master-Passwort) sshtermy restore # Gesamtsicherung einspielen (ersetzt alles, alter Ordner bleibt) sshtermy mcp # MCP-Server für KI-Clients (stdin/stdout), siehe „sshTermy als MCP-Server“ +sshtermy doctor # Selbstprüfung: Datenordner, Tresor, Schlüsselbund, SSH-Agent, Update-Signatur, Internet, Uhr ``` ## Bedienung @@ -742,11 +745,18 @@ Claude Desktop (`claude_desktop_config.json`): `{"mcpServers": {"sshtermy": {"co die Stelle im Programm (Stack). **Vor dem Speichern** werden alle Passwörter, Keys, Passphrasen und API-Keys aus dem Store wörtlich entfernt, dazu Hosts, Aliase, IP-Adressen, der Home-Ordner und typische Muster (`password=…`, `Bearer …`, Private Keys). -- Ein Absturz in der Oberfläche wird abgefangen: Das Terminal wird wiederhergestellt und sshTermy fragt, ob der +- **Absturzschutz:** Ein Fehler an einer Stelle (KI-Antwort auslesen, Geräteausgabe auswerten, Dateiansicht, + Hintergrundarbeit) beendet sshTermy nicht mehr samt allen Verbindungen. Der Fehler wird abgefangen, ein Bericht + geschrieben, oben rechts erscheint eine Meldung, und alles andere läuft weiter. Erst wenn sich Fehler häufen + (mehr als 5 in einer Minute), endet sshTermy wie früher. +- Ein Absturz in der Oberfläche, der sich nicht abfangen lässt: Das Terminal wird wiederhergestellt und sshTermy fragt, ob der Bericht als GitHub-Issue gemeldet werden soll. Bei einem harten Absturz (Prozess endet sofort) entsteht der Bericht nach dem nächsten Entsperren und erscheint in einem Dialog (`g` = als Issue melden, `o` = Bericht öffnen). - Nichts wird automatisch verschickt. Das Issue öffnet sich im Browser mit dem Bericht; du siehst alles vor dem - Absenden. Die letzten 10 Berichte bleiben liegen. Ausprobieren: `sshtermy -crash-test ui` (oder `cmd`, `fatal`). + Absenden. Die letzten 10 Berichte bleiben liegen. Ausprobieren: `sshtermy -crash-test ui` oder `cmd` (abgefangen, sshTermy läuft weiter) oder `fatal`. +- **Selbstprüfung** (Palette › Hilfe › Fehlersuche › „Selbstprüfung“ oder `sshtermy doctor`): Datenordner und Rechte, + Tresor, Schlüsselbund, SSH-Agent, Update-Signatur, Internet und Uhr (eine falsche Uhr lässt Einmal-Codes und + Zertifikate scheitern), Absturzberichte und in der App der KI-Endpunkt. `c` kopiert das Ergebnis für den Fehlerbericht. ### Auto-Update diff --git a/README.md b/README.md index b9e5a1c..677f2ac 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,8 @@ lets them in. The AI status report treats syslog lines as hints, not as proof. T AI requests (host/model only). Each line is chained and signed with a key from the store, so changes, deleted or reordered lines are detected. “Verify and save audit log” writes the check result and a readable copy to Downloads. Commands with a leading space appear only as “(privat)” +- **Keeps running after errors:** an error in one part (AI answer, device output, file view) is caught instead of + ending sshTermy with all connections; **self-check** with `sshtermy doctor` or palette › Help › Troubleshooting. - **Debug log for bug reports** (Settings or `sshtermy --debug`): connection attempts, drops, updates, AI requests and sync as events, never passwords or screen content. Help › “Save cleaned debug log” writes a copy without hosts, IPs and user names to Downloads, ready to attach to a GitHub issue. Very slow frames (over 50 ms) are logged there too @@ -327,6 +329,7 @@ sshtermy --debug # write a debug log for this run (debug.log in the config sshtermy backup [file] # full backup of all data (asks for the master password) sshtermy restore # restore a full backup (replaces all data, keeps the old folder) sshtermy mcp # MCP server for AI clients (stdin/stdout), see “sshTermy as MCP server” +sshtermy doctor # self-check: data folder, vault, keychain, SSH agent, update signature, internet, clock ``` ## Usage @@ -727,11 +730,18 @@ Claude Desktop (`claude_desktop_config.json`): `{"mcpServers": {"sshtermy": {"co stack trace. **Before saving**, all passwords, keys, passphrases and API keys from the store are removed verbatim, as are hosts, aliases, IP addresses, the home folder and typical patterns (`password=…`, `Bearer …`, private keys). -- A crash in the interface is caught: the terminal is restored and sshTermy asks whether to report it as a +- **Crash protection:** an error in one part (reading an AI answer, parsing device output, the file view, a + background task) no longer ends sshTermy and all your connections. The error is caught, a report is written, + a message appears top right, and everything else keeps running. Only if errors pile up (more than 5 in a + minute) does sshTermy end as before. +- A crash in the interface that cannot be caught: the terminal is restored and sshTermy asks whether to report it as a GitHub issue. A hard crash (the process ends immediately) is turned into a report after the next unlock and shown in a dialog (`g` = report as issue, `o` = open report). - Nothing is sent automatically. The issue opens in the browser with the report pre-filled; you see everything - before you submit. The last 10 reports are kept. Try it: `sshtermy -crash-test ui` (or `cmd`, `fatal`). + before you submit. The last 10 reports are kept. Try it: `sshtermy -crash-test ui` or `cmd` (caught, sshTermy keeps running) or `fatal`. +- **Self-check** (palette › Help › Troubleshooting › “Self-check” or `sshtermy doctor`): data folder and permissions, + vault, keychain, SSH agent, update signature, internet and clock (a wrong clock breaks one-time codes and + certificates), crash reports and, in the app, the AI endpoint. `c` copies the result for a bug report. ### Auto-update diff --git a/cmd/sshtermy/doctorcmd.go b/cmd/sshtermy/doctorcmd.go new file mode 100644 index 0000000..f7d2ce1 --- /dev/null +++ b/cmd/sshtermy/doctorcmd.go @@ -0,0 +1,45 @@ +package main + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/charmbracelet/x/term" + + "github.com/db9979/sshtermy/internal/doctor" + "github.com/db9979/sshtermy/internal/i18n" +) + +// runDoctor: „sshtermy doctor“ prüft die Umgebung ohne Oberfläche und ohne +// Master-Passwort. 0 = in Ordnung (auch mit Hinweisen), 1 = Probleme. +func runDoctor(dir string) int { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + fmt.Println(i18n.T("sshTermy-Selbstprüfung …")) + rs := doctor.Run(ctx, doctor.Env{Dir: dir, Extra: []doctor.Check{checkTerminal}}) + fmt.Print("\n" + doctor.Format(rs)) + if doctor.Worst(rs) == doctor.Fail { + return 1 + } + return 0 +} + +// checkTerminal: Farben und Größe des Terminals, in dem sshtermy läuft. +func checkTerminal(context.Context) doctor.Result { + name := i18n.T("Terminal") + t, ct := os.Getenv("TERM"), os.Getenv("COLORTERM") + if !term.IsTerminal(os.Stdout.Fd()) { + return doctor.Result{Name: name, Status: doctor.Info, Detail: i18n.T("Ausgabe ist kein Terminal (umgeleitet)")} + } + w, h, _ := term.GetSize(os.Stdout.Fd()) + d := fmt.Sprintf("%dx%d, TERM=%s", w, h, t) + if ct != "" { + d += ", COLORTERM=" + ct + } + if w > 0 && (w < 80 || h < 20) { + return doctor.Result{Name: name, Status: doctor.Warn, Detail: d + i18n.T(" (kleiner als 80×20: manches wird gekürzt)")} + } + return doctor.Result{Name: name, Status: doctor.OK, Detail: d} +} diff --git a/cmd/sshtermy/keep.go b/cmd/sshtermy/keep.go index f86d974..a4a0dad 100644 --- a/cmd/sshtermy/keep.go +++ b/cmd/sshtermy/keep.go @@ -17,6 +17,7 @@ import ( "github.com/db9979/sshtermy/internal/crash" "github.com/db9979/sshtermy/internal/detach" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/store" "github.com/db9979/sshtermy/internal/ui" "github.com/db9979/sshtermy/internal/update" @@ -130,6 +131,7 @@ func runKeepServe(dir string, noIntro, debug bool) int { scr.Attach(c, i18n.T("sshTermy wurde in einem anderen Fenster angehängt.")) // Send wartet, bis die Oberfläche läuft: daher nebenher go func() { + defer safe.Recover("cmd/sshtermy/keep.go") if again { p.Send(tea.WindowSizeMsg{Width: cols, Height: rows}) p.Send(tea.ClearScreen()) // neues Fenster: alles neu zeichnen @@ -137,6 +139,7 @@ func runKeepServe(dir string, noIntro, debug bool) int { p.Send(tea.FocusMsg{}) }() go func() { + defer safe.Recover("cmd/sshtermy/keep.go") for { ev, err := c.Read() if err != nil { @@ -156,6 +159,7 @@ func runKeepServe(dir string, noIntro, debug bool) int { } serve(f.c, f.cols, f.rows, false) go func() { + defer safe.Recover("cmd/sshtermy/keep.go") for { c, cols, rows, err := hub.Accept() if err != nil { @@ -165,6 +169,7 @@ func runKeepServe(dir string, noIntro, debug bool) int { } }() guard := crash.Start(st.Dir) + app.CatchPanics() // einzelne Fehler abfangen statt alles zu beenden (internal/safe) _, err = p.Run() bye := "" if errors.Is(err, tea.ErrProgramPanic) { diff --git a/cmd/sshtermy/main.go b/cmd/sshtermy/main.go index 03b9e80..e9db921 100644 --- a/cmd/sshtermy/main.go +++ b/cmd/sshtermy/main.go @@ -56,6 +56,9 @@ func main() { os.Exit(runBackup(os.Args[2:])) case "restore", "einspielen": os.Exit(runRestore(os.Args[2:])) + case "doctor", "pruefen", "prüfen": + // Selbstprüfung für Fehlerberichte (internal/doctor) + os.Exit(runDoctor(dir)) case "mcp": // MCP-Server für KI-Clients über stdin/stdout (internal/mcp) if err := mcp.Serve(os.Stdin, os.Stdout, &mcp.Remote{DataDir: dir}); err != nil { @@ -160,6 +163,8 @@ func main() { } // Absturzbericht: ab hier landen Paniken im crash-Ordner (internal/crash). guard := crash.Start(st.Dir) + // Absturzschutz: einzelne Fehler abfangen statt alles zu beenden (internal/safe) + app.CatchPanics() // Bibliotheken (z. B. der SSH-Agent bei der Weiterleitung) schreiben // Meldungen mit log.Printf nach stderr: das würde das Bild zerreißen. log.SetOutput(io.Discard) diff --git a/cmd/sshtermy/sshtermy b/cmd/sshtermy/sshtermy deleted file mode 100755 index ba36f63..0000000 Binary files a/cmd/sshtermy/sshtermy and /dev/null differ diff --git a/docs/ui-aufteilung.md b/docs/ui-aufteilung.md new file mode 100644 index 0000000..7a82a15 --- /dev/null +++ b/docs/ui-aufteilung.md @@ -0,0 +1,32 @@ +# internal/ui aufteilen + +`internal/ui` ist mit über 300 Dateien und gut 80.000 Zeilen ein einziges Paket. Das macht Änderungen +riskanter (alles sieht alles) und die Tests langsam (jede Änderung baut und testet das ganze Paket). + +## Stand + +Erster Schritt (2026-11-20): zwei Teile ohne Bezug zu `App`/`session` sind eigene Pakete: + +| Paket | Inhalt | +|---|---| +| `internal/ui/clickzone` | klickbare Bereiche im fertigen Bild (`Map`, `Action`, `Rect`) | +| `internal/ui/dropped` | ins Fenster gezogene Dateien erkennen (`Paths`, `Split`) | +| `internal/ui/theme` | Farben der Themes (schon vorher) | + +## Vorgehen für weitere Teile + +1. Datei probeweise in ein leeres Paket kopieren und bauen: die Meldungen `undefined: …` zeigen, was sie + noch aus `ui` braucht. Gut geeignet sind Dateien ohne `*App`, `*session`, `modal`, `Styles`. +2. Mit `gopls rename -w datei.go:Zeile:Spalte NeuerName` erst alle Namen in `ui` auf eindeutige + Zwischennamen bringen (z. B. `CzMap`), Felder und Methoden gleich exportiert benennen. +3. Datei mit `git mv` verschieben, Paketzeile ändern, Zwischennamen im neuen Paket kürzen (`CzMap` → `Map`) + und in `ui` durch den qualifizierten Namen ersetzen (`clickzone.Map`). Weil die Zwischennamen eindeutig + sind, ist das ein sicheres Suchen/Ersetzen. +4. `go build ./... && go test ./internal/ui/...` + +## Nächste Kandidaten + +- `logtree.go` (Baum der Sitzungsprotokolle, braucht nur `plural`) → `ui/logtree` +- `stamp.go` + `fillbg.go` (Overlays zusammensetzen) → `ui/canvas` +- `graph.go` (Kurven, braucht `mixColor`) zusammen mit den Farbhilfen +- danach Bereiche mit eigenem Zustand (Dateiansicht F5, Teilen, KI-Begleiter) hinter kleinen Schnittstellen diff --git a/go.mod b/go.mod index 63f353e..fbaef13 100644 --- a/go.mod +++ b/go.mod @@ -4,15 +4,15 @@ go 1.27.0 require ( charm.land/bubbles/v2 v2.2.1 - charm.land/bubbletea/v2 v2.1.1 - charm.land/lipgloss/v2 v2.1.0 + charm.land/bubbletea/v2 v2.1.2 + charm.land/lipgloss/v2 v2.1.1 filippo.io/cpace v0.0.0-20210101143347-24d601e2e469 github.com/Microsoft/go-winio v0.6.4 github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e github.com/atotto/clipboard v0.1.4 github.com/charmbracelet/colorprofile v0.4.3 - github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f - github.com/charmbracelet/x/ansi v0.11.9 + github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c + github.com/charmbracelet/x/ansi v0.11.10 github.com/charmbracelet/x/term v0.2.2 github.com/charmbracelet/x/vt v0.1.0 github.com/charmbracelet/x/xpty v0.1.4 @@ -21,7 +21,7 @@ require ( github.com/hajimehoshi/ebiten/v2 v2.10.6 github.com/jcmturner/gofork v1.7.6 github.com/jcmturner/gokrb5/v8 v8.4.4 - github.com/masterzen/winrm v0.0.0-20261004123143-57b335310d59 + github.com/masterzen/winrm v0.0.0-20261114181639-d693523ae428 github.com/pkg/sftp v1.13.12 go.bug.st/serial v1.8.0 golang.org/x/crypto v0.59.0 @@ -32,7 +32,7 @@ require ( require ( filippo.io/edwards25519 v1.1.0 // indirect - github.com/Azure/go-ntlmssp v0.1.2-0.20260824092057-1c8077778c2c // indirect + github.com/Azure/go-ntlmssp v0.1.2-0.20261111092545-5846b35b583b // indirect github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6 // indirect github.com/charmbracelet/x/conpty v0.2.0 // indirect github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect diff --git a/go.sum b/go.sum index c78acf2..32dadba 100644 --- a/go.sum +++ b/go.sum @@ -1,15 +1,15 @@ charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU= charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= -charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU= -charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= -charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU= -charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI= +charm.land/bubbletea/v2 v2.1.2 h1:vB3XAcHhLB2gR3HOHpwO3lHB3nbvaowIgL3e5x/DUZo= +charm.land/bubbletea/v2 v2.1.2/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= +charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc= +charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc= filippo.io/cpace v0.0.0-20210101143347-24d601e2e469 h1:+gAICE3DIgwMKUzUuVCjd5R4ws+HFL19bKegPYkcgmQ= filippo.io/cpace v0.0.0-20210101143347-24d601e2e469/go.mod h1:b8UFwXF0HGYD8OWBGJEPwu3IMDHqTpzCtGFtY2xRwTU= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/Azure/go-ntlmssp v0.1.2-0.20260824092057-1c8077778c2c h1:HyK5+m8TFO4iAmMJ7u8tyUjE9C/y4/mvFRT0nqEPfJY= -github.com/Azure/go-ntlmssp v0.1.2-0.20260824092057-1c8077778c2c/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= +github.com/Azure/go-ntlmssp v0.1.2-0.20261111092545-5846b35b583b h1:bjbfDOR1AKL94pAT8/sD6RFm+MtcWskNqt8ELP33c+w= +github.com/Azure/go-ntlmssp v0.1.2-0.20261111092545-5846b35b583b/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6 h1:w0E0fgc1YafGEh5cROhlROMWXiNoZqApk2PDN0M1+Ns= github.com/ChrisTrenkamp/goxpath v0.0.0-20210404020558-97928f7e12b6/go.mod h1:nuWgzSkT5PnyOd+272uUmV0dnAnAn42Mk7PiQC5VzN4= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= @@ -24,8 +24,8 @@ github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= -github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f h1:D2JpB65eehsnkEwEG401dMBSNYtTDgvKXZZSl7ZCxWI= -github.com/charmbracelet/ultraviolet v0.0.0-20261023060817-a45b7c86333f/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= +github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c h1:izHJ6cjHd9HGtre1J+c/+QE3rQZ2t4EZH6BqykQbpjc= +github.com/charmbracelet/ultraviolet v0.0.0-20261119151026-8ecbcf0e188c/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= github.com/charmbracelet/x/conpty v0.2.0 h1:eKtA2hm34qNfgJCDp/M6Dc0gLy7e07YEK4qAdNGOvVY= github.com/charmbracelet/x/conpty v0.2.0/go.mod h1:fexgUnVrZgw8scD49f6VSi0Ggj9GWYIrpedRthAwW/8= github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA= @@ -102,8 +102,8 @@ github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBql github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786 h1:2ZKn+w/BJeL43sCxI2jhPLRv73oVVOjEKZjKkflyqxg= github.com/masterzen/simplexml v0.0.0-20190410153822-31eea3082786/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc= -github.com/masterzen/winrm v0.0.0-20261004123143-57b335310d59 h1:ZvQGbOpXorIxtua/7uFpXUZ1FyarecLn9BoxqJI6miY= -github.com/masterzen/winrm v0.0.0-20261004123143-57b335310d59/go.mod h1:56p25CXdyKsQWriUDfygyVGv5OvFBDY27/yzRy7NuSs= +github.com/masterzen/winrm v0.0.0-20261114181639-d693523ae428 h1:pmewvRot1g5dLBFnnaIoOzuE1b5+QK2XiFLO4+wpqQ0= +github.com/masterzen/winrm v0.0.0-20261114181639-d693523ae428/go.mod h1:cA0bunbrhVEbw3G1WdgFifKsQFaZFvcEXmUIOGZRwf0= github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo= github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= diff --git a/internal/agent/fuzz_test.go b/internal/agent/fuzz_test.go new file mode 100644 index 0000000..7249bb9 --- /dev/null +++ b/internal/agent/fuzz_test.go @@ -0,0 +1,30 @@ +package agent + +import ( + "testing" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +// Antworten der KI sind fremder Text: halbes JSON, Markdown drumherum, +// falsche Typen. Lesen darf scheitern, aber nie abstürzen. +func FuzzAnswers(f *testing.F) { + f.Add(`{"cmd":"uptime","why":"Last","done":false}`) + f.Add("```json\n{\"plan\":[{\"cmd\":\"ls\"}],\"files\":[{\"path\":\"/tmp/x\",\"content\":\"a\"}]}\n```") + f.Add(`{"windows":[{"n":1,"cmd":"df -h"}],"options":["a",2,null]}`) + f.Add(`{"pick":3}`) + f.Add(`[`) + f.Fuzz(func(t *testing.T, s string) { + fuzzguard.Run(t, func() { + for _, kind := range []string{"unix", "windows", "network"} { + _, _ = parseStep(s, kind) + _, _ = parsePlan(s, kind, true) + _, _ = parseAuto(s, kind, true) + _, _ = parseReview(s, 3, kind) + _ = ParseStepCommand(s, kind) + } + _, _ = ParseMulti(s, []Window{{N: 1, Name: "web"}, {N: 2, Name: "db", Prod: true}}) + _ = ParseMenuPick(s, 5) + }) + }) +} diff --git a/internal/broadcast/broadcast.go b/internal/broadcast/broadcast.go index e9640c1..78a0cbd 100644 --- a/internal/broadcast/broadcast.go +++ b/internal/broadcast/broadcast.go @@ -20,6 +20,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/safety" "github.com/db9979/sshtermy/internal/sshx" ) @@ -165,7 +166,7 @@ func Run(ctx context.Context, j Job, dial Dialer, update func(i int, r Result)) } for i := first; i < len(j.Conns); i++ { wg.Add(1) - go start(i, j.Conns[i]) + safe.Go("broadcast/broadcast.go", func() { start(i, j.Conns[i]) }) } wg.Wait() return res diff --git a/internal/crash/crash.go b/internal/crash/crash.go index fdbddff..2c76eeb 100644 --- a/internal/crash/crash.go +++ b/internal/crash/crash.go @@ -178,8 +178,9 @@ func Resolve(base string) { _ = os.Remove(filepath.Join(Dir(base), prevName)) } type Kind int const ( - KindUI Kind = iota // Panik in der Oberfläche, Terminal wurde wiederhergestellt - KindFatal // Prozess sofort beendet, Bericht beim nächsten Start + KindUI Kind = iota // Panik in der Oberfläche, Terminal wurde wiederhergestellt + KindFatal // Prozess sofort beendet, Bericht beim nächsten Start + KindCaught // Fehler abgefangen (internal/safe), sshTermy lief weiter ) // Report ist ein fertiger, bereinigter Bericht. @@ -210,8 +211,11 @@ func Write(base string, kind Kind, raw string, sensitive []string) (*Report, err func Build(kind Kind, raw string, sensitive []string, at time.Time) *Report { clean := Clean(raw, sensitive) what := i18n.T("Absturz in der Oberfläche (Terminal wurde wiederhergestellt)") - if kind == KindFatal { + switch kind { + case KindFatal: what = i18n.T("Programm wurde sofort beendet (Bericht beim nächsten Start erstellt)") + case KindCaught: + what = i18n.T("Fehler abgefangen, sshTermy lief weiter") } msg := firstMeaningful(clean) var b strings.Builder diff --git a/internal/detach/client.go b/internal/detach/client.go index 752dee2..d7fcaa1 100644 --- a/internal/detach/client.go +++ b/internal/detach/client.go @@ -9,6 +9,8 @@ import ( "time" "github.com/charmbracelet/x/term" + + "github.com/db9979/sshtermy/internal/safe" ) // Texte des Fensters; sshTermy setzt sie übersetzt (i18n liegt eine Ebene höher). @@ -53,6 +55,7 @@ func Attach(dir string) int { // Tasten → sshTermy go func() { + defer safe.Recover("detach/client.go") buf := make([]byte, 4096) for { n, err := os.Stdin.Read(buf) @@ -69,7 +72,7 @@ func Attach(dir string) int { // Fenstergröße beobachten stop := make(chan struct{}) defer close(stop) - go watchSize(out, stop, func(c, r int) { _ = fw.write(frResize, sizePayload(c, r)) }) + safe.Go("detach/client.go", func() { watchSize(out, stop, func(c, r int) { _ = fw.write(frResize, sizePayload(c, r)) }) }) for { f, err := readFrame(nc) @@ -110,6 +113,7 @@ func waitKey() { fmt.Print(MsgPressKey) done := make(chan struct{}) go func() { + defer safe.Recover("detach/client.go") b := make([]byte, 1) _, _ = os.Stdin.Read(b) close(done) diff --git a/internal/detach/fuzz_test.go b/internal/detach/fuzz_test.go new file mode 100644 index 0000000..754408a --- /dev/null +++ b/internal/detach/fuzz_test.go @@ -0,0 +1,27 @@ +package detach + +import ( + "bytes" + "testing" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +// Rahmen aus der lokalen Verbindung zum abgetrennten Fenster. +func FuzzFrame(f *testing.F) { + f.Add([]byte{1, 0, 0, 0, 4, 0, 80, 0, 24}) + f.Add([]byte{0, 0xff, 0xff, 0xff, 0xff}) + f.Add([]byte{}) + f.Fuzz(func(t *testing.T, b []byte) { + fuzzguard.Run(t, func() { + r := bytes.NewReader(b) + for { + fr, err := readFrame(r) + if err != nil { + return + } + _, _, _ = parseSize(fr.p) + } + }) + }) +} diff --git a/internal/detach/hub.go b/internal/detach/hub.go index ed4090e..fbcdc60 100644 --- a/internal/detach/hub.go +++ b/internal/detach/hub.go @@ -9,6 +9,8 @@ import ( "path/filepath" "sync" "time" + + "github.com/db9979/sshtermy/internal/safe" ) // Hintergrunddienst (Idee aus herdr): sshTermy läuft als eigener Prozess @@ -64,7 +66,7 @@ func ListenHub(dir string) (*Hub, error) { h.Close() return nil, err } - go h.acceptLoop() + safe.Go("detach/hub.go", func() { h.acceptLoop() }) return h, nil } @@ -79,6 +81,7 @@ func (h *Hub) acceptLoop() { return } go func() { + defer safe.Recover("detach/hub.go") c, cols, rows, err := handshake(nc, h.token) if err != nil { nc.Close() // Probe von HubAlive oder falsches Zugangswort @@ -157,6 +160,7 @@ func dialTimeout(network, addr string, d time.Duration) (net.Conn, error) { return r.c, r.err case <-time.After(d): go func() { + defer safe.Recover("detach/hub.go") if r := <-ch; r.c != nil { r.c.Close() } diff --git a/internal/detach/server.go b/internal/detach/server.go index 9fab961..2911aa0 100644 --- a/internal/detach/server.go +++ b/internal/detach/server.go @@ -12,6 +12,8 @@ import ( "strings" "sync" "time" + + "github.com/db9979/sshtermy/internal/safe" ) const ( @@ -79,6 +81,7 @@ func (s *Server) Accept(timeout time.Duration) (*Conn, int, int, error) { } ch := make(chan res, 1) go func() { + defer safe.Recover("detach/server.go") for { nc, err := s.ln.Accept() if err != nil { diff --git a/internal/doctor/doctor.go b/internal/doctor/doctor.go new file mode 100644 index 0000000..7e4582c --- /dev/null +++ b/internal/doctor/doctor.go @@ -0,0 +1,253 @@ +// Package doctor ist die Selbstprüfung (sshtermy doctor, Palette › Hilfe › +// Fehlersuche › Selbstprüfung): Datenordner und Rechte, Tresor, +// Schlüsselbund, SSH-Agent, Update-Signatur, Internet und Uhrzeit, +// Absturzberichte. Das Ergebnis ist reiner Text ohne Geheimnisse und Hosts, +// damit man es in einen Fehlerbericht kopieren kann. +package doctor + +import ( + "context" + "fmt" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/db9979/sshtermy/internal/crash" + "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/keychain" + "github.com/db9979/sshtermy/internal/sshx" + "github.com/db9979/sshtermy/internal/update" + "github.com/db9979/sshtermy/internal/vault" + "github.com/db9979/sshtermy/internal/version" +) + +// Status einer Prüfung. +type Status int + +const ( + OK Status = iota + Info // nur zur Kenntnis (z. B. Version) + Warn // geht, aber etwas fehlt + Fail // so funktioniert etwas nicht +) + +// Mark: Zeichen vor der Zeile (nur ASCII/Cascadia-sicher). +func (s Status) Mark() string { + switch s { + case OK: + return "✓" + case Warn: + return "!" + case Fail: + return "×" + } + return "·" +} + +// Result ist eine Zeile der Selbstprüfung. +type Result struct { + Name string + Status Status + Detail string +} + +// Check ist eine einzelne Prüfung. +type Check func(ctx context.Context) Result + +// Env: Umgebung der Prüfungen. Leere Felder = Standard. +type Env struct { + Dir string // Datenordner + HTTP *http.Client // für Internet/Uhrzeit (Tests setzen einen eigenen) + Probe string // Adresse für Internet/Uhrzeit (Standard: GitHub-API) + Now func() time.Time + Extra []Check // z. B. KI-Endpunkt (Oberfläche) oder Terminal (Kommandozeile) +} + +// Run führt alle Prüfungen aus (Reihenfolge fest, jede mit eigener Frist). +func Run(ctx context.Context, env Env) []Result { + if env.HTTP == nil { + env.HTTP = &http.Client{Timeout: 8 * time.Second} + } + if env.Probe == "" { + env.Probe = "https://api.github.com" + } + if env.Now == nil { + env.Now = time.Now + } + checks := []Check{ + func(context.Context) Result { return checkVersion() }, + func(context.Context) Result { return checkDir(env.Dir) }, + func(context.Context) Result { return checkVault(env.Dir) }, + func(context.Context) Result { return checkKeychain() }, + func(context.Context) Result { return checkAgent() }, + func(context.Context) Result { return checkSigned() }, + func(ctx context.Context) Result { return checkNet(ctx, env) }, + func(context.Context) Result { return checkCrashes(env.Dir) }, + } + checks = append(checks, env.Extra...) + out := make([]Result, 0, len(checks)) + for _, c := range checks { + cctx, cancel := context.WithTimeout(ctx, 15*time.Second) + out = append(out, c(cctx)) + cancel() + } + return out +} + +// Worst: schlechtester Status (für den Rückgabewert der Kommandozeile). +func Worst(rs []Result) Status { + w := OK + for _, r := range rs { + if r.Status != Info && r.Status > w { + w = r.Status + } + } + return w +} + +// Format: Text zum Anzeigen und Kopieren. +func Format(rs []Result) string { + n := 0 + for _, r := range rs { + n = max(n, len([]rune(r.Name))) + } + var b strings.Builder + for _, r := range rs { + pad := strings.Repeat(" ", n-len([]rune(r.Name))) + fmt.Fprintf(&b, "%s %s%s %s\n", r.Status.Mark(), r.Name, pad, r.Detail) + } + switch Worst(rs) { + case OK: + b.WriteString("\n" + i18n.T("Alles in Ordnung.") + "\n") + case Warn: + b.WriteString("\n" + i18n.T("Läuft, aber nicht alles ist eingerichtet (Zeilen mit !).") + "\n") + default: + b.WriteString("\n" + i18n.T("Es gibt Probleme (Zeilen mit ×). Text kopieren und dem Fehlerbericht beilegen.") + "\n") + } + return b.String() +} + +func checkVersion() Result { + return Result{i18n.T("Version"), Info, fmt.Sprintf("%s · %s/%s · %s", version.Short(), runtime.GOOS, runtime.GOARCH, runtime.Version())} +} + +func checkDir(dir string) Result { + name := i18n.T("Datenordner") + if dir == "" { + return Result{name, Fail, i18n.T("unbekannt (kein Benutzerordner?)")} + } + fi, err := os.Stat(dir) + if os.IsNotExist(err) { + return Result{name, Info, i18n.T("noch nicht angelegt (erster Start)")} + } + if err != nil { + return Result{name, Fail, err.Error()} + } + if !fi.IsDir() { + return Result{name, Fail, i18n.T("ist eine Datei, kein Ordner")} + } + probe := filepath.Join(dir, ".doctor-probe") + if err := os.WriteFile(probe, []byte("ok"), 0o600); err != nil { + return Result{name, Fail, i18n.T("nicht beschreibbar: ") + err.Error()} + } + _ = os.Remove(probe) + if runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 { + return Result{name, Warn, fmt.Sprintf(i18n.T("für andere lesbar (%o), besser: chmod 700"), fi.Mode().Perm())} + } + return Result{name, OK, i18n.T("beschreibbar")} +} + +func checkVault(dir string) Result { + name := i18n.T("Tresor") + p := filepath.Join(dir, "store.vault") + if _, err := os.Stat(p); os.IsNotExist(err) { + return Result{name, Info, i18n.T("noch nicht angelegt (erster Start)")} + } + v, err := vault.Open(p) + if err != nil { + return Result{name, Fail, err.Error()} + } + d := i18n.T("lesbar, Master-Passwort") + if v.HasDPAPI() { + d += i18n.T(" + Windows-Konto") + } + return Result{name, OK, d} +} + +func checkKeychain() Result { + name := i18n.T("Schlüsselbund") + if keychain.Available() { + return Result{name, OK, i18n.T("verfügbar (Passwörter können dort liegen)")} + } + return Result{name, Warn, i18n.T("nicht verfügbar: Passwörter liegen nur im Tresor")} +} + +func checkAgent() Result { + name := i18n.T("SSH-Agent") + if err := sshx.AgentReachable(); err != nil { + return Result{name, Info, i18n.T("nicht erreichbar (nur nötig für Schlüssel im Agenten): ") + err.Error()} + } + return Result{name, OK, i18n.T("erreichbar")} +} + +func checkSigned() Result { + name := i18n.T("Update-Signatur") + if update.Signed() { + return Result{name, OK, i18n.T("Updates werden vor dem Einspielen geprüft")} + } + return Result{name, Warn, i18n.T("eigener Build ohne Schlüssel: Updates werden nicht geprüft")} +} + +// checkNet: Internet (für Updates) und Uhrzeit (falsche Uhr ⇒ Zertifikate, +// Einmal-Codes und SSH-Zertifikate scheitern scheinbar grundlos). +func checkNet(ctx context.Context, env Env) Result { + name := i18n.T("Internet und Uhr") + req, err := http.NewRequestWithContext(ctx, http.MethodHead, env.Probe, nil) + if err != nil { + return Result{name, Warn, err.Error()} + } + req.Header.Set("User-Agent", version.Short()) + resp, err := env.HTTP.Do(req) + if err != nil { + return Result{name, Warn, i18n.T("GitHub nicht erreichbar, Updates gehen nicht: ") + err.Error()} + } + resp.Body.Close() + srv, err := http.ParseTime(resp.Header.Get("Date")) + if err != nil { + return Result{name, OK, i18n.T("GitHub erreichbar")} + } + diff := env.Now().Sub(srv) + if diff < 0 { + diff = -diff + } + if diff > 2*time.Minute { + return Result{name, Warn, fmt.Sprintf(i18n.T("Uhr geht %s falsch: Anmeldung mit Einmal-Codes oder Zertifikaten kann scheitern"), diff.Round(time.Second))} + } + return Result{name, OK, i18n.T("GitHub erreichbar, Uhr stimmt")} +} + +func checkCrashes(dir string) Result { + name := i18n.T("Absturzberichte") + es, _ := os.ReadDir(crash.Dir(dir)) + n := 0 + for _, e := range es { + if strings.HasPrefix(e.Name(), "sshtermy-crash-") { + n++ + } + } + if n == 0 { + return Result{name, OK, i18n.T("keine")} + } + return Result{name, Info, fmt.Sprintf(i18n.T("%d im Ordner %s"), n, tilde(crash.Dir(dir)))} +} + +// tilde: Home-Ordner als ~ (der Text landet ggf. in einem Fehlerbericht). +func tilde(p string) string { + if h, err := os.UserHomeDir(); err == nil && h != "" && strings.HasPrefix(p, h) { + return "~" + p[len(h):] + } + return p +} diff --git a/internal/doctor/doctor_test.go b/internal/doctor/doctor_test.go new file mode 100644 index 0000000..7f519b9 --- /dev/null +++ b/internal/doctor/doctor_test.go @@ -0,0 +1,111 @@ +package doctor + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func server(t *testing.T, date time.Time) string { + t.Helper() + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Date", date.UTC().Format(http.TimeFormat)) + })) + t.Cleanup(ts.Close) + return ts.URL +} + +func find(t *testing.T, rs []Result, prefix string) Result { + t.Helper() + for _, r := range rs { + if strings.HasPrefix(r.Name, prefix) { + return r + } + } + t.Fatalf("keine Zeile %q", prefix) + return Result{} +} + +func TestRunFreshDir(t *testing.T) { + dir := t.TempDir() + now := time.Now() + rs := Run(context.Background(), Env{Dir: dir, Probe: server(t, now), Now: func() time.Time { return now }}) + if r := find(t, rs, "Datenordner"); r.Status != OK && !(runtime.GOOS != "windows" && r.Status == Warn) { + t.Fatalf("Datenordner: %+v", r) + } + if r := find(t, rs, "Tresor"); r.Status != Info { + t.Fatalf("Tresor bei erstem Start: %+v", r) + } + if r := find(t, rs, "Internet"); r.Status != OK { + t.Fatalf("Internet: %+v", r) + } + if r := find(t, rs, "Absturz"); r.Status != OK { + t.Fatalf("Absturzberichte: %+v", r) + } + if _, err := os.Stat(filepath.Join(dir, ".doctor-probe")); !os.IsNotExist(err) { + t.Fatal("Probedatei liegen geblieben") + } + txt := Format(rs) + if !strings.Contains(txt, "Version") || !strings.Contains(txt, "✓") { + t.Fatalf("Format: %s", txt) + } +} + +func TestClockSkew(t *testing.T) { + now := time.Now() + rs := Run(context.Background(), Env{Dir: t.TempDir(), Probe: server(t, now.Add(-10*time.Minute)), Now: func() time.Time { return now }}) + r := find(t, rs, "Internet") + if r.Status != Warn || !strings.Contains(r.Detail, "10m") { + t.Fatalf("falsche Uhr nicht erkannt: %+v", r) + } +} + +func TestOfflineAndBrokenDir(t *testing.T) { + dir := filepath.Join(t.TempDir(), "datei") + _ = os.WriteFile(dir, []byte("x"), 0o600) + if r := checkDir(filepath.Join(t.TempDir(), "fehlt")); r.Status != Info { + t.Fatalf("erster Start: %+v", r) + } + rs := Run(context.Background(), Env{Dir: dir, Probe: "http://127.0.0.1:1"}) + if r := find(t, rs, "Datenordner"); r.Status != Fail { + t.Fatalf("Datei statt Ordner: %+v", r) + } + if r := find(t, rs, "Internet"); r.Status != Warn { + t.Fatalf("offline: %+v", r) + } + if Worst(rs) != Fail { + t.Fatal("Worst") + } + if !strings.Contains(Format(rs), "×") { + t.Fatal("Fehlerzeile fehlt") + } +} + +func TestCrashesAndExtra(t *testing.T) { + dir := t.TempDir() + _ = os.MkdirAll(filepath.Join(dir, "crash"), 0o700) + _ = os.WriteFile(filepath.Join(dir, "crash", "sshtermy-crash-1.txt"), []byte("x"), 0o600) + extra := func(context.Context) Result { return Result{"KI", Fail, "antwortet nicht"} } + rs := Run(context.Background(), Env{Dir: dir, Probe: server(t, time.Now()), Extra: []Check{extra}}) + if r := find(t, rs, "Absturz"); r.Status != Info || !strings.HasPrefix(r.Detail, "1 ") { + t.Fatalf("Absturzberichte: %+v", r) + } + if rs[len(rs)-1].Name != "KI" { + t.Fatal("Zusatzprüfung fehlt am Ende") + } +} + +func TestVaultGarbage(t *testing.T) { + dir := t.TempDir() + _ = os.WriteFile(filepath.Join(dir, "store.vault"), []byte("{kaputt"), 0o600) + r := checkVault(dir) + if r.Status != Fail { + t.Fatalf("kaputter Tresor: %+v", r) + } +} diff --git a/internal/gui/attach.go b/internal/gui/attach.go index 158f602..f569947 100644 --- a/internal/gui/attach.go +++ b/internal/gui/attach.go @@ -6,6 +6,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/detach" + "github.com/db9979/sshtermy/internal/safe" ) // RunAttach: abgetrennter Tab (⇧F10) im zweiten eigenen Fenster. Das @@ -27,6 +28,7 @@ func RunAttach(dir string, opts Options) int { w.onQuit = c.Close out := w.output() go func() { + defer safe.Recover("gui/attach.go") defer close(w.done) for { m, err := c.Next() diff --git a/internal/gui/queue.go b/internal/gui/queue.go index 8e1db55..13a434e 100644 --- a/internal/gui/queue.go +++ b/internal/gui/queue.go @@ -3,6 +3,8 @@ package gui import ( "io" "sync" + + "github.com/db9979/sshtermy/internal/safe" ) // queueWriter reicht Bytes in eigener Goroutine weiter, in Reihenfolge, und @@ -25,7 +27,7 @@ type queueWriter struct { func newQueueWriter(dst io.Writer) *queueWriter { q := &queueWriter{dst: dst} q.cond = sync.NewCond(&q.mu) - go q.loop() + safe.Go("gui/queue.go", func() { q.loop() }) return q } diff --git a/internal/gui/window.go b/internal/gui/window.go index ec739c5..30ffed2 100644 --- a/internal/gui/window.go +++ b/internal/gui/window.go @@ -24,6 +24,7 @@ import ( "github.com/hajimehoshi/ebiten/v2/inpututil" "github.com/hajimehoshi/ebiten/v2/text/v2" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/termemu" "github.com/db9979/sshtermy/internal/winstate" ) @@ -96,6 +97,7 @@ func Run(model tea.Model, opts Options) (tea.Model, error) { var final tea.Model var runErr error go func() { + defer safe.Recover("gui/window.go") final, runErr = prog.Run() close(w.done) }() @@ -161,7 +163,7 @@ func (w *window) output() io.Writer { // run öffnet das Fenster und kehrt zurück, wenn done zu ist. func (w *window) run() error { - go w.resizer() + safe.Go("gui/window.go", func() { w.resizer() }) w.setFaces(1) ebiten.SetWindowTitle(w.opts.Title) ebiten.SetWindowSize(int(float64(startCols)*w.cellW+2*padding), int(float64(startRows)*w.cellH+2*padding)) @@ -524,6 +526,7 @@ func keyRune(k ebiten.Key) rune { func (w *window) paste() { go func() { + defer safe.Recover("gui/window.go") s, err := clipboard.ReadAll() if err == nil && s != "" { w.term.Paste(s) diff --git a/internal/i18n/en_stability.go b/internal/i18n/en_stability.go new file mode 100644 index 0000000..4b32717 --- /dev/null +++ b/internal/i18n/en_stability.go @@ -0,0 +1,49 @@ +package i18n + +// Stabilität (2026-11-20): Absturzschutz (ui/safety.go, internal/safe), +// Selbstprüfung (sshtermy doctor). +func init() { + for k, v := range enStability { + en[k] = v + } +} + +var enStability = map[string]string{ + "Fehler abgefangen, sshTermy lief weiter": "Error caught, sshTermy kept running", + "Interner Fehler abgefangen, sshTermy läuft weiter.": "Internal error caught, sshTermy keeps running.", + "update: Download kam %s lang nicht voran": "update: download made no progress for %s", + " (kleiner als 80×20: manches wird gekürzt)": " (smaller than 80×20: some things get cut off)", + " + Windows-Konto": " + Windows account", + " antwortet": " answers", + " antwortet nicht: ": " does not answer: ", + "%d im Ordner %s": "%d in folder %s", + "Absturzberichte": "Crash reports", + "Alles in Ordnung.": "Everything is fine.", + "Ausgabe ist kein Terminal (umgeleitet)": "Output is not a terminal (redirected)", + "Es gibt Probleme (Zeilen mit ×). Text kopieren und dem Fehlerbericht beilegen.": "There are problems (lines with ×). Copy this text and attach it to your bug report.", + "GitHub erreichbar": "GitHub reachable", + "GitHub erreichbar, Uhr stimmt": "GitHub reachable, clock is correct", + "GitHub nicht erreichbar, Updates gehen nicht: ": "GitHub not reachable, updates won't work: ", + "Internet und Uhr": "Internet and clock", + "Läuft, aber nicht alles ist eingerichtet (Zeilen mit !).": "Works, but not everything is set up (lines with !).", + "Selbstprüfung": "Self-check", + "Selbstprüfung (Ordner, Tresor, KI, Internet, Uhr)": "Self-check (folder, vault, AI, internet, clock)", + "Selbstprüfung läuft …": "Self-check running …", + "Tresor": "Vault", + "Uhr geht %s falsch: Anmeldung mit Einmal-Codes oder Zertifikaten kann scheitern": "Clock is off by %s: sign-in with one-time codes or certificates may fail", + "Update-Signatur": "Update signature", + "Updates werden vor dem Einspielen geprüft": "Updates are verified before installing", + "beschreibbar": "writable", + "eigener Build ohne Schlüssel: Updates werden nicht geprüft": "own build without key: updates are not verified", + "für andere lesbar (%o), besser: chmod 700": "readable by others (%o), better: chmod 700", + "ist eine Datei, kein Ordner": "is a file, not a folder", + "lesbar, Master-Passwort": "readable, master password", + "nicht beschreibbar: ": "not writable: ", + "nicht eingerichtet": "not set up", + "nicht erreichbar (nur nötig für Schlüssel im Agenten): ": "not reachable (only needed for keys in the agent): ", + "nicht verfügbar: Passwörter liegen nur im Tresor": "not available: passwords are kept in the vault only", + "noch nicht angelegt (erster Start)": "not created yet (first start)", + "sshTermy-Selbstprüfung …": "sshTermy self-check …", + "unbekannt (kein Benutzerordner?)": "unknown (no user folder?)", + "verfügbar (Passwörter können dort liegen)": "available (passwords can be stored there)", +} diff --git a/internal/localsh/localsh.go b/internal/localsh/localsh.go index cb79b74..bf941f9 100644 --- a/internal/localsh/localsh.go +++ b/internal/localsh/localsh.go @@ -15,6 +15,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/db9979/sshtermy/internal/safe" ) // ptyFile: Pseudo-Terminal je System (pty_unix.go, pty_windows.go). @@ -62,10 +64,12 @@ func Start(shell, dir string, cols, rows int, out io.Writer) (*Stream, error) { s := &Stream{Shell: argv[0], Done: make(chan error, 1), pty: p, cmd: cmd} readDone := make(chan struct{}) go func() { + defer safe.Recover("localsh/localsh.go") defer close(readDone) _, _ = io.Copy(out, p) }() go func() { + defer safe.Recover("localsh/localsh.go") err := waitProcess(cmd) // Nach dem Ende der Shell den Rest der Ausgabe noch abholen. Hält ein // Hintergrundprozess das Terminal offen (oder bei ConPTY, das erst diff --git a/internal/logscan/fuzz_test.go b/internal/logscan/fuzz_test.go new file mode 100644 index 0000000..e46e5a7 --- /dev/null +++ b/internal/logscan/fuzz_test.go @@ -0,0 +1,30 @@ +package logscan + +import ( + "testing" + "time" + + "github.com/db9979/sshtermy/internal/hostinfo" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +// Syslog kommt per UDP von irgendwem, Protokolle von fremden Servern und +// Switches: beliebige Bytes dürfen nichts kaputt machen. +func FuzzSyslog(f *testing.F) { + now := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC) + f.Add("<187>Nov 20 09:59:01 sw1 %LINK-3-UPDOWN: Interface Gi1/0/1, changed state to down") + f.Add("<34>1 2026-11-20T09:00:00Z host app 1 ID47 - BOM'su root' failed") + f.Add("2026-11-20T09:00:00+01:00 web kernel: EXT4-fs error (device sda1)") + f.Add("<999999999999999999999>") + f.Fuzz(func(t *testing.T, s string) { + fuzzguard.Run(t, func() { + _, _ = SyslogPacket(s, now) + _ = ParseUnix(s, 24, now) + _ = ParseWindows(s, 24, now) + for _, v := range []hostinfo.Vendor{hostinfo.VendorUnknown, hostinfo.VendorProCurve, hostinfo.VendorCisco, hostinfo.VendorUniFi} { + _ = ParseNetwork(v, []string{s, s}, s, 24, now) + } + }) + }) +} diff --git a/internal/mcp/fuzz_test.go b/internal/mcp/fuzz_test.go new file mode 100644 index 0000000..9276cd9 --- /dev/null +++ b/internal/mcp/fuzz_test.go @@ -0,0 +1,38 @@ +package mcp + +import ( + "bytes" + "encoding/json" + "io" + "strings" + "testing" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +type nopBackend struct{} + +func (nopBackend) Call(tool string, args json.RawMessage) (string, error) { return "ok", nil } + +// Anfragen kommen von einem fremden Programm (KI-Werkzeug): jede Zeile muss +// beantwortet oder verworfen werden, ohne Absturz und ohne Hänger. +func FuzzServe(f *testing.F) { + f.Add(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`) + f.Add(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_connections"}}`) + f.Add(`{"jsonrpc":"2.0","id":"x","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":1}}}`) + f.Add(`{"id":null}`) + f.Add("\x00{\n}") + f.Fuzz(func(t *testing.T, in string) { + fuzzguard.Run(t, func() { + var out bytes.Buffer + if err := Serve(strings.NewReader(in), &out, nopBackend{}); err != nil && err != io.EOF { + return // z. B. Zeile zu lang: Fehler ist erlaubt, Absturz nicht + } + for _, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { + if line != "" && !json.Valid([]byte(line)) { + t.Errorf("Antwort ist kein JSON: %q", line) + } + } + }) + }) +} diff --git a/internal/mcp/host.go b/internal/mcp/host.go index 9c4a20e..883a638 100644 --- a/internal/mcp/host.go +++ b/internal/mcp/host.go @@ -14,6 +14,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/localsock" + "github.com/db9979/sshtermy/internal/safe" ) // Verbindung Brücke ↔ App: erste Zeile das Token aus mcp.json, danach je @@ -71,7 +72,7 @@ func Listen(dataDir string, h Handler) (*Host, error) { x.Close() return nil, err } - go x.accept() + safe.Go("mcp/host.go", func() { x.accept() }) return x, nil } @@ -88,7 +89,7 @@ func (x *Host) accept() { if err != nil { return } - go x.serve(nc) + safe.Go("mcp/host.go", func() { x.serve(nc) }) } } @@ -110,6 +111,7 @@ func (x *Host) serve(nc net.Conn) { return } go func() { + defer safe.Recover("mcp/host.go") text, err := x.handle(q.Tool, q.Args) resp := wireResp{ID: q.ID, Text: text} if err != nil { @@ -162,7 +164,7 @@ func (r *Remote) connect() error { return ErrNotRunning } r.nc, r.enc, r.wait = nc, json.NewEncoder(nc), map[int64]chan wireResp{} - go r.read(nc) + safe.Go("mcp/host.go", func() { r.read(nc) }) return nil } diff --git a/internal/mcp/mcp.go b/internal/mcp/mcp.go index 3c278dd..a918e6a 100644 --- a/internal/mcp/mcp.go +++ b/internal/mcp/mcp.go @@ -14,6 +14,7 @@ import ( "io" "sync" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/version" ) @@ -223,7 +224,12 @@ func Serve(in io.Reader, out io.Writer, b Backend) error { wg.Add(1) go func(id json.RawMessage) { defer wg.Done() - text, err := b.Call(p.Name, p.Arguments) + var text string + var err error + // Fehler im Werkzeug: dem Client trotzdem antworten, sonst wartet er ewig + if !safe.Run("mcp/mcp.go "+p.Name, func() { text, err = b.Call(p.Name, p.Arguments) }) { + err = errors.New("internal error in sshTermy (report written)") + } res := map[string]any{"content": []textContent{{"text", text}}} if err != nil { res = map[string]any{"content": []textContent{{"text", err.Error()}}, "isError": true} diff --git a/internal/netscan/netscan.go b/internal/netscan/netscan.go index 76d659b..c1cfb69 100644 --- a/internal/netscan/netscan.go +++ b/internal/netscan/netscan.go @@ -18,6 +18,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" ) @@ -208,6 +209,7 @@ func Scan(ctx context.Context, addrs []netip.Addr, o Options, progress func(done case sem <- struct{}{}: wg.Add(1) go func(a netip.Addr) { + defer safe.Recover("netscan/netscan.go") defer wg.Done() defer func() { <-sem }() h, ok := probe(ctx, a, o) diff --git a/internal/psremote/stream.go b/internal/psremote/stream.go index 75d2408..9ad2430 100644 --- a/internal/psremote/stream.go +++ b/internal/psremote/stream.go @@ -12,6 +12,8 @@ import ( "unicode/utf8" "github.com/charmbracelet/x/ansi" + + "github.com/db9979/sshtermy/internal/safe" ) // backend: wo PowerShell läuft (WinRM, in Tests ein lokaler Prozess). @@ -103,7 +105,7 @@ func newStream(be backend, cols int, out io.Writer, timeout time.Duration) (*Str } s := &Stream{Done: make(chan error, 1), be: be, out: out, cols: cols, atBOL: true, compWait: -1, ready1: make(chan struct{}), sendq: make(chan sendItem, 256)} - go s.sender() + safe.Go("psremote/stream.go", func() { s.sender() }) if err := s.startProc(""); err != nil { close(s.sendq) be.close() @@ -228,6 +230,7 @@ func (s *Stream) finish(err error) { close(s.sendq) s.mu.Unlock() go func() { + defer safe.Recover("psremote/stream.go") if p != nil { p.stop() } @@ -737,7 +740,7 @@ func (s *Stream) basePrompt() string { // finishLater: exit/Strg+D; finish nimmt s.mu selbst. func (s *Stream) finishLater() { s.ready = false - go s.finish(nil) + safe.Go("psremote/stream.go", func() { s.finish(nil) }) } func (s *Stream) enter() { @@ -812,6 +815,7 @@ func (s *Stream) interrupt() { s.p = nil s.gen++ // Ausgaben des alten Prozesses verwerfen go func() { + defer safe.Recover("psremote/stream.go") if old != nil { old.stop() } diff --git a/internal/psremote/winrm.go b/internal/psremote/winrm.go index 3eb795d..8d4cc22 100644 --- a/internal/psremote/winrm.go +++ b/internal/psremote/winrm.go @@ -25,6 +25,8 @@ import ( "github.com/masterzen/winrm" "github.com/masterzen/winrm/soap" + + "github.com/db9979/sshtermy/internal/safe" ) // Auth: Anmeldeverfahren. @@ -70,6 +72,7 @@ func Dial(ctx context.Context, cfg Config, cols int, out io.Writer) (*Stream, er } ch := make(chan res, 1) go func() { + defer safe.Recover("psremote/winrm.go") w, err := openWSMan(cfg) ch <- res{w, err} }() @@ -82,6 +85,7 @@ func Dial(ctx context.Context, cfg Config, cols int, out io.Writer) (*Stream, er w = r.w case <-ctx.Done(): go func() { + defer safe.Recover("psremote/winrm.go") if r := <-ch; r.w != nil { r.w.close() } @@ -196,7 +200,7 @@ func (w *wsman) start(dir string, h handlers) (proc, error) { return nil, err } c := &wsCmd{w: w, id: id, quit: make(chan struct{})} - go c.receive(h) + safe.Go("psremote/winrm.go", func() { c.receive(h) }) return c, nil } diff --git a/internal/relay/anchor.go b/internal/relay/anchor.go index c0ec234..cca7f65 100644 --- a/internal/relay/anchor.go +++ b/internal/relay/anchor.go @@ -21,6 +21,7 @@ import ( "golang.org/x/crypto/ssh" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // AnchorConfig: was der Anker auf dem Server weiß (anker.json, 0600). @@ -234,6 +235,7 @@ func (a *Anchor) once(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) defer cancel() go func() { + defer safe.Recover("relay/anchor.go") t := time.NewTicker(pingEvery) defer t.Stop() for { @@ -263,7 +265,7 @@ func (a *Anchor) once(ctx context.Context) error { if json.Unmarshal(b, &m) != nil || m.Typ != "kanal" || len(m.ID) != 32 { continue } - go a.channel(ctx, m.ID) + safe.Go("relay/anchor.go", func() { a.channel(ctx, m.ID) }) } } diff --git a/internal/relay/fuzz_test.go b/internal/relay/fuzz_test.go new file mode 100644 index 0000000..7dc5f6d --- /dev/null +++ b/internal/relay/fuzz_test.go @@ -0,0 +1,22 @@ +package relay + +import ( + "testing" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +// Kopplungszeilen und Teilen-Links tippt oder fügt man ein; sie können +// beliebig kaputt sein. +func FuzzParse(f *testing.F) { + f.Add("sshtermy-pair https://relay.example:8443 abcd 0123") + f.Add("sshtermy://zusehen/7-taube-kompass-ofen") + f.Add("") + f.Add("\x00%%%://") + f.Fuzz(func(t *testing.T, s string) { + fuzzguard.Run(t, func() { + _, _ = ParseLine(s) + _, _ = ParseShareLink(s) + }) + }) +} diff --git a/internal/relay/lan.go b/internal/relay/lan.go index 5488908..26684e7 100644 --- a/internal/relay/lan.go +++ b/internal/relay/lan.go @@ -20,6 +20,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/webwatch" ) @@ -86,7 +87,7 @@ func StartLAN() (*LAN, error) { } if u, err := net.ListenUDP("udp4", &net.UDPAddr{Port: LANPort}); err == nil { l.udp = u - go l.answer() + safe.Go("relay/lan.go", func() { l.answer() }) } return l, nil } diff --git a/internal/relay/serve.go b/internal/relay/serve.go index 6c92261..9a3950d 100644 --- a/internal/relay/serve.go +++ b/internal/relay/serve.go @@ -19,6 +19,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // ServeOptions für `sshtermy vermittler start`. @@ -101,8 +102,9 @@ func Serve(ctx context.Context, o ServeOptions) error { if cert != nil { hs.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{*cert}} } - go s.Watch(ctx) + safe.Go("relay/serve.go", func() { s.Watch(ctx) }) go func() { + defer safe.Recover("relay/serve.go") <-ctx.Done() sc, c := context.WithTimeout(context.Background(), 3*time.Second) defer c() diff --git a/internal/relay/server.go b/internal/relay/server.go index 089c510..c8b403d 100644 --- a/internal/relay/server.go +++ b/internal/relay/server.go @@ -15,6 +15,7 @@ import ( "time" "github.com/coder/websocket" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/webwatch" "golang.org/x/crypto/ssh" ) @@ -493,6 +494,7 @@ func (s *Server) anchorCtrl(w http.ResponseWriter, r *http.Request) { s.log("anker_zu", n) }() go func() { + defer safe.Recover("relay/server.go") t := time.NewTicker(pingEvery) defer t.Stop() for { diff --git a/internal/relay/share.go b/internal/relay/share.go index 5b66ca4..5d0e830 100644 --- a/internal/relay/share.go +++ b/internal/relay/share.go @@ -19,6 +19,7 @@ import ( "golang.org/x/crypto/chacha20poly1305" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // Sitzung live teilen @@ -136,7 +137,7 @@ func (c *Client) StartShare(ctx context.Context) (*ShareHost, error) { ws.SetReadLimit(64 * 1024) sh := &ShareHost{Link: ShareLink{Base: c.Base, ID: r.ID, Key: key, FP: c.FP}, ws: ws, viewers: make(chan int, 8), done: make(chan struct{})} - go sh.readCtrl() + safe.Go("relay/share.go", func() { sh.readCtrl() }) return sh, nil } diff --git a/internal/relay/share2.go b/internal/relay/share2.go index c009bc4..f90969b 100644 --- a/internal/relay/share2.go +++ b/internal/relay/share2.go @@ -12,6 +12,7 @@ import ( "github.com/coder/websocket" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // Teilen v2: Einladung mit Code, Zulassung durch den Gastgeber @@ -348,6 +349,7 @@ func (s *Server) watch2(w http.ResponseWriter, r *http.Request) { hostText(host, map[string]any{"typ": "neu", "v": id, "ip": ip}) // Wer nicht zugelassen wird, fliegt nach pendingWait raus. go func() { + defer safe.Recover("relay/share2.go") t := time.NewTimer(pendingWait) defer t.Stop() select { @@ -439,7 +441,7 @@ func (c *Client) StartShare2(ctx context.Context, minutes int) (*Share2, error) ws.SetReadLimit(guestMsgMax + 64) sh := &Share2{ID: r.ID, Platz: r.Platz, Base: c.Base, FP: c.FP, Until: time.Unix(r.Bis, 0), ws: ws, ev: make(chan HostEvent, 64), done: make(chan struct{})} - go sh.read() + safe.Go("relay/share2.go", func() { sh.read() }) return sh, nil } diff --git a/internal/relay/sharesess.go b/internal/relay/sharesess.go index 7554b9b..4920108 100644 --- a/internal/relay/sharesess.go +++ b/internal/relay/sharesess.go @@ -14,6 +14,7 @@ import ( "golang.org/x/crypto/chacha20poly1305" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // Gastgeber-Seite einer Freigabe v2 (Ablauf: siehe internal/sharewire/guest.go). @@ -155,6 +156,7 @@ func (h *HostSession) guestMsg(g *GuestState, b []byte) (HostUI, bool) { // Nicht stumm bleiben: sonst wartet der Zuschauer ewig auf „Prüfe den Code“. v := g.V go func() { + defer safe.Recover("relay/sharesess.go") _ = h.Sh.To(v, append([]byte{MsgNo}, "gesperrt"...)) _ = h.Sh.Kick(v) }() @@ -176,6 +178,7 @@ func (h *HostSession) guestMsg(g *GuestState, b []byte) (HostUI, bool) { h.burn() v := g.V go func() { + defer safe.Recover("relay/sharesess.go") _ = h.Sh.To(v, append([]byte{MsgNo}, "Code passt nicht"...)) _ = h.Sh.Kick(v) }() diff --git a/internal/safe/safe.go b/internal/safe/safe.go new file mode 100644 index 0000000..06cd07e --- /dev/null +++ b/internal/safe/safe.go @@ -0,0 +1,122 @@ +// Package safe fängt Paniken in Hintergrundarbeit ab, damit ein Fehler an +// einer Stelle (KI-Antwort auslesen, Geräteausgabe auswerten, Dateiansicht …) +// nicht das ganze Programm mit allen offenen Verbindungen beendet. +// +// Ohne Handler (Tests, Unterbefehle) wird die Panik unverändert +// weitergereicht: Fehler fallen dort weiterhin sofort auf. Erst die +// Oberfläche setzt mit SetHandler einen Handler, der einen Absturzbericht +// schreibt und eine Meldung zeigt. +// +// Häufen sich die Paniken (Sturm: mehr als StormN in StormWindow), ist der +// Zustand vermutlich kaputt: dann wird wie früher weitergereicht und das +// Programm endet mit dem gewohnten Absturzbericht. +package safe + +import ( + "fmt" + "runtime/debug" + "sync" + "sync/atomic" + "time" +) + +// Caught beschreibt eine abgefangene Panik. +type Caught struct { + Where string // Stelle, z. B. „ui.Update“ oder „sshx/client.go:464“ + Value any // Wert aus panic(…) + Stack []byte + At time.Time +} + +// Raw: Text wie bei einer echten Panik (für den Absturzbericht). +func (c Caught) Raw() string { + return fmt.Sprintf("panic: %v [recovered in %s]\n\n%s", c.Value, c.Where, c.Stack) +} + +const ( + StormN = 5 + StormWindow = time.Minute +) + +var ( + handler atomic.Pointer[func(Caught)] + count atomic.Int64 + + mu sync.Mutex + recent []time.Time +) + +// SetHandler legt fest, was mit abgefangenen Paniken passiert. nil schaltet +// das Abfangen ab (Paniken laufen dann wie gewohnt durch). +func SetHandler(fn func(Caught)) { + if fn == nil { + handler.Store(nil) + return + } + handler.Store(&fn) +} + +// Active: ist ein Handler gesetzt? +func Active() bool { return handler.Load() != nil } + +// Count: so viele Paniken wurden seit dem Start abgefangen. +func Count() int64 { return count.Load() } + +// Recover gehört direkt hinter defer: `defer safe.Recover("wo")`. +func Recover(where string) { + if r := recover(); r != nil { + handle(where, r) + } +} + +// Go startet fn nebenher mit Absturzschutz. +func Go(where string, fn func()) { + go func() { + defer Recover(where) + fn() + }() +} + +// Run führt fn aus; false, wenn dabei eine Panik abgefangen wurde. +func Run(where string, fn func()) (ok bool) { + defer func() { + if r := recover(); r != nil { + handle(where, r) + ok = false + } + }() + fn() + return true +} + +func handle(where string, r any) { + h := handler.Load() + if h == nil || storm(time.Now()) { + panic(r) + } + count.Add(1) + (*h)(Caught{Where: where, Value: r, Stack: debug.Stack(), At: time.Now()}) +} + +// storm merkt sich den Zeitpunkt und meldet, ob es zu viele waren. +func storm(now time.Time) bool { + mu.Lock() + defer mu.Unlock() + keep := recent[:0] + for _, t := range recent { + if now.Sub(t) < StormWindow { + keep = append(keep, t) + } + } + recent = append(keep, now) + return len(recent) > StormN +} + +// Reset: nur für Tests (Zähler, Sturm-Fenster, Handler zurücksetzen). +func Reset() { + mu.Lock() + recent = nil + mu.Unlock() + count.Store(0) + handler.Store(nil) +} diff --git a/internal/safe/safe_test.go b/internal/safe/safe_test.go new file mode 100644 index 0000000..18b18be --- /dev/null +++ b/internal/safe/safe_test.go @@ -0,0 +1,86 @@ +package safe + +import ( + "strings" + "sync" + "testing" + "time" +) + +func TestRunWithoutHandlerRepanics(t *testing.T) { + Reset() + defer func() { + if recover() == nil { + t.Fatal("ohne Handler muss die Panik durchlaufen") + } + }() + Run("x", func() { panic("boom") }) +} + +func TestRunCatches(t *testing.T) { + Reset() + defer Reset() + var got Caught + SetHandler(func(c Caught) { got = c }) + if Run("ui.Update", func() { panic("boom") }) { + t.Fatal("Run meldet ok trotz Panik") + } + if got.Where != "ui.Update" || got.Value != "boom" || !strings.Contains(got.Raw(), "panic: boom") { + t.Fatalf("falsch erfasst: %+v", got) + } + if !Run("x", func() {}) { + t.Fatal("ohne Panik muss Run ok melden") + } + if Count() != 1 { + t.Fatalf("Count = %d", Count()) + } +} + +func TestGoCatches(t *testing.T) { + Reset() + defer Reset() + var wg sync.WaitGroup + wg.Add(1) + SetHandler(func(c Caught) { wg.Done() }) + Go("bg", func() { + var xs []int + i := len(xs) + _ = xs[i] // Index außerhalb: echte Laufzeit-Panik + }) + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Handler nicht aufgerufen") + } +} + +func TestStormRepanics(t *testing.T) { + Reset() + defer Reset() + SetHandler(func(Caught) {}) + for i := 0; i < StormN; i++ { + Run("x", func() { panic(i) }) + } + defer func() { + if recover() == nil { + t.Fatal("beim Sturm muss die Panik durchlaufen") + } + }() + Run("x", func() { panic("zu viel") }) +} + +func TestStormForgets(t *testing.T) { + Reset() + defer Reset() + now := time.Now() + for i := 0; i < StormN; i++ { + if storm(now) { + t.Fatal("zu früh Sturm") + } + } + if storm(now.Add(StormWindow + time.Second)) { + t.Fatal("alte Paniken müssen vergessen werden") + } +} diff --git a/internal/serialx/serial.go b/internal/serialx/serial.go index 29085e2..0f59693 100644 --- a/internal/serialx/serial.go +++ b/internal/serialx/serial.go @@ -14,6 +14,8 @@ import ( "time" "go.bug.st/serial" + + "github.com/db9979/sshtermy/internal/safe" ) // Port: eine gefundene serielle Schnittstelle. @@ -151,13 +153,16 @@ type Stream struct { closed atomic.Bool } +// openPort: Variable für Tests (Gerät ohne echtes Kabel). +var openPort = serial.Open + // Open öffnet die Schnittstelle; alles, was ankommt, geht an out. func Open(name string, baud int, frame string, out io.Writer) (*Stream, error) { mode, err := Mode(baud, frame) if err != nil { return nil, err } - p, err := serial.Open(name, mode) + p, err := openPort(name, mode) if err != nil { return nil, explain(name, err) } @@ -165,7 +170,7 @@ func Open(name string, baud int, frame string, out io.Writer) (*Stream, error) { _ = p.SetDTR(true) _ = p.SetRTS(true) s := &Stream{Name: name, Done: make(chan error, 1), p: p} - go s.read(out) + safe.Go("serialx/serial.go", func() { s.read(out) }) return s, nil } diff --git a/internal/serialx/stream_test.go b/internal/serialx/stream_test.go new file mode 100644 index 0000000..4a7dc06 --- /dev/null +++ b/internal/serialx/stream_test.go @@ -0,0 +1,189 @@ +package serialx + +import ( + "bytes" + "errors" + "strings" + "sync" + "testing" + "time" + + "go.bug.st/serial" +) + +// fakePort: Konsolenkabel ohne Kabel. Liefert die Stücke aus in, danach +// je nach gone: (0, nil) wie ein abgezogenes Kabel unter Linux/macOS oder +// blockiert, bis Close kommt. +type fakePort struct { + mu sync.Mutex + in [][]byte + readErr error + gone bool + closed chan struct{} + written bytes.Buffer + breaks int + dtr bool +} + +func newFake(chunks ...string) *fakePort { + f := &fakePort{closed: make(chan struct{})} + for _, c := range chunks { + f.in = append(f.in, []byte(c)) + } + return f +} + +func (f *fakePort) Read(p []byte) (int, error) { + f.mu.Lock() + if len(f.in) > 0 { + n := copy(p, f.in[0]) + f.in = f.in[1:] + f.mu.Unlock() + return n, nil + } + err, gone := f.readErr, f.gone + f.mu.Unlock() + if err != nil { + return 0, err + } + if gone { + return 0, nil + } + <-f.closed + return 0, errors.New("closed") +} +func (f *fakePort) Write(p []byte) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.written.Write(p) +} +func (f *fakePort) SetMode(*serial.Mode) error { return nil } +func (f *fakePort) Drain() error { return nil } +func (f *fakePort) ResetInputBuffer() error { return nil } +func (f *fakePort) ResetOutputBuffer() error { return nil } +func (f *fakePort) SetDTR(on bool) error { f.dtr = on; return nil } +func (f *fakePort) SetRTS(bool) error { return nil } +func (f *fakePort) SetReadTimeout(time.Duration) error { return nil } +func (f *fakePort) Break(time.Duration) error { f.breaks++; return nil } +func (f *fakePort) Close() error { close(f.closed); return nil } +func (f *fakePort) GetModemStatusBits() (*serial.ModemStatusBits, error) { + return &serial.ModemStatusBits{}, nil +} + +type syncBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuf) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) } +func (s *syncBuf) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } + +func withFake(t *testing.T, f *fakePort) { + t.Helper() + old := openPort + openPort = func(string, *serial.Mode) (serial.Port, error) { return f, nil } + t.Cleanup(func() { openPort = old }) +} + +func waitDone(t *testing.T, s *Stream) error { + t.Helper() + select { + case err := <-s.Done: + return err + case <-time.After(5 * time.Second): + t.Fatal("Stream meldet kein Ende") + return nil + } +} + +func TestStreamReadWriteClose(t *testing.T) { + f := newFake("Switch login: ", "\r\n") + withFake(t, f) + var out syncBuf + s, err := Open("/dev/ttyUSB0", 9600, "8N1", &out) + if err != nil { + t.Fatal(err) + } + if !f.dtr { + t.Fatal("DTR nicht gesetzt (manche Adapter schweigen sonst)") + } + deadline := time.Now().Add(2 * time.Second) + for !strings.Contains(out.String(), "login:") && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if !strings.Contains(out.String(), "Switch login: ") { + t.Fatalf("Ausgabe: %q", out.String()) + } + if _, err := s.Write([]byte("admin\r")); err != nil || f.written.String() != "admin\r" { + t.Fatalf("Write: %v %q", err, f.written.String()) + } + if err := s.Break(); err != nil || f.breaks != 1 { + t.Fatal("Break nicht gesendet") + } + if s.Resize(80, 24) != nil { + t.Fatal("Resize") + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + if s.Close() != nil { + t.Fatal("zweites Close") + } + if err := waitDone(t, s); err != nil { + t.Fatalf("selbst geschlossen muss nil melden: %v", err) + } +} + +// Kabel gezogen: Read liefert ständig 0 Bytes ohne Fehler. +func TestStreamCableGone(t *testing.T) { + f := newFake("x") + f.gone = true + withFake(t, f) + s, err := Open("/dev/ttyUSB0", 115200, "", &syncBuf{}) + if err != nil { + t.Fatal(err) + } + if err := waitDone(t, s); err == nil || !strings.Contains(err.Error(), "gone") { + t.Fatalf("abgezogenes Kabel: %v", err) + } +} + +func TestStreamReadError(t *testing.T) { + f := newFake() + f.readErr = errors.New("I/O error") + withFake(t, f) + s, err := Open("COM3", 9600, "8N1", &syncBuf{}) + if err != nil { + t.Fatal(err) + } + if err := waitDone(t, s); err == nil || err.Error() != "I/O error" { + t.Fatalf("Lesefehler: %v", err) + } +} + +func TestOpenErrors(t *testing.T) { + if _, err := Open("COM3", 9600, "9Z9", &syncBuf{}); err == nil { + t.Fatal("kaputter Rahmen angenommen") + } + old := openPort + defer func() { openPort = old }() + openPort = func(string, *serial.Mode) (serial.Port, error) { return nil, errors.New("kaputt") } + if _, err := Open("COM9", 9600, "8N1", &syncBuf{}); err == nil || !strings.HasPrefix(err.Error(), "COM9: ") { + t.Fatalf("Fehler ohne Schnittstellenname: %v", err) + } +} + +func TestPortNamesAndVendors(t *testing.T) { + if (Port{Name: "COM3"}).String() != "COM3" || (Port{Name: "COM3", Desc: "FTDI"}).String() != "COM3 (FTDI)" { + t.Fatal("Port.String") + } + for vid, want := range map[string]string{"0403": "FTDI", "067B": "Prolific", "10c4": "Silicon Labs", "1a86": "WCH", "05ad": "Cisco", "dead": "USB dead"} { + if got := usbVendor(vid); got != want { + t.Errorf("%s: %q", vid, got) + } + } + e := &AmbiguousError{Ports: []Port{{Name: "COM3"}, {Name: "COM4"}}} + if e.Error() != "several serial ports: COM3, COM4" { + t.Fatal(e.Error()) + } +} diff --git a/internal/sharewire/fuzz_test.go b/internal/sharewire/fuzz_test.go new file mode 100644 index 0000000..3ad1460 --- /dev/null +++ b/internal/sharewire/fuzz_test.go @@ -0,0 +1,47 @@ +package sharewire + +import ( + "bytes" + "testing" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +// Rahmen und Einladungen kommen von fremden Rechnern (Zuschauer, Vermittler): +// nichts davon darf sshTermy zum Absturz bringen. +func FuzzOpen(f *testing.F) { + key := bytes.Repeat([]byte{7}, 32) + good, _ := Seal(key, "sitzung", 3, []byte("hallo")) + f.Add(good, "sitzung") + f.Add([]byte{}, "") + f.Add(make([]byte, 41), "x") + f.Fuzz(func(t *testing.T, frame []byte, id string) { + fuzzguard.Run(t, func() { + typ, p, err := Open(key, id, frame) + if err == nil { + // nur echte Rahmen gehen durch: neu versiegelt wieder lesbar + again, _ := Seal(key, id, typ, p) + if t2, p2, err := Open(key, id, again); err != nil || t2 != typ || !bytes.Equal(p2, p) { + t.Errorf("Rundreise kaputt: %v", err) + } + } + }) + }) +} + +func FuzzInvite(f *testing.F) { + f.Add("7-taube-kompass-ofen") + f.Add("sshtermy://zusehen/7-taube-kompass-ofen") + f.Add("https://example.org/zusehen/#7 taube") + f.Add("\x00\xff 🐟") + f.Fuzz(func(t *testing.T, s string) { + fuzzguard.Run(t, func() { + _, _ = ParseInvite(s) + _, _ = NormBase(s) + _ = IsFP(s) + if c := Clean(s, 40); len(c) > 40+4 { + t.Errorf("Clean zu lang: %d", len(c)) + } + }) + }) +} diff --git a/internal/sshx/agent_unix.go b/internal/sshx/agent_unix.go index 623f14e..2e4fbff 100644 --- a/internal/sshx/agent_unix.go +++ b/internal/sshx/agent_unix.go @@ -19,3 +19,12 @@ func dialAgent() (net.Conn, error) { } return net.Dial("unix", sock) } + +// AgentReachable: läuft ein SSH-Agent, den sshTermy erreicht (Selbstprüfung)? +func AgentReachable() error { + c, err := dialAgent() + if err != nil { + return err + } + return c.Close() +} diff --git a/internal/sshx/agent_windows.go b/internal/sshx/agent_windows.go index bc15392..82af65c 100644 --- a/internal/sshx/agent_windows.go +++ b/internal/sshx/agent_windows.go @@ -21,3 +21,13 @@ func dialAgent() (net.Conn, error) { t := 3 * time.Second return winio.DialPipe(pipe, &t) } + +// AgentReachable: läuft ein SSH-Agent (Pageant oder OpenSSH-Dienst), den +// sshTermy erreicht (Selbstprüfung)? +func AgentReachable() error { + c, err := dialAgent() + if err != nil { + return err + } + return c.Close() +} diff --git a/internal/sshx/client.go b/internal/sshx/client.go index d903fc6..37b701d 100644 --- a/internal/sshx/client.go +++ b/internal/sshx/client.go @@ -21,6 +21,7 @@ import ( "github.com/db9979/sshtermy/internal/debuglog" "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sysprof" ) @@ -461,7 +462,7 @@ func dial(ctx context.Context, c domain.Connection, o Options) (*Client, error) cl.Remote.OS = i18n.T("Windows (OpenSSH) oder unbekannt") } } - go cl.keepAlive(kctx, c.KeepAlive) + safe.Go("sshx/client.go", func() { cl.keepAlive(kctx, c.KeepAlive) }) return cl, nil } @@ -471,6 +472,7 @@ func dial(ctx context.Context, c domain.Connection, o Options) (*Client, error) func (c *Client) alive() bool { done := make(chan error, 1) go func() { + defer safe.Recover("sshx/client.go") _, _, err := c.SendRequest("keepalive@openssh.com", true, nil) done <- err }() @@ -492,6 +494,7 @@ func (c *Client) Check(d time.Duration) bool { } done := make(chan error, 1) go func() { + defer safe.Recover("sshx/client.go") _, _, err := c.SendRequest("keepalive@openssh.com", true, nil) done <- err }() @@ -612,6 +615,7 @@ func (c *Client) keepAliveLoop(ctx context.Context, ping, deadAfter time.Duratio send := func() { inflight, sent = true, time.Now() go func() { + defer safe.Recover("sshx/client.go") _, _, err := c.SendRequest("keepalive@openssh.com", true, nil) res <- err }() diff --git a/internal/sshx/run.go b/internal/sshx/run.go index 1150c93..f1f20de 100644 --- a/internal/sshx/run.go +++ b/internal/sshx/run.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // ErrNetDevice: Exec-Abfragen sind bei Netzwerkgeräten tabu, weil z. B. @@ -62,6 +63,7 @@ func (c *Client) StreamScript(ctx context.Context, script string, line func(stri return err } go func() { + defer safe.Recover("sshx/run.go") <-ctx.Done() _ = s.Close() // beendet auch das Lesen unten }() diff --git a/internal/sshx/sftp_test.go b/internal/sshx/sftp_test.go new file mode 100644 index 0000000..f407293 --- /dev/null +++ b/internal/sshx/sftp_test.go @@ -0,0 +1,178 @@ +package sshx + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "io" + "net" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + + "github.com/db9979/sshtermy/internal/domain" +) + +// startSFTPServer: SSH-Server mit sftp-Subsystem auf einem echten Ordner. +func startSFTPServer(t *testing.T, root string) string { + t.Helper() + _, priv, _ := ed25519.GenerateKey(rand.Reader) + signer, _ := ssh.NewSignerFromKey(priv) + cfg := &ssh.ServerConfig{PasswordCallback: func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) { return nil, nil }} + cfg.AddHostKey(signer) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + nc, err := ln.Accept() + if err != nil { + return + } + go func() { + sc, chans, reqs, err := ssh.NewServerConn(nc, cfg) + if err != nil { + return + } + defer sc.Close() + go ssh.DiscardRequests(reqs) + for nch := range chans { + ch, creqs, err := nch.Accept() + if err != nil { + continue + } + go func() { + for r := range creqs { + ok := r.Type == "subsystem" && len(r.Payload) > 4 && string(r.Payload[4:]) == "sftp" + _ = r.Reply(ok, nil) + if ok { + srv, err := sftp.NewServer(ch, sftp.WithServerWorkingDirectory(root)) + if err == nil { + _ = srv.Serve() + } + ch.Close() + return + } + } + }() + } + }() + } + }() + return ln.Addr().String() +} + +func TestSFTPRoundTrip(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Server-Pfade im Test sind Unix-Pfade") + } + remote := t.TempDir() + cl := dialAddr(t, startSFTPServer(t, remote), domain.DeviceServer) + r, err := cl.OpenSFTP() + if err != nil { + t.Fatal(err) + } + defer r.Close() + if r.Label() != "x" || r.Home() == "" { + t.Fatalf("Label/Home: %q %q", r.Label(), r.Home()) + } + dir := r.Join(remote, "ordner", "unter") + if err := r.Mkdir(dir); err != nil { + t.Fatal(err) + } + if r.Dir(dir) != filepath.ToSlash(filepath.Join(remote, "ordner")) && r.Dir(dir) != r.Join(remote, "ordner") { + t.Fatalf("Dir: %q", r.Dir(dir)) + } + f := r.Join(dir, "a.txt") + w, err := r.Create(f, 0o640) + if err != nil { + t.Fatal(err) + } + _, _ = io.WriteString(w, "hallo welt") + if err := w.Close(); err != nil { + t.Fatal(err) + } + if err := r.Rewrite(f, []byte("neu")); err != nil { + t.Fatal(err) + } + rc, err := r.Open(f) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(rc) + rc.Close() + if string(b) != "neu" { + t.Fatalf("Inhalt: %q", b) + } + e, err := r.Stat(f) + if err != nil || e.IsDir || e.Size != 3 { + t.Fatalf("Stat: %+v %v", e, err) + } + if err := r.Chmod(f, 0o600); err != nil { + t.Fatal(err) + } + // Umbenennen überschreibt nie + g := r.Join(dir, "b.txt") + if err := r.Rewrite(g, []byte("b")); err != nil { + t.Fatal(err) + } + if err := r.Rename(f, g); err == nil || !strings.Contains(err.Error(), "b.txt") { + t.Fatalf("Umbenennen auf vorhandene Datei: %v", err) + } + h := r.Join(dir, "c.txt") + if err := r.Rename(f, h); err != nil { + t.Fatal(err) + } + es, err := r.ReadDir(dir) + if err != nil || len(es) != 2 { + t.Fatalf("ReadDir: %+v %v", es, err) + } + if _, err := r.Stat(r.Join(remote, "gibt-es-nicht")); err == nil { + t.Fatal("Stat auf fehlende Datei ohne Fehler") + } + + // Kopieren in beide Richtungen mit Fortschritt + local := t.TempDir() + var pr Progress + if err := Copy(context.Background(), r, r.Join(remote, "ordner"), LocalFS{}, local, &pr); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(local, "ordner", "unter", "c.txt")) + if err != nil || string(got) != "neu" { + t.Fatalf("heruntergeladen: %q %v", got, err) + } + if pr.Files.Load() != 2 { + t.Fatalf("Fortschritt Dateien: %d", pr.Files.Load()) + } + up := r.Join(remote, "hoch") + _ = r.Mkdir(up) + if err := Copy(context.Background(), LocalFS{}, filepath.Join(local, "ordner"), r, up, &Progress{}); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(remote, "hoch", "ordner", "unter", "b.txt")); err != nil { + t.Fatalf("hochgeladen: %v", err) + } + n, files, err := Size(context.Background(), r, up) + if err != nil || files != 2 || n != 4 { + t.Fatalf("Size: %d %d %v", n, files, err) + } + // Abbrechen + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := Copy(ctx, r, up, LocalFS{}, t.TempDir(), &Progress{}); err == nil { + t.Fatal("abgebrochene Kopie ohne Fehler") + } + if err := r.RemoveAll(r.Join(remote, "ordner")); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(remote, "ordner")); !os.IsNotExist(err) { + t.Fatalf("RemoveAll: %v", err) + } +} diff --git a/internal/sshx/tunnel.go b/internal/sshx/tunnel.go index 28e6099..a1a50d1 100644 --- a/internal/sshx/tunnel.go +++ b/internal/sshx/tunnel.go @@ -14,6 +14,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // ActiveTunnel ist ein laufendes Forwarding mit Zählern für die Oberfläche. @@ -122,7 +123,7 @@ func (m *TunnelManager) Start(t domain.Tunnel) (*ActiveTunnel, error) { m.active[t.ID] = a m.mu.Unlock() - go m.serve(a) + safe.Go("sshx/tunnel.go", func() { m.serve(a) }) if t.AutoOpen && a.URL() != "" { _ = OpenBrowser(a.URL()) } @@ -140,6 +141,7 @@ func (m *TunnelManager) serve(a *ActiveTunnel) { a.Conns.Add(1) a.Total.Add(1) go func() { + defer safe.Recover("sshx/tunnel.go") defer a.Conns.Add(-1) defer in.Close() switch a.Spec.Kind { diff --git a/internal/sshx/x11.go b/internal/sshx/x11.go index 52a129d..74163c2 100644 --- a/internal/sshx/x11.go +++ b/internal/sshx/x11.go @@ -21,6 +21,7 @@ import ( "golang.org/x/crypto/ssh" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // X11-Weiterleitung (wie ssh -X) @@ -69,8 +70,9 @@ func (c *Client) requestX11(sess *ssh.Session) { } c.x11 = f go func() { + defer safe.Recover("sshx/x11.go") for nc := range ch { - go f.serve(nc) + safe.Go("sshx/x11.go", func() { f.serve(nc) }) } }() }) @@ -193,6 +195,7 @@ func (f *x11Fwd) serve(nc ssh.NewChannel) { var wg sync.WaitGroup wg.Add(1) go func() { + defer safe.Recover("sshx/x11.go") defer wg.Done() _, _ = io.Copy(local, ch) if cw, ok := local.(interface{ CloseWrite() error }); ok { diff --git a/internal/syncx/fuzz_test.go b/internal/syncx/fuzz_test.go new file mode 100644 index 0000000..743071a --- /dev/null +++ b/internal/syncx/fuzz_test.go @@ -0,0 +1,29 @@ +package syncx + +import ( + "testing" + + "github.com/db9979/sshtermy/internal/fuzzguard" +) + +// Die Sync-Datei liegt in einem fremden Ordner (Cloud, WebDAV, USB-Stick): +// kaputte oder manipulierte Dateien müssen sauber abgelehnt werden. +func FuzzDecode(f *testing.F) { + k, err := NewKey([]byte("ein langes sync passwort")) + if err != nil { + f.Fatal(err) + } + good, err := Encode(k, &Payload{}) + if err != nil { + f.Fatal(err) + } + f.Add(good) + f.Add([]byte(`{"format":"sshtermy-sync","version":99}`)) + f.Add([]byte(`{}`)) + f.Fuzz(func(t *testing.T, raw []byte) { + fuzzguard.Run(t, func() { + _, _ = Decode(k, raw) + _, _ = ParseKey(string(raw)) + }) + }) +} diff --git a/internal/team/link.go b/internal/team/link.go index 9038f81..c9dae3a 100644 --- a/internal/team/link.go +++ b/internal/team/link.go @@ -68,9 +68,13 @@ func request(ctx context.Context, method, loc string, body []byte) (*http.Respon if user != "" { req.SetBasicAuth(user, pass) } - return http.DefaultClient.Do(req) + return linkClient.Do(req) } +// linkClient: eigene Zeitgrenze, auch wenn ein Aufrufer keine setzt (ein +// hängender WebDAV-/HTTP-Server darf den Abgleich nicht ewig festhalten). +var linkClient = &http.Client{Timeout: 60 * time.Second} + // ReadLoc liest das Team-Paket von einem Ort. func ReadLoc(ctx context.Context, loc string) ([]byte, error) { if !IsURL(loc) { diff --git a/internal/telnet/telnet.go b/internal/telnet/telnet.go index b56053e..2a23cde 100644 --- a/internal/telnet/telnet.go +++ b/internal/telnet/telnet.go @@ -12,6 +12,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/db9979/sshtermy/internal/safe" ) // Telnet-Befehle und -Optionen. @@ -73,7 +75,7 @@ func Dial(ctx context.Context, addr string, cols, rows int, out io.Writer) (*Con func newConn(nc net.Conn, cols, rows int, out io.Writer) *Conn { c := &Conn{c: nc, Done: make(chan error, 1), cols: cols, rows: rows} - go c.read(out) + safe.Go("telnet/telnet.go", func() { c.read(out) }) return c } diff --git a/internal/termemu/hostqueue.go b/internal/termemu/hostqueue.go index 8365207..e6a8260 100644 --- a/internal/termemu/hostqueue.go +++ b/internal/termemu/hostqueue.go @@ -4,6 +4,8 @@ import ( "io" "sync" "time" + + "github.com/db9979/sshtermy/internal/safe" ) // hostQueueMax: so viel darf auf dem Weg zum Server warten. Mehr sammelt sich @@ -28,7 +30,7 @@ type hostQueue struct { func newHostQueue(w io.Writer) *hostQueue { q := &hostQueue{w: w} q.cond = sync.NewCond(&q.mu) - go q.run() + safe.Go("termemu/hostqueue.go", func() { q.run() }) return q } diff --git a/internal/termemu/term.go b/internal/termemu/term.go index e00632c..cf2523d 100644 --- a/internal/termemu/term.go +++ b/internal/termemu/term.go @@ -22,6 +22,8 @@ import ( uv "github.com/charmbracelet/ultraviolet" "github.com/charmbracelet/x/ansi" "github.com/charmbracelet/x/vt" + + "github.com/db9979/sshtermy/internal/safe" ) // Term ist ein emuliertes Terminal für genau eine SSH-Shell. @@ -133,6 +135,7 @@ func New(cols, rows int, toHost io.Writer) *Term { return true }) go func() { + defer safe.Recover("termemu/term.go") buf := make([]byte, 4096) for { n, err := t.emu.Read(buf) @@ -294,6 +297,11 @@ func (t *Term) SendText(s string) { t.emu.SendText(s) } +// SendRaw schickt Bytes unverändert in die Warteschlange zum Server, in +// derselben Reihenfolge wie Tasten. Kehrt sofort zurück, auch wenn die +// Verbindung hängt (anders als ein direktes Schreiben in die Shell). +func (t *Term) SendRaw(p []byte) { _, _ = t.host.Write(p) } + // Paste nutzt Bracketed Paste, wenn die Shell es eingeschaltet hat. func (t *Term) Paste(s string) { if t.muted.Load() { diff --git a/internal/ui/activity.go b/internal/ui/activity.go index e0c5dc1..9edfa03 100644 --- a/internal/ui/activity.go +++ b/internal/ui/activity.go @@ -95,7 +95,7 @@ func (a *App) activityBlock(rb *strings.Builder, logs []*sessionlog.Log, w int, } if n := perDay[d]; n > 0 { day := d - cell = a.z.click(cell, func(tea.Mouse, bool) tea.Cmd { a.jumpToDay(day); return nil }) + cell = a.z.Click(cell, func(tea.Mouse, bool) tea.Cmd { a.jumpToDay(day); return nil }) } line.WriteString(cell + " ") } diff --git a/internal/ui/agentmode_view.go b/internal/ui/agentmode_view.go index 7e57c63..949c0da 100644 --- a/internal/ui/agentmode_view.go +++ b/internal/ui/agentmode_view.go @@ -36,7 +36,7 @@ func (a *App) viewModeChoice(b *strings.Builder, s *session, w int) { } line := mark + style.Render(trunc(o.name, max(4, w-2))) o := o - b.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd { + b.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { s.panelFocus = true g.auto, g.level, g.planFirst = o.auto, o.level, o.plan return g.input.Focus() diff --git a/internal/ui/aicards.go b/internal/ui/aicards.go index 5fc5ff6..dcd075e 100644 --- a/internal/ui/aicards.go +++ b/internal/ui/aicards.go @@ -13,6 +13,8 @@ import ( "github.com/db9979/sshtermy/internal/agent" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/safety" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // KI-Antworten als Karten: Befehle aus Codeblöcken stehen in eigenen, @@ -224,7 +226,7 @@ func (a *App) viewAnswer(b *strings.Builder, s *session, ans string, w int) { arrow, hint = "▸ ", i18n.T("ausklappen") } head := st.AI.Render(arrow+i18n.T("Erklärung")) + st.Muted.Render(" z "+hint) - b.WriteString(a.z.click(head, func(tea.Mouse, bool) tea.Cmd { + b.WriteString(a.z.Click(head, func(tea.Mouse, bool) tea.Cmd { q.collapsed = !q.collapsed s.panelFocus = true return nil @@ -357,7 +359,7 @@ func (a *App) commandCard(s *session, i int, cd card, sel, armed bool, kind stri if withText && (!armed || bt.key == "a") { // scharf: nur die Rückfrage zählt txt += lipgloss.NewStyle().Foreground(st.T.Muted).Render(" " + bt.text) } - out = append(out, a.z.click(txt, func(tea.Mouse, bool) tea.Cmd { + out = append(out, a.z.Click(txt, func(tea.Mouse, bool) tea.Cmd { s.ask.sel = i return bt.f() })) @@ -377,7 +379,7 @@ func (a *App) commandCard(s *session, i int, cd card, sel, armed bool, kind stri content += "\n" + bar } card := box.Render(content) - return a.z.mark(card, zoneAction{block: true, click: func(_ tea.Mouse, double bool) tea.Cmd { + return a.z.Mark(card, clickzone.Action{Block: true, Click: func(_ tea.Mouse, double bool) tea.Cmd { s.ask.sel, s.panelFocus = i, true if double && cd.runnable() { return a.cardInsert(s, i) diff --git a/internal/ui/app.go b/internal/ui/app.go index 0b4807f..502aca9 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -25,6 +25,7 @@ import ( "image/color" "os" "strings" + "sync/atomic" "time" tea "charm.land/bubbletea/v2" @@ -44,6 +45,8 @@ import ( "github.com/db9979/sshtermy/internal/vault" "github.com/db9979/sshtermy/internal/version" "github.com/db9979/sshtermy/internal/vuln" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) type screen int @@ -88,6 +91,10 @@ const ( // App ist das Wurzel-Modell. type App struct { + // Absturzschutz (safety.go): letztes gutes Bild, wartende Empfänger + lastView tea.View + listening atomic.Int32 + // asyncModals: Rückfragen, die von selbst kamen, während schon ein Dialog // offen war (modalguard.go). Sie überschreiben ihn nicht, sie warten. asyncModals []*modal @@ -222,8 +229,8 @@ type App struct { keys keymap // aktuelle Tastenbelegung lookSig string // Theme+Tasten, zuletzt übernommen - z zones // klickbare Bereiche des letzten Bildes - click clickState // für Doppel-/Dreifachklick + z clickzone.Map // klickbare Bereiche des letzten Bildes + click clickState // für Doppel-/Dreifachklick pick *picker // Auswahlliste mit Suche (Jump-Host, Ordner, Tag) @@ -261,7 +268,11 @@ func New(st *store.Store) (*App, error) { func (a *App) listen() tea.Cmd { ev := a.events - return func() tea.Msg { return <-ev } + return func() tea.Msg { + a.listening.Add(1) // safety.go: nach abgefangenem Fehler neu anstoßen? + defer a.listening.Add(-1) + return <-ev + } } type tickMsg time.Time @@ -289,7 +300,7 @@ func (a *App) checkUpdate() tea.Cmd { // checkRelease: Variable für Tests. var checkRelease = update.CheckAged -func (a *App) Init() tea.Cmd { +func (a *App) init0() tea.Cmd { var intro tea.Cmd if a.intro != nil { a.intro.start = time.Now() @@ -314,7 +325,7 @@ func (a *App) byID(id int) *session { return nil } -func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (a *App) update0(msg tea.Msg) (tea.Model, tea.Cmd) { if a.scr != scrManager { a.mgr.forTab = false // „+“-Auswahl gilt nur, solange der Manager offen ist } @@ -614,6 +625,10 @@ func (a *App) coreMsg(msg tea.Msg) (tea.Cmd, bool) { // featureMsg reicht die Nachricht an die Bereiche weiter (Broadcast, Sync, // KI, Dateien …); jeder nimmt nur seine eigenen. func (a *App) featureMsg(msg tea.Msg) (tea.Cmd, bool) { + if m, ok := msg.(doctorMsg); ok { // Selbstprüfung (doctor.go) + a.doctorDone(m) + return nil, true + } if m, ok := msg.(palFindMsg); ok { // „Wo finde ich …?“ (palask.go) return a.palFindDone(m), true } @@ -935,11 +950,8 @@ func (a *App) onTick() tea.Cmd { // ---------------------------------------------------------------- Layout -// View: gemessen, bei Ausgabeflut gedrosselt (perf.go). -func (a *App) View() tea.View { return a.view() } - func (a *App) viewFrame() tea.View { - a.z.reset() + a.z.Reset() var body string var cur *tea.Cursor switch a.scr { @@ -996,9 +1008,9 @@ func (a *App) viewFrame() tea.View { case scrScan: body = a.frame(a.viewScan(), a.scanKeys()) } - body = a.z.scan(body, 0, 0) + body = a.z.Scan(body, 0, 0) if a.lock != nil { - a.z.reset() // gesperrt: nichts klickbar, nichts zu sehen + a.z.Reset() // gesperrt: nichts klickbar, nichts zu sehen body, cur = a.viewLock(), nil } else if a.modal != nil { body = a.overlay(body, a.modalView()) @@ -1021,7 +1033,7 @@ func (a *App) viewFrame() tea.View { body = a.withPerf(body) } if a.intro != nil && introFits(a.w, a.h) { - a.z.reset() // während der Animation ist nichts klickbar + a.z.Reset() // während der Animation ist nichts klickbar body, cur = a.viewIntro(), nil } if cur != nil && !a.s.T.Dark { @@ -1052,7 +1064,7 @@ func (a *App) headerLeft() string { logo := a.logoChip(">_ " + version.Name) // gradient.go if a.scr == scrTerminal && len(a.sessions) > 0 { // Klick aufs Logo: Manager für einen weiteren Tab, wie „+“ (tabs.go) - return a.z.click(logo, func(tea.Mouse, bool) tea.Cmd { return a.openNewTab() }) + return a.z.Click(logo, func(tea.Mouse, bool) tea.Cmd { return a.openNewTab() }) } return logo } @@ -1276,8 +1288,8 @@ func (a *App) overlay(base, box string) string { if k, run := a.fadeLevel(); run && !a.fx.out { box = fadeANSI(box, a.s.T, k) } - a.z.rects = a.z.rects[:0] - box = a.z.scan(box, x, y) + a.z.ClearRects() + box = a.z.Scan(box, x, y) return stamp(a.overlayBackground(base, x, y, bw, bh), box, x, y, a.w) } diff --git a/internal/ui/bcgrid.go b/internal/ui/bcgrid.go index 26d1ffd..0120014 100644 --- a/internal/ui/bcgrid.go +++ b/internal/ui/bcgrid.go @@ -18,6 +18,8 @@ import ( "github.com/db9979/sshtermy/internal/broadcast" "github.com/db9979/sshtermy/internal/i18n" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) const ( @@ -137,16 +139,16 @@ func (a *App) bcTile(i, w, h, bodyH int) (string, int) { } tb.WriteString(bs.Render(string(bc[0]) + strings.Repeat("─", inner) + string(bc[1]))) i2 := i - tile := a.z.mark(tb.String(), zoneAction{ - block: true, - click: func(_ tea.Mouse, double bool) tea.Cmd { + tile := a.z.Mark(tb.String(), clickzone.Action{ + Block: true, + Click: func(_ tea.Mouse, double bool) tea.Cmd { b.sel = i2 if double { b.zoom = !b.zoom } return nil }, - wheel: func(up bool) tea.Cmd { + Wheel: func(up bool) tea.Cmd { if up { b.scroll = max(0, b.scroll-3) } else { diff --git a/internal/ui/broadcast.go b/internal/ui/broadcast.go index 988443d..577a963 100644 --- a/internal/ui/broadcast.go +++ b/internal/ui/broadcast.go @@ -18,6 +18,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/runbook" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" ) @@ -363,6 +364,7 @@ func (a *App) bcStart(targets []domain.Connection, steps []string, per [][]strin job.Canary, job.StopAfter = !b.noCanary, bcStopAfter } go func() { + defer safe.Recover("ui/broadcast.go") broadcast.Run(ctx, job, dial, func(i int, r broadcast.Result) { ev <- bcUpdateMsg{seq, i, r} }) ev <- bcDoneMsg{seq} }() @@ -601,7 +603,7 @@ func (a *App) viewBcSetup() string { m = s.Accent.Render("▌ ") st = lipgloss.NewStyle().Foreground(s.T.Text).Bold(true).Width(20) } - return m + a.z.click(st.Render(title), func(tea.Mouse, bool) tea.Cmd { return b.setFocus(focus) }) + return m + a.z.Click(st.Render(title), func(tea.Mouse, bool) tea.Cmd { return b.setFocus(focus) }) } // Hosts @@ -646,7 +648,7 @@ func (a *App) viewBcSetup() string { line = s.Selected.Width(w - 4).Render(ansi.Strip(line)) } i, id := i, c.ID - line = a.z.click(line, func(tea.Mouse, bool) tea.Cmd { + line = a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { b.cur, b.picked[id], b.err = i, !b.picked[id], "" return b.setFocus(bcFocusHosts) }) @@ -663,7 +665,7 @@ func (a *App) viewBcSetup() string { p = s.Selected.Render(" " + trunc(n, 24) + " ") } i := i - parts = append(parts, a.z.click(p, func(tea.Mouse, bool) tea.Cmd { b.src = i; return b.setFocus(bcFocusSource) })) + parts = append(parts, a.z.Click(p, func(tea.Mouse, bool) tea.Cmd { b.src = i; return b.setFocus(bcFocusSource) })) } src := strings.Join(parts, "") if lipgloss.Width(src) > w-24 { diff --git a/internal/ui/clickzone/zones.go b/internal/ui/clickzone/zones.go new file mode 100644 index 0000000..3a32e4c --- /dev/null +++ b/internal/ui/clickzone/zones.go @@ -0,0 +1,222 @@ +// Package clickzone: klickbare Bereiche im fertigen Bild (Maus), aus +// internal/ui ausgelagert (erster Schritt der Aufteilung). +package clickzone + +import ( + "math" + "strconv" + "strings" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +// Klickbare Bereiche (Zonen) +// +// Beim Zeichnen wird anklickbarer Text mit zwei unsichtbaren Markern +// umschlossen (CSI z, eine Sequenz, die kein Terminal kennt und die +// lipgloss als Breite 0 behandelt). Nach dem Zusammensetzen eines Bildes +// sucht Map.Scan die Marker, merkt sich die Rechtecke und entfernt die +// Marker wieder. So bleibt jede Ansicht frei in ihrem Layout, und die +// Mausbehandlung muss keine Positionen nachrechnen. + +const Base = 71000 + +type Action struct { + Click func(m tea.Mouse, double bool) tea.Cmd // nil = nicht klickbar + Menu func(m tea.Mouse) tea.Cmd // Rechts- oder Mittelklick, nil = keiner + Wheel func(up bool) tea.Cmd // nil = Rad geht weiter nach außen + Block bool // rechteckiger Block (Box), sonst Fließtext + Row int // Manager: Zeile+1 als Ziel beim Ziehen (0 = keins); Dateien: Eintrag+1 + Pane int // Dateien: Seite+1 (0 = keine) + Tab int // Tab-Leiste: Tab+1 als Ziel beim Ziehen (0 = keins) + Tip func() string // Karte beim Verweilen der Maus (motion.go) +} + +type Rect struct { + X0, Y0, X1, Y1 int // inklusive + id int + block bool +} + +func (r Rect) Contains(x, y int) bool { + if y < r.Y0 || y > r.Y1 { + return false + } + if r.Y0 == r.Y1 || r.block { + return x >= r.X0 && x <= r.X1 + } + // mehrzeilig: wie Fließtext (erste Zeile ab x0, letzte bis x1) + switch y { + case r.Y0: + return x >= r.X0 + case r.Y1: + return x <= r.X1 + } + return true +} + +type Map struct { + acts []Action + rects []Rect +} + +func (z *Map) Reset() { z.acts, z.rects = z.acts[:0], z.rects[:0] } + +// ClearRects vergisst nur die Rechtecke (Overlay wird neu vermessen). +func (z *Map) ClearRects() { z.rects = z.rects[:0] } + +func Marker(id int) string { return "\x1b[" + strconv.Itoa(Base+id) + "z" } + +// Mark umschließt s mit einer Zone. +func (z *Map) Mark(s string, act Action) string { + if s == "" { + return s + } + id := len(z.acts) + z.acts = append(z.acts, act) + m := Marker(id) + return m + s + m +} + +func (z *Map) Click(s string, f func(m tea.Mouse, double bool) tea.Cmd) string { + return z.Mark(s, Action{Click: f}) +} + +// Scan entfernt die Marker aus s und merkt sich die Rechtecke, verschoben +// um ox/oy (für Overlays). +func (z *Map) Scan(s string, ox, oy int) string { + if !strings.Contains(s, "\x1b[") { + return s + } + var out strings.Builder + out.Grow(len(s)) + open := map[int][2]int{} + x, y := 0, 0 + state := byte(0) + for len(s) > 0 { + seq, width, n, newState := ansi.DecodeSequence(s, state, nil) + state = newState + if n <= 0 { + break + } + if seq == "\n" { + x, y = 0, y+1 + out.WriteString(seq) + s = s[n:] + continue + } + if width == 0 && len(seq) > 3 && seq[0] == 0x1b && seq[1] == '[' && seq[len(seq)-1] == 'z' { + if v, err := strconv.Atoi(seq[2 : len(seq)-1]); err == nil && v >= Base && v-Base < len(z.acts) { + id := v - Base + if st, ok := open[id]; ok { + delete(open, id) + if x > st[0] || y > st[1] { + z.rects = append(z.rects, Rect{st[0] + ox, st[1] + oy, x - 1 + ox, y + oy, id, z.acts[id].Block}) + } + } else { + open[id] = [2]int{x, y} + } + s = s[n:] + continue + } + } + out.WriteString(seq) + x += width + s = s[n:] + } + for id, st := range open { // Ende abgeschnitten: bis zum Bildende + z.rects = append(z.rects, Rect{st[0] + ox, st[1] + oy, 1 << 20, y + oy, id, z.acts[id].Block}) + } + return out.String() +} + +// At: die innerste (zuletzt geöffnete, also kleinste) Zone unter x/y, die +// die gewünschte Aktion hat. +func (z *Map) At(x, y int, wheel bool) *Action { + var best *Action + bestArea := math.MaxInt + for _, r := range z.rects { + if !r.Contains(x, y) { + continue + } + act := &z.acts[r.id] + if (wheel && act.Wheel == nil) || (!wheel && act.Click == nil) { + continue + } + area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0) + if area <= bestArea { + best, bestArea = act, area + } + } + return best +} + +// TipAt: die innerste Zone unter x/y mit Hover-Karte. +func (z *Map) TipAt(x, y int) (*Action, Rect) { + var best *Action + var br Rect + bestArea := math.MaxInt + for _, r := range z.rects { + if !r.Contains(x, y) || z.acts[r.id].Tip == nil { + continue + } + if area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0); area <= bestArea { + best, br, bestArea = &z.acts[r.id], r, area + } + } + return best, br +} + +// AtMenu: die innerste Zone unter x/y mit Rechtsklick-Aktion (Tabs). +func (z *Map) AtMenu(x, y int) *Action { + var best *Action + bestArea := math.MaxInt + for _, r := range z.rects { + if !r.Contains(x, y) || z.acts[r.id].Menu == nil { + continue + } + if area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0); area <= bestArea { + best, bestArea = &z.acts[r.id], area + } + } + return best +} + +// RowAt: Zeile (row-1) unter x/y für das Ziehen im Manager, sonst -1. +func (z *Map) RowAt(x, y int) int { + for _, r := range z.rects { + if y >= r.Y0 && y <= r.Y1 && z.acts[r.id].Row > 0 && z.acts[r.id].Pane == 0 { // nur die Zeile zählt + _ = x + return z.acts[r.id].Row - 1 + } + } + return -1 +} + +// TabAt: Tab (tab-1) unter x/y für das Ziehen in der Tab-Leiste, sonst -1. +func (z *Map) TabAt(x, y int) int { + for _, r := range z.rects { + if z.acts[r.id].Tab > 0 && r.Contains(x, y) { + return z.acts[r.id].Tab - 1 + } + } + return -1 +} + +// FileAt: Seite und Eintrag des Dateibrowsers unter x/y (je -1 = keiner). +func (z *Map) FileAt(x, y int) (side, row int) { + side, row = -1, -1 + bestArea := math.MaxInt + for _, r := range z.rects { + act := z.acts[r.id] + if act.Pane == 0 || !r.Contains(x, y) { + continue + } + area := (r.Y1-r.Y0+1)*4096 + (r.X1 - r.X0) + if area <= bestArea { + bestArea, side, row = area, act.Pane-1, act.Row-1 + } + } + return side, row +} diff --git a/internal/ui/zones_test.go b/internal/ui/clickzone/zones_test.go similarity index 85% rename from internal/ui/zones_test.go rename to internal/ui/clickzone/zones_test.go index 929f3c3..12bae14 100644 --- a/internal/ui/zones_test.go +++ b/internal/ui/clickzone/zones_test.go @@ -1,4 +1,4 @@ -package ui +package clickzone import ( "strings" @@ -10,17 +10,17 @@ import ( ) func TestZonesSurviveLayout(t *testing.T) { - var z zones + var z Map hit := "" mk := func(name, s string) string { - return z.click(s, func(tea.Mouse, bool) tea.Cmd { hit = name; return nil }) + return z.Click(s, func(tea.Mouse, bool) tea.Cmd { hit = name; return nil }) } st := lipgloss.NewStyle().Background(lipgloss.Color("#333")).Padding(0, 1) left := lipgloss.NewStyle().Width(20).Render("Liste\n" + st.Render(mk("a", "Eintrag A")) + "\n" + mk("b", "Eintrag B")) right := lipgloss.NewStyle().Width(30).Render("Detail " + mk("c", lipgloss.NewStyle().Bold(true).Render("Knopf"))) body := lipgloss.JoinHorizontal(lipgloss.Top, left, "│", right) body = lipgloss.Place(60, 6, lipgloss.Center, lipgloss.Center, body) - clean := z.scan(body, 0, 0) + clean := z.Scan(body, 0, 0) if strings.Contains(clean, "71000z") || strings.Contains(clean, "\x1b[710") { t.Fatalf("Marker nicht entfernt: %q", clean) } @@ -37,14 +37,14 @@ func TestZonesSurviveLayout(t *testing.T) { for _, c := range []struct{ word, want string }{{"Eintrag A", "a"}, {"Eintrag B", "b"}, {"Knopf", "c"}} { x, y := find(c.word) hit = "" - if act := z.at(x+2, y, false); act != nil { - act.click(tea.Mouse{}, false) + if act := z.At(x+2, y, false); act != nil { + act.Click(tea.Mouse{}, false) } if hit != c.want { t.Errorf("%s bei %d,%d: Treffer %q, erwartet %q", c.word, x+2, y, hit, c.want) } } - if act := z.at(0, 0, false); act != nil { + if act := z.At(0, 0, false); act != nil { t.Errorf("Treffer außerhalb aller Zonen") } } diff --git a/internal/ui/cmdsets.go b/internal/ui/cmdsets.go index aa06366..35bd0fe 100644 --- a/internal/ui/cmdsets.go +++ b/internal/ui/cmdsets.go @@ -281,7 +281,7 @@ func (a *App) viewCmdSets() string { line = s.Text.Render(name) + " " + s.Muted.Render(id) + " " + s.Muted.Render(src) + " " } i := i - b.WriteString(a.z.click(" "+mark+line+state, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(" "+mark+line+state, func(_ tea.Mouse, double bool) tea.Cmd { c.sel = i if double { a.modal = textModal(rows[i].Set.Name, a.cmdsetDetails(rows[i])) diff --git a/internal/ui/colors.go b/internal/ui/colors.go index 8cdff83..2cb3e4d 100644 --- a/internal/ui/colors.go +++ b/internal/ui/colors.go @@ -215,7 +215,7 @@ func (a *App) viewColors() string { if th.Name == ThemeByName(e.c.Base).Name { chip = s.Badge.Foreground(t.Accent).Bold(true).Render("✓ " + short) } - line += a.z.click(chip, func(tea.Mouse, bool) tea.Cmd { + line += a.z.Click(chip, func(tea.Mouse, bool) tea.Cmd { e.sel, e.c = 0, domain.CustomColors{Base: th.Name} a.previewColors() return nil @@ -245,7 +245,7 @@ func (a *App) viewColors() string { name = s.Text.Render(name) } row := name + sw + " " + val + mark - b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { e.sel = i + 1 if double { e.editing, e.buf = true, hexOf(f.of(CustomTheme(e.c))) diff --git a/internal/ui/companion_view.go b/internal/ui/companion_view.go index f6e4b11..e99a027 100644 --- a/internal/ui/companion_view.go +++ b/internal/ui/companion_view.go @@ -91,7 +91,7 @@ func (a *App) companionLine(s *session) string { l += strings.Repeat(" ", max(0, a.w-lipgloss.Width(l)-lipgloss.Width(end))) + end out[i] = ansi.Truncate(l, a.w, "") } - return a.z.click(strings.Join(out, "\n"), func(tea.Mouse, bool) tea.Cmd { return a.toggleCompanionBar(s) }) + return a.z.Click(strings.Join(out, "\n"), func(tea.Mouse, bool) tea.Cmd { return a.toggleCompanionBar(s) }) } // toggleCompanionBar: Leiste ein/aus (Taste, Klick). diff --git a/internal/ui/detach.go b/internal/ui/detach.go index 3965cb4..a9e155c 100644 --- a/internal/ui/detach.go +++ b/internal/ui/detach.go @@ -12,6 +12,7 @@ import ( "github.com/db9979/sshtermy/internal/detach" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/termemu" "github.com/db9979/sshtermy/internal/version" ) @@ -100,6 +101,7 @@ func (a *App) toggleDetach(s *session) tea.Cmd { s.panelFocus = false sid, ev := s.id, a.events go func() { + defer safe.Recover("ui/detach.go") c, cols, rows, err := srv.Accept(20 * time.Second) ev <- detachConnMsg{sid, srv, c, cols, rows, err} }() @@ -148,6 +150,7 @@ func (a *App) onDetachConn(m detachConnMsg) { // Tasten und Größe aus dem Fenster sid, ev, c := s.id, a.events, m.conn go func() { + defer safe.Recover("ui/detach.go") for { e, err := c.Read() if err != nil { diff --git a/internal/ui/doctor.go b/internal/ui/doctor.go new file mode 100644 index 0000000..41f4210 --- /dev/null +++ b/internal/ui/doctor.go @@ -0,0 +1,58 @@ +package ui + +import ( + "context" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/doctor" + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/llm" +) + +// Selbstprüfung (internal/doctor) aus der Palette: wie „sshtermy doctor“, +// dazu der KI-Endpunkt (dafür muss der Tresor offen sein). Das Ergebnis +// steht in einem Textfenster, c kopiert es für den Fehlerbericht. + +type doctorMsg struct{ text string } + +func (a *App) runDoctor() tea.Cmd { + a.flash(i18n.T("Selbstprüfung läuft …")) + dir := a.st.Dir + chain := a.st.LLM().Chain() + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + rs := doctor.Run(ctx, doctor.Env{Dir: dir, Extra: []doctor.Check{aiCheck(chain[0])}}) + return doctorMsg{doctor.Format(rs)} + } +} + +// aiCheck: antwortet der eingestellte KI-Endpunkt? (ohne Schlüssel im Text) +func aiCheck(cfg domain.LLMConfig) doctor.Check { + return func(ctx context.Context) doctor.Result { + name := i18n.T("KI") + if cfg.Model == "" && cfg.BaseURL == "" { + return doctor.Result{Name: name, Status: doctor.Info, Detail: i18n.T("nicht eingerichtet")} + } + what := cfg.Model + if what == "" { + what = string(cfg.Provider) + } + cctx, cancel := context.WithTimeout(ctx, testTimeout(cfg)) + defer cancel() + if err := llm.Probe(cctx, cfg); err != nil { + return doctor.Result{Name: name, Status: doctor.Warn, Detail: what + i18n.T(" antwortet nicht: ") + err.Error()} + } + return doctor.Result{Name: name, Status: doctor.OK, Detail: what + i18n.T(" antwortet")} + } +} + +func (a *App) doctorDone(m doctorMsg) { + md := textModal(i18n.T("Selbstprüfung"), strings.Split(strings.TrimRight(m.text, "\n"), "\n")) + md.copy = m.text + a.modal = md +} diff --git a/internal/ui/doctor_test.go b/internal/ui/doctor_test.go new file mode 100644 index 0000000..d3675ec --- /dev/null +++ b/internal/ui/doctor_test.go @@ -0,0 +1,46 @@ +package ui + +import ( + "context" + "strings" + "testing" + + "github.com/db9979/sshtermy/internal/doctor" + "github.com/db9979/sshtermy/internal/domain" +) + +func TestDoctorModal(t *testing.T) { + a := newPaletteTestApp(t) + a.modal = nil + a.Update(doctorMsg{"✓ Datenordner beschreibbar\n\nAlles in Ordnung.\n"}) + if a.modal == nil || a.modal.kind != mText || a.modal.title != "Selbstprüfung" { + t.Fatalf("kein Ergebnisfenster: %+v", a.modal) + } + if !strings.Contains(a.modal.copy, "Alles in Ordnung.") { + t.Fatal("c kopiert nicht das Ergebnis") + } +} + +func TestDoctorAICheck(t *testing.T) { + r := aiCheck(domain.LLMConfig{})(context.Background()) + if r.Status != doctor.Info { + t.Fatalf("ohne KI: %+v", r) + } + r = aiCheck(domain.LLMConfig{Provider: domain.ProviderOllama, BaseURL: "http://127.0.0.1:1", Model: "test", TimeoutSec: 2})(context.Background()) + if r.Status != doctor.Warn || !strings.HasPrefix(r.Detail, "test") { + t.Fatalf("KI nicht erreichbar: %+v", r) + } +} + +func TestDoctorInPalette(t *testing.T) { + a := newPaletteTestApp(t) + found := false + for _, it := range a.palMenuItems() { + if it.menu == "help/debug" && strings.HasPrefix(it.label, "Selbstprüfung") { + found = true + } + } + if !found { + t.Fatal("Selbstprüfung fehlt unter Hilfe › Fehlersuche") + } +} diff --git a/internal/ui/drop.go b/internal/ui/dropped/dropped.go similarity index 79% rename from internal/ui/drop.go rename to internal/ui/dropped/dropped.go index b4cab1f..9276166 100644 --- a/internal/ui/drop.go +++ b/internal/ui/dropped/dropped.go @@ -1,4 +1,6 @@ -package ui +// Package dropped erkennt Dateien, die ins Terminalfenster gezogen wurden +// (aus internal/ui ausgelagert, erster Schritt der Aufteilung). +package dropped import ( "net/url" @@ -20,16 +22,16 @@ import ( // GNOME/Konsole '/home/me/My File.txt' '/home/me/b.txt' // manche Linux-DEs file:///home/me/My%20File.txt // -// droppedPaths erkennt das: Nur wenn der eingefügte Text ausschließlich aus +// Paths erkennt das: Nur wenn der eingefügte Text ausschließlich aus // absoluten Pfaden besteht, die es auf diesem Rechner gibt, gilt er als // „abgelegte Dateien“. Sonst ist es normaler Text. -const maxDropped = 500 +const Max = 500 -// droppedPaths: die abgelegten Dateien, oder nil, wenn der Text keine ist. -func droppedPaths(text string) []string { - toks := splitDropped(text, runtime.GOOS == "windows") - if len(toks) == 0 || len(toks) > maxDropped { +// Paths: die abgelegten Dateien, oder nil, wenn der Text keine ist. +func Paths(text string) []string { + toks := Split(text, runtime.GOOS == "windows") + if len(toks) == 0 || len(toks) > Max { return nil } for _, p := range toks { @@ -40,10 +42,10 @@ func droppedPaths(text string) []string { return toks } -// splitDropped zerlegt den Text in Pfade (ohne Prüfung, ob es sie gibt). +// Split zerlegt den Text in Pfade (ohne Prüfung, ob es sie gibt). // nil, wenn ein Teil kein absoluter Pfad ist. win: Backslash ist dann // Pfadtrenner und kein Fluchtzeichen. -func splitDropped(text string, win bool) []string { +func Split(text string, win bool) []string { text = strings.TrimSpace(strings.TrimPrefix(text, "\ufeff")) if text == "" { return nil @@ -101,7 +103,7 @@ func splitDropped(text string, win bool) []string { p = p[1:] // /C:/x → C:/x } } - if !isAbsPath(p, win) { + if !IsAbs(p, win) { return nil } out[i] = p @@ -109,7 +111,7 @@ func splitDropped(text string, win bool) []string { return out } -func isAbsPath(p string, win bool) bool { +func IsAbs(p string, win bool) bool { if !win { return strings.HasPrefix(p, "/") } diff --git a/internal/ui/drop_test.go b/internal/ui/dropped/dropped_test.go similarity index 85% rename from internal/ui/drop_test.go rename to internal/ui/dropped/dropped_test.go index a119af5..7309dcc 100644 --- a/internal/ui/drop_test.go +++ b/internal/ui/dropped/dropped_test.go @@ -1,4 +1,4 @@ -package ui +package dropped import ( "os" @@ -29,7 +29,7 @@ func TestSplitDropped(t *testing.T) { {`/tmp`, true, nil}, // unter Windows nicht absolut } for _, c := range cases { - if got := splitDropped(c.in, c.win); !reflect.DeepEqual(got, c.want) { + if got := Split(c.in, c.win); !reflect.DeepEqual(got, c.want) { t.Errorf("splitDropped(%q, %v) = %q, want %q", c.in, c.win, got, c.want) } } @@ -44,10 +44,10 @@ func TestDroppedPathsMustExist(t *testing.T) { if filepath.Separator != '/' { t.Skip("Pfade im Test sind Unix-Schreibweise") } - if got := droppedPaths("'" + a + "' "); !reflect.DeepEqual(got, []string{a}) { + if got := Paths("'" + a + "' "); !reflect.DeepEqual(got, []string{a}) { t.Fatalf("got %q", got) } - if got := droppedPaths("'" + a + "' " + filepath.Join(dir, "fehlt")); got != nil { + if got := Paths("'" + a + "' " + filepath.Join(dir, "fehlt")); got != nil { t.Fatalf("fehlende Datei: got %q", got) } } diff --git a/internal/ui/fileplaces.go b/internal/ui/fileplaces.go index 6e909a8..5f0f921 100644 --- a/internal/ui/fileplaces.go +++ b/internal/ui/fileplaces.go @@ -15,6 +15,8 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/sshx" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Orte und Verlauf im Dateien-Fenster (F5) @@ -339,9 +341,9 @@ func (a *App) viewPlacesBar(s *session, w, h int) string { style = st.Selected.Width(w) } target := pl.path - b.WriteString(a.z.mark(style.Render(label), zoneAction{ - click: func(tea.Mouse, bool) tea.Cmd { return a.goPlace(s, side, target) }, - tip: func() string { return target }, + b.WriteString(a.z.Mark(style.Render(label), clickzone.Action{ + Click: func(tea.Mouse, bool) tea.Cmd { return a.goPlace(s, side, target) }, + Tip: func() string { return target }, }) + "\n") n++ } diff --git a/internal/ui/files.go b/internal/ui/files.go index df24888..01afda5 100644 --- a/internal/ui/files.go +++ b/internal/ui/files.go @@ -16,6 +16,10 @@ import ( "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/sshx" + + "github.com/db9979/sshtermy/internal/ui/clickzone" + + "github.com/db9979/sshtermy/internal/ui/dropped" ) // Dateien (F5): links lokal, rechts der Server, per SFTP über dieselbe @@ -417,7 +421,7 @@ func (a *App) filesPaste(s *session, m tea.PasteMsg) tea.Cmd { *f.mkdir, cmd = f.mkdir.Update(m) return cmd } - if paths := droppedPaths(m.Content); paths != nil { + if paths := dropped.Paths(m.Content); paths != nil { return a.uploadDropped(s, paths) } a.flash(i18n.T("Hier lassen sich nur Dateien aus dem Explorer/Finder ablegen")) @@ -445,7 +449,7 @@ func (a *App) filesDragMouse(s *session, msg tea.MouseMsg) tea.Cmd { f := &s.files d := f.drag m := msg.Mouse() - side, row := a.z.fileAt(m.X, m.Y) + side, row := a.z.FileAt(m.X, m.Y) switch msg.(type) { case tea.MouseMotionMsg: d.over, d.overRow = side, row @@ -823,9 +827,9 @@ func (a *App) viewPane(s *session, side, w, h int) string { line = st.Text.Render(line) } i := i - line = a.z.mark(line, zoneAction{pane: side + 1, row: i + 1, - click: func(m tea.Mouse, double bool) tea.Cmd { return a.entryClick(s, side, i, m, double) }, - menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, i, m.X, m.Y) }, + line = a.z.Mark(line, clickzone.Action{Pane: side + 1, Row: i + 1, + Click: func(m tea.Mouse, double bool) tea.Cmd { return a.entryClick(s, side, i, m, double) }, + Menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, i, m.X, m.Y) }, }) b.WriteString(line + "\n") } @@ -837,12 +841,12 @@ func (a *App) viewPane(s *session, side, w, h int) string { list += "\n" + a.viewPeek(s, p, side, w, peekH) } box := lipgloss.NewStyle().Width(w).Height(h).MaxHeight(h).Render(list) - return a.z.mark(box, zoneAction{ - block: true, - pane: side + 1, - click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return nil }, - menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, -1, m.X, m.Y) }, - wheel: func(up bool) tea.Cmd { + return a.z.Mark(box, clickzone.Action{ + Block: true, + Pane: side + 1, + Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return nil }, + Menu: func(m tea.Mouse) tea.Cmd { return a.fileMenu(s, side, -1, m.X, m.Y) }, + Wheel: func(up bool) tea.Cmd { f.side = side if up { p.sel = max(0, p.sel-3) diff --git a/internal/ui/filesmouse.go b/internal/ui/filesmouse.go index 951b135..4ce6473 100644 --- a/internal/ui/filesmouse.go +++ b/internal/ui/filesmouse.go @@ -15,6 +15,8 @@ import ( "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/packx" "github.com/db9979/sshtermy/internal/sshx" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Dateien (F5) mit der Maus @@ -154,7 +156,7 @@ func (a *App) filesPaneTitle(s *session, f *filesState, side, w int) string { if active { ts = st.TabActive.Foreground(st.T.Accent) } - tr := a.z.click(ts.Render(title), func(tea.Mouse, bool) tea.Cmd { f.side = side; return a.filesPeek(s) }) + tr := a.z.Click(ts.Render(title), func(tea.Mouse, bool) tea.Cmd { f.side = side; return a.filesPeek(s) }) // Knöpfe rechts (nur wenn Platz ist) btn := lipgloss.NewStyle().Background(st.T.Surface2).Foreground(st.T.Accent) @@ -178,9 +180,9 @@ func (a *App) filesPaneTitle(s *session, f *filesState, side, w int) string { if w >= 48 { for _, b := range buttons { b := b - bar += " " + a.z.mark(btn.Render(" "+b.label+" "), zoneAction{ - click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return b.run() }, - tip: func() string { return b.tip }, + bar += " " + a.z.Mark(btn.Render(" "+b.label+" "), clickzone.Action{ + Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; return b.run() }, + Tip: func() string { return b.tip }, }) } } @@ -207,9 +209,9 @@ func (a *App) filesPaneTitle(s *session, f *filesState, side, w int) string { if i == len(parts)-1 { style = st.Text } - shown = append(shown, a.z.mark(style.Render(label), zoneAction{ - click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.goTo(target, f.hidden); return nil }, - tip: func() string { return target }, + shown = append(shown, a.z.Mark(style.Render(label), clickzone.Action{ + Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.goTo(target, f.hidden); return nil }, + Tip: func() string { return target }, })) used += wid } @@ -243,9 +245,9 @@ func (a *App) paneHeader(p *pane, f *filesState, side, nameW, sizeW, dateW int) if right { txt = fmt.Sprintf("%*s", wid, trunc(label, wid)) } - return a.z.mark(style.Render(txt), zoneAction{ - click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.sortClick(c, f.hidden); return nil }, - tip: func() string { return i18n.T("sortieren (s)") }, + return a.z.Mark(style.Render(txt), clickzone.Action{ + Click: func(tea.Mouse, bool) tea.Cmd { f.side = side; p.sortClick(c, f.hidden); return nil }, + Tip: func() string { return i18n.T("sortieren (s)") }, }) } return " " + col(sortName, nameW, false) + " " + col(sortSize, sizeW, true) + " " + col(sortTime, dateW, true) @@ -599,7 +601,7 @@ func (a *App) filesBack(s *session, x, y int) tea.Cmd { if f.panes[0] == nil { return nil } - side, _ := a.z.fileAt(x, y) + side, _ := a.z.FileAt(x, y) if side < 0 { side = f.side } diff --git a/internal/ui/fileview.go b/internal/ui/fileview.go index 1af4c1f..82bb9fa 100644 --- a/internal/ui/fileview.go +++ b/internal/ui/fileview.go @@ -20,6 +20,8 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/sshx" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Datei ansehen (Dateien, F5) @@ -750,7 +752,7 @@ func (a *App) viewPeek(s *session, p *pane, side int, w, h int) string { body = append(body, "") } b.WriteString(strings.Join(body[:rows], "\n")) - return a.z.mark(lipgloss.NewStyle().Width(w).Height(h).MaxHeight(h).Render(b.String()), zoneAction{block: true, click: func(tea.Mouse, bool) tea.Cmd { + return a.z.Mark(lipgloss.NewStyle().Width(w).Height(h).MaxHeight(h).Render(b.String()), clickzone.Action{Block: true, Click: func(tea.Mouse, bool) tea.Cmd { return a.openEntry(s, side, p.sel) }}) } @@ -811,7 +813,7 @@ func (a *App) viewFileView(s *session, w, h int) string { if v.follow { info += i18n.T(" · liest mit") } - closeBtn := a.z.click(st.Danger.Render(i18n.T(" × zu ")), func(tea.Mouse, bool) tea.Cmd { f.view = nil; return nil }) + closeBtn := a.z.Click(st.Danger.Render(i18n.T(" × zu ")), func(tea.Mouse, bool) tea.Cmd { f.view = nil; return nil }) tag := st.TabActive.Foreground(st.T.Accent).Render(i18n.T("Ansehen")) if v.follow { tag = st.TabActive.Foreground(st.T.OK).Render(i18n.T("Mitlesen")) @@ -899,10 +901,10 @@ func (a *App) viewFileView(s *session, w, h int) string { lines = append(lines, "") } text := lipgloss.NewStyle().Width(w).Height(bodyH).MaxHeight(bodyH).Render(strings.Join(lines[:bodyH], "\n")) - text = a.z.mark(text, zoneAction{ - block: true, - click: func(m tea.Mouse, double bool) tea.Cmd { return a.viewClick(s, m, double) }, - menu: func(tea.Mouse) tea.Cmd { + text = a.z.Mark(text, clickzone.Action{ + Block: true, + Click: func(m tea.Mouse, double bool) tea.Cmd { return a.viewClick(s, m, double) }, + Menu: func(tea.Mouse) tea.Cmd { if v.sel != nil && v.sel.a != v.sel.b { cmd := a.copyViewSel(v) v.sel = nil @@ -910,7 +912,7 @@ func (a *App) viewFileView(s *session, w, h int) string { } return nil }, - wheel: func(up bool) tea.Cmd { + Wheel: func(up bool) tea.Cmd { if up { v.scroll(-3) } else { diff --git a/internal/ui/firmware.go b/internal/ui/firmware.go index 4ce7a7a..1c9ee70 100644 --- a/internal/ui/firmware.go +++ b/internal/ui/firmware.go @@ -15,6 +15,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/hostinfo" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/vuln" ) @@ -198,6 +199,7 @@ func (a *App) runFirmware(title string, ts []fwTarget, single bool) tea.Cmd { seq, ev := f.seq, a.events get := fwProduct(a) go func() { + defer safe.Recover("ui/firmware.go") defer cancel() ev <- fwDoneMsg{seq: seq, res: firmwareCheck(ctx, ts, get, fwKEV, func(s string) { ev <- fwStepMsg{seq, s} })} }() diff --git a/internal/ui/form.go b/internal/ui/form.go index 8a2c1f4..28caafb 100644 --- a/internal/ui/form.go +++ b/internal/ui/form.go @@ -12,6 +12,8 @@ import ( "github.com/charmbracelet/x/ansi" "github.com/db9979/sshtermy/internal/i18n" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // fieldKind: Text, Geheimnis, Zahl, Auswahl oder Schalter. @@ -271,7 +273,7 @@ func (f *form) update(msg tea.Msg) (submit bool, cmd tea.Cmd) { // Ruhig gehalten: Auswahlfelder zeigen ohne Fokus nur den gewählten Wert, // die Hilfe steht in einer festen Zeile unten (statt sich unter das Feld // zu schieben) und das Formular wird nie wieder kleiner, solange es offen ist. -func (f *form) view(s Styles, width int, z *zones) string { +func (f *form) view(s Styles, width int, z *clickzone.Map) string { var b strings.Builder lines := 0 out := func(str string) { b.WriteString(str + "\n"); lines++ } @@ -343,7 +345,7 @@ func (f *form) view(s Styles, width int, z *zones) string { row := marker + label + val if z != nil { i, fl := i, fl - row = z.click(row, func(_ tea.Mouse, _ bool) tea.Cmd { + row = z.Click(row, func(_ tea.Mouse, _ bool) tea.Cmd { if fl.kind == fBool { fl.on = !fl.on } @@ -413,7 +415,7 @@ func (f *form) view(s Styles, width int, z *zones) string { // choiceView: mit Fokus alle Optionen (passt es nicht, ‹ Wert › zum // Durchschalten), ohne Fokus nur der gewählte Wert. -func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.Color, inW int, z *zones) string { +func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.Color, inW int, z *clickzone.Map) string { if fl.opt >= len(fl.options) { return "" } @@ -448,7 +450,7 @@ func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.C } if z != nil { j := j - parts[j] = z.click(parts[j], func(tea.Mouse, bool) tea.Cmd { fl.opt = j; return f.setFocus(i) }) + parts[j] = z.Click(parts[j], func(tea.Mouse, bool) tea.Cmd { fl.opt = j; return f.setFocus(i) }) } } val := strings.Join(parts, "") @@ -460,7 +462,7 @@ func (f *form) choiceView(s Styles, i int, fl *field, focused bool, tint color.C } // headerRow: „── Anmeldung ──────“; einklappbar mit ▸/▾ und Zusammenfassung. -func (f *form) headerRow(s Styles, i int, fl *field, focused bool, tint color.Color, width int, z *zones) string { +func (f *form) headerRow(s Styles, i int, fl *field, focused bool, tint color.Color, width int, z *clickzone.Map) string { tc := lipgloss.NewStyle().Foreground(tint) title := tc.Bold(true).Render(fl.label) lead := tc.Render("━━ ") @@ -484,7 +486,7 @@ func (f *form) headerRow(s Styles, i int, fl *field, focused bool, tint color.Co row += tc.Faint(true).Render(strings.Repeat("─", rest)) } if fl.fold && z != nil { - row = z.click(row, func(tea.Mouse, bool) tea.Cmd { fl.on = !fl.on; return f.setFocus(i) }) + row = z.Click(row, func(tea.Mouse, bool) tea.Cmd { fl.on = !fl.on; return f.setFocus(i) }) } return row } diff --git a/internal/ui/goalhistory.go b/internal/ui/goalhistory.go index f29a17a..0baf24e 100644 --- a/internal/ui/goalhistory.go +++ b/internal/ui/goalhistory.go @@ -161,7 +161,7 @@ func (a *App) viewGoalHist(b *strings.Builder, s *session, w, base int) { row = st.Selected.Width(w).Render(line + strings.Repeat(" ", gap) + meta) } r := r - b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { s.panelFocus = true a.goalPickSet(s, idx) if double { diff --git a/internal/ui/goalux.go b/internal/ui/goalux.go index 4804beb..e499537 100644 --- a/internal/ui/goalux.go +++ b/internal/ui/goalux.go @@ -32,6 +32,7 @@ import ( "github.com/db9979/sshtermy/internal/agent" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sessionlog" "github.com/db9979/sshtermy/internal/sshx" ) @@ -174,7 +175,7 @@ func (a *App) viewInputWait(b *strings.Builder, s *session, w int) { for _, k := range agent.InputKeys(g.inputWait) { send := k.Send lbl := st.Accent.Render("["+inputKeyLabel(k.Key)+"]") + " " + st.Text.Render(i18n.T(k.Label)) - row = append(row, a.z.click(lbl, func(tea.Mouse, bool) tea.Cmd { + row = append(row, a.z.Click(lbl, func(tea.Mouse, bool) tea.Cmd { a.sendInputAnswer(s, send) return nil })) @@ -406,6 +407,7 @@ func readBackups(local bool, cl *sshx.Client, need []agent.FileChange) []fileBac } done := make(chan []fileBackup, 1) go func() { + defer safe.Recover("ui/goalux.go") res := make([]fileBackup, len(need)) copy(res, out) fsys, closeFn, err := agentFS(local, cl) @@ -649,7 +651,7 @@ func (a *App) viewBackups(b *strings.Builder, s *session, w int, key string) { } head := st.Warn.Render("← " + plural(len(g.backups), i18n.T("Datei geändert"), i18n.T("Dateien geändert"))) if n > 0 { - head += st.Muted.Render(" · ") + a.z.click(st.Accent.Render(key)+" "+st.Text.Render(i18n.T("zurückholen")), func(tea.Mouse, bool) tea.Cmd { + head += st.Muted.Render(" · ") + a.z.Click(st.Accent.Render(key)+" "+st.Text.Render(i18n.T("zurückholen")), func(tea.Mouse, bool) tea.Cmd { s.panelFocus = true return a.startUndo(s) }) diff --git a/internal/ui/harden.go b/internal/ui/harden.go index 92a4ed0..90753ca 100644 --- a/internal/ui/harden.go +++ b/internal/ui/harden.go @@ -14,6 +14,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/harden" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // Härtungs-Check (F6 h, Palette „Härtungs-Check“): nur lesend, Bewertung @@ -72,6 +73,7 @@ func forHosts(ctx context.Context, conns []domain.Connection, par int, fn func(c for i, c := range conns { wg.Add(1) go func() { + defer safe.Recover("ui/harden.go") defer wg.Done() select { case sem <- struct{}{}: @@ -193,6 +195,7 @@ func (a *App) runHardenFolder(folder string) tea.Cmd { } seq, ev, run := h.seq, a.events, hardenRunHost(a) go func() { + defer safe.Recover("ui/harden.go") defer cancel() forHosts(ctx, conns, 4, func(ctx context.Context, i int, c domain.Connection) { if ctx.Err() != nil { diff --git a/internal/ui/hostlive.go b/internal/ui/hostlive.go index 4431293..4e23353 100644 --- a/internal/ui/hostlive.go +++ b/internal/ui/hostlive.go @@ -18,6 +18,7 @@ import ( "github.com/db9979/sshtermy/internal/hostinfo" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) const ( @@ -81,6 +82,7 @@ func (a *App) liveStart(s *session) tea.Cmd { ch := make(chan liveEvent, 8) cl := s.client go func() { + defer safe.Recover("ui/hostlive.go") defer close(ch) var p hostinfo.LiveParser var prev *hostinfo.LiveSample diff --git a/internal/ui/hostpanel.go b/internal/ui/hostpanel.go index 9e26804..1a7336c 100644 --- a/internal/ui/hostpanel.go +++ b/internal/ui/hostpanel.go @@ -960,7 +960,7 @@ func (a *App) viewHost(b *strings.Builder, s *session, w int) { line = st.Text.Render(line) } i := i - b.WriteString(a.z.click(mark+line, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(mark+line, func(_ tea.Mouse, double bool) tea.Cmd { s.panelFocus, h.sel = true, i if double { a.showBackupDiff(s) diff --git a/internal/ui/importui.go b/internal/ui/importui.go index cb54769..efced5b 100644 --- a/internal/ui/importui.go +++ b/internal/ui/importui.go @@ -296,7 +296,7 @@ func (a *App) viewImport() string { } } i := i - out = a.z.click(out, func(_ tea.Mouse, double bool) tea.Cmd { + out = a.z.Click(out, func(_ tea.Mouse, double bool) tea.Cmd { m.sel = i m.items[i].on = !m.items[i].on return nil diff --git a/internal/ui/inventory.go b/internal/ui/inventory.go index 26289ba..c817e07 100644 --- a/internal/ui/inventory.go +++ b/internal/ui/inventory.go @@ -15,6 +15,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/inventory" + "github.com/db9979/sshtermy/internal/safe" ) // Inventar & Änderungen (F6 i, Palette): Pakete, Benutzer, Admins, Cron, @@ -106,6 +107,7 @@ func (a *App) runInventoryFolder(folder string) tea.Cmd { } seq, ev, run := v.seq, a.events, invRunHost(a) go func() { + defer safe.Recover("ui/inventory.go") defer cancel() forHosts(ctx, conns, 4, func(ctx context.Context, i int, c domain.Connection) { if ctx.Err() != nil { diff --git a/internal/ui/keyinv.go b/internal/ui/keyinv.go index 2579ead..b5c2cd1 100644 --- a/internal/ui/keyinv.go +++ b/internal/ui/keyinv.go @@ -16,6 +16,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/keyinv" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" ) @@ -213,6 +214,7 @@ func (a *App) runKeyinv(title string, conns []domain.Connection) tea.Cmd { } seq, ev, run := k.seq, a.events, keyinvRun(a) go func() { + defer safe.Recover("ui/keyinv.go") defer cancel() forHosts(ctx, conns, 4, func(ctx context.Context, i int, c domain.Connection) { if ctx.Err() != nil { diff --git a/internal/ui/layout.go b/internal/ui/layout.go index e7b2067..00f5c51 100644 --- a/internal/ui/layout.go +++ b/internal/ui/layout.go @@ -9,6 +9,8 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Auswahl der Aufteilung (Strg+T) @@ -127,7 +129,7 @@ func (a *App) layoutView() string { if i == m.sel { box = lipgloss.NewStyle().Background(st.T.Surface).Render(box) } - cells = append(cells, a.z.mark(box, zoneAction{block: true, click: func(tea.Mouse, bool) tea.Cmd { + cells = append(cells, a.z.Mark(box, clickzone.Action{Block: true, Click: func(tea.Mouse, bool) tea.Cmd { a.applyLayout(i) return nil }})) diff --git a/internal/ui/links.go b/internal/ui/links.go index 830d595..921b195 100644 --- a/internal/ui/links.go +++ b/internal/ui/links.go @@ -450,7 +450,7 @@ func (a *App) menuView(m *modal) string { b.WriteString(lipgloss.NewStyle().Foreground(st.T.Border).Render(strings.Repeat("─", w)) + "\n") } } - b.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd { + b.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { m.sel = i return a.menuRun() })) diff --git a/internal/ui/llmhealth.go b/internal/ui/llmhealth.go index 43a75da..e4c9745 100644 --- a/internal/ui/llmhealth.go +++ b/internal/ui/llmhealth.go @@ -185,7 +185,7 @@ func (a *App) llmChip() string { txt += a.s.Header.Foreground(a.llmColor(h.level)).Render(" " + h.badgeText()) } txt += a.s.Header.Render(" ") - return a.z.click(txt, func(tea.Mouse, bool) tea.Cmd { return a.openLLMStatus() }) + return a.z.Click(txt, func(tea.Mouse, bool) tea.Cmd { return a.openLLMStatus() }) } // llmTick plant die Hintergrundprüfung (einmal pro Sekunde aufgerufen). diff --git a/internal/ui/llmtest.go b/internal/ui/llmtest.go index 2012788..74bb346 100644 --- a/internal/ui/llmtest.go +++ b/internal/ui/llmtest.go @@ -11,6 +11,8 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/llm" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // KI-Einstellungen: Endpunkt testen (Strg+T) und Modell aus der Liste des @@ -243,9 +245,9 @@ func (a *App) viewLLMExtra(w int) string { line = a.s.Selected.Width(w - 2).Render(" " + trunc(vis[i], w-6)) } i := i - line = a.z.mark(line, zoneAction{ - click: func(tea.Mouse, bool) tea.Cmd { p.sel = i; return a.pressKey("⏎") }, - wheel: func(up bool) tea.Cmd { return a.pressKey(wheelKey(up)) }, + line = a.z.Mark(line, clickzone.Action{ + Click: func(tea.Mouse, bool) tea.Cmd { p.sel = i; return a.pressKey("⏎") }, + Wheel: func(up bool) tea.Cmd { return a.pressKey(wheelKey(up)) }, }) b.WriteString(line + "\n") } diff --git a/internal/ui/logfolder.go b/internal/ui/logfolder.go index 84a837f..f5b8318 100644 --- a/internal/ui/logfolder.go +++ b/internal/ui/logfolder.go @@ -16,6 +16,7 @@ import ( "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/logscan" "github.com/db9979/sshtermy/internal/psremote" + "github.com/db9979/sshtermy/internal/safe" ) // Ordner-Scan: Log-Blick für alle Hosts eines Ordners auf einmal, nur @@ -142,6 +143,7 @@ func (a *App) runFolderScan(folder string) tea.Cmd { conns[i] = h.conn } go func() { + defer safe.Recover("ui/logfolder.go") defer cancel() scanHosts(ctx, conns, hours, scan, func(i int, r *logscan.Report, err error) { ev <- folderHostMsg{seq: seq, i: i, rep: r, err: err} @@ -159,6 +161,7 @@ func scanHosts(ctx context.Context, conns []domain.Connection, hours int, for i, c := range conns { wg.Add(1) go func() { + defer safe.Recover("ui/logfolder.go") defer wg.Done() select { case sem <- struct{}{}: diff --git a/internal/ui/logs.go b/internal/ui/logs.go index 807b5ef..3fad288 100644 --- a/internal/ui/logs.go +++ b/internal/ui/logs.go @@ -487,7 +487,7 @@ func (a *App) viewLogs() string { st = lipgloss.NewStyle().Background(s.T.Accent).Foreground(s.T.Bg).Bold(true).Padding(0, 1) } f := f - chips += a.z.click(st.Render(label), func(tea.Mouse, bool) tea.Cmd { a.logs.filter = f; a.selectLog(0); return nil }) + chips += a.z.Click(st.Render(label), func(tea.Mouse, bool) tea.Cmd { a.logs.filter = f; a.selectLog(0); return nil }) } if view != "" && lipgloss.Width(chips)+lipgloss.Width(view)+3 <= leftW { chips += strings.Repeat(" ", leftW-lipgloss.Width(chips)-lipgloss.Width(view)-2) + a.keyZone("Tab", s.Muted.Render(view)) @@ -527,7 +527,7 @@ func (a *App) viewLogs() string { for i := start; i < len(rows) && i < start+room; i++ { i := i line := a.logRowLine(rows[i], i == m.sel, timeW, nameW, sessW, leftW, now) - lb.WriteString(a.z.click(line, func(_ tea.Mouse, _ bool) tea.Cmd { + lb.WriteString(a.z.Click(line, func(_ tea.Mouse, _ bool) tea.Cmd { if a.logs.sel == i { if rs := a.logRows(); i < len(rs) { a.setLogOpen(rs[i], !rs[i].open) diff --git a/internal/ui/logscan_view.go b/internal/ui/logscan_view.go index 7a33b95..a400fe0 100644 --- a/internal/ui/logscan_view.go +++ b/internal/ui/logscan_view.go @@ -135,7 +135,7 @@ func (a *App) viewLogScan() string { for i := l.top; i < min(len(vis), l.top+room); i++ { i := i row := a.findingRow(vis[i], cols, i == l.sel) - b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { l.sel = i if double { a.showFindingLines(vis[i]) @@ -287,7 +287,7 @@ func (a *App) findingDetail(f logscan.Finding, w int) []string { used += cw s := a.byID(a.lscan.sid) cmd := c - chips = append(chips, a.z.click(chip, func(tea.Mouse, bool) tea.Cmd { + chips = append(chips, a.z.Click(chip, func(tea.Mouse, bool) tea.Cmd { if s == nil { return nil } diff --git a/internal/ui/logwatch.go b/internal/ui/logwatch.go index f40d12d..b1e2b3f 100644 --- a/internal/ui/logwatch.go +++ b/internal/ui/logwatch.go @@ -15,6 +15,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/logscan" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" ) @@ -248,7 +249,7 @@ func (a *App) startWatch(s *session) *logStream { st := &logStream{cancel: cancel, client: s.client} ev := a.events b := &watchBatcher{} - go b.run(ctx, ev) + safe.Go("ui/logwatch.go", func() { b.run(ctx, ev) }) sid := s.id warn := a.watchLevel() == 2 end := func(err error) { @@ -266,6 +267,7 @@ func (a *App) startWatch(s *session) *logStream { lvl = 3 } go func() { + defer safe.Recover("ui/logwatch.go") since := time.Now().Add(-watchWinPoll).Unix() for { out, err := a.winrmRun(ctx, s, logscan.WindowsSinceScript(since, lvl)) @@ -294,6 +296,7 @@ func (a *App) startWatch(s *session) *logStream { } cl := s.client go func() { + defer safe.Recover("ui/logwatch.go") err := cl.StreamScript(ctx, logscan.UnixWatchScript(warn), func(line string) { if e, ok := logscan.UnixWatchLine(line, time.Now()); ok { b.add(watchItem{sid: sid, kind: logscan.KindUnix, e: e}) @@ -318,12 +321,14 @@ func (a *App) startSyslog(port int) context.CancelFunc { a.flashErr(fmt.Sprintf(i18n.T("Syslog-Empfang auf UDP %d geht nicht: %v"), port, err)) return cancel } - go b.run(ctx, ev) + safe.Go("ui/logwatch.go", func() { b.run(ctx, ev) }) go func() { + defer safe.Recover("ui/logwatch.go") <-ctx.Done() _ = pc.Close() }() go func() { + defer safe.Recover("ui/logwatch.go") buf := make([]byte, 8192) for { n, addr, err := pc.ReadFrom(buf) @@ -340,14 +345,17 @@ func (a *App) startSyslog(port int) context.CancelFunc { if h, _, e := net.SplitHostPort(ip); e == nil { ip = h } - for _, line := range strings.Split(string(buf[:n]), "\n") { - if e, ok := logscan.SyslogPacket(line, time.Now()); ok { - b.add(watchItem{addr: ip, kind: logscan.KindNetwork, e: e}) + // ein kaputtes Paket kostet nur sich selbst, nicht den Empfang + safe.Run("ui/logwatch.go syslog", func() { + for _, line := range strings.Split(string(buf[:n]), "\n") { + if e, ok := logscan.SyslogPacket(line, time.Now()); ok { + b.add(watchItem{addr: ip, kind: logscan.KindNetwork, e: e}) + } } - } + }) } }() - go a.resolveHosts(ctx) + safe.Go("ui/logwatch.go", func() { a.resolveHosts(ctx) }) return cancel } diff --git a/internal/ui/look.go b/internal/ui/look.go index 4c9ff8e..fcad976 100644 --- a/internal/ui/look.go +++ b/internal/ui/look.go @@ -246,7 +246,7 @@ func (a *App) viewKeys() string { if i == e.sel { selLine = len(lines) } - lines = append(lines, a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd { + lines = append(lines, a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd { e.sel = i if double { e.capturing = true diff --git a/internal/ui/manager.go b/internal/ui/manager.go index 5786363..491613a 100644 --- a/internal/ui/manager.go +++ b/internal/ui/manager.go @@ -23,6 +23,8 @@ import ( "github.com/db9979/sshtermy/internal/sshx" "github.com/db9979/sshtermy/internal/store" "github.com/db9979/sshtermy/internal/wol" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) type managerState struct { @@ -438,7 +440,7 @@ func (a *App) viewManager() string { info = s.OK.Render(fmt.Sprintf(i18n.T(" ✓ %d markiert"), n)) // vorn: bleibt lesbar, wenn die Zeile voll ist } if m.tag != "" { - info += a.z.click(s.Accent.Render(" #"+m.tag+" ×"), func(tea.Mouse, bool) tea.Cmd { m.tag = ""; return nil }) + info += a.z.Click(s.Accent.Render(" #"+m.tag+" ×"), func(tea.Mouse, bool) tea.Cmd { m.tag = ""; return nil }) } if a.mgrFiltering() { n := 0 @@ -523,7 +525,7 @@ func (a *App) viewManager() string { line = lipgloss.NewStyle().Foreground(s.T.Warn).Underline(true).Width(leftW - 1).Render(plain) } i, r := i, r - line = a.z.mark(line, zoneAction{row: i + 1, click: func(_ tea.Mouse, double bool) tea.Cmd { + line = a.z.Mark(line, clickzone.Action{Row: i + 1, Click: func(_ tea.Mouse, double bool) tea.Cmd { m.sel = i m.drag = &mgrDrag{from: i, over: i, dbl: double} if double && !r.isFolder() { @@ -531,7 +533,7 @@ func (a *App) viewManager() string { return a.connect(r.conn) } return nil - }, menu: func(ms tea.Mouse) tea.Cmd { + }, Menu: func(ms tea.Mouse) tea.Cmd { if ms.Button != tea.MouseRight { return nil } @@ -549,7 +551,7 @@ func (a *App) viewManager() string { lb.WriteString(a.mgrEmpty(leftW)) } } - listBox := a.z.mark(lb.String(), zoneAction{block: true, wheel: func(up bool) tea.Cmd { + listBox := a.z.Mark(lb.String(), clickzone.Action{Block: true, Wheel: func(up bool) tea.Cmd { if up { m.sel = max(0, m.sel-1) } else { @@ -670,7 +672,7 @@ func (a *App) mgrConnDetails(c domain.Connection, rightW int, now time.Time) str row(i18n.T("Startbefehl"), c.StartCmd) } if canWake(c) && !a.connected(c.ID) { - rb.WriteString(" " + label.Render(i18n.T("Aufwecken")) + a.z.click(s.Key.Render(i18n.T("Wake-on-LAN senden")), func(tea.Mouse, bool) tea.Cmd { return a.wake(c) }) + s.Muted.Render(" "+c.MAC) + "\n") + rb.WriteString(" " + label.Render(i18n.T("Aufwecken")) + a.z.Click(s.Key.Render(i18n.T("Wake-on-LAN senden")), func(tea.Mouse, bool) tea.Cmd { return a.wake(c) }) + s.Muted.Render(" "+c.MAC) + "\n") } if c.Profile != nil && !c.Profile.Empty() { sum := c.Profile.Summary() @@ -710,7 +712,7 @@ func (a *App) mgrConnDetails(c domain.Connection, rightW int, now time.Time) str } t := t line := fmt.Sprintf(" %s %-20s %s%s", icon, trunc(t.Name, 20), s.Muted.Render(t.Spec()), auto) - rb.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd { return a.openTunnelForm(t) }) + "\n") + rb.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { return a.openTunnelForm(t) }) + "\n") } return rb.String() } @@ -1461,5 +1463,5 @@ func (a *App) syncChip() string { if a.st.SyncConfig().Enabled() { txt = " ↕ Sync " + ansi.Strip(a.syncStatus()) + " " } - return a.z.click(s.Header.Foreground(s.T.Muted).Render(trunc(txt, 40)), func(tea.Mouse, bool) tea.Cmd { return a.openSync() }) + s.Header.Render(" ") + return a.z.Click(s.Header.Foreground(s.T.Muted).Render(trunc(txt, 40)), func(tea.Mouse, bool) tea.Cmd { return a.openSync() }) + s.Header.Render(" ") } diff --git a/internal/ui/mgrtree.go b/internal/ui/mgrtree.go index ef3bc6c..edacafb 100644 --- a/internal/ui/mgrtree.go +++ b/internal/ui/mgrtree.go @@ -581,7 +581,7 @@ func (a *App) mgrDragMouse(msg tea.MouseMsg) tea.Cmd { m := msg.Mouse() switch msg.(type) { case tea.MouseMotionMsg: - if r := a.z.rowAt(m.X, m.Y); r >= 0 { + if r := a.z.RowAt(m.X, m.Y); r >= 0 { if r != d.from { d.moved = true } @@ -596,7 +596,7 @@ func (a *App) mgrDragMouse(msg tea.MouseMsg) tea.Cmd { return nil case tea.MouseReleaseMsg: a.mgr.drag = nil - r := a.z.rowAt(m.X, m.Y) + r := a.z.RowAt(m.X, m.Y) rows := a.mgr.rows if !d.moved || r == d.from { if d.from < len(rows) && rows[d.from].isFolder() && !d.dbl { @@ -679,7 +679,7 @@ func (a *App) viewFolderDetails(n *domain.TreeNode, w int) string { line += " " + ansi.Truncate(a.reachText(c), rest, "…") } c := c - b.WriteString(a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd { if double { return a.connect(c) } diff --git a/internal/ui/motion.go b/internal/ui/motion.go index 56c3a93..7069487 100644 --- a/internal/ui/motion.go +++ b/internal/ui/motion.go @@ -388,16 +388,16 @@ func (a *App) trackHover(m tea.Mouse) { a.hov = hoverState{} return } - act, r := a.z.tipAt(m.X, m.Y) + act, r := a.z.TipAt(m.X, m.Y) if act == nil { a.hov = hoverState{} return } - key := [2]int{r.x0, r.y0} + key := [2]int{r.X0, r.Y0} if a.hov.tip != nil && a.hov.key == key { return } - a.hov = hoverState{tip: act.tip, x: r.x0, y: r.y1 + 1, key: key, since: time.Now(), mx: m.X, my: m.Y} + a.hov = hoverState{tip: act.Tip, x: r.X0, y: r.Y1 + 1, key: key, since: time.Now(), mx: m.X, my: m.Y} } // withHover legt die Karte über das Bild, sobald die Maus kurz verweilt. diff --git a/internal/ui/mouse.go b/internal/ui/mouse.go index d4b7e9a..7a4d152 100644 --- a/internal/ui/mouse.go +++ b/internal/ui/mouse.go @@ -147,8 +147,8 @@ func (a *App) mouse(msg tea.MouseMsg) tea.Cmd { if m.Button != tea.MouseWheelUp && m.Button != tea.MouseWheelDown { return nil } - if act := a.z.at(m.X, m.Y, true); act != nil { - return act.wheel(up) + if act := a.z.At(m.X, m.Y, true); act != nil { + return act.Wheel(up) } if a.modal != nil && (a.modal.kind == mHelp || a.modal.kind == mChangelog) { return a.pressKey(wheelKey(up)) @@ -195,15 +195,15 @@ func (a *App) mouse(msg tea.MouseMsg) tea.Cmd { return a.mgrDragMouse(msg) } if isClick && (m.Button == tea.MouseRight || m.Button == tea.MouseMiddle) { - if act := a.z.atMenu(m.X, m.Y); act != nil { - return act.menu(m) + if act := a.z.AtMenu(m.X, m.Y); act != nil { + return act.Menu(m) } } if !isClick || m.Button != tea.MouseLeft { return nil } - if act := a.z.at(m.X, m.Y, false); act != nil { - cmd := act.click(m, clicks >= 2) + if act := a.z.At(m.X, m.Y, false); act != nil { + cmd := act.Click(m, clicks >= 2) a.formChanged() // Klick auf eine Auswahl wirkt wie ←/→ return cmd } @@ -335,7 +335,7 @@ func (a *App) keyZone(label, rendered string) string { if _, ok := keyFromLabel(label); !ok { return rendered } - return a.z.click(rendered, func(tea.Mouse, bool) tea.Cmd { return a.pressKey(label) }) + return a.z.Click(rendered, func(tea.Mouse, bool) tea.Cmd { return a.pressKey(label) }) } // keyChip: Taste + Beschreibung als ein Knopf (Fußzeile). @@ -378,7 +378,7 @@ func (a *App) hintsIn(s *session, style lipgloss.Style, items ...[2]string) stri b.WriteString(r) continue } - b.WriteString(a.z.click(r, func(tea.Mouse, bool) tea.Cmd { + b.WriteString(a.z.Click(r, func(tea.Mouse, bool) tea.Cmd { if s != nil { s.panelFocus = true } diff --git a/internal/ui/netwatch.go b/internal/ui/netwatch.go index 7664634..0c20e1b 100644 --- a/internal/ui/netwatch.go +++ b/internal/ui/netwatch.go @@ -12,6 +12,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/netwatch" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" ) @@ -68,7 +69,7 @@ func (a *App) onNetEvent(ev netwatch.Event) tea.Cmd { } return func() tea.Msg { for _, c := range checks { - go netWatchCheck(c) // abgerissene melden sich als shellClosed → Auto-Reconnect + safe.Go("ui/netwatch.go", func() { netWatchCheck(c) }) // abgerissene melden sich als shellClosed → Auto-Reconnect } return nil } diff --git a/internal/ui/palette.go b/internal/ui/palette.go index 472d69c..d5c97c0 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -15,6 +15,8 @@ import ( "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/relay" "github.com/db9979/sshtermy/internal/sshx" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Befehlspalette (Strg+Leertaste): ein Einstieg für alles. Was getippt wird, @@ -1115,6 +1117,8 @@ func (a *App) palMenuItems() []palItem { a.palNewFolder(), // Hilfe & Info › Fehlersuche + palItem{group: pgHelp, menu: "help/debug", icon: ic("llmcheck"), label: i18n.T("Selbstprüfung (Ordner, Tresor, KI, Internet, Uhr)"), hint: "doctor", + keys: "selbstprüfung doctor check prüfen diagnose fehler problem geht nicht", run: func() tea.Cmd { return a.runDoctor() }}, proItem(help("help/debug", palToggle(ic("sesslog"), i18n.T("Debug-Protokoll für Fehlerberichte"), a.debugOn(), "debug log protokoll fehler bug support", func() tea.Cmd { return a.toggleDebug() }))), palItem{group: pgHelp, menu: "help/debug", icon: ic("export"), label: i18n.T("Debug-Protokoll bereinigt speichern (für Fehlerbericht)"), hint: ".txt", keys: "debug log protokoll fehler bug support issue", run: func() tea.Cmd { return a.exportDebug() }}, @@ -1428,14 +1432,14 @@ func (a *App) viewPalette() string { line = fadeANSI(line, st.T, k) // Zeilen blenden nacheinander ein } i, it := i, it - line = a.z.mark(line, zoneAction{click: func(tea.Mouse, bool) tea.Cmd { + line = a.z.Mark(line, clickzone.Action{Click: func(tea.Mouse, bool) tea.Cmd { p.sel = i if it.danger != "" && p.armed != i { p.armed = i // rot: erst scharf schalten, zweiter Klick führt aus return nil } return a.palRunTrack(it) - }, menu: func(tea.Mouse) tea.Cmd { // Rechtsklick: anheften / lösen + }, Menu: func(tea.Mouse) tea.Cmd { // Rechtsklick: anheften / lösen p.sel = i if palTrackable(it) || it.group == pgPinned { a.palTogglePin(it) @@ -1486,7 +1490,7 @@ func (a *App) viewPalette() string { } box := st.dialog(dialog{icon: "◆", title: title, sub: sub, tone: st.T.AI, body: body, keys: keys, width: width, maxW: maxW, compact: true}, a.w) - return a.z.mark(box, zoneAction{block: true, wheel: func(up bool) tea.Cmd { + return a.z.Mark(box, clickzone.Action{Block: true, Wheel: func(up bool) tea.Cmd { if up { p.sel = max(0, p.sel-1) } else { diff --git a/internal/ui/palstyle.go b/internal/ui/palstyle.go index fc4f80e..5dd7d46 100644 --- a/internal/ui/palstyle.go +++ b/internal/ui/palstyle.go @@ -177,7 +177,7 @@ func (a *App) palTabsRow() string { s = lipgloss.NewStyle().Background(st.T.Surface2).Foreground(st.T.Muted).Render(" " + name + " ") } g := g - parts = append(parts, a.z.click(s, func(tea.Mouse, bool) tea.Cmd { + parts = append(parts, a.z.Click(s, func(tea.Mouse, bool) tea.Cmd { p.tab, p.sel, p.armed = g, 0, -1 return nil })) diff --git a/internal/ui/panels.go b/internal/ui/panels.go index 0323e65..7782577 100644 --- a/internal/ui/panels.go +++ b/internal/ui/panels.go @@ -1071,7 +1071,7 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { row = st.Selected.Width(w).Render(line + strings.Repeat(" ", gap) + meta) } i, rb := i, rb - b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { s.panelFocus = true g.rbSel = i g.input.SetValue(rb.Goal) @@ -1148,7 +1148,7 @@ func (a *App) viewGoal(b *strings.Builder, s *session, w int) { mark, style = "● ", st.Accent } line := st.Muted.Render(mark) + style.Render(trunc(o, w-3)) - b.WriteString(a.z.click(line, func(tea.Mouse, bool) tea.Cmd { + b.WriteString(a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { s.panelFocus = true return a.answerQuestion(s, o) }) + "\n") @@ -1286,7 +1286,7 @@ func (a *App) viewTunnels(b *strings.Builder, s *session, w int) { sw = st.OK.Render("● " + i18n.T("an") + " ") } i, t := i, t - sw = a.z.click(sw, func(tea.Mouse, bool) tea.Cmd { + sw = a.z.Click(sw, func(tea.Mouse, bool) tea.Cmd { s.panelFocus, s.tunSel = true, i a.toggleTunnel(s, t) return nil @@ -1299,7 +1299,7 @@ func (a *App) viewTunnels(b *strings.Builder, s *session, w int) { if i == s.tunSel { name = st.Selected.Render(name) } - b.WriteString(sw + " " + a.z.click(name+auto, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(sw + " " + a.z.Click(name+auto, func(_ tea.Mouse, double bool) tea.Cmd { s.panelFocus, s.tunSel = true, i if double { a.toggleTunnel(s, t) @@ -1309,7 +1309,7 @@ func (a *App) viewTunnels(b *strings.Builder, s *session, w int) { b.WriteString(" " + st.Muted.Render(trunc(t.Spec()+via, w-2)) + "\n") if at != nil { if u := at.URL(); u != "" { - b.WriteString(" " + a.z.click(st.Accent.Underline(true).Render(u)+st.Muted.Render(i18n.T(" o öffnen")), + b.WriteString(" " + a.z.Click(st.Accent.Underline(true).Render(u)+st.Muted.Render(i18n.T(" o öffnen")), func(tea.Mouse, bool) tea.Cmd { _ = sshx.OpenBrowser(u); return nil }) + "\n") } else { b.WriteString(" " + st.Text.Render(i18n.T("lauscht auf ")+at.Addr) + "\n") diff --git a/internal/ui/panelsel.go b/internal/ui/panelsel.go index 8aa00b6..9c83bf8 100644 --- a/internal/ui/panelsel.go +++ b/internal/ui/panelsel.go @@ -128,7 +128,7 @@ func (a *App) panelSelMouse(s *session, msg tea.MouseMsg, clicks int) (tea.Cmd, } // Anklickbares bleibt anklickbar (Hinweise, Vorschläge, Runbooks); nur // große Blöcke (KI-Karten) lassen sich zusätzlich markieren. - if act := a.z.at(m.X, m.Y, false); act != nil && !act.block { + if act := a.z.At(m.X, m.Y, false); act != nil && !act.Block { s.psel = nil return nil, false } @@ -148,8 +148,8 @@ func (a *App) panelSelMouse(s *session, msg tea.MouseMsg, clicks int) (tea.Cmd, } s.psel = &panelSel{a: p, b: p, dragging: true} // Klick auf eine KI-Karte wählt sie weiterhin aus. - if act := a.z.at(m.X, m.Y, false); act != nil { - return act.click(m, false), true + if act := a.z.At(m.X, m.Y, false); act != nil { + return act.Click(m, false), true } return nil, true } diff --git a/internal/ui/patchround.go b/internal/ui/patchround.go index 3f9c44f..e72a6e4 100644 --- a/internal/ui/patchround.go +++ b/internal/ui/patchround.go @@ -16,6 +16,7 @@ import ( "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/logscan" "github.com/db9979/sshtermy/internal/patchrun" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" "github.com/db9979/sshtermy/internal/vuln" ) @@ -356,6 +357,7 @@ func (a *App) patchNext() tea.Cmd { job, seq, ev, ctx := p.jobs[i], p.seq, a.events, p.ctx run := patchHostRun(a) go func() { + defer safe.Recover("ui/patchround.go") h := run(ctx, job, func(h patchHost) { ev <- patchHostMsg{seq: seq, i: i, h: h} }) ev <- patchHostMsg{seq: seq, i: i, h: h, final: true} }() diff --git a/internal/ui/picker.go b/internal/ui/picker.go index a5f6866..b4309fd 100644 --- a/internal/ui/picker.go +++ b/internal/ui/picker.go @@ -11,6 +11,8 @@ import ( "github.com/charmbracelet/x/ansi" "github.com/db9979/sshtermy/internal/i18n" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Auswahlliste mit Suche (Jump-Host, Ordner, Tag-Filter). Liegt als Overlay @@ -229,30 +231,30 @@ func (a *App) viewPicker() string { line = s.Selected.Width(w - 4).Render(ansi.Strip(line)) } i, it := i, it - act := zoneAction{click: func(tea.Mouse, bool) tea.Cmd { + act := clickzone.Action{Click: func(tea.Mouse, bool) tea.Cmd { p.sel = i return a.pickerChoose(it) }} if p.onMenu != nil { - act.menu = func(m tea.Mouse) tea.Cmd { + act.Menu = func(m tea.Mouse) tea.Cmd { p.sel = i return p.onMenu(it, m) } } - line = a.z.mark(line, act) + line = a.z.Mark(line, act) list.WriteString(line + "\n") } if len(vis) == 0 { list.WriteString(a.keyZone("Esc", s.Muted.Render(i18n.T(" nichts gefunden · Esc zurück, Rücktaste ändert die Suche"))) + "\n") } - b.WriteString(a.z.mark(list.String(), zoneAction{wheel: func(up bool) tea.Cmd { + b.WriteString(a.z.Mark(list.String(), clickzone.Action{Wheel: func(up bool) tea.Cmd { if up { p.sel = max(0, p.sel-1) } else { p.sel = min(len(vis)-1, p.sel+1) } return nil - }, block: true})) + }, Block: true})) more := "" if len(vis) > rows { more = strconv.Itoa(p.top+1) + "–" + strconv.Itoa(min(len(vis), p.top+rows)) + i18n.T(" von ") + strconv.Itoa(len(vis)) diff --git a/internal/ui/planmode.go b/internal/ui/planmode.go index 91a0642..5b2a3ee 100644 --- a/internal/ui/planmode.go +++ b/internal/ui/planmode.go @@ -248,7 +248,7 @@ func (a *App) viewPlan(b *strings.Builder, s *session, w int) { line = st.Selected.Width(w).Render(fmt.Sprintf("%2d ", i+1) + map[bool]string{true: "− ", false: " "}[g.planOff[i]] + text) } i := i - b.WriteString(a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd { s.panelFocus, g.planSel = true, i if double { g.planOff[i] = !g.planOff[i] diff --git a/internal/ui/quick.go b/internal/ui/quick.go index 1004e6b..e942c40 100644 --- a/internal/ui/quick.go +++ b/internal/ui/quick.go @@ -325,7 +325,7 @@ func (a *App) quickModalView(m *modal) string { } } i := i - lines = append(lines, a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + lines = append(lines, a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { if m.scroll == i || double { return a.quickModalKey("enter") } @@ -352,7 +352,7 @@ func (a *App) quickModalView(m *modal) string { row = st.ChipDanger.Render(ansi.Strip(row)) } } - lines = append(lines, a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + lines = append(lines, a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { if m.scroll == i || double { return a.quickModalKey("enter") } diff --git a/internal/ui/rawconn.go b/internal/ui/rawconn.go index 86c22d4..ae0d493 100644 --- a/internal/ui/rawconn.go +++ b/internal/ui/rawconn.go @@ -14,6 +14,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/localsh" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/serialx" "github.com/db9979/sshtermy/internal/telnet" "github.com/db9979/sshtermy/internal/termemu" @@ -67,6 +68,7 @@ func (a *App) connectRawCmd(s *session, cols, rows int, keepTerm bool) tea.Cmd { var st termStream login := autologin.New(c.Username, c.Password.Reveal(), func(txt string) { go func() { + defer safe.Recover("ui/rawconn.go") <-ready _, _ = st.Write([]byte(txt)) }() @@ -128,6 +130,7 @@ func (a *App) connectRawCmd(s *session, cols, rows int, keepTerm bool) tea.Cmd { _, _ = st.Write([]byte("\r")) } go func() { + defer safe.Recover("ui/rawconn.go") err := <-done // exit in der lokalen Shell ist ein gewolltes Ende, kein Abriss ev <- shellClosedMsg{s.id, st, err, err != nil && c.Protocol != domain.ProtoLocal && c.Protocol != domain.ProtoWatch} diff --git a/internal/ui/reach.go b/internal/ui/reach.go index e50ff31..bc28586 100644 --- a/internal/ui/reach.go +++ b/internal/ui/reach.go @@ -15,6 +15,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // Online-Punkt im Manager: Solange der Manager offen ist, prüft sshTermy @@ -179,6 +180,7 @@ func checkReach(conns []domain.Connection) map[string]reachResult { wg.Add(1) sem <- struct{}{} go func(c domain.Connection) { + defer safe.Recover("ui/reach.go") defer func() { <-sem; wg.Done() }() ctx, cancel := context.WithTimeout(context.Background(), reachTimeout) defer cancel() diff --git a/internal/ui/relay.go b/internal/ui/relay.go index 48fd53b..85ab78c 100644 --- a/internal/ui/relay.go +++ b/internal/ui/relay.go @@ -16,6 +16,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/relay" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" ) @@ -172,6 +173,7 @@ func (a *App) fetchAll(rs []domain.Relay) { for _, r := range rs { wg.Add(1) go func(id string) { + defer safe.Recover("ui/relay.go") defer wg.Done() ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() diff --git a/internal/ui/safety.go b/internal/ui/safety.go new file mode 100644 index 0000000..f61f256 --- /dev/null +++ b/internal/ui/safety.go @@ -0,0 +1,139 @@ +package ui + +import ( + "reflect" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/crash" + "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" +) + +// Absturzschutz (internal/safe): Ein Fehler in Update, View, einem Kommando +// oder einer Hintergrund-Goroutine beendet nicht mehr das ganze Programm mit +// allen Verbindungen. Stattdessen entsteht ein Absturzbericht, oben rechts +// erscheint eine Meldung, und alles andere läuft weiter. Häufen sich die +// Fehler, endet sshTermy wie früher (safe.StormN). + +// caughtMsg: eine Panik wurde abgefangen, der Bericht liegt unter path. +type caughtMsg struct { + where string + path string + err string +} + +// CatchPanics schaltet den Absturzschutz ein (main, keep). Tests lassen ihn +// aus, damit Fehler dort sofort auffallen. +func (a *App) CatchPanics() { + safe.SetHandler(func(c safe.Caught) { + // Bericht nebenher schreiben: die Panik kann mitten in einer Sperre + // passiert sein (Store), dann darf der Handler nicht warten. + go func() { + defer func() { _ = recover() }() + msg := caughtMsg{where: c.Where} + if r, err := crash.Write(a.st.Dir, crash.KindCaught, c.Raw(), a.st.Sensitive()); err == nil { + msg.path = r.Path + } else { + msg.err = err.Error() + } + select { + case a.events <- msg: + default: + } + }() + }) +} + +func (a *App) onCaught(m caughtMsg) { + text := i18n.T("Interner Fehler abgefangen, sshTermy läuft weiter.") + if m.path != "" { + text += " " + i18n.T("Bericht: ") + m.path + } else if m.err != "" { + text += " " + i18n.T("Absturzbericht ließ sich nicht schreiben: ") + m.err + } + a.pushToast(toastErr, text) +} + +func (a *App) Init() tea.Cmd { + var c tea.Cmd + if !safe.Run("ui.Init", func() { c = a.init0() }) { + return a.listen() + } + return guardCmd(c) +} + +func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + if m, ok := msg.(caughtMsg); ok { + a.onCaught(m) + return a, a.listen() + } + var ( + model tea.Model = a + c tea.Cmd + ) + if !safe.Run("ui.Update", func() { model, c = a.update0(msg) }) { + return a, a.rearm(msg) + } + return model, guardCmd(c) +} + +// rearm: update0 ist mittendrin abgebrochen und hat die Ketten nicht neu +// angestoßen, die sonst jede Nachricht verlängert: den Sekundentakt und den +// Empfang aus a.events (Ausgabe der Sitzungen, Meldungen). +func (a *App) rearm(msg tea.Msg) tea.Cmd { + var cmds []tea.Cmd + if _, ok := msg.(tickMsg); ok { + cmds = append(cmds, tick()) + } + if a.listening.Load() == 0 { + cmds = append(cmds, a.listen()) + } + return tea.Batch(cmds...) +} + +// View: gemessen, bei Ausgabeflut gedrosselt (perf.go). Scheitert das +// Zeichnen, bleibt das letzte gute Bild stehen. +func (a *App) View() tea.View { + var v tea.View + if !safe.Run("ui.View", func() { v = a.view() }) { + return a.lastView + } + a.lastView = v + return v +} + +// guardCmd schützt ein Kommando und alle, die es über Batch/Sequence +// nachreicht. +func guardCmd(c tea.Cmd) tea.Cmd { + if c == nil || !safe.Active() { + return c + } + return func() tea.Msg { + var m tea.Msg + if !safe.Run("ui.Cmd", func() { m = c() }) { + return nil + } + return guardMsg(m) + } +} + +var cmdType = reflect.TypeFor[tea.Cmd]() + +// guardMsg: BatchMsg und das (nicht exportierte) sequenceMsg sind Listen von +// Kommandos; jedes einzeln schützen, Typ und Reihenfolge bleiben. +func guardMsg(m tea.Msg) tea.Msg { + if m == nil { + return nil + } + v := reflect.ValueOf(m) + if v.Kind() != reflect.Slice || v.Type().Elem() != cmdType { + return m + } + out := reflect.MakeSlice(v.Type(), v.Len(), v.Len()) + for i := 0; i < v.Len(); i++ { + c, _ := v.Index(i).Interface().(tea.Cmd) + out.Index(i).Set(reflect.ValueOf(guardCmd(c))) + } + return out.Interface() +} diff --git a/internal/ui/safety_test.go b/internal/ui/safety_test.go new file mode 100644 index 0000000..d6174f5 --- /dev/null +++ b/internal/ui/safety_test.go @@ -0,0 +1,122 @@ +package ui + +import ( + "os" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/safe" +) + +func safetyApp(t *testing.T) *App { + t.Helper() + a := newPaletteTestApp(t) + safe.Reset() + a.CatchPanics() + t.Cleanup(safe.Reset) + return a +} + +// waitCaught holt die Meldung über die abgefangene Panik aus a.events. +func waitCaught(t *testing.T, a *App) caughtMsg { + t.Helper() + deadline := time.After(5 * time.Second) + for { + select { + case m := <-a.events: + if c, ok := m.(caughtMsg); ok { + return c + } + case <-deadline: + t.Fatal("keine Meldung über den abgefangenen Fehler") + } + } +} + +func TestUpdatePanicIsCaught(t *testing.T) { + a := safetyApp(t) + before := safe.Count() + _, cmd := a.Update(crashTestMsg{}) // panic in update0 + if cmd == nil { + t.Fatal("nach dem Fehler muss der Empfang neu angestoßen werden") + } + if safe.Count() != before+1 { + t.Fatal("Panik nicht gezählt") + } + c := waitCaught(t, a) + if c.where != "ui.Update" || c.path == "" { + t.Fatalf("Meldung unvollständig: %+v", c) + } + raw, err := os.ReadFile(c.path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "hunter2") { + t.Fatal("Bericht enthält das Passwort") + } + if !strings.Contains(string(raw), "sshTermy crash test (ui)") { + t.Fatal("Bericht ohne Meldung") + } + a.Update(c) + if len(a.toasts) == 0 || a.toasts[len(a.toasts)-1].kind != toastErr { + t.Fatal("keine Fehlermeldung oben rechts") + } +} + +func TestTickPanicKeepsTicking(t *testing.T) { + a := safetyApp(t) + // Panik mitten im Takt: rearm muss den Takt neu anstoßen. + cmd := a.rearm(tickMsg(time.Now())) + if cmd == nil { + t.Fatal("Takt nicht neu angestoßen") + } +} + +func TestGuardCmdNested(t *testing.T) { + _ = safetyApp(t) + boom := func() tea.Msg { panic("cmd boom") } + ok := func() tea.Msg { return "fein" } + c := guardCmd(tea.Batch(boom, ok)) + m := c() + batch, isBatch := m.(tea.BatchMsg) + if !isBatch || len(batch) != 2 { + t.Fatalf("Batch verloren: %T", m) + } + if got := batch[0](); got != nil { + t.Fatalf("abgefangene Panik muss nil liefern, nicht %v", got) + } + if got := batch[1](); got != "fein" { + t.Fatalf("zweites Kommando: %v", got) + } + // Sequence (nicht exportierter Typ) bleibt dieselbe Art Liste + s := guardCmd(tea.Sequence(boom, ok))() + if s == nil { + t.Fatal("Sequence verloren") + } + if _, isBatch := s.(tea.BatchMsg); isBatch { + t.Fatal("Sequence darf kein Batch werden (Reihenfolge)") + } +} + +func TestOutputPanicDropsBlock(t *testing.T) { + _ = safetyApp(t) + w := outWriter{s: nil, ev: nil} // nil-Sitzung: write0 stürzt ab + n, err := w.Write([]byte("hallo")) + if n != 5 || err != nil { + t.Fatalf("Block muss verworfen werden, Verbindung bleibt: %d %v", n, err) + } +} + +func TestWithoutHandlerPanicsStillSurface(t *testing.T) { + a := newPaletteTestApp(t) + safe.SetHandler(nil) + defer func() { + if recover() == nil { + t.Fatal("ohne Absturzschutz (Tests) muss die Panik durchlaufen") + } + }() + a.Update(crashTestMsg{}) +} diff --git a/internal/ui/scan.go b/internal/ui/scan.go index 128b67c..378bb30 100644 --- a/internal/ui/scan.go +++ b/internal/ui/scan.go @@ -15,6 +15,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/netscan" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/store" ) @@ -130,6 +131,7 @@ func (a *App) scanStart() tea.Cmd { sc.phase = scRun ev := a.events go func() { + defer safe.Recover("ui/scan.go") last := time.Time{} netscan.Scan(ctx, addrs, netscan.Options{Port: port}, func(d, n int) { @@ -426,7 +428,7 @@ func (a *App) viewScan() string { line = ansi.Truncate(line, w-4, "…") } i, k := i, k - line = a.z.click(line, func(tea.Mouse, bool) tea.Cmd { sc.cur, sc.picked[k] = i, !sc.picked[k]; return nil }) + line = a.z.Click(line, func(tea.Mouse, bool) tea.Cmd { sc.cur, sc.picked[k] = i, !sc.picked[k]; return nil }) o.WriteString(line + "\n") } return lipgloss.Place(a.w, a.h-2, lipgloss.Center, lipgloss.Center, s.Panel.Width(w).Render(o.String())) diff --git a/internal/ui/search.go b/internal/ui/search.go index f3ece7d..06aa713 100644 --- a/internal/ui/search.go +++ b/internal/ui/search.go @@ -258,7 +258,7 @@ func (a *App) viewErrorList(s *session, w, h int) string { line = st.Selected.Render(padRight(num+text, w)) } i := i - lines = append(lines, a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd { + lines = append(lines, a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd { sr.idx = i if double { sr.list = false diff --git a/internal/ui/session.go b/internal/ui/session.go index 7606629..7628e6f 100644 --- a/internal/ui/session.go +++ b/internal/ui/session.go @@ -14,6 +14,7 @@ import ( "github.com/db9979/sshtermy/internal/detach" "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sessionlog" "github.com/db9979/sshtermy/internal/sshx" "github.com/db9979/sshtermy/internal/termemu" @@ -179,7 +180,18 @@ type outWriter struct { type outputMsg struct{ sid int } -func (w outWriter) Write(p []byte) (int, error) { +func (w outWriter) Write(p []byte) (n int, err error) { + // Serverausgabe läuft durch Emulator, Erkennung, Aufnahme, Teilen: ein + // Fehler dort darf nicht das ganze Programm beenden (safety.go). Der + // Block wird dann verworfen, die Verbindung bleibt. + n = len(p) + if !safe.Run("ui.output", func() { n, err = w.write0(p) }) { + return len(p), nil + } + return n, err +} + +func (w outWriter) write0(p []byte) (int, error) { full := len(p) outBytes.Add(int64(full)) // Ausgaberate für die Bildrate (perf.go) if p = w.s.trzScan(p, w.ev); len(p) == 0 { @@ -292,6 +304,7 @@ func (a *App) connectCmd(s *session) tea.Cmd { return connectErrMsg{s.id, err} } go func() { + defer safe.Recover("ui/session.go") err := <-sh.Done // exit/logout endet mit Exit-Status; ohne Status (oder mit Fehler) // prüfen, ob die ganze Leitung weg ist → Auto-Reconnect. diff --git a/internal/ui/share.go b/internal/ui/share.go index 5f3442a..5ca9fb1 100644 --- a/internal/ui/share.go +++ b/internal/ui/share.go @@ -22,6 +22,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/relay" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sessionlog" "github.com/db9979/sshtermy/internal/sshx" "github.com/db9979/sshtermy/internal/termemu" @@ -334,7 +335,7 @@ func (a *App) shareMsg(msg tea.Msg) (tea.Cmd, bool) { m.lan.Announce(m.sh.Platz, true) } s.share.Store(o) - go o.pump(s.id, a.events) + safe.Go("ui/share.go", func() { o.pump(s.id, a.events) }) a.shareLog(s, fmt.Sprintf(i18n.T("# Teilen gestartet (%s, %d min, höchstens %d Zuschauer)"), o.via, m.opts.minutes, m.opts.max)) a.showInvite(s, o) return nil, true @@ -462,14 +463,14 @@ func (a *App) shareGuestKeys(s *session, o *shareOut, g *relay.GuestState, data } i := strings.IndexAny(string(data), "\r\n") if i < 0 || !isProduction(s.conn) { - _, _ = s.shell.Write(data) + s.term.SendRaw(data) // Warteschlange: hängt nie die Oberfläche auf if i >= 0 { a.shareLog(s, fmt.Sprintf(i18n.T("# ⏎ von %s (mitschreiben)"), g.Hello.Name)) } return nil } if i > 0 { - _, _ = s.shell.Write(data[:i]) + s.term.SendRaw(data[:i]) } line := strings.TrimSpace(s.term.CursorLine()) name := g.Hello.Name @@ -477,7 +478,7 @@ func (a *App) shareGuestKeys(s *session, o *shareOut, g *relay.GuestState, data fmt.Sprintf(i18n.T("%s darf mitschreiben und möchte ⏎ drücken. %s gilt als produktiv.\n\nZeile: %s\n\nj = ausführen n = verwerfen (Zeile bleibt stehen)"), name, s.conn.Alias, trunc(line, 200)), func() tea.Cmd { if s.shell != nil { - _, _ = s.shell.Write([]byte{'\r'}) + s.term.SendRaw([]byte{'\r'}) a.shareLog(s, fmt.Sprintf(i18n.T("# ⏎ von %s (mitschreiben, bestätigt)"), name)) } return nil @@ -856,6 +857,7 @@ func dialWatchV1(sid int, link string, out io.Writer, ev chan<- tea.Msg) (termSt } done := make(chan error, 1) go func() { + defer safe.Recover("ui/share.go") for { typ, p, err := v.Next(context.Background()) if err != nil { @@ -998,6 +1000,7 @@ func (a *App) dialWatch(sid int, link string, out io.Writer, ev chan<- tea.Msg) say(fmt.Sprintf("\x1b[2m%s\x1b[0m\n", fmt.Sprintf(i18n.T("sshTermy: Freigabe %d gefunden (%s). Prüfe den Code …"), inv.Platz, strings.TrimPrefix(base, "https://")))) done := make(chan error, 1) go func() { + defer safe.Recover("ui/share.go") name, host := localName() wctx, wcancel := context.WithTimeout(jctx, 4*time.Minute) w, err := relay.Join(wctx, g, inv, relay.Hello{Name: name, Rechner: host, Version: version.Version}, func(chk [3]string) { diff --git a/internal/ui/share_test.go b/internal/ui/share_test.go index 997d661..e0ae95e 100644 --- a/internal/ui/share_test.go +++ b/internal/ui/share_test.go @@ -72,7 +72,7 @@ func TestShareAndWatchV2(t *testing.T) { if err != nil { t.Fatal(err) } - s, _ := typedSession(domain.Connection{Alias: "web"}, "$ ", "cat geheim-von-vorher") + s, host := typedSession(domain.Connection{Alias: "web"}, "$ ", "cat geheim-von-vorher") sh := &shareShell{} s.shell = sh a.sessions = append(a.sessions, s) @@ -153,20 +153,23 @@ func TestShareAndWatchV2(t *testing.T) { _, _ = ws.Write([]byte("rm -rf /\r")) time.Sleep(200 * time.Millisecond) pumpUntil(t, a, "nichts", func() bool { return true }) - if sh.String() != "" { - t.Fatalf("Zuschauer-Tasten kamen an: %q", sh.String()) + s.term.Flush(time.Second) + if sh.String() != "" || host.String() != "" { + t.Fatalf("Zuschauer-Tasten kamen an: %q %q", sh.String(), host.String()) } g := o.hs.Guests()[0] _ = o.hs.SetWrite(g.V, time.Now().Add(time.Minute)) pumpUntil(t, a, "Schreibrecht beim Zuschauer", func() bool { return ws.(*watch2Stream).writeTo.Load() > 0 }) _, _ = ws.Write([]byte("uptime\r")) pumpUntil(t, a, "⏎-Rückfrage (produktiv)", func() bool { return a.modal != nil && strings.Contains(a.modal.title, "⏎") }) - if sh.String() != "uptime" { - t.Fatalf("vor der Bestätigung: %q", sh.String()) + s.term.Flush(time.Second) // Gast-Tasten laufen über die Warteschlange (SendRaw) + if host.String() != "uptime" { + t.Fatalf("vor der Bestätigung: %q", host.String()) } a.modal.onYes() - if sh.String() != "uptime\r" { - t.Fatalf("nach der Bestätigung: %q", sh.String()) + s.term.Flush(time.Second) + if host.String() != "uptime\r" { + t.Fatalf("nach der Bestätigung: %q", host.String()) } a.modal = nil diff --git a/internal/ui/soak_test.go b/internal/ui/soak_test.go new file mode 100644 index 0000000..d60708e --- /dev/null +++ b/internal/ui/soak_test.go @@ -0,0 +1,138 @@ +package ui + +import ( + "net" + "os" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/db9979/sshtermy/internal/devfake" + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/store" +) + +// TestSoak ist der Dauerlauf (make soak, nachts in CI): immer wieder Tabs zu +// einem Test-Switch öffnen, Befehle tippen, Ausgabe abwarten, die Hälfte +// der Verbindungen abreißen lassen und alle Tabs schließen. Am Ende dürfen +// Hintergrundabläufe (Goroutinen) und Speicher nicht gewachsen sein, sonst +// hätte sshTermy nach Tagen im Betrieb ein Leck. +// +// SSHTERMY_SOAK=30m go test -run TestSoak -v ./internal/ui +func TestSoak(t *testing.T) { + d := os.Getenv("SSHTERMY_SOAK") + if d == "" { + t.Skip("Dauerlauf: make soak") + } + dur, err := time.ParseDuration(d) + if err != nil { + t.Fatalf("SSHTERMY_SOAK=%q: %v", d, err) + } + t.Setenv("SSHTERMY_HOME", t.TempDir()) + st, err := store.Open() + if err != nil { + t.Fatal(err) + } + if err := st.Init([]byte("correct horse"), false); err != nil { + t.Fatal(err) + } + sw, err := devfake.StartSwitch("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer sw.Close() + a, err := New(st) + if err != nil { + t.Fatal(err) + } + a.w, a.h, a.scr = 140, 40, scrTerminal + stop := make(chan struct{}) + defer close(stop) + go func() { // Rückfragen beantworten, Ausgabe-Meldungen verwerfen + for { + select { + case m := <-a.events: + if hk, ok := m.(hostKeyAskMsg); ok { + hk.reply <- true + } + case <-stop: + return + } + } + }() + host, port, _ := net.SplitHostPort(sw.Addr) + p, _ := strconv.Atoi(port) + c, err := st.UpsertConnection(domain.Connection{Alias: "sw-dauer", Host: host, Port: p, Username: "manager", + Auth: domain.AuthPassword, Password: "x", GuardOff: true}) + if err != nil { + t.Fatal(err) + } + + const tabs = 8 + nextID := 1 + round := func() { + var open []*session + for i := 0; i < tabs; i++ { + s := &session{id: nextID, conn: c, chipArmed: -1} + nextID++ + a.sessions = append(a.sessions, s) + msg := a.connectCmd(s)() + if e, ok := msg.(connectErrMsg); ok { + t.Fatal(e.err) + } + a.Update(msg) + open = append(open, s) + } + for _, s := range open { + waitFor(t, func() bool { return strings.HasSuffix(strings.TrimSpace(s.term.CursorLine()), "#") }) + s.term.SendText("show system\r") + } + for _, s := range open { + waitFor(t, func() bool { return strings.Contains(s.term.PlainLines(40), "Software revision") }) + } + for i, s := range open { + if i%2 == 0 && s.client != nil { + _ = s.client.Close() // Verbindung reißt ab + } + a.closeTab(s) + } + } + settle := func() (int, uint64) { + var ms runtime.MemStats + for i := 0; i < 3; i++ { + time.Sleep(200 * time.Millisecond) + runtime.GC() + } + runtime.ReadMemStats(&ms) + return runtime.NumGoroutine(), ms.HeapAlloc + } + + for i := 0; i < 3; i++ { // Aufwärmen: Puffer, Caches, Pools + round() + } + g0, h0 := settle() + rounds := 0 + for end := time.Now().Add(dur); time.Now().Before(end); rounds++ { + round() + } + // Aufräumen braucht einen Moment (Keepalive, Lesen enden nach Close) + var g1 int + var h1 uint64 + for i := 0; i < 20; i++ { + if g1, h1 = settle(); g1 <= g0+tabs { + break + } + } + t.Logf("Dauerlauf %s: %d Runden à %d Tabs; Goroutinen %d → %d; Heap %.1f → %.1f MB", + dur, rounds, tabs, g0, g1, float64(h0)/1e6, float64(h1)/1e6) + if g1 > g0+tabs { + buf := make([]byte, 1<<20) + n := runtime.Stack(buf, true) + t.Fatalf("Goroutinen-Leck: %d → %d\n%s", g0, g1, buf[:n]) + } + if h1 > 2*h0+32<<20 { + t.Fatalf("Speicher wächst: %.1f → %.1f MB", float64(h0)/1e6, float64(h1)/1e6) + } +} diff --git a/internal/ui/statusline.go b/internal/ui/statusline.go index b43628d..868962d 100644 --- a/internal/ui/statusline.go +++ b/internal/ui/statusline.go @@ -91,7 +91,7 @@ func (a *App) termHeader(s *session) string { b.WriteString(st.ChipDanger.Render(i18n.T("● REC"))) } if chip := a.shareChip(s); chip != "" { - b.WriteString(a.z.click(chip, func(tea.Mouse, bool) tea.Cmd { + b.WriteString(a.z.Click(chip, func(tea.Mouse, bool) tea.Cmd { if o := s.share.Load(); o != nil { return a.openShareManage(s, o) } @@ -176,7 +176,7 @@ func (a *App) termHeader(s *session) string { } } ai = st.Badge.Foreground(a.llmColor(h.level)).PaddingRight(0).Render(h.dot(a.lh.probing)) + ai - return a.z.click(ai, func(tea.Mouse, bool) tea.Cmd { return a.openLLMStatus() }) + return a.z.Click(ai, func(tea.Mouse, bool) tea.Cmd { return a.openLLMStatus() }) } tun := func(short bool) string { txt := "↔ " + plural(nT, i18n.Pick("Tunnel", "tunnel"), i18n.Pick("Tunnel", "tunnels")) @@ -199,7 +199,7 @@ func (a *App) termHeader(s *session) string { } } if s.scroll > 0 { - goal = a.z.click(st.Badge.Foreground(st.T.Warn).Render(fmt.Sprintf(i18n.T("⇡ Verlauf −%d · Esc"), s.scroll)), + goal = a.z.Click(st.Badge.Foreground(st.T.Warn).Render(fmt.Sprintf(i18n.T("⇡ Verlauf −%d · Esc"), s.scroll)), func(tea.Mouse, bool) tea.Cmd { s.scroll, s.sel = 0, nil; return nil }) + " " + goal } hb := a.hostBadge(s) diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index c41e06a..fd95cd6 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -140,7 +140,7 @@ func (a *App) tabDragMouse(msg tea.MouseMsg) tea.Cmd { a.tabDrag = nil case tea.MouseMotionMsg: i := a.indexOf(a.byID(d.id)) - j := a.z.tabAt(m.X, m.Y) + j := a.z.TabAt(m.X, m.Y) if i < 0 { a.tabDrag = nil return nil diff --git a/internal/ui/team.go b/internal/ui/team.go index 54294ad..e344134 100644 --- a/internal/ui/team.go +++ b/internal/ui/team.go @@ -540,7 +540,7 @@ func (a *App) viewTeam() string { } } i := i - out = a.z.click(out, func(tea.Mouse, bool) tea.Cmd { + out = a.z.Click(out, func(tea.Mouse, bool) tea.Cmd { t.sel = i t.items[i].on = !t.items[i].on return nil diff --git a/internal/ui/terminal.go b/internal/ui/terminal.go index 9bf0e21..1575338 100644 --- a/internal/ui/terminal.go +++ b/internal/ui/terminal.go @@ -15,6 +15,10 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" "github.com/db9979/sshtermy/internal/llm" + + "github.com/db9979/sshtermy/internal/ui/clickzone" + + "github.com/db9979/sshtermy/internal/ui/dropped" ) const ( @@ -97,7 +101,7 @@ func (a *App) panelRail(s *session, h int) string { } lines[i] = side + ansi.Truncate(c, 1, "") + " " } - return a.z.mark(strings.Join(lines, "\n"), zoneAction{block: true, click: func(tea.Mouse, bool) tea.Cmd { + return a.z.Mark(strings.Join(lines, "\n"), clickzone.Action{Block: true, Click: func(tea.Mouse, bool) tea.Cmd { s.panelFocus = true return nil }}) @@ -163,7 +167,7 @@ func (a *App) updateTerminal(msg tea.Msg) tea.Cmd { } // Dateien aus dem Explorer/Finder ins Fenster gezogen: hochladen? if s.client != nil && s.state == stConnected && s.term != nil && !s.term.AltScreen() { - if paths := droppedPaths(m.Content); paths != nil { + if paths := dropped.Paths(m.Content); paths != nil { a.dropMenu(s, m.Content, paths) return nil } @@ -706,12 +710,12 @@ func (a *App) chipBar(s *session) string { st := a.s var b strings.Builder if g := a.visibleGhost(s); g != "" { - b.WriteString(a.z.click(st.AI.Render(" ◆ ")+st.Muted.Render(i18n.T("Tab übernimmt: "))+st.Ghost.Render(trunc(g, 60)), + b.WriteString(a.z.Click(st.AI.Render(" ◆ ")+st.Muted.Render(i18n.T("Tab übernimmt: "))+st.Ghost.Render(trunc(g, 60)), func(tea.Mouse, bool) tea.Cmd { s.panelFocus = false; return a.pressKey("Tab") }) + " ") } else { if f := s.fail; f != nil { why := orDefault(f.Reason, i18n.T("fehlgeschlagen")) - b.WriteString(a.z.click(st.Danger.Render(" × "+trunc(why, 34))+" "+st.Key.Render("Alt+0")+st.AI.Render(i18n.T(" Warum? & Fix ")), + b.WriteString(a.z.Click(st.Danger.Render(" × "+trunc(why, 34))+" "+st.Key.Render("Alt+0")+st.AI.Render(i18n.T(" Warum? & Fix ")), func(tea.Mouse, bool) tea.Cmd { s.panelFocus = false; return a.pressKey("alt+0") }) + " ") } a.chipList(s, &b) @@ -734,7 +738,7 @@ func (a *App) chipList(s *session, b *strings.Builder) { } id := []action{actChip1, actChip2, actChip3, actChip4}[min(i, 3)] lbl := a.keys.label(id) - b.WriteString(a.z.click(st.Key.Render(lbl)+style.Render(trunc(c.Command, 34)), + b.WriteString(a.z.Click(st.Key.Render(lbl)+style.Render(trunc(c.Command, 34)), func(tea.Mouse, bool) tea.Cmd { s.panelFocus = false; return a.pressKey(lbl) }) + " ") } if len(s.chips) > 0 && s.chips[0].Reason != "" { @@ -947,25 +951,25 @@ func (a *App) tabStrip(room int) string { if i == a.cur { end = "" } - tab := a.z.mark(ts.Render(stripe+dot+ts.UnsetPadding().Render(text+end)), zoneAction{ - tab: i + 1, - click: func(m tea.Mouse, _ bool) tea.Cmd { + tab := a.z.Mark(ts.Render(stripe+dot+ts.UnsetPadding().Render(text+end)), clickzone.Action{ + Tab: i + 1, + Click: func(m tea.Mouse, _ bool) tea.Cmd { a.focusSession(i) a.tabDrag = &tabDrag{id: x.id, x: m.X} // Ziehen sortiert um (tabs.go) return nil }, - menu: func(m tea.Mouse) tea.Cmd { + Menu: func(m tea.Mouse) tea.Cmd { if m.Button == tea.MouseMiddle { return a.closeTabAsk(x, nil) } a.modal = a.tabMenu(x, m.X, m.Y, nil) return nil }, - tip: func() string { return a.tabTip(x) }, + Tip: func() string { return a.tabTip(x) }, }) if i == a.cur { // × schließt den aktiven Tab (bei laufender Verbindung mit Rückfrage) - close := a.z.click(ts.Padding(0, 1, 0, 0).UnsetBold().Render("×"), func(tea.Mouse, bool) tea.Cmd { + close := a.z.Click(ts.Padding(0, 1, 0, 0).UnsetBold().Render("×"), func(tea.Mouse, bool) tea.Cmd { return a.closeTabAsk(x, nil) }) tab += close @@ -975,6 +979,6 @@ func (a *App) tabStrip(room int) string { if to < n { b.WriteString(st.Header.Foreground(st.T.Muted).Render(" ›")) } - b.WriteString(a.z.click(plus, func(tea.Mouse, bool) tea.Cmd { return a.openNewTab() })) + b.WriteString(a.z.Click(plus, func(tea.Mouse, bool) tea.Cmd { return a.openNewTab() })) return b.String() } diff --git a/internal/ui/themepick.go b/internal/ui/themepick.go index ecc93bd..85820b5 100644 --- a/internal/ui/themepick.go +++ b/internal/ui/themepick.go @@ -165,7 +165,7 @@ func (a *App) viewThemes() string { row = s.Text.Render(row) } line := row + swatch(t) + " " + mark - list = append(list, a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd { + list = append(list, a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd { p.sel = i a.previewTheme() if double { diff --git a/internal/ui/tmuxscroll.go b/internal/ui/tmuxscroll.go index 961d13e..ca8319f 100644 --- a/internal/ui/tmuxscroll.go +++ b/internal/ui/tmuxscroll.go @@ -7,6 +7,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/sshx" "github.com/db9979/sshtermy/internal/termemu" ) @@ -114,6 +115,7 @@ func (q *tmuxScroller) add(c *sshx.Client, name string, op tmuxOp) { } q.running = true go func() { + defer safe.Recover("ui/tmuxscroll.go") for { q.mu.Lock() if len(q.pending) == 0 { diff --git a/internal/ui/toast.go b/internal/ui/toast.go index dde5941..de6d477 100644 --- a/internal/ui/toast.go +++ b/internal/ui/toast.go @@ -9,6 +9,8 @@ import ( "github.com/charmbracelet/x/ansi" "github.com/db9979/sshtermy/internal/i18n" + + "github.com/db9979/sshtermy/internal/ui/clickzone" ) // Toasts: kurze Einblendungen oben rechts („verbunden“, „kopiert“, Fehler), @@ -197,7 +199,7 @@ func (a *App) withToasts(base string) string { t := a.toasts[i] text, undo := t.text, t.undo box := a.toastBox(t, w, now) - box = a.z.mark(box, zoneAction{block: true, click: func(tea.Mouse, bool) tea.Cmd { + box = a.z.Mark(box, clickzone.Action{Block: true, Click: func(tea.Mouse, bool) tea.Cmd { if undo && a.undo != nil && a.undo.toast == text { return a.doUndo() } @@ -219,7 +221,7 @@ func (a *App) withToasts(base string) string { } box = strings.Join(ls, "\n") } - box = a.z.scan(box, x, y) + box = a.z.Scan(box, x, y) base = stamp(base, box, x, y, a.w) // stamp.go y += bh } diff --git a/internal/ui/trzsz.go b/internal/ui/trzsz.go index e18a2d9..03c3d1d 100644 --- a/internal/ui/trzsz.go +++ b/internal/ui/trzsz.go @@ -198,7 +198,7 @@ func (a *App) trzMsg(msg tea.Msg) (tea.Cmd, bool) { case zmodemMsg: if s := a.byID(m.sid); s != nil && s.shell != nil { // Abbruch: fünfmal CAN, dann Backspaces (so bricht lrzsz ab) - _, _ = s.shell.Write([]byte("\x18\x18\x18\x18\x18\x08\x08\x08\x08\x08")) + s.term.SendRaw([]byte("\x18\x18\x18\x18\x18\x08\x08\x08\x08\x08")) a.flashErr(i18n.T("ZMODEM (sz/rz) kann sshTermy nicht; auf dem Server trzsz nutzen (tsz/trz) oder F5 (SFTP)")) } return a.listen(), true diff --git a/internal/ui/trzsz_test.go b/internal/ui/trzsz_test.go index 5c28b36..0c89828 100644 --- a/internal/ui/trzsz_test.go +++ b/internal/ui/trzsz_test.go @@ -119,7 +119,7 @@ func TestTrzszTriggerAndCancel(t *testing.T) { func TestZmodemHint(t *testing.T) { a := dangerApp(t) - s, _ := typedSession(domain.Connection{Alias: "srv"}, "$ ", "") + s, host := typedSession(domain.Connection{Alias: "srv"}, "$ ", "") sh := &fakeShell{} s.setShell(sh) a.sessions = []*session{s} @@ -138,7 +138,8 @@ func TestZmodemHint(t *testing.T) { } } a.trzMsg(m) - if !strings.Contains(sh.String(), "\x18\x18\x18\x18\x18") { + s.term.Flush(time.Second) // Abbruch läuft über die Warteschlange (SendRaw) + if !strings.Contains(host.String(), "\x18\x18\x18\x18\x18") { t.Fatal("ZMODEM nicht abgebrochen") } } diff --git a/internal/ui/usability1111_test.go b/internal/ui/usability1111_test.go index 71406cf..c9c949d 100644 --- a/internal/ui/usability1111_test.go +++ b/internal/ui/usability1111_test.go @@ -162,11 +162,11 @@ func TestSearchAllTabs(t *testing.T) { func TestTabDragReorders(t *testing.T) { a := tabsApp(4) a.scr = scrTerminal - view := a.z.scan(a.tabStrip(a.w-lipgloss.Width(a.headerLeft())-1), 0, 0) + view := a.z.Scan(a.tabStrip(a.w-lipgloss.Width(a.headerLeft())-1), 0, 0) _ = view at := func(i int) int { // Spalte in der Mitte von Tab i for x := 0; x < a.w; x++ { - if a.z.tabAt(x, 0) == i && a.z.tabAt(x+2, 0) == i { + if a.z.TabAt(x, 0) == i && a.z.TabAt(x+2, 0) == i { return x + 1 } } @@ -186,8 +186,8 @@ func TestTabDragReorders(t *testing.T) { if a.current().conn.Alias != "host-a" { t.Fatalf("aktiver Tab: %s", a.current().conn.Alias) } - a.z.reset() - a.z.scan(a.tabStrip(a.w-lipgloss.Width(a.headerLeft())-1), 0, 0) + a.z.Reset() + a.z.Scan(a.tabStrip(a.w-lipgloss.Width(a.headerLeft())-1), 0, 0) // Maus bewegt sich nach links über Tab 3 hinweg: kein Sprung nach rechts a.tabDrag.x = at(3) + 1 a.mouse(tea.MouseMotionMsg{X: at(3), Y: 0, Button: tea.MouseLeft}) diff --git a/internal/ui/vorgang_view.go b/internal/ui/vorgang_view.go index c11c534..eb218b6 100644 --- a/internal/ui/vorgang_view.go +++ b/internal/ui/vorgang_view.go @@ -73,7 +73,7 @@ func (a *App) viewVorgang() string { l = ansi.Truncate(" "+l, w, "…") out = append(out, l+strings.Repeat(" ", max(0, w-lipgloss.Width(l)))) } - return a.z.click(strings.Join(out, "\n"), func(tea.Mouse, bool) tea.Cmd { + return a.z.Click(strings.Join(out, "\n"), func(tea.Mouse, bool) tea.Cmd { g.focus = true _ = st return a.vgFocusInput() @@ -271,7 +271,7 @@ func (a *App) vgStepLine(i, w int, run bool) string { room := max(10, w-lipgloss.Width(left)-lipgloss.Width(kind)-lipgloss.Width(extra)-lipgloss.Width(note)-6) line := left + st.Accent.Render(trunc(cmd, room)) + " " + kind + extra + note idx := i - return a.z.click(line, func(_ tea.Mouse, double bool) tea.Cmd { + return a.z.Click(line, func(_ tea.Mouse, double bool) tea.Cmd { g.focus = true if run { return nil diff --git a/internal/ui/vuln_view.go b/internal/ui/vuln_view.go index f8bd492..fd09783 100644 --- a/internal/ui/vuln_view.go +++ b/internal/ui/vuln_view.go @@ -261,7 +261,7 @@ func (a *App) viewVuln() string { for i := v.top; i < min(len(vis), v.top+room); i++ { i := i row := a.vulnRow(vis[i], cols, i == v.sel, fresh[vis[i].Key()] && v.prev != nil) - b.WriteString(a.z.click(row, func(_ tea.Mouse, double bool) tea.Cmd { + b.WriteString(a.z.Click(row, func(_ tea.Mouse, double bool) tea.Cmd { v.sel = i if double { a.showVulnDetail(vis[i]) diff --git a/internal/ui/vulnfolder.go b/internal/ui/vulnfolder.go index b755c26..0f07945 100644 --- a/internal/ui/vulnfolder.go +++ b/internal/ui/vulnfolder.go @@ -12,6 +12,7 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" "github.com/db9979/sshtermy/internal/vuln" ) @@ -150,6 +151,7 @@ func (a *App) runVulnFolder(folder string) tea.Cmd { src, h := vulnSources(a) scan := vulnScanHost(a) go func() { + defer safe.Recover("ui/vulnfolder.go") defer cancel() vulnHosts(ctx, conns, func(ctx context.Context, c domain.Connection) (*vuln.Report, error) { return scan(ctx, c, src, h, cfg) @@ -168,6 +170,7 @@ func vulnHosts(ctx context.Context, conns []domain.Connection, scan func(context for i, c := range conns { wg.Add(1) go func() { + defer safe.Recover("ui/vulnfolder.go") defer wg.Done() select { case sem <- struct{}{}: diff --git a/internal/ui/zones.go b/internal/ui/zones.go deleted file mode 100644 index 0470086..0000000 --- a/internal/ui/zones.go +++ /dev/null @@ -1,217 +0,0 @@ -package ui - -import ( - "math" - "strconv" - "strings" - - tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" -) - -// Klickbare Bereiche (Zonen) -// -// Beim Zeichnen wird anklickbarer Text mit zwei unsichtbaren Markern -// umschlossen (CSI z, eine Sequenz, die kein Terminal kennt und die -// lipgloss als Breite 0 behandelt). Nach dem Zusammensetzen eines Bildes -// sucht scanZones die Marker, merkt sich die Rechtecke und entfernt die -// Marker wieder. So bleibt jede Ansicht frei in ihrem Layout, und die -// Mausbehandlung muss keine Positionen nachrechnen. - -const zoneBase = 71000 - -type zoneAction struct { - click func(m tea.Mouse, double bool) tea.Cmd // nil = nicht klickbar - menu func(m tea.Mouse) tea.Cmd // Rechts- oder Mittelklick, nil = keiner - wheel func(up bool) tea.Cmd // nil = Rad geht weiter nach außen - block bool // rechteckiger Block (Box), sonst Fließtext - row int // Manager: Zeile+1 als Ziel beim Ziehen (0 = keins); Dateien: Eintrag+1 - pane int // Dateien: Seite+1 (0 = keine) - tab int // Tab-Leiste: Tab+1 als Ziel beim Ziehen (0 = keins) - tip func() string // Karte beim Verweilen der Maus (motion.go) -} - -type zoneRect struct { - x0, y0, x1, y1 int // inklusive - id int - block bool -} - -func (r zoneRect) contains(x, y int) bool { - if y < r.y0 || y > r.y1 { - return false - } - if r.y0 == r.y1 || r.block { - return x >= r.x0 && x <= r.x1 - } - // mehrzeilig: wie Fließtext (erste Zeile ab x0, letzte bis x1) - switch y { - case r.y0: - return x >= r.x0 - case r.y1: - return x <= r.x1 - } - return true -} - -type zones struct { - acts []zoneAction - rects []zoneRect -} - -func (z *zones) reset() { z.acts, z.rects = z.acts[:0], z.rects[:0] } - -func zoneMarker(id int) string { return "\x1b[" + strconv.Itoa(zoneBase+id) + "z" } - -// mark umschließt s mit einer Zone. -func (z *zones) mark(s string, act zoneAction) string { - if s == "" { - return s - } - id := len(z.acts) - z.acts = append(z.acts, act) - m := zoneMarker(id) - return m + s + m -} - -func (z *zones) click(s string, f func(m tea.Mouse, double bool) tea.Cmd) string { - return z.mark(s, zoneAction{click: f}) -} - -// scan entfernt die Marker aus s und merkt sich die Rechtecke, verschoben -// um ox/oy (für Overlays). -func (z *zones) scan(s string, ox, oy int) string { - if !strings.Contains(s, "\x1b[") { - return s - } - var out strings.Builder - out.Grow(len(s)) - open := map[int][2]int{} - x, y := 0, 0 - state := byte(0) - for len(s) > 0 { - seq, width, n, newState := ansi.DecodeSequence(s, state, nil) - state = newState - if n <= 0 { - break - } - if seq == "\n" { - x, y = 0, y+1 - out.WriteString(seq) - s = s[n:] - continue - } - if width == 0 && len(seq) > 3 && seq[0] == 0x1b && seq[1] == '[' && seq[len(seq)-1] == 'z' { - if v, err := strconv.Atoi(seq[2 : len(seq)-1]); err == nil && v >= zoneBase && v-zoneBase < len(z.acts) { - id := v - zoneBase - if st, ok := open[id]; ok { - delete(open, id) - if x > st[0] || y > st[1] { - z.rects = append(z.rects, zoneRect{st[0] + ox, st[1] + oy, x - 1 + ox, y + oy, id, z.acts[id].block}) - } - } else { - open[id] = [2]int{x, y} - } - s = s[n:] - continue - } - } - out.WriteString(seq) - x += width - s = s[n:] - } - for id, st := range open { // Ende abgeschnitten: bis zum Bildende - z.rects = append(z.rects, zoneRect{st[0] + ox, st[1] + oy, 1 << 20, y + oy, id, z.acts[id].block}) - } - return out.String() -} - -// at: die innerste (zuletzt geöffnete, also kleinste) Zone unter x/y, die -// die gewünschte Aktion hat. -func (z *zones) at(x, y int, wheel bool) *zoneAction { - var best *zoneAction - bestArea := math.MaxInt - for _, r := range z.rects { - if !r.contains(x, y) { - continue - } - act := &z.acts[r.id] - if (wheel && act.wheel == nil) || (!wheel && act.click == nil) { - continue - } - area := (r.y1-r.y0+1)*4096 + (r.x1 - r.x0) - if area <= bestArea { - best, bestArea = act, area - } - } - return best -} - -// tipAt: die innerste Zone unter x/y mit Hover-Karte. -func (z *zones) tipAt(x, y int) (*zoneAction, zoneRect) { - var best *zoneAction - var br zoneRect - bestArea := math.MaxInt - for _, r := range z.rects { - if !r.contains(x, y) || z.acts[r.id].tip == nil { - continue - } - if area := (r.y1-r.y0+1)*4096 + (r.x1 - r.x0); area <= bestArea { - best, br, bestArea = &z.acts[r.id], r, area - } - } - return best, br -} - -// atMenu: die innerste Zone unter x/y mit Rechtsklick-Aktion (Tabs). -func (z *zones) atMenu(x, y int) *zoneAction { - var best *zoneAction - bestArea := math.MaxInt - for _, r := range z.rects { - if !r.contains(x, y) || z.acts[r.id].menu == nil { - continue - } - if area := (r.y1-r.y0+1)*4096 + (r.x1 - r.x0); area <= bestArea { - best, bestArea = &z.acts[r.id], area - } - } - return best -} - -// rowAt: Zeile (row-1) unter x/y für das Ziehen im Manager, sonst -1. -func (z *zones) rowAt(x, y int) int { - for _, r := range z.rects { - if y >= r.y0 && y <= r.y1 && z.acts[r.id].row > 0 && z.acts[r.id].pane == 0 { // nur die Zeile zählt - _ = x - return z.acts[r.id].row - 1 - } - } - return -1 -} - -// tabAt: Tab (tab-1) unter x/y für das Ziehen in der Tab-Leiste, sonst -1. -func (z *zones) tabAt(x, y int) int { - for _, r := range z.rects { - if z.acts[r.id].tab > 0 && r.contains(x, y) { - return z.acts[r.id].tab - 1 - } - } - return -1 -} - -// fileAt: Seite und Eintrag des Dateibrowsers unter x/y (je -1 = keiner). -func (z *zones) fileAt(x, y int) (side, row int) { - side, row = -1, -1 - bestArea := math.MaxInt - for _, r := range z.rects { - act := z.acts[r.id] - if act.pane == 0 || !r.contains(x, y) { - continue - } - area := (r.y1-r.y0+1)*4096 + (r.x1 - r.x0) - if area <= bestArea { - bestArea, side, row = area, act.pane-1, act.row-1 - } - } - return side, row -} diff --git a/internal/update/update.go b/internal/update/update.go index da0c40c..79073c8 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -61,9 +61,23 @@ var errRedirect = errors.New("redirect") // httpClient: Tests setzen einen eigenen ein. var httpClient = client +// Zeitgrenzen: Abfragen (JSON) dürfen insgesamt jsonTimeout dauern. Die +// Programmdatei (30–40 MB) kann auf langsamen Leitungen länger brauchen; +// dort zählt, dass Daten fließen: stallTimeout ohne ein einziges Byte = Abbruch +// und neuer Versuch, binTimeout ist die äußerste Grenze. +var ( + jsonTimeout = 2 * time.Minute + binTimeout = 30 * time.Minute + stallTimeout = 60 * time.Second +) + +var errStalled = errors.New("update: download stalled") + func client() *http.Client { + tr := http.DefaultTransport.(*http.Transport).Clone() + tr.ResponseHeaderTimeout = 30 * time.Second return &http.Client{ - Timeout: 2 * time.Minute, + Transport: tr, CheckRedirect: func(req *http.Request, via []*http.Request) error { if req.URL.Scheme != "https" || !allowedHosts[req.URL.Hostname()] || len(via) > 5 { return fmt.Errorf("%w: "+i18n.T("update: Weiterleitung nach %s abgelehnt"), errRedirect, req.URL.Host) @@ -96,13 +110,23 @@ func get(ctx context.Context, u, accept string, limit int64) ([]byte, error) { } } -func getOnce(ctx context.Context, u, accept string, limit int64) ([]byte, bool, error) { +func getOnce(parent context.Context, u, accept string, limit int64) ([]byte, bool, error) { + total := jsonTimeout + if accept == acceptBin { + total = binTimeout + } + tctx, tcancel := context.WithTimeout(parent, total) + defer tcancel() + ctx, cancel := context.WithCancelCause(tctx) + defer cancel(nil) + idle := time.AfterFunc(stallTimeout, func() { cancel(errStalled) }) + defer idle.Stop() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) req.Header.Set("User-Agent", version.Short()) req.Header.Set("Accept", accept) resp, err := httpClient().Do(req) if err != nil { - return nil, ctx.Err() == nil && !errors.Is(err, errRedirect), err + return nil, parent.Err() == nil && !errors.Is(err, errRedirect), err } defer resp.Body.Close() if resp.StatusCode != 200 { @@ -111,8 +135,27 @@ func getOnce(ctx context.Context, u, accept string, limit int64) ([]byte, bool, } return nil, false, fmt.Errorf(i18n.T("update: HTTP %d"), resp.StatusCode) } - b, err := io.ReadAll(io.LimitReader(resp.Body, limit)) - return b, err != nil && ctx.Err() == nil, err + b, err := io.ReadAll(io.LimitReader(stallReader{resp.Body, idle}, limit)) + // Auch ohne Lesefehler: wurde wegen Stillstand abgebrochen, kann das Ende + // des Körpers abgeschnitten sein (Verbindung zu = scheinbar fertig). + if errors.Is(context.Cause(ctx), errStalled) && parent.Err() == nil { + return nil, true, fmt.Errorf(i18n.T("update: Download kam %s lang nicht voran"), stallTimeout) + } + return b, err != nil && parent.Err() == nil, err +} + +// stallReader verlängert die Leerlauf-Frist bei jedem empfangenen Byte. +type stallReader struct { + r io.Reader + idle *time.Timer +} + +func (s stallReader) Read(p []byte) (int, error) { + n, err := s.r.Read(p) + if n > 0 { + s.idle.Reset(stallTimeout) + } + return n, err } const ( diff --git a/internal/update/update_test.go b/internal/update/update_test.go index b0c3239..44e2ef0 100644 --- a/internal/update/update_test.go +++ b/internal/update/update_test.go @@ -67,3 +67,44 @@ func TestGetRetries(t *testing.T) { t.Fatalf("%v %d", err, n) } } + +// Ein Download, der mittendrin stehen bleibt, wird nach stallTimeout +// abgebrochen und neu versucht; ein langsamer, aber fließender läuft durch. +func TestGetStallRetries(t *testing.T) { + oldWait, oldStall := retryWait, stallTimeout + retryWait = []time.Duration{time.Millisecond} + stallTimeout = 150 * time.Millisecond + defer func() { retryWait, stallTimeout = oldWait, oldStall }() + n := 0 + release := make(chan struct{}) + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n++ + fl := w.(http.Flusher) + if n == 1 { // hängt nach dem ersten Stück + _, _ = w.Write([]byte("ha")) + fl.Flush() + select { + case <-release: + case <-r.Context().Done(): + } + return + } + for _, c := range []string{"o", "k"} { // langsam, aber jedes Stück innerhalb der Frist + _, _ = w.Write([]byte(c)) + fl.Flush() + time.Sleep(100 * time.Millisecond) + } + })) + defer ts.Close() + defer close(release) + u, _ := url.Parse(ts.URL) + allowedHosts[u.Hostname()] = true + defer delete(allowedHosts, u.Hostname()) + oldClient := httpClient + httpClient = func() *http.Client { return ts.Client() } + defer func() { httpClient = oldClient }() + b, err := get(context.Background(), ts.URL, acceptBin, 100) + if err != nil || string(b) != "ok" || n != 2 { + t.Fatalf("%q %v %d", b, err, n) + } +} diff --git a/internal/vault/more_test.go b/internal/vault/more_test.go new file mode 100644 index 0000000..5ea1189 --- /dev/null +++ b/internal/vault/more_test.go @@ -0,0 +1,217 @@ +package vault + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "runtime" + "testing" +) + +func freshVault(t *testing.T, pw string) (*Vault, string) { + t.Helper() + p := filepath.Join(t.TempDir(), "store.json") + v, err := Open(p) + if err != nil { + t.Fatal(err) + } + if v.Exists() { + t.Fatal("neuer Store gilt als vorhanden") + } + if err := v.Create([]byte(pw), false); err != nil { + t.Fatal(err) + } + if !v.Exists() { + t.Fatal("Store nach Create nicht vorhanden") + } + return v, p +} + +func TestCreateRejectsShortPassword(t *testing.T) { + v, _ := Open(filepath.Join(t.TempDir(), "s.json")) + if err := v.Create([]byte("kurz"), false); err == nil { + t.Fatal("zu kurzes Master-Passwort angenommen") + } +} + +// Passwort wechseln: altes geht nicht mehr, neues schon, Daten bleiben. +func TestChangePassword(t *testing.T) { + v, p := freshVault(t, "altes passwort") + if err := v.Save(payload{"geheim"}); err != nil { + t.Fatal(err) + } + if err := v.ChangePassword([]byte("falsches pw"), []byte("neues passwort")); !errors.Is(err, ErrWrongPassword) { + t.Fatalf("falsches altes Passwort: %v", err) + } + if err := v.ChangePassword([]byte("altes passwort"), []byte("kurz")); err == nil { + t.Fatal("zu kurzes neues Passwort angenommen") + } + if err := v.ChangePassword([]byte("altes passwort"), []byte("neues passwort")); err != nil { + t.Fatal(err) + } + if err := v.Save(payload{"geheim"}); err != nil { + t.Fatal(err) + } + v2, _ := Open(p) + if err := v2.UnlockPassword([]byte("altes passwort")); !errors.Is(err, ErrWrongPassword) { + t.Fatalf("altes Passwort geht noch: %v", err) + } + if err := v2.CheckPassword([]byte("neues passwort")); err != nil { + t.Fatal(err) + } + if v2.Unlocked() { + t.Fatal("CheckPassword darf nicht entsperren") + } + if err := v2.UnlockPassword([]byte("neues passwort")); err != nil { + t.Fatal(err) + } + var out payload + if err := v2.Load(&out); err != nil || out.Secret != "geheim" { + t.Fatalf("Daten nach Passwortwechsel: %v %q", err, out.Secret) + } +} + +func TestLockedRefuses(t *testing.T) { + v, _ := freshVault(t, "correct horse") + _ = v.Save(payload{"x"}) + v.Lock() + if v.Unlocked() { + t.Fatal("nach Lock noch offen") + } + var out payload + if err := v.Load(&out); !errors.Is(err, ErrLocked) { + t.Fatalf("Load gesperrt: %v", err) + } + if _, err := v.SealBlob([]byte("a"), nil); !errors.Is(err, ErrLocked) { + t.Fatalf("SealBlob gesperrt: %v", err) + } + if _, err := v.OpenBlob(make([]byte, 40), nil); !errors.Is(err, ErrLocked) { + t.Fatalf("OpenBlob gesperrt: %v", err) + } + if _, err := v.DeriveKey("x"); !errors.Is(err, ErrLocked) { + t.Fatalf("DeriveKey gesperrt: %v", err) + } + if err := v.SetDPAPI(false); !errors.Is(err, ErrLocked) { + t.Fatalf("SetDPAPI gesperrt: %v", err) + } +} + +// Blobs (z. B. Switch-Sicherungen): an den Ablageort gebunden. +func TestBlobBoundToPlace(t *testing.T) { + v, _ := freshVault(t, "correct horse") + blob, err := v.SealBlob([]byte("running-config"), []byte("sw1/2026-11-20")) + if err != nil { + t.Fatal(err) + } + got, err := v.OpenBlob(blob, []byte("sw1/2026-11-20")) + if err != nil || string(got) != "running-config" { + t.Fatalf("%q %v", got, err) + } + if _, err := v.OpenBlob(blob, []byte("sw2/2026-11-20")); err == nil { + t.Fatal("vertauschte Datei akzeptiert") + } + blob[len(blob)-1] ^= 1 + if _, err := v.OpenBlob(blob, []byte("sw1/2026-11-20")); err == nil { + t.Fatal("veränderter Blob akzeptiert") + } + if _, err := v.OpenBlob([]byte{1, 2, 3}, nil); err == nil { + t.Fatal("zu kurzer Blob akzeptiert") + } + k1, _ := v.DeriveKey("logs") + k2, _ := v.DeriveKey("audit") + if bytes.Equal(k1, k2) || len(k1) != 32 { + t.Fatal("abgeleitete Schlüssel nicht getrennt") + } +} + +// Manipulierte KDF-Werte: zu schwach (Downgrade) oder absurd (Speicher-DoS). +func TestKDFCheck(t *testing.T) { + good, err := DefaultKDF() + if err != nil { + t.Fatal(err) + } + if err := good.Check(); err != nil { + t.Fatalf("Vorgabe abgelehnt: %v", err) + } + bad := []func(*KDFParams){ + func(p *KDFParams) { p.Alg = "pbkdf2" }, + func(p *KDFParams) { p.Salt = p.Salt[:4] }, + func(p *KDFParams) { p.Time = 0 }, + func(p *KDFParams) { p.Time = 1000 }, + func(p *KDFParams) { p.MemoryKiB = 1024 }, + func(p *KDFParams) { p.MemoryKiB = 64 * 1024 * 1024 }, + func(p *KDFParams) { p.Threads = 0 }, + } + for i, mod := range bad { + p := good + p.Salt = append([]byte(nil), good.Salt...) + mod(&p) + if p.Check() == nil { + t.Errorf("Fall %d: schwache/absurde KDF angenommen", i) + } + } + a, b := good.Derive([]byte("pw")), good.Derive([]byte("pw")) + if !bytes.Equal(a, b) || bytes.Equal(a, good.Derive([]byte("pW"))) { + t.Fatal("Derive nicht stabil oder nicht passwortabhängig") + } + Wipe(a) + if !bytes.Equal(a, make([]byte, len(a))) { + t.Fatal("Wipe hat nicht genullt") + } +} + +func TestGCMHelpers(t *testing.T) { + key := bytes.Repeat([]byte{1}, 32) + n, ct, err := SealGCM(key, []byte("hallo"), []byte("ort")) + if err != nil { + t.Fatal(err) + } + if got, err := OpenGCM(key, n, ct, []byte("ort")); err != nil || string(got) != "hallo" { + t.Fatalf("%q %v", got, err) + } + if _, err := OpenGCM(key, n, ct, []byte("anderer")); err == nil { + t.Fatal("falsche AAD angenommen") + } +} + +func TestOpenRejectsGarbage(t *testing.T) { + dir := t.TempDir() + cases := map[string]string{ + "kaputt.json": "{nicht json", + "fremd.json": `{"format":"anderes","version":1}`, + "zu-neu.json": `{"format":"sshtermy-vault","version":99}`, + } + for name, body := range cases { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Open(p); err == nil { + t.Errorf("%s: angenommen", name) + } + } +} + +// Ohne Windows gibt es kein DPAPI: Anfragen werden klar abgelehnt, der +// Passwort-Weg bleibt. +func TestDPAPIOffWindows(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("echtes DPAPI: siehe Plattform-Job") + } + v, p := freshVault(t, "correct horse") + if err := v.SetDPAPI(true); !errors.Is(err, ErrDPAPI) { + t.Fatalf("SetDPAPI ohne Windows: %v", err) + } + if err := v.SetDPAPI(false); err != nil { + t.Fatal(err) + } + if v.HasDPAPI() { + t.Fatal("DPAPI-Wrap ohne Windows") + } + _ = v.Save(payload{"x"}) + v2, _ := Open(p) + if err := v2.UnlockDPAPI(); !errors.Is(err, ErrNoUnlockPath) { + t.Fatalf("UnlockDPAPI ohne Wrap: %v", err) + } +} diff --git a/internal/vuln/scan.go b/internal/vuln/scan.go index b09cf89..7d0ed2c 100644 --- a/internal/vuln/scan.go +++ b/internal/vuln/scan.go @@ -9,6 +9,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // CVE: eine Lücke in einem Paket. @@ -404,6 +405,7 @@ func enrich(ctx context.Context, src Source, fs map[string]*Finding, step func(s for _, id := range ids { wg.Add(1) go func() { + defer safe.Recover("vuln/scan.go") defer wg.Done() sem <- struct{}{} defer func() { <-sem }() diff --git a/internal/vuln/source.go b/internal/vuln/source.go index 9972601..a459fd9 100644 --- a/internal/vuln/source.go +++ b/internal/vuln/source.go @@ -19,6 +19,7 @@ import ( "time" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/safe" ) // Woher die Einträge kommen: @@ -194,6 +195,7 @@ func (o *Online) Find(ctx context.Context, qs []Query, step func(string)) ([][]* for _, r := range uniq { wg.Add(1) go func() { + defer safe.Recover("vuln/source.go") defer wg.Done() sem <- struct{}{} defer func() { <-sem }() diff --git a/internal/webwatch/assets/zusehen.wasm.gz b/internal/webwatch/assets/zusehen.wasm.gz index 0cc150a..35a93fe 100644 Binary files a/internal/webwatch/assets/zusehen.wasm.gz and b/internal/webwatch/assets/zusehen.wasm.gz differ diff --git a/site/de/handbuch.html b/site/de/handbuch.html index 9d79948..cc6e6d0 100644 --- a/site/de/handbuch.html +++ b/site/de/handbuch.html @@ -204,13 +204,14 @@

Fehler melden

+

Zuerst die Selbstprüfung: Hilfe › Fehlersuche › „Selbstprüfung“ oder sshtermy doctor. Sie prüft Datenordner, Tresor, Schlüsselbund, SSH-Agent, Update-Signatur, Internet, Uhr und den KI-Endpunkt; c kopiert das Ergebnis.

  1. Einstellungen › „Debug-Protokoll für Fehlerberichte“ einschalten (oder sshtermy --debug starten).
  2. Den Fehler nachstellen.
  3. Hilfe › „Debug-Protokoll bereinigt speichern“: eine Kopie ohne Hosts, IPs, Benutzernamen und Passwörter landet in Downloads.
  4. Ein Issue auf GitHub öffnen und die Datei anhängen.
-

Stürzt sshTermy ab, bietet es beim nächsten Start einen bereinigten Absturzbericht an.

+

Ein Fehler an einer Stelle (KI-Antwort, Geräteausgabe, Dateiansicht) wird abgefangen: sshTermy läuft mit allen Verbindungen weiter, schreibt einen bereinigten Bericht und zeigt eine Meldung. Stürzt es doch ab, bietet es beim nächsten Start einen bereinigten Absturzbericht an.

@@ -247,6 +248,7 @@

Start und Tipps

+ diff --git a/site/de/index.html b/site/de/index.html index 50368df..af561d9 100644 --- a/site/de/index.html +++ b/site/de/index.html @@ -127,6 +127,7 @@ sudo apt update && sudo apt install sshtermy

Verbindungsmanager

Ordner, Tags, Jump-Hosts, Import aus ~/.ssh/config, PuTTY und MobaXterm.

Fehlerverzeihend

Beenden fragt bei offenen Verbindungen nach, Löschen lässt sich 10 Sekunden lang rückgängig machen, Strg+T im Formular testet die Verbindung vor dem Speichern, und fehlgeschlagene Verbindungen erklären in Klartext, was los ist (mit Taste zum Beheben, z. B. neuen Host-Key nach Neuinstallation übernehmen). Der einfache Modus blendet Profi-Funktionen aus.

+

Läuft weiter

Ein Fehler an einer Stelle (eine seltsame KI-Antwort, ungewöhnliche Geräteausgabe, die Dateiansicht) reißt sshTermy nicht mehr samt allen Verbindungen mit: Er wird abgefangen, ein bereinigter Bericht entsteht, und eine Meldung erscheint. sshtermy doctor oder Hilfe › Fehlersuche › „Selbstprüfung“ prüft Ordner, Tresor, Schlüsselbund, SSH-Agent, Internet, Uhr und KI auf einen Blick.

Eigenes Fenster

Kein Terminal nötig: Doppelklick auf die .exe, die .app öffnen oder sshtermy -window. Schrift, Nerd-Font-Symbole und Emoji sind eingebaut, jede Taste kommt an (Alt+⏎, ⇧F-Tasten, Strg+Leertaste), Bilder erscheinen pixelgenau, abgelegte Dateien werden hochgeladen, ⇧F10 öffnet ein zweites Fenster, das den Verlauf mitnimmt und mit Mausrad oder ⇧+Bild↑ blättert. Startet im Vollbild (F11 schaltet um; maximiert oder „wie zuletzt“ in den Einstellungen), Schriftgröße und Fensterposition werden gemerkt. Im Terminal gestartet läuft es wie bisher im Terminal.

Ziel-Modus im Einsatz

? gibt der KI mitten im Ziel eine Anweisung, ⇧S überspringt einen Schritt mit Grund. Fragt ein Befehl [Y/n] oder wartet ein Pager, zeigt das Panel Antwort-Knöpfe. Dateien, die ein Schritt ändert, werden vorher gesichert, u holt alle zurück; f startet ein Folgeziel, frühere Ziele stehen im Verlauf. Nach einem Verbindungsabbruch setzt ⏎ fort, und der Tab zeigt, wenn ein Ziel auf dich wartet.

Wer auf dich wartet

Ein Tab, der auf ein Passwort, eine [j/N]-Frage oder im Pager wartet, bekommt ein ?; Alt+G springt hin. KI-Coding-Agenten im Tab (Claude Code, Codex, Gemini CLI und mehr) werden erkannt: arbeitet, wartet auf deine Freigabe (◆ plus Desktop-Meldung) oder fertig. Ein Klick auf die Desktop-Meldung öffnet den richtigen Tab.

diff --git a/site/index.html b/site/index.html index c13234b..c0f09c5 100644 --- a/site/index.html +++ b/site/index.html @@ -127,6 +127,7 @@ sudo apt update && sudo apt install sshtermy

Connection manager

Folders, tags, jump hosts, import from ~/.ssh/config, PuTTY and MobaXterm.

Forgiving

Quitting asks while connections are open, deleting offers undo for 10 s, Ctrl+T in the form tests the connection before saving, and failed connections explain in plain language what's wrong (with a key to fix it, e.g. accept a new host key after a reinstall). Simple mode hides the pro features.

+

Keeps running

An error in one part (an odd AI answer, strange device output, the file view) no longer takes down sshTermy and all your connections: it is caught, a cleaned report is written and a message appears. sshtermy doctor or Help › Troubleshooting › “Self-check” checks folder, vault, keychain, SSH agent, internet, clock and AI in one go.

Own window

No terminal needed: double-click the .exe, open the .app or run sshtermy -window. Font, Nerd Font symbols and emoji are built in, every key arrives (Alt+⏎, ⇧F-keys, Ctrl+Space), images show pixel-perfect, dropped files are uploaded, ⇧F10 opens a second window that takes the scrollback along and scrolls with the mouse wheel or ⇧+PgUp. Starts in full screen (F11 toggles; maximized or “as last time” in the settings), font size and window position are remembered. From a terminal it runs in the terminal as before.

Goal mode in daily use

? gives the AI an instruction mid-goal, ⇧S skips a step with a reason. When a command asks [Y/n] or a pager waits, the panel shows answer buttons. Files a step changes are backed up first, u restores them all; f starts a follow-up goal, earlier goals are in the history. After a connection drop ⏎ continues, and the tab shows when a goal is waiting for you.

Who is waiting for you

A tab waiting for a password, a [y/N] question or a pager gets a ?; Alt+G jumps there. AI coding agents in a tab (Claude Code, Codex, Gemini CLI and more) are recognized: working, waiting for your approval (◆ plus desktop notification) or done. A click on the desktop notification opens the right tab.

diff --git a/site/manual.html b/site/manual.html index d081f21..b9d11ce 100644 --- a/site/manual.html +++ b/site/manual.html @@ -204,13 +204,14 @@

Reporting bugs

+

First try the self-check: Help › Troubleshooting › “Self-check” or sshtermy doctor. It checks the data folder, vault, keychain, SSH agent, update signature, internet, clock and the AI endpoint; c copies the result.

  1. Turn on Settings › “Debug log for bug reports” (or start sshtermy --debug).
  2. Reproduce the problem.
  3. Help › “Save cleaned debug log”: a copy without hosts, IPs, user names and passwords lands in Downloads.
  4. Open an issue on GitHub and attach the file.
-

If sshTermy crashes, it offers a cleaned crash report on the next start.

+

An error in one part (AI answer, device output, file view) is caught: sshTermy keeps running with all connections, writes a cleaned report and shows a message. If it does crash, it offers a cleaned crash report on the next start.

@@ -247,6 +248,7 @@

Start and tips

sshtermy backup · sshtermy mcpalles sichern · MCP-Server für KI-Clients
sshtermy doctorSelbstprüfung für Fehlerberichte
--no-intro · --debugohne Startanimation · Debug-Protokoll
-window · -tuieigenes Fenster · immer im Terminal
tsz / trzDatei vom / zum Server (trzsz)
+ diff --git a/tools/check-fmt.sh b/tools/check-fmt.sh new file mode 100755 index 0000000..5de3520 --- /dev/null +++ b/tools/check-fmt.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Meldet Go-Dateien, die gofmt anders formatieren würde (make check). +files=$(gofmt -l cmd internal tools) +if [ -n "$files" ]; then + echo "gofmt fehlt bei:" + echo "$files" + exit 1 +fi
sshtermy backup · sshtermy mcpfull backup · MCP server for AI clients
sshtermy doctorself-check for bug reports
--no-intro · --debugno start animation · debug log
-window · -tuiown window · always in the terminal
tsz / trzfile from / to the server (trzsz)