diff --git a/README.md b/README.md index 47e8135..f1dc06b 100644 --- a/README.md +++ b/README.md @@ -369,6 +369,8 @@ On Windows and Linux, use `--config FILE` to select another file; command-line v - When `agent.upstream` is empty, `UPSTREAM_SSH_AUTH_SOCK` takes precedence over `SSH_AUTH_SOCK`. If neither is set, the GUI uses the native OpenSSH agent endpoint: `\\.\pipe\openssh-ssh-agent` on Windows and `~/.ssh/ssh-agent.sock` on macOS and Linux. - To keep the upstream endpoint tied to a changing environment variable, set `agent.upstream = "env:SSH_AUTH_SOCK"`, or choose Environment variable in GUI Settings and enter its name. The GUI resolves this reference at startup and when Settings are applied, while saving the `env:NAME` reference in the config file. The variable must be set and non-empty. - Environment variables in ordinary paths and a leading `~` are expanded using the GUI process environment. +- `[history].path` selects the selection-history database when set. If omitted or empty, the GUI uses `history.sqlite` in the application data folder; relative paths are resolved from that folder. GUI Settings leaves the field blank and shows the resolved default path as its placeholder. It saves `history.path` only when you enter or choose a path. +- `[history].enabled` controls whether the GUI records and shows selection history. `[history].remember_selection` controls whether it remembers the last selected key for each verified target host. Both default to `true`, can be changed in GUI Settings, and are written to the config only when set to `false`. When both are `false`, the GUI does not create or open the SQLite database. - If the configured Listen endpoint is active or blocked by a non-socket file, the GUI starts with the proxy `Not configured`. A stale socket owned by the current user is replaced when KeySelect confirms that it is no longer listening. The configuration loader rejects unknown keys. Logging is off by default. Set `log.level` to enable it and optionally set `log.file` to append logs to a file. When `log.file` is empty, logs go to standard error. @@ -385,6 +387,12 @@ banner exchange: Connection to port : Software caused connection abor Example configuration for `Git Bash` on Windows, using a Cygwin-compatible listener: ```toml +[history] +# Add a setting only to override its default: +# enabled = false +# path = "/path/to/history.sqlite" +# remember_selection = false + [agent] # Replace USERNAME with your Windows user name: upstream = 'C:\Users\USERNAME\.ssh\ssh-upstream-agent.sock' @@ -421,6 +429,10 @@ The GUI has an Auto Select switch beside Agent Proxy. Enabling it requires confi The window title combines the action, application name, and local display time. The request-context area begins with the same timestamp followed by host details. It lets you scroll to earlier hops. Use the arrow keys to move through matches, Enter to select, and Esc to cancel. +When `history.remember_selection` is enabled and the request includes a verified target host key, the GUI remembers the selected key for that host and preselects it the next time the same host key is seen. The picker still opens and requires you to confirm a selection. Requests without a verified target host key start with the first key. + +When `history.enabled` is enabled, choose `File > History…` or press Ctrl+Shift+H (Cmd+Shift+H on macOS) to review request time, target host and forwarded hops, selected key, selection time, and whether the picker completed, was canceled, or timed out. Right-click a row to copy its displayed information or delete it. Use `Export CSV` to save the full history and host paths. The result describes the picker interaction; it does not indicate whether the SSH server accepted authentication. + Right-click a key row and choose `Copy`, or press Ctrl+C, to copy its Comment, Type, Size, and Fingerprint as tab-separated text. ## Shared behavior @@ -501,7 +513,7 @@ SSH KeySelect has no telemetry, analytics, automatic update checks, or diagnosti The proxy communicates with SSH clients and the upstream agent configured through its endpoints. SSH clients receive public key identities and permitted authentication signatures. With SSH agent forwarding, remote processes can receive these responses through your SSH connection. Private key material stays in the upstream agent and is never received by KeySelect. See [Security and limitations](#security-and-limitations) and the [agent forwarding guidance](#through-agent-forwarding). -The GUI stores configuration locally when you save it. The pickers can read local `known_hosts` files to display host-name hints. +The GUI stores configuration locally. When History is enabled, it stores verified target-host and forwarding-hop key fingerprints, `known_hosts` display hints, the selected public-key data, fingerprint and comment, and local request and selection times. When key remembrance is enabled, it also stores target-host and selected-key fingerprints to restore the prior choice. Public-key data does not include private keys. Host names shown in history are local `known_hosts` hints, not verified host names. Diagnostic logging is off by default. When enabled, logs go to local output or the CLI log file you specify and can contain endpoint paths, host key fingerprints, and request metadata. Review logs before sharing them. Bundled libraries do not add third-party online services to the application. Your upstream agent and SSH client have their own settings and privacy policies. diff --git a/cmd/ssh-keyselect-gui/gui.go b/cmd/ssh-keyselect-gui/gui.go index 9dec586..4f491cb 100644 --- a/cmd/ssh-keyselect-gui/gui.go +++ b/cmd/ssh-keyselect-gui/gui.go @@ -24,6 +24,7 @@ import ( "github.com/jfut/ssh-keyselect/internal/config" "github.com/jfut/ssh-keyselect/internal/guitable" "github.com/jfut/ssh-keyselect/internal/identity" + "github.com/jfut/ssh-keyselect/internal/selectionhistory" "github.com/jfut/ssh-keyselect/internal/selector" "github.com/jfut/ssh-keyselect/internal/transport" "github.com/jfut/ssh-keyselect/internal/upstream" @@ -48,8 +49,15 @@ type guiApp struct { endpointAgent *guiEndpointAgent server *agentproxy.Server selector *selector.GUISelector + historyStore *selectionhistory.Store + historyStores []*selectionhistory.Store + historyPath string + historyError string + userDataPath string runtime *guiRuntime window *mygo.Window + historyWindow *mygo.Window + historyView *guiHistoryState mainWindow atomic.Pointer[mygo.Window] mainVisible atomic.Bool tray *mygo.Tray @@ -230,9 +238,28 @@ func executeGUI(args []string, stdout, stderr io.Writer) int { mygo.App.SetName("SSH KeySelect") mygo.App.SetVersion(version) - if err := setGUIUserDataPath(); err != nil { + userDataPath, err := setGUIUserDataPath() + if err != nil { return cmdutil.ReportError(stderr, guiCommandName, err) } + app.userDataPath = userDataPath + if cfg.History.Enabled || cfg.History.RememberSelection { + historyPath, pathErr := guiHistoryDatabasePath(userDataPath, cfg.History.Path) + if pathErr != nil { + app.historyError = pathErr.Error() + logger.Warn("could not resolve GUI selection data path", "error", pathErr) + } else { + app.historyPath = historyPath + historyStore, openErr := selectionhistory.Open(historyPath) + if openErr != nil { + app.historyError = openErr.Error() + logger.Warn("could not open GUI selection data", "error", openErr) + } else { + app.historyStore = historyStore + } + } + } + guiSelector.SetHistoryOptions(app.historyStore, cfg.History.Enabled, cfg.History.RememberSelection) mygo.Theme.SetSource(mygo.ThemeSource(cfg.GUI.Theme)) // Keep the native application menu on macOS; other platforms use the // in-window menu bar so its text follows the app's normal UI size. @@ -255,17 +282,17 @@ func executeGUI(args []string, stdout, stderr io.Writer) int { } // setGUIUserDataPath keeps MyGo's per-user files alongside ssh-keyselect config. -func setGUIUserDataPath() error { +func setGUIUserDataPath() (string, error) { base, err := os.UserConfigDir() if err != nil { - return fmt.Errorf("locate user data directory: %w", err) + return "", fmt.Errorf("locate user data directory: %w", err) } path := filepath.Join(base, "ssh-keyselect") if err := os.MkdirAll(path, 0o700); err != nil { - return fmt.Errorf("create user data directory: %w", err) + return "", fmt.Errorf("create user data directory: %w", err) } mygo.App.SetPath(mygo.PathUserData, path) - return nil + return path, nil } func (a *guiApp) shutdown() { @@ -275,6 +302,16 @@ func (a *guiApp) shutdown() { if a.runtime != nil { a.runtime.Close() } + if a.historyWindow != nil && !a.historyWindow.IsDestroyed() { + a.historyWindow.Close() + } + for _, store := range append(a.historyStores, a.historyStore) { + if store != nil { + if err := store.Close(); err != nil { + a.logger.Warn("close GUI selection history", "error", err) + } + } + } if a.tray != nil { a.tray.Destroy() } diff --git a/cmd/ssh-keyselect-gui/gui_config.go b/cmd/ssh-keyselect-gui/gui_config.go index 810dff0..4792e00 100644 --- a/cmd/ssh-keyselect-gui/gui_config.go +++ b/cmd/ssh-keyselect-gui/gui_config.go @@ -21,6 +21,7 @@ import ( "github.com/jfut/ssh-keyselect/internal/config" "github.com/jfut/ssh-keyselect/internal/guitable" "github.com/jfut/ssh-keyselect/internal/listener" + "github.com/jfut/ssh-keyselect/internal/selectionhistory" "github.com/jfut/ssh-keyselect/internal/transport" ) @@ -37,6 +38,44 @@ func (a *guiApp) applyConfig(cfg config.Config, dirty bool, complete func(error) } return } + historyPath := "" + var err error + selectionDataEnabled := cfg.History.Enabled || cfg.History.RememberSelection + if selectionDataEnabled { + historyPath, err = guiHistoryDatabasePath(a.userDataPath, cfg.History.Path) + if err != nil { + if complete != nil { + complete(err) + } else { + a.statusMessage = "Could not resolve selection data path: " + err.Error() + if a.window != nil { + a.window.Invalidate() + } + } + return + } + } + nextHistoryStore := a.historyStore + historyChanged := false + if !selectionDataEnabled { + nextHistoryStore = nil + historyChanged = a.historyStore != nil || a.historyPath != "" + } else if a.historyStore == nil || historyPath != a.historyPath { + nextHistoryStore, err = selectionhistory.Open(historyPath) + if err != nil { + err = fmt.Errorf("open selection data database: %w", err) + if complete != nil { + complete(err) + } else { + a.statusMessage = err.Error() + if a.window != nil { + a.window.Invalidate() + } + } + return + } + historyChanged = true + } a.applying = true a.statusMessage = "" a.updateConfigurationMenu() @@ -47,19 +86,37 @@ func (a *guiApp) applyConfig(cfg config.Config, dirty bool, complete func(error) go func() { actualListen, effectiveMode, err := a.runtime.Apply(cfg) if window == nil { + if historyChanged && nextHistoryStore != nil { + _ = nextHistoryStore.Close() + } return } window.Update(func() { a.applying = false a.updateConfigurationMenu() if a.ctx.Err() != nil { + if historyChanged && nextHistoryStore != nil { + _ = nextHistoryStore.Close() + } return } if err == nil { cfg.Agent.Upstream = config.ExpandPath(cfg.Agent.Upstream) cfg.Agent.Listen = config.ExpandPath(cfg.Agent.Listen) cfg.Log.File = config.ExpandPath(cfg.Log.File) + cfg.History.Path = config.ExpandPath(cfg.History.Path) + previousHistoryEnabled := a.cfg.History.Enabled + previousRememberSelection := a.cfg.History.RememberSelection a.cfg = cfg + if historyChanged { + a.replaceHistoryStore(nextHistoryStore, historyPath) + } else { + a.selector.SetHistoryOptions(a.historyStore, cfg.History.Enabled, cfg.History.RememberSelection) + if previousHistoryEnabled != cfg.History.Enabled || previousRememberSelection != cfg.History.RememberSelection { + a.syncHistoryView() + } + } + a.updateConfigurationMenu() mygo.Theme.SetSource(mygo.ThemeSource(cfg.GUI.Theme)) a.actualListen = actualListen a.listenMode = effectiveMode @@ -71,6 +128,9 @@ func (a *guiApp) applyConfig(cfg config.Config, dirty bool, complete func(error) a.updateWindowTitle() a.refreshIdentities() } else { + if historyChanged && nextHistoryStore != nil { + _ = nextHistoryStore.Close() + } a.statusMessage = "Could not apply configuration: " + err.Error() } if complete != nil { @@ -402,6 +462,9 @@ func (a *guiApp) applicationMenu() *mygo.Menu { mygo.Separator(), {ID: "settings.open", Label: "Settings…", Accelerator: "CmdOrCtrl+,", Click: func(*mygo.MenuItem, *mygo.Window) { a.openSettings() }}, mygo.Separator(), + {ID: "history.open", Label: "History…", Accelerator: "CmdOrCtrl+Shift+H", Disabled: !a.cfg.History.Enabled, + Click: func(*mygo.MenuItem, *mygo.Window) { a.openHistory() }}, + mygo.Separator(), {Role: mygo.RoleQuit}, } helpItems := []*mygo.MenuItem{ @@ -463,6 +526,9 @@ func (a *guiApp) updateConfigurationMenu() { item.SetEnabled(enabled) } } + if item := menu.ItemByID("history.open"); item != nil { + item.SetEnabled(enabled && a.cfg.History.Enabled) + } } // guiChooseConfigToOpen asks the native file dialog to choose a TOML file. @@ -527,6 +593,9 @@ type guiSettingsValues struct { upstreamEnvName string listenPath string logFile string + historyFile string + historyEnabled bool + rememberSelection bool upstreamMode string listenMode string logLevel string @@ -546,6 +615,10 @@ type guiSettingsState struct { resolvedUpstream string listenPath string logFile string + historyFile string + historyPlaceholder string + historyEnabled bool + rememberSelection bool upstreamMode string listenMode string logLevel string @@ -561,6 +634,7 @@ type guiSettingsState struct { browsingUpstream bool browsingListen bool browsingLog bool + browsingHistory bool err string } @@ -580,14 +654,14 @@ func (a *guiApp) openSettings() { mygo.Dialog.Error("Could not open settings.", err.Error()) return } - // Keep the centered footer compact while reserving room for the source selector. - height, minHeight := 566, 566 + // Leave enough height for the settings sections and visible space below the footer. + height, minHeight := 644, 644 switch runtime.GOOS { case "darwin": // Match the Windows action spacing while preserving clearance around rounded sheet corners. - height, minHeight = 520, 520 + height, minHeight = 598, 598 case "linux": - height, minHeight = 500, 500 + height, minHeight = 578, 578 } window := mygo.NewWindow(mygo.WindowOptions{ Title: "Settings", Parent: a.window, Modal: true, @@ -637,12 +711,19 @@ func newGUISettingsState(app *guiApp, cfg config.Config) (*guiSettingsState, err if environmentBacked { upstreamSource = guiUpstreamEnvironmentSource } + historyPlaceholder, err := guiHistoryDatabasePath(app.userDataPath, "") + if err != nil { + return nil, err + } state := &guiSettingsState{ app: app, cfg: cfg, upstreamSource: upstreamSource, upstreamPath: guiDisplayEndpointPath(upstreamEndpoint), upstreamEnvName: upstreamEnvName, resolvedUpstream: upstreamEndpoint, listenPath: guiDisplayEndpointPath(listenEndpoint), logFile: guiDisplayFilePath(cfg.Log.File), - upstreamMode: upstreamMode, listenMode: listenMode, logLevel: strings.ToLower(cfg.Log.Level), + historyFile: guiDisplayFilePath(strings.TrimSpace(cfg.History.Path)), + historyPlaceholder: guiDisplayFilePath(historyPlaceholder), historyEnabled: cfg.History.Enabled, + rememberSelection: cfg.History.RememberSelection, + upstreamMode: upstreamMode, listenMode: listenMode, logLevel: strings.ToLower(cfg.Log.Level), theme: guiThemeLabel(cfg.GUI.Theme), selectionTimeout: float64(cfg.Agent.SelectionTimeout), allowUnboundSigningOnBindFailure: cfg.Agent.AllowUnboundSigningOnBindFailure, @@ -662,7 +743,9 @@ func (s *guiSettingsState) values() guiSettingsValues { return guiSettingsValues{ upstreamSource: s.upstreamSource, upstreamPath: s.upstreamPath, upstreamEnvName: s.upstreamEnvName, listenPath: s.listenPath, logFile: s.logFile, - upstreamMode: s.upstreamMode, listenMode: s.listenMode, logLevel: s.logLevel, + historyFile: s.historyFile, historyEnabled: s.historyEnabled, + rememberSelection: s.rememberSelection, + upstreamMode: s.upstreamMode, listenMode: s.listenMode, logLevel: s.logLevel, theme: s.theme, selectionTimeout: s.selectionTimeout, allowUnboundSigningOnBindFailure: s.allowUnboundSigningOnBindFailure, } @@ -685,6 +768,7 @@ func (s *guiSettingsState) view(c *ui.Context) { s.endpointSection(c, theme, "Listen", false) s.selectionSection(c, theme) s.loggingSection(c, theme) + s.historySection(c, theme) s.themeSection(c, theme) if s.err != "" { ui.Text(c, s.err).MaxLines(2).Ellipsis("…").Tooltip(s.err).TextColor(theme.Danger) @@ -697,7 +781,7 @@ func (s *guiSettingsState) view(c *ui.Context) { if cancel.Clicked() { guiCloseWindowAfterFrame(s.window) } - apply := guiDialogActionButton(c, "Apply", true, s.applying || s.browsingListen || s.browsingUpstream || s.browsingLog) + apply := guiDialogActionButton(c, "Apply", true, s.applying || s.browsingListen || s.browsingUpstream || s.browsingLog || s.browsingHistory) if apply.Clicked() { s.apply() } @@ -851,6 +935,33 @@ func (s *guiSettingsState) loggingSection(c *ui.Context, theme *ui.Theme) { }) } +// historySection lets the user choose where the GUI stores selection history. +func (s *guiSettingsState) historySection(c *ui.Context, theme *ui.Theme) { + section := ui.Column(c).Shrink(0).Gap(theme.Space(1)). + Padding(theme.Space(1.5), theme.Space(2)). + Border(1, theme.Border).Radius(theme.Space(2)).Background(theme.Surface) + section.Children(func() { + ui.Text(c, "History").FontWeight(500) + ui.Row(c).Gap(theme.Space(3)).AlignItems(ui.Center).Children(func() { + ui.Checkbox(c, &s.historyEnabled, "Enable History") + ui.Checkbox(c, &s.rememberSelection, "Remember key selection per target host") + }) + ui.Row(c).Gap(theme.Space(2)).AlignItems(ui.Center).Children(func() { + ui.Text(c, "DB path").Width(theme.Space(26)).Shrink(0) + input := ui.TextInput(c, &s.historyFile).Label("History database file"). + Placeholder(s.historyPlaceholder).Grow(1) + if input.Changed() { + s.historyFile = guiFormatPathInput(s.historyFile) + s.err = "" + } + browse := ui.Button(c, "Browse…").Disabled(s.browsingHistory) + if browse.Clicked() { + s.browseHistoryFile() + } + }) + }) +} + func (s *guiSettingsState) changeListenMode() { selected := guiModeFromDisplay(s.listenMode) previous := guiModeFromDisplay(s.previousListenMode) @@ -1006,6 +1117,9 @@ func (s *guiSettingsState) buildConfig() (config.Config, error) { cfg.Log.File = config.ExpandPath(guiFilePathFromDisplay(s.logFile)) cfg.Log.Level = s.logLevel cfg.GUI.Theme = guiThemeValue(s.theme) + cfg.History.Path = config.ExpandPath(guiFilePathFromDisplay(strings.TrimSpace(s.historyFile))) + cfg.History.Enabled = s.historyEnabled + cfg.History.RememberSelection = s.rememberSelection if err := cfg.Validate(); err != nil { return config.Config{}, err } @@ -1034,6 +1148,35 @@ func (s *guiSettingsState) browseLogFile() { }() } +// browseHistoryFile lets the user choose a custom history database file. +func (s *guiSettingsState) browseHistoryFile() { + defaultPath, err := guiHistoryDatabasePath(s.app.userDataPath, guiFilePathFromDisplay(s.historyFile)) + if err != nil { + s.err = err.Error() + return + } + s.browsingHistory = true + window := s.window + go func() { + path, err := mygo.Dialog.Save(mygo.SaveDialogOptions{ + Parent: window, Title: "Choose history database", DefaultPath: defaultPath, + Filters: []mygo.FileFilter{{Name: "SQLite databases", Extensions: []string{"sqlite", "db"}}}, + }) + if window == nil || window.IsDestroyed() { + return + } + window.Update(func() { + s.browsingHistory = false + if err != nil { + s.err = err.Error() + } else if path != "" { + s.historyFile = guiDisplayFilePath(path) + s.err = "" + } + }) + }() +} + // guiChooseLogFile uses the native save dialog and adds the conventional suffix when omitted. func guiChooseLogFile(parent *mygo.Window, currentPath string) (string, error) { path, err := mygo.Dialog.Save(mygo.SaveDialogOptions{ diff --git a/cmd/ssh-keyselect-gui/gui_history.go b/cmd/ssh-keyselect-gui/gui_history.go new file mode 100644 index 0000000..2b460b2 --- /dev/null +++ b/cmd/ssh-keyselect-gui/gui_history.go @@ -0,0 +1,756 @@ +//go:build gui + +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright contributors to the ssh-keyselect project. + +package main + +import ( + "context" + "encoding/base64" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/egoist/mygo" + "github.com/egoist/mygo/ui" + guiassets "github.com/jfut/ssh-keyselect/assets/gui" + "github.com/jfut/ssh-keyselect/internal/config" + "github.com/jfut/ssh-keyselect/internal/guitable" + "github.com/jfut/ssh-keyselect/internal/identity" + "github.com/jfut/ssh-keyselect/internal/selectionhistory" +) + +const selectionHistoryPageSize = 50 + +// guiHistoryDatabasePath resolves the configured file or the per-user default. +func guiHistoryDatabasePath(userDataPath, configuredPath string) (string, error) { + configuredPath = config.ExpandPath(strings.TrimSpace(configuredPath)) + if configuredPath == "" { + configuredPath = filepath.Join(userDataPath, "history.sqlite") + } else if !filepath.IsAbs(configuredPath) { + configuredPath = filepath.Join(userDataPath, configuredPath) + } + path, err := filepath.Abs(configuredPath) + if err != nil { + return "", fmt.Errorf("resolve selection history database path: %w", err) + } + return path, nil +} + +var selectionHistoryColumns = []ui.TableColumn{ + {ID: "requested", Title: "Requested", Width: 140, MinWidth: 125, Sortable: true}, + {ID: "target-host", Title: "Target host", Width: 145, MinWidth: 120, Sortable: true}, + {ID: "target-key", Title: "Target host key", Width: 185, MinWidth: 150, Sortable: true}, + {ID: "forwarded", Title: "Forwarded", Width: 205, MinWidth: 150, Sortable: true}, + {ID: "key-comment", Title: "Key comment", Width: 135, MinWidth: 110, Sortable: true}, + {ID: "key", Title: "Key", Width: 210, MinWidth: 160, Sortable: true}, + {ID: "key-fingerprint", Title: "Fingerprint", Width: 185, MinWidth: 155, Sortable: true}, + {ID: "selected", Title: "Selected at", Width: 140, MinWidth: 125, Sortable: true}, + {ID: "result", Title: "Result", Width: 82, MinWidth: 72, Sortable: true}, +} + +type guiHistoryState struct { + store *selectionhistory.Store + window *mygo.Window + page int + total int + events []selectionhistory.Event + allEvents []selectionhistory.Event + sortedAllEvents []selectionhistory.Event + sortedAllOrder ui.SortOrder + allEventsLoaded bool + allEventsLoadFail bool + observedSort ui.SortOrder + observedSortSet bool + sort ui.SortOrder + rememberSelection bool + tableState ui.ListState + selectedRow int + loadGeneration uint64 + loading bool + deleting bool + confirmDelete bool + pendingDelete int64 + loadError string + status string +} + +// openHistory shows the persisted picker history in a separate native window. +func (a *guiApp) openHistory() { + if !a.cfg.History.Enabled { + return + } + if a.historyWindow != nil && !a.historyWindow.IsDestroyed() { + a.historyWindow.Show() + a.historyWindow.Focus() + if a.historyView != nil && a.historyStore != nil { + a.historyView.loadPage(a.historyView.page) + } + return + } + state := &guiHistoryState{ + store: a.historyStore, rememberSelection: a.cfg.History.RememberSelection, selectedRow: -1, + } + if a.historyError != "" { + state.loadError = "Could not open history: " + a.historyError + } + window := mygo.NewWindow(mygo.WindowOptions{ + Title: "History - SSH KeySelect", Parent: a.window, + Width: 1000, Height: 430, MinWidth: 820, MinHeight: 350, + Content: ui.View(state.view), + }) + state.window = window + a.historyWindow = window + a.historyView = state + if icon, err := guiassets.WindowIconPNG(); err == nil { + _ = window.SetIcon(icon) + } + window.OnClosed(func() { + if a.historyWindow == window { + a.historyWindow = nil + a.historyView = nil + } + }) + window.Show() + window.Focus() + if state.store != nil { + state.loadPage(0) + } +} + +// replaceHistoryStore activates a newly opened database without interrupting in-flight requests. +func (a *guiApp) replaceHistoryStore(store *selectionhistory.Store, path string) { + var retired *selectionhistory.Store + if a.historyStore != nil && a.historyStore != store { + retired = a.historyStore + a.historyStores = append(a.historyStores, a.historyStore) + } + a.historyStore = store + a.historyPath = path + a.historyError = "" + if a.selector != nil { + a.selector.SetHistoryOptions(store, a.cfg.History.Enabled, a.cfg.History.RememberSelection) + } + a.syncHistoryView() + if retired != nil { + go func() { + if err := retired.Close(); err != nil && a.logger != nil { + a.logger.Warn("close previous selection history database", "error", err) + } + }() + } +} + +func (a *guiApp) syncHistoryView() { + if a.historyView != nil { + state := a.historyView + state.loadGeneration++ + state.loading = false + state.page = 0 + state.total = 0 + state.events = nil + state.clearAllEvents() + state.selectedRow = -1 + state.loadError = "" + state.rememberSelection = a.cfg.History.RememberSelection + if !a.cfg.History.Enabled { + state.store = nil + if state.window != nil && !state.window.IsDestroyed() { + state.window.Close() + } + return + } + state.store = a.historyStore + if a.historyStore == nil && a.historyError != "" { + state.loadError = "Could not open history: " + a.historyError + } + state.loadPage(0) + } +} + +func (s *guiHistoryState) clearAllEvents() { + s.allEvents = nil + s.sortedAllEvents = nil + s.allEventsLoaded = false + s.allEventsLoadFail = false +} + +func (s *guiHistoryState) loadPage(page int) { + if s.store == nil || s.window == nil || s.window.IsDestroyed() { + return + } + if page < 0 { + page = 0 + } + s.selectedRow = -1 + if page != s.page { + columns := s.tableState.Columns + s.tableState = ui.ListState{Columns: columns} + s.tableState.ScrollTo(0, ui.Start) + } + s.page = page + s.loadError = "" + s.status = "" + if s.allEventsLoaded { + s.loading = false + s.window.Invalidate() + return + } + if s.sort.Column != "" { + s.allEventsLoadFail = false + s.loadAllEvents() + return + } + s.loading = true + s.loadGeneration++ + generation := s.loadGeneration + window, store := s.window, s.store + release, err := store.Retain() + if err != nil { + s.loading = false + s.loadError = "Could not load history: " + err.Error() + window.Invalidate() + return + } + window.Invalidate() + go func() { + defer release() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + events, total, err := store.ListPage(ctx, page, selectionHistoryPageSize) + if window.IsDestroyed() { + return + } + window.Update(func() { + if window.IsDestroyed() || generation != s.loadGeneration { + return + } + s.loading = false + if err != nil { + s.loadError = "Could not load history: " + err.Error() + return + } + lastPage := max((total-1)/selectionHistoryPageSize, 0) + if page > lastPage { + s.loadPage(lastPage) + return + } + s.events, s.total = events, total + }) + }() +} + +// loadAllEvents fetches one consistent snapshot when a header sort must span every page. +func (s *guiHistoryState) loadAllEvents() { + if s.store == nil || s.window == nil || s.window.IsDestroyed() || s.loading { + return + } + s.loading = true + s.allEventsLoadFail = false + s.loadError = "" + s.status = "" + s.selectedRow = -1 + s.loadGeneration++ + generation := s.loadGeneration + window, store := s.window, s.store + release, err := store.Retain() + if err != nil { + s.loading = false + s.allEventsLoadFail = true + s.loadError = "Could not load sorted history: " + err.Error() + window.Invalidate() + return + } + window.Invalidate() + go func() { + defer release() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + events, err := store.ListAll(ctx) + if window.IsDestroyed() { + return + } + window.Update(func() { + if window.IsDestroyed() || generation != s.loadGeneration { + return + } + s.loading = false + if err != nil { + s.allEventsLoadFail = true + s.loadError = "Could not load sorted history: " + err.Error() + return + } + s.allEvents = events + s.sortedAllEvents = nil + s.allEventsLoaded = true + s.allEventsLoadFail = false + s.events = nil + s.total = len(events) + lastPage := max((s.total-1)/selectionHistoryPageSize, 0) + if s.page > lastPage { + s.page = lastPage + } + }) + }() +} + +func (s *guiHistoryState) refresh() { + if s.store == nil { + return + } + s.clearAllEvents() + s.events = nil + s.loadPage(s.page) +} + +func (s *guiHistoryState) view(c *ui.Context) { + theme := guitable.CompactTheme(c) + root := ui.Column(c).Fill().Padding(theme.Space(3)).Gap(theme.Space(2)) + root.Children(func() { + ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(theme.Space(2)).Children(func() { + ui.Text(c, "History").FontWeight(500) + ui.Spacer(c) + ui.Text(c, fmt.Sprintf("%d requests", s.total)).TextColor(theme.TextMuted) + }) + if s.loadError != "" { + ui.Text(c, s.loadError).TextColor(theme.Danger) + } + if s.status != "" { + ui.Text(c, s.status).TextColor(theme.Success) + } + card := ui.Column(c).Grow(1).MinHeight(theme.Space(42)).Padding(theme.Space(1.5)). + Background(theme.Surface).Border(1, theme.Border).Radius(theme.Space(2)) + card.Clip() + card.Children(func() { + events := s.pageEvents() + switch { + case s.loading && len(events) == 0: + ui.Column(c).Grow(1).Center().Children(func() { + ui.Text(c, "Loading history…").TextColor(theme.TextMuted) + }) + case len(events) == 0: + ui.Column(c).Grow(1).Center().Children(func() { + if s.store == nil { + ui.Text(c, "History is unavailable.").TextColor(theme.TextMuted) + } else { + ui.Text(c, "No history yet.").TextColor(theme.TextMuted) + } + }) + default: + s.tableState.Key = func(row int) any { return events[row].ID } + s.tableState.Selected = &s.selectedRow + s.tableState.Sort = &s.sort + table := ui.Table(c, &s.tableState, selectionHistoryColumns, len(events), func(row, column int) { + event := events[row] + cell := guitable.CompactCell(c, row, s.selectedRow, theme) + cell.ContextMenu(func(menu *ui.Menu) { + copyRow := menu.Item("Copy row").Shortcut(ui.Cmd, ui.KeyC).Disabled(s.deleting) + if copyRow.Chosen() && !s.deleting { + mygo.Clipboard.WriteText(selectionHistoryCopyText(event)) + } + menu.Separator() + deleteRow := menu.Item("Delete row").Disabled(s.deleting) + if deleteRow.Chosen() && !s.deleting { + s.pendingDelete = event.ID + s.confirmDelete = true + } + }) + cell.Children(func() { + value := selectionHistoryCell(event, selectionHistoryColumns[column].ID) + ui.Text(c, value).SingleLine().Tooltip(value) + }) + }).Grow(1).FontSize(theme.Rem(1) - 1) + if s.selectedRow >= 0 && s.selectedRow < len(events) && table.Shortcut(ui.Cmd, ui.KeyC) { + mygo.Clipboard.WriteText(selectionHistoryCopyText(events[s.selectedRow])) + } + if s.sort.Column != "" && !s.allEventsLoaded && !s.loading && !s.allEventsLoadFail { + s.loadAllEvents() + } + } + }) + ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(theme.Space(1.5)).Children(func() { + previous := guiIconButton(c, guiChevronLeft, "Previous page", false, theme). + Size(theme.Space(8), theme.Space(8)). + Disabled(s.loading || s.deleting || s.page == 0 || s.store == nil) + if previous.Clicked() { + s.loadPage(s.page - 1) + } + totalPages := max((s.total+selectionHistoryPageSize-1)/selectionHistoryPageSize, 1) + ui.Text(c, fmt.Sprintf("%d / %d", s.page+1, totalPages)).TextColor(theme.TextMuted) + next := guiIconButton(c, guiChevronRight, "Next page", false, theme). + Size(theme.Space(8), theme.Space(8)). + Disabled(s.loading || s.deleting || s.page+1 >= totalPages || s.store == nil) + if next.Clicked() { + s.loadPage(s.page + 1) + } + refresh := guiIconButton(c, guiRefreshIcon, "Refresh history", true, theme) + refresh.Size(theme.Space(8), theme.Space(8)) + refresh.Disabled(s.loading || s.deleting || s.store == nil) + if refresh.Clicked() { + s.refresh() + } + ui.Spacer(c) + export := ui.PrimaryButton(c, "Export CSV").Disabled(s.loading || s.deleting || s.total == 0 || s.store == nil) + if export.Clicked() { + go s.exportCSV(s.store) + } + }) + }) + if s.confirmDelete { + if ui.AlertDialog(c, &s.confirmDelete, "Delete history row?", "This removes the selected event from the history database.", "Cancel", "Delete") == 1 { + s.deleteEvent(s.pendingDelete) + } + } +} + +func selectionHistoryCopyText(event selectionhistory.Event) string { + values := make([]string, 0, len(selectionHistoryColumns)) + for _, column := range selectionHistoryColumns { + values = append(values, selectionHistoryCell(event, column.ID)) + } + return strings.Join(values, "\t") +} + +// pageEvents sorts all rows when needed, then returns only the requested display page. +func (s *guiHistoryState) pageEvents() []selectionhistory.Event { + if !s.observedSortSet || s.observedSort != s.sort { + s.selectedRow = -1 + s.observedSort = s.sort + s.observedSortSet = true + s.allEventsLoadFail = false + s.loadError = "" + } + if s.allEventsLoaded { + if s.sortedAllEvents == nil || s.sortedAllOrder != s.sort { + s.sortedAllEvents = sortHistoryEvents(s.allEvents, s.sort) + s.sortedAllOrder = s.sort + } + start := min(s.page*selectionHistoryPageSize, len(s.sortedAllEvents)) + end := min(start+selectionHistoryPageSize, len(s.sortedAllEvents)) + return s.sortedAllEvents[start:end] + } + return sortHistoryEvents(s.events, s.sort) +} + +func sortHistoryEvents(source []selectionhistory.Event, order ui.SortOrder) []selectionhistory.Event { + events := append([]selectionhistory.Event(nil), source...) + if order.Column == "" { + return events + } + sort.SliceStable(events, func(i, j int) bool { + comparison := compareHistoryEvents(events[i], events[j], order.Column) + if order.Descending { + return comparison > 0 + } + return comparison < 0 + }) + return events +} + +func compareHistoryEvents(left, right selectionhistory.Event, column string) int { + switch column { + case "requested": + return left.RequestedAt.Compare(right.RequestedAt) + case "selected": + return left.SelectedAt.Compare(right.SelectedAt) + default: + leftValue := strings.ToLower(selectionHistoryCell(left, column)) + rightValue := strings.ToLower(selectionHistoryCell(right, column)) + return strings.Compare(leftValue, rightValue) + } +} + +func (s *guiHistoryState) deleteEvent(eventID int64) { + if s.store == nil || eventID < 1 || s.deleting { + return + } + s.deleting = true + s.loadError = "" + if s.window != nil { + s.window.Invalidate() + } + window, store := s.window, s.store + rememberSelection := s.rememberSelection + release, err := store.Retain() + if err != nil { + s.deleting = false + s.loadError = "Could not delete history row: " + err.Error() + if window != nil { + window.Invalidate() + } + return + } + go func() { + defer release() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + var err error + if rememberSelection { + err = store.Delete(ctx, eventID) + } else { + err = store.DeleteHistory(ctx, eventID) + } + if window == nil || window.IsDestroyed() { + return + } + window.Update(func() { + if window.IsDestroyed() { + return + } + s.deleting = false + s.pendingDelete = 0 + if err != nil { + s.loadError = "Could not delete history row: " + err.Error() + return + } + s.clearAllEvents() + s.events = nil + s.loadPage(s.page) + }) + }() +} + +func selectionHistoryCell(event selectionhistory.Event, column string) string { + switch column { + case "requested": + return formatHistoryTime(event.RequestedAt) + case "target-host": + return historyTargetHostName(event) + case "target-key": + return historyTargetHostKey(event) + case "forwarded": + return historyForwardedLabel(event.HostHops) + case "key-comment": + if event.SelectedKeyFingerprint == "" { + return "-" + } + return displayHistoryValue(event.SelectedKeyComment) + case "key": + if event.SelectedKeyFingerprint == "" || len(event.SelectedKeyBlob) == 0 { + return "-" + } + algorithm := displayHistoryValue(event.SelectedKeyAlgorithm) + if algorithm == "-" { + return base64.StdEncoding.EncodeToString(event.SelectedKeyBlob) + } + return algorithm + " " + base64.StdEncoding.EncodeToString(event.SelectedKeyBlob) + case "key-fingerprint": + if event.SelectedKeyFingerprint == "" { + return "-" + } + return displayHistoryValue(event.SelectedKeyFingerprint) + case "selected": + if event.SelectedAt.IsZero() { + return "-" + } + return formatHistoryTime(event.SelectedAt) + case "result": + switch event.Outcome { + case selectionhistory.OutcomeSelected: + return "Selected" + case selectionhistory.OutcomeCancelled: + return "Cancelled" + case selectionhistory.OutcomeTimedOut: + return "Timed out" + case selectionhistory.OutcomeNoKeys: + return "No keys" + default: + return "Failed" + } + default: + return "" + } +} + +func formatHistoryTime(value time.Time) string { + if value.IsZero() { + return "-" + } + return value.Local().Format("2006-01-02 15:04:05 MST") +} + +func displayHistoryValue(value string) string { + if safe := identity.DisplayText(value); safe != "" { + return safe + } + return "-" +} + +func historyTargetHostName(event selectionhistory.Event) string { + if event.TargetHostFingerprint == "" { + return "-" + } + if len(event.HostHops) == 0 { + return "-" + } + target := event.HostHops[len(event.HostHops)-1] + if target.IsForwarding { + return "-" + } + names := make([]string, 0, len(target.KnownHosts)) + for _, name := range target.KnownHosts { + if safe := identity.DisplayText(name); safe != "" { + names = append(names, safe) + } + } + if len(names) == 0 { + return "-" + } + return strings.Join(names, ", ") +} + +func historyTargetHostKey(event selectionhistory.Event) string { + if event.TargetHostFingerprint == "" { + return "-" + } + key := displayHistoryValue(event.TargetHostFingerprint) + for index := len(event.HostHops) - 1; index >= 0; index-- { + hop := event.HostHops[index] + if hop.IsForwarding || hop.Fingerprint != event.TargetHostFingerprint { + continue + } + algorithm := displayHistoryValue(hop.Algorithm) + if algorithm != "-" { + return algorithm + " " + key + } + break + } + return key +} + +func historyForwardedLabel(hops []selectionhistory.HostHop) string { + var forwarded []string + for _, hop := range hops { + if !hop.IsForwarding { + continue + } + key := displayHistoryValue(hop.Fingerprint) + if algorithm := displayHistoryValue(hop.Algorithm); algorithm != "-" && key != "-" { + key = algorithm + " " + key + } + label := key + if len(hop.KnownHosts) > 0 { + names := make([]string, 0, len(hop.KnownHosts)) + for _, name := range hop.KnownHosts { + if safe := identity.DisplayText(name); safe != "" { + names = append(names, safe) + } + } + if len(names) > 0 { + label = strings.Join(names, ", ") + if key != "-" { + label += " [" + key + "]" + } + } + } + if label == "" { + label = "-" + } + forwarded = append(forwarded, label) + } + if len(forwarded) == 0 { + return "-" + } + return strings.Join(forwarded, " -> ") +} + +func (s *guiHistoryState) exportCSV(store *selectionhistory.Store) { + if store == nil || s.window == nil || s.window.IsDestroyed() { + return + } + window := s.window + release, err := store.Retain() + if err != nil { + window.Update(func() { + if !window.IsDestroyed() { + s.loadError = "Could not export history: " + err.Error() + window.Invalidate() + } + }) + return + } + defer release() + path, err := mygo.Dialog.Save(mygo.SaveDialogOptions{ + Parent: window, Title: "Export History", DefaultPath: guiDefaultHistoryCSVPath(), + Filters: []mygo.FileFilter{{Name: "CSV files", Extensions: []string{"csv"}}}, + }) + if err == nil && path != "" { + if filepath.Ext(path) == "" { + path += ".csv" + } else if !strings.EqualFold(filepath.Ext(path), ".csv") { + err = fmt.Errorf("history export file must use the .csv extension") + } + } + if err != nil { + message := "Could not export history: " + err.Error() + window.Update(func() { + if !window.IsDestroyed() { + s.loadError = message + window.Invalidate() + } + }) + return + } + if path == "" { + return + } + if err := writeGUIHistoryCSV(path, store); err != nil { + message := "Could not export history: " + err.Error() + window.Update(func() { + if !window.IsDestroyed() { + s.loadError = message + window.Invalidate() + } + }) + return + } + window.Update(func() { + if !window.IsDestroyed() { + s.status = "" + s.loadError = "" + window.Invalidate() + } + }) +} + +func guiDefaultHistoryCSVPath() string { + base, err := os.UserConfigDir() + if err != nil { + return "history.csv" + } + return filepath.Join(base, "ssh-keyselect", "history.csv") +} + +// writeGUIHistoryCSV keeps a failed export from replacing an existing destination. +func writeGUIHistoryCSV(path string, store *selectionhistory.Store) error { + directory := filepath.Dir(path) + temporary, err := os.CreateTemp(directory, ".selection-history-*.csv") + if err != nil { + return fmt.Errorf("create CSV temporary file: %w", err) + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err := temporary.Chmod(0o600); err != nil { + _ = temporary.Close() + return fmt.Errorf("set CSV file permissions: %w", err) + } + if err := store.ExportCSV(context.Background(), temporary); err != nil { + _ = temporary.Close() + return err + } + if err := temporary.Sync(); err != nil { + _ = temporary.Close() + return fmt.Errorf("sync CSV file: %w", err) + } + if err := temporary.Close(); err != nil { + return fmt.Errorf("close CSV file: %w", err) + } + if err := os.Rename(temporaryPath, path); err != nil { + return fmt.Errorf("replace CSV file: %w", err) + } + return nil +} diff --git a/cmd/ssh-keyselect-gui/gui_status.go b/cmd/ssh-keyselect-gui/gui_status.go index 8a8586a..46d4d9c 100644 --- a/cmd/ssh-keyselect-gui/gui_status.go +++ b/cmd/ssh-keyselect-gui/gui_status.go @@ -27,6 +27,9 @@ import ( var ( guiRefreshIcon = ui.MustParseSVG([]byte(``)) guiSettingsIcon = ui.MustParseSVG([]byte(``)) + guiHistoryIcon = ui.MustParseSVG([]byte(``)) + guiChevronLeft = ui.MustParseSVG([]byte(``)) + guiChevronRight = ui.MustParseSVG([]byte(``)) guiCopyIcon = ui.MustParseSVG([]byte(``)) guiCloseIcon = ui.MustParseSVG([]byte(``)) ) @@ -158,6 +161,9 @@ func (a *guiApp) view(c *ui.Context) { if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyS) { a.saveAsConfiguration() } + if c.Shortcut(ui.Cmd|ui.Shift, ui.KeyH) { + a.openHistory() + } if c.Shortcut(ui.Cmd, ui.KeyComma) { a.openSettings() } @@ -223,7 +229,7 @@ func (a *guiApp) view(c *ui.Context) { // applicationMenuBar draws themed in-window menus on platforms without an app menu bar. func (a *guiApp) applicationMenuBar(c *ui.Context, theme *ui.Theme) { barColor := theme.Surface - fileMenuWidth, helpMenuWidth := theme.Space(64), theme.Space(48) + fileMenuWidth, helpMenuWidth := theme.Space(72), theme.Space(48) if theme.Dark { barColor = ui.Hex("#181818") } @@ -248,6 +254,10 @@ func (a *guiApp) applicationMenuBar(c *ui.Context, theme *ui.Theme) { a.applicationMenuItem(c, theme, "Save As", "Ctrl+Shift+S", a.applying, a.saveAsConfiguration) guiApplicationMenuSeparator(c, theme) a.applicationMenuItem(c, theme, "Settings…", "Ctrl+,", a.applying, a.openSettings) + if a.cfg.History.Enabled { + guiApplicationMenuSeparator(c, theme) + a.applicationMenuItem(c, theme, "History…", "Ctrl+Shift+H", false, a.openHistory) + } guiApplicationMenuSeparator(c, theme) a.applicationMenuItem(c, theme, "Quit", "Ctrl+Q", false, mygo.App.Quit) }) @@ -388,6 +398,14 @@ func (a *guiApp) connectionCard(c *ui.Context, theme *ui.Theme) { if settings.Clicked() && !a.applying { a.openSettings() } + if a.cfg.History.Enabled { + history := guiIconButton(c, guiHistoryIcon, "History", true, theme) + history.Size(theme.Space(8), theme.Space(8)) + history.Disabled(a.applying) + if history.Clicked() && !a.applying { + a.openHistory() + } + } if a.statusMessage != "" { ui.Row(c).Grow(1).Gap(theme.Space(1)).AlignItems(ui.Center).Children(func() { ui.Text(c, a.statusMessage).TextColor(theme.Warning). diff --git a/docs/dev.md b/docs/dev.md index 3bbfb6f..0ea1b07 100644 --- a/docs/dev.md +++ b/docs/dev.md @@ -119,6 +119,14 @@ OpenSSH records session bindings for the lifetime of an agent connection and rej The proxy opens a temporary upstream session for each bound operation and replays the verified binding chain before forwarding the request. This preserves session context for OpenSSH-compatible agents without holding a connection open while the picker waits. Without session bindings, ordinary requests use the upstream agent directly. By default, an explicit upstream refusal blocks signing for that frontend connection. When `agent.allow_unbound_signing_on_bind_failure` is enabled, an explicit `SSH_AGENT_FAILURE` or extension failure during binding activates a per-connection fallback: KeySelect retains its locally verified context, retries identity listing without bindings, and retries signing without bindings after a replay refusal. Other setup and I/O errors do not activate the fallback. This can bypass upstream destination restrictions, so the setting is off by default. +#### GUI selection history + +`internal/selectionhistory` stores GUI selection events, verified host hops, and the last selected key for each verified target host in `history.sqlite` under the per-user application-data directory by default. `[history].path` selects another file when set; it is omitted from saved configuration when empty, and relative paths resolve from the application-data directory. GUI Settings leaves the field empty and shows the resolved default path as its placeholder. `[history].enabled` and `[history].remember_selection` both default to true, are saved only when false, and are independent: the first controls event recording and the History window, while the second controls per-host preference reads and writes. The application opens the database only when at least one switch is enabled; when both are disabled, startup and configuration apply skip database path resolution and SQLite open/create. If both features are enabled, the event and preference update share one transaction. History-only recording does not update preferences; preference-only recording does not create events. Preferences use the final non-forwarding host-key fingerprint and selected public-key fingerprint; they only set the picker's initial row. Requests without a verified target host key do not read or update a preference. + +When history is enabled, the proxy captures `requested_at` when it receives `RequestIdentities`, before listing upstream identities. The GUI records when the picker opens, when the user selects or cancels, and the outcome. Host hops preserve binding order, forwarding flags, fingerprints, and `known_hosts` display hints. The compact history table pages 50 rows ordered by request time, shows target host names separately from the host key, and shows selected-key comment, public-key data, and fingerprint in separate columns. It copies its displayed row fields and deletes events with their host-hop rows. Forwarding paths use ` -> ` between hops and comma-separated known-host hints followed by the key in brackets. CSV export starts with the table's columns in display order, then adds event and connection metadata, the complete host path as JSON, and the selected key algorithm and blob in Base64. When key remembrance is enabled, deleting the latest event for a host restores the prior surviving key preference. The result is the picker outcome, not SSH authentication acceptance, which the agent protocol does not expose. + +The database starts at schema version 1, defined in `internal/selectionhistory/store.go`. It uses WAL mode, a 5-second busy timeout, and foreign keys. The database file is mode `0600`; missing parent directories are created with mode `0700`. Event timestamps are stored as UTC Unix nanoseconds and formatted in local time in the GUI and CSV; CSV timestamps use RFC 3339 with the local UTC offset. CSV key comments are sanitized and spreadsheet formula prefixes are neutralized. The ncruces SQLite driver embeds its SQLite WebAssembly module and keeps the database compatible with the repository's `CGO_ENABLED=0` builds without downloading a native library at runtime. Run `just deps-credits` after this dependency change. + #### Selection cache The proxy serializes each selected identity list once and retains it with the authorized key digests until the binding chain changes or the listen-socket connection closes. @@ -357,7 +365,7 @@ Before submitting the SignPath application, jfut must add this text to the lates ## Dependency license inventory -The application project uses Apache-2.0. The current shipped module graph includes Apache-2.0, MIT, and BSD-3-Clause packages. +The application project uses Apache-2.0. The current shipped module graph includes Apache-2.0, MIT, MIT-0, and BSD-3-Clause packages. The credits generator scans Linux, macOS, and Windows builds with the GUI tag. `CREDITS` includes full notices for the Go standard library and third-party modules. diff --git a/go.mod b/go.mod index 3627a8c..26a5a7a 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/alecthomas/kong v1.16.1 github.com/ebitengine/purego v0.11.2 github.com/egoist/mygo v0.5.5 + github.com/ncruces/go-sqlite3 v0.36.0 go.digitalxero.dev/go-msi v0.5.0 golang.org/x/crypto v0.58.0 golang.org/x/image v0.47.0 @@ -20,6 +21,8 @@ require ( require ( github.com/go-text/typesetting v0.3.5 // indirect + github.com/ncruces/go-sqlite3-wasm/v6 v6.4.35401 // indirect + github.com/ncruces/julianday v1.0.0 // indirect golang.org/x/text v0.43.0 // indirect software.sslmate.com/src/go-pkcs12 v0.7.4 // indirect ) diff --git a/go.sum b/go.sum index 14f4e22..49542dc 100644 --- a/go.sum +++ b/go.sum @@ -24,6 +24,12 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/ncruces/go-sqlite3 v0.36.0 h1:/tmetPB+789WApzUWWfXVlDRtraPKil2iopXlQbET4A= +github.com/ncruces/go-sqlite3 v0.36.0/go.mod h1:HhzaJ0fX5RHXe+09Nfz7pKiNuJVexXTAqX0/gNmA06w= +github.com/ncruces/go-sqlite3-wasm/v6 v6.4.35401 h1:CJ7ClSmm84xWaefcVSbiMlU3luCiMfC/eJ0vaPntbhQ= +github.com/ncruces/go-sqlite3-wasm/v6 v6.4.35401/go.mod h1:KG11ycVocsrsZ6OoNm4j2T7SKyzb/6ELHo0M+bAX50A= +github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M= +github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= diff --git a/internal/agentproxy/server.go b/internal/agentproxy/server.go index f7f7f0b..c2b9b8b 100644 --- a/internal/agentproxy/server.go +++ b/internal/agentproxy/server.go @@ -237,6 +237,7 @@ func (s *Server) handleConnection(parent context.Context, conn net.Conn, session return } if cachedResponse == nil { + requestedAt := time.Now() available, err := listAgent(ctx, s.Agent, upstreamSessionBinds, requestTimeout) if errors.Is(err, upstream.ErrSessionBindingRejected) && s.allowUnboundSigningOnBindFailure.Load() { upstreamSessionBindingFallback = true @@ -248,7 +249,10 @@ func (s *Server) handleConnection(parent context.Context, conn net.Conn, session var chosen []identity.Identity if err == nil { selectionCtx, cancelSelection := s.newSelectionContext(ctx) - chosen, err = s.selectAvailableIdentities(selectionCtx, log, selectionContext(sessionBinds), available) + requestContext := selectionContext(sessionBinds) + requestContext.ConnectionID = sessionID + requestContext.RequestedAt = requestedAt + chosen, err = s.selectAvailableIdentities(selectionCtx, log, requestContext, available) if errors.Is(selectionCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil { log.Warn("identity selection timed out", "timeout", s.selectionTimeoutDuration()) err = errSelectionTimeout diff --git a/internal/config/config.go b/internal/config/config.go index 001b78b..b6bbdd1 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -29,9 +29,17 @@ const ( ) type Config struct { - Agent AgentConfig `toml:"agent"` - Log LogConfig `toml:"log"` - GUI GUIConfig `toml:"gui"` + History HistoryConfig `toml:"history"` + Agent AgentConfig `toml:"agent"` + Log LogConfig `toml:"log"` + GUI GUIConfig `toml:"gui"` +} + +// HistoryConfig holds selection-history storage and key-remembrance settings. +type HistoryConfig struct { + Enabled bool `toml:"enabled"` + Path string `toml:"path"` + RememberSelection bool `toml:"remember_selection"` } type AgentConfig struct { @@ -48,15 +56,22 @@ type LogConfig struct { Level string `toml:"level"` } -// GUIConfig holds settings that affect only the native GUI presentation. +// GUIConfig holds settings specific to the native GUI. type GUIConfig struct { Theme string `toml:"theme"` } type saveConfig struct { - Agent saveAgentConfig `toml:"agent"` - Log LogConfig `toml:"log"` - GUI GUIConfig `toml:"gui"` + History *saveHistoryConfig `toml:"history,omitempty"` + Agent saveAgentConfig `toml:"agent"` + Log LogConfig `toml:"log"` + GUI GUIConfig `toml:"gui"` +} + +type saveHistoryConfig struct { + Enabled *bool `toml:"enabled,omitempty"` + Path tomlPath `toml:"path,omitempty"` + RememberSelection *bool `toml:"remember_selection,omitempty"` } type saveAgentConfig struct { @@ -93,7 +108,7 @@ func isTOMLLiteralString(value string) bool { } func configForSave(cfg Config) saveConfig { - return saveConfig{ + encoded := saveConfig{ Agent: saveAgentConfig{ Listen: tomlPath(cfg.Agent.Listen), Upstream: tomlPath(cfg.Agent.Upstream), @@ -105,6 +120,19 @@ func configForSave(cfg Config) saveConfig { Log: cfg.Log, GUI: cfg.GUI, } + if cfg.History.Path != "" || !cfg.History.Enabled || !cfg.History.RememberSelection { + history := &saveHistoryConfig{Path: tomlPath(cfg.History.Path)} + if !cfg.History.Enabled { + disabled := false + history.Enabled = &disabled + } + if !cfg.History.RememberSelection { + disabled := false + history.RememberSelection = &disabled + } + encoded.History = history + } + return encoded } // UpstreamEnvironmentReference returns the config value for an environment-backed endpoint. @@ -155,8 +183,9 @@ func Default() Config { UpstreamMode: transport.Auto, ListenMode: transport.Auto, SelectionTimeout: defaultSelectionTimeoutSeconds, }, - Log: LogConfig{Level: "off"}, - GUI: GUIConfig{Theme: GUIThemeLight}, + Log: LogConfig{Level: "off"}, + History: HistoryConfig{Enabled: true, RememberSelection: true}, + GUI: GUIConfig{Theme: GUIThemeLight}, } } @@ -220,6 +249,7 @@ func Load(path string) (Config, error) { cfg.Agent.Listen = ExpandPath(cfg.Agent.Listen) cfg.Agent.Upstream = ExpandPath(cfg.Agent.Upstream) cfg.Log.File = ExpandPath(cfg.Log.File) + cfg.History.Path = ExpandPath(cfg.History.Path) if err := cfg.Validate(); err != nil { return Config{}, err } diff --git a/internal/guitable/table.go b/internal/guitable/table.go index e223f22..3a3bd40 100644 --- a/internal/guitable/table.go +++ b/internal/guitable/table.go @@ -177,6 +177,11 @@ func identityColumns(numbered, sortable bool) []ui.TableColumn { // IdentityCell applies the compact type and alternating row colors in both key tables. func IdentityCell(c *ui.Context, row, selected int, theme *ui.Theme, content func()) { + CompactCell(c, row, selected, theme).Children(content) +} + +// CompactCell builds a key-table cell so other tables can share its row density and striping. +func CompactCell(c *ui.Context, row, selected int, theme *ui.Theme) ui.Element { cell := ui.Row(c).Grow(1). Margin(-theme.Space(1.5), -theme.Space(2.5)). Padding(theme.Space(1.5), theme.Space(2.5)).FontSize(theme.Rem(0.9)) @@ -187,5 +192,5 @@ func IdentityCell(c *ui.Context, row, selected int, theme *ui.Theme, content fun cell.Background(ui.Hex("#edf3fa")) } } - cell.Children(content) + return cell } diff --git a/internal/selectionhistory/store.go b/internal/selectionhistory/store.go new file mode 100644 index 0000000..7ff4c8b --- /dev/null +++ b/internal/selectionhistory/store.go @@ -0,0 +1,920 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright contributors to the ssh-keyselect project. + +// Package selectionhistory stores GUI key-selection events and per-host defaults. +package selectionhistory + +import ( + "context" + "database/sql" + "encoding/base64" + "encoding/csv" + "encoding/json" + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "github.com/jfut/ssh-keyselect/internal/identity" + _ "github.com/ncruces/go-sqlite3/driver" +) + +const ( + pageSizeLimit = 200 + schemaVersion = 1 + selectionOutcomeSelected = "selected" + selectionOutcomeCancelled = "cancelled" + selectionOutcomeTimedOut = "timed_out" + selectionOutcomeNoKeys = "no_keys" + selectionOutcomeFailed = "failed" +) + +// Outcome names the result of a GUI picker request. +type Outcome string + +const ( + OutcomeSelected Outcome = selectionOutcomeSelected + OutcomeCancelled Outcome = selectionOutcomeCancelled + OutcomeTimedOut Outcome = selectionOutcomeTimedOut + OutcomeNoKeys Outcome = selectionOutcomeNoKeys + OutcomeFailed Outcome = selectionOutcomeFailed +) + +// HostHop snapshots one verified host key in the request's forwarding path. +type HostHop struct { + Algorithm string + Fingerprint string + IsForwarding bool + KnownHosts []string +} + +// Event is one completed GUI identity-selection request and its visible host path. +type Event struct { + ID int64 + ConnectionID string + RequestedAt time.Time + DialogOpenedAt time.Time + ResolvedAt time.Time + SelectedAt time.Time + Outcome Outcome + TargetHostFingerprint string + SelectedKeyFingerprint string + SelectedKeyAlgorithm string + SelectedKeyBlob []byte + SelectedKeyComment string + HostHops []HostHop +} + +// Store owns the local SQLite database for selection history and host defaults. +type Store struct { + writeMu sync.Mutex + lifecycle sync.Mutex + activeCond *sync.Cond + activeUses int + closing bool + closeDone chan struct{} + closeErr error + db *sql.DB +} + +// Open creates or opens a private local history database and applies its schema. +func Open(path string) (*Store, error) { + if path == "" { + return nil, errors.New("selection history database path is empty") + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return nil, fmt.Errorf("create selection history directory: %w", err) + } + dsn, err := databaseDSN(path) + if err != nil { + return nil, err + } + db, err := sql.Open("sqlite3", dsn) + if err != nil { + return nil, fmt.Errorf("open selection history database: %w", err) + } + db.SetMaxOpenConns(4) + db.SetMaxIdleConns(4) + store := &Store{db: db, closeDone: make(chan struct{})} + store.activeCond = sync.NewCond(&store.lifecycle) + if err := store.initialize(context.Background()); err != nil { + _ = db.Close() + return nil, err + } + if err := os.Chmod(path, 0o600); err != nil { + _ = db.Close() + return nil, fmt.Errorf("set selection history database permissions: %w", err) + } + return store, nil +} + +// databaseDSN quotes a filesystem path and applies connection-local SQLite safeguards. +func databaseDSN(path string) (string, error) { + absolutePath, err := filepath.Abs(path) + if err != nil { + return "", fmt.Errorf("resolve selection history database path: %w", err) + } + databaseURL := url.URL{Scheme: "file"} + if runtime.GOOS == "windows" { + // Keep the drive letter at the start of the URI path. A hierarchical + // file:///C:/ URI reaches Windows VFS as the invalid path /C:/... . + databaseURL.Opaque = filepath.ToSlash(absolutePath) + } else { + databaseURL.Path = absolutePath + } + query := databaseURL.Query() + query.Add("_pragma", "busy_timeout(5000)") + query.Add("_pragma", "foreign_keys(1)") + databaseURL.RawQuery = query.Encode() + return databaseURL.String(), nil +} + +// initialize enables WAL and applies the current schema version transactionally. +func (s *Store) initialize(ctx context.Context) error { + if err := s.db.PingContext(ctx); err != nil { + return fmt.Errorf("connect to selection history database: %w", err) + } + var journalMode string + if err := s.db.QueryRowContext(ctx, "PRAGMA journal_mode=WAL").Scan(&journalMode); err != nil { + return fmt.Errorf("enable selection history WAL: %w", err) + } + if !strings.EqualFold(journalMode, "wal") { + return fmt.Errorf("selection history database uses %q journal mode, want WAL", journalMode) + } + var currentVersion int + if err := s.db.QueryRowContext(ctx, "PRAGMA user_version").Scan(¤tVersion); err != nil { + return fmt.Errorf("read selection history schema version: %w", err) + } + if currentVersion > schemaVersion { + return fmt.Errorf("selection history schema version %d is newer than supported version %d", currentVersion, schemaVersion) + } + if currentVersion == schemaVersion { + return nil + } + if currentVersion != 0 { + return fmt.Errorf("selection history schema version %d is unsupported", currentVersion) + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin selection history schema creation: %w", err) + } + statements := []string{ + `CREATE TABLE selection_events ( + id INTEGER PRIMARY KEY, + connection_id TEXT NOT NULL, + requested_at_ns INTEGER NOT NULL, + dialog_opened_at_ns INTEGER, + resolved_at_ns INTEGER NOT NULL, + selected_at_ns INTEGER, + outcome TEXT NOT NULL, + target_host_fingerprint TEXT NOT NULL DEFAULT '', + selected_key_fingerprint TEXT NOT NULL DEFAULT '', + selected_key_algorithm TEXT NOT NULL DEFAULT '', + selected_key_blob BLOB NOT NULL DEFAULT X'', + selected_key_comment TEXT NOT NULL DEFAULT '' + )`, + `CREATE INDEX selection_events_requested_at ON selection_events(requested_at_ns DESC, id DESC)`, + `CREATE INDEX selection_events_target_host ON selection_events(target_host_fingerprint, requested_at_ns DESC, id DESC)`, + `CREATE TABLE selection_host_hops ( + event_id INTEGER NOT NULL REFERENCES selection_events(id) ON DELETE CASCADE, + ordinal INTEGER NOT NULL, + key_algorithm TEXT NOT NULL, + host_key_fingerprint TEXT NOT NULL, + is_forwarding INTEGER NOT NULL CHECK (is_forwarding IN (0, 1)), + known_hosts_hints TEXT NOT NULL, + PRIMARY KEY (event_id, ordinal) + )`, + `CREATE TABLE selection_preferences ( + target_host_fingerprint TEXT PRIMARY KEY, + selected_key_fingerprint TEXT NOT NULL, + selected_at_ns INTEGER NOT NULL + )`, + `PRAGMA user_version = 1`, + } + for _, statement := range statements { + if _, err := tx.ExecContext(ctx, statement); err != nil { + _ = tx.Rollback() + return fmt.Errorf("apply selection history schema: %w", err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit selection history schema: %w", err) + } + return nil +} + +// Retain keeps the database open until the returned release function is called. +func (s *Store) Retain() (func(), error) { + if s == nil || s.db == nil { + return nil, errors.New("selection history database is unavailable") + } + s.lifecycle.Lock() + if s.closing && s.activeUses == 0 { + s.lifecycle.Unlock() + return nil, errors.New("selection history database is closing") + } + s.activeUses++ + s.lifecycle.Unlock() + + var once sync.Once + return func() { + once.Do(func() { + s.lifecycle.Lock() + s.activeUses-- + if s.closing && s.activeUses == 0 { + s.activeCond.Broadcast() + } + s.lifecycle.Unlock() + }) + }, nil +} + +// Close waits for retained users before releasing SQLite's WAL and SHM handles. +func (s *Store) Close() error { + if s == nil || s.db == nil { + return nil + } + s.lifecycle.Lock() + if s.closing { + done := s.closeDone + s.lifecycle.Unlock() + <-done + s.lifecycle.Lock() + err := s.closeErr + s.lifecycle.Unlock() + return err + } + s.closing = true + for s.activeUses > 0 { + s.activeCond.Wait() + } + s.lifecycle.Unlock() + + err := s.db.Close() + s.lifecycle.Lock() + s.closeErr = err + close(s.closeDone) + s.lifecycle.Unlock() + return err +} + +// PreferredSelection returns the last explicitly selected key fingerprint for a target host. +func (s *Store) PreferredSelection(ctx context.Context, targetHostFingerprint string) (string, bool, error) { + if s == nil || s.db == nil || targetHostFingerprint == "" { + return "", false, nil + } + release, err := s.Retain() + if err != nil { + return "", false, err + } + defer release() + var fingerprint string + err = s.db.QueryRowContext(ctx, + `SELECT selected_key_fingerprint FROM selection_preferences WHERE target_host_fingerprint = ?`, + targetHostFingerprint, + ).Scan(&fingerprint) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + if err != nil { + return "", false, fmt.Errorf("read selection preference: %w", err) + } + return fingerprint, true, nil +} + +// RememberSelection stores a selected key without creating a history event. +func (s *Store) RememberSelection(ctx context.Context, targetHostFingerprint, selectedKeyFingerprint string, selectedAt time.Time) error { + if s == nil || s.db == nil { + return errors.New("selection history database is unavailable") + } + if targetHostFingerprint == "" || selectedKeyFingerprint == "" || selectedAt.IsZero() { + return errors.New("selection preference is incomplete") + } + release, err := s.Retain() + if err != nil { + return err + } + defer release() + s.writeMu.Lock() + defer s.writeMu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + _, err = s.db.ExecContext(ctx, ` + INSERT INTO selection_preferences (target_host_fingerprint, selected_key_fingerprint, selected_at_ns) + VALUES (?, ?, ?) + ON CONFLICT(target_host_fingerprint) DO UPDATE SET + selected_key_fingerprint = excluded.selected_key_fingerprint, + selected_at_ns = excluded.selected_at_ns`, + targetHostFingerprint, selectedKeyFingerprint, selectedAt.UTC().UnixNano(), + ) + if err != nil { + return fmt.Errorf("update selection preference: %w", err) + } + return nil +} + +// Record appends one completed event and updates its host preference in one transaction. +func (s *Store) Record(ctx context.Context, event Event) error { + return s.record(ctx, event, true) +} + +// RecordHistory appends one event without reading or updating host preferences. +func (s *Store) RecordHistory(ctx context.Context, event Event) error { + return s.record(ctx, event, false) +} + +func (s *Store) record(ctx context.Context, event Event, rememberSelection bool) error { + if s == nil || s.db == nil { + return errors.New("selection history database is unavailable") + } + release, err := s.Retain() + if err != nil { + return err + } + defer release() + s.writeMu.Lock() + defer s.writeMu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + if event.RequestedAt.IsZero() { + event.RequestedAt = time.Now() + } + if event.ResolvedAt.IsZero() { + event.ResolvedAt = time.Now() + } + if event.Outcome == "" { + return errors.New("selection history outcome is empty") + } + if event.TargetHostFingerprint == "" && len(event.HostHops) > 0 { + target := event.HostHops[len(event.HostHops)-1] + if !target.IsForwarding { + event.TargetHostFingerprint = target.Fingerprint + } + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin selection history write: %w", err) + } + defer tx.Rollback() + var dialogOpenedAt, selectedAt any + if !event.DialogOpenedAt.IsZero() { + dialogOpenedAt = event.DialogOpenedAt.UTC().UnixNano() + } + if !event.SelectedAt.IsZero() { + selectedAt = event.SelectedAt.UTC().UnixNano() + } + selectedKeyBlob := event.SelectedKeyBlob + if selectedKeyBlob == nil { + selectedKeyBlob = []byte{} + } + result, err := tx.ExecContext(ctx, ` + INSERT INTO selection_events ( + connection_id, requested_at_ns, dialog_opened_at_ns, resolved_at_ns, selected_at_ns, + outcome, target_host_fingerprint, selected_key_fingerprint, + selected_key_algorithm, selected_key_blob, selected_key_comment + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + event.ConnectionID, event.RequestedAt.UTC().UnixNano(), dialogOpenedAt, + event.ResolvedAt.UTC().UnixNano(), selectedAt, string(event.Outcome), + event.TargetHostFingerprint, event.SelectedKeyFingerprint, + event.SelectedKeyAlgorithm, selectedKeyBlob, event.SelectedKeyComment, + ) + if err != nil { + return fmt.Errorf("insert selection history event: %w", err) + } + eventID, err := result.LastInsertId() + if err != nil { + return fmt.Errorf("read selection history event ID: %w", err) + } + for ordinal, hop := range event.HostHops { + hints, err := json.Marshal(hop.KnownHosts) + if err != nil { + return fmt.Errorf("encode known_hosts hints: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + INSERT INTO selection_host_hops ( + event_id, ordinal, key_algorithm, host_key_fingerprint, is_forwarding, known_hosts_hints + ) VALUES (?, ?, ?, ?, ?, ?)`, + eventID, ordinal, hop.Algorithm, hop.Fingerprint, hop.IsForwarding, string(hints), + ); err != nil { + return fmt.Errorf("insert selection host hop: %w", err) + } + } + if rememberSelection && event.Outcome == OutcomeSelected && event.TargetHostFingerprint != "" && event.SelectedKeyFingerprint != "" && !event.SelectedAt.IsZero() { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO selection_preferences (target_host_fingerprint, selected_key_fingerprint, selected_at_ns) + VALUES (?, ?, ?) + ON CONFLICT(target_host_fingerprint) DO UPDATE SET + selected_key_fingerprint = excluded.selected_key_fingerprint, + selected_at_ns = excluded.selected_at_ns`, + event.TargetHostFingerprint, event.SelectedKeyFingerprint, event.SelectedAt.UTC().UnixNano(), + ); err != nil { + return fmt.Errorf("update selection preference: %w", err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit selection history event: %w", err) + } + return nil +} + +// DeleteHistory removes an event and its host path without touching preferences. +func (s *Store) DeleteHistory(ctx context.Context, eventID int64) error { + if s == nil || s.db == nil { + return errors.New("selection history database is unavailable") + } + release, err := s.Retain() + if err != nil { + return err + } + defer release() + s.writeMu.Lock() + defer s.writeMu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + if eventID < 1 { + return errors.New("selection history event ID is invalid") + } + if _, err := s.db.ExecContext(ctx, `DELETE FROM selection_events WHERE id = ?`, eventID); err != nil { + return fmt.Errorf("delete selection history event: %w", err) + } + return nil +} + +// Delete removes a history event and restores the previous host preference when needed. +func (s *Store) Delete(ctx context.Context, eventID int64) error { + if s == nil || s.db == nil { + return errors.New("selection history database is unavailable") + } + release, err := s.Retain() + if err != nil { + return err + } + defer release() + s.writeMu.Lock() + defer s.writeMu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + if eventID < 1 { + return errors.New("selection history event ID is invalid") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin selection history delete: %w", err) + } + defer tx.Rollback() + + var targetHost, selectedKey string + var selectedAt sql.NullInt64 + err = tx.QueryRowContext(ctx, ` + SELECT target_host_fingerprint, selected_key_fingerprint, selected_at_ns + FROM selection_events WHERE id = ?`, eventID, + ).Scan(&targetHost, &selectedKey, &selectedAt) + if errors.Is(err, sql.ErrNoRows) { + return tx.Commit() + } + if err != nil { + return fmt.Errorf("read selection history event to delete: %w", err) + } + if targetHost != "" && selectedKey != "" && selectedAt.Valid { + var latestEventID int64 + err := tx.QueryRowContext(ctx, ` + SELECT id FROM selection_events + WHERE target_host_fingerprint = ? AND outcome = ? AND selected_key_fingerprint != '' AND selected_at_ns IS NOT NULL + ORDER BY id DESC LIMIT 1`, targetHost, selectionOutcomeSelected, + ).Scan(&latestEventID) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("find latest host selection before delete: %w", err) + } + if latestEventID == eventID { + result, err := tx.ExecContext(ctx, ` + DELETE FROM selection_preferences + WHERE target_host_fingerprint = ? AND selected_key_fingerprint = ? AND selected_at_ns = ?`, + targetHost, selectedKey, selectedAt.Int64, + ) + if err != nil { + return fmt.Errorf("delete host preference for removed event: %w", err) + } + deleted, err := result.RowsAffected() + if err != nil { + return fmt.Errorf("check deleted host preference: %w", err) + } + if deleted > 0 { + var previousKey string + var previousSelectedAt int64 + err := tx.QueryRowContext(ctx, ` + SELECT selected_key_fingerprint, selected_at_ns FROM selection_events + WHERE target_host_fingerprint = ? AND id != ? AND outcome = ? AND selected_key_fingerprint != '' AND selected_at_ns IS NOT NULL + ORDER BY id DESC LIMIT 1`, targetHost, eventID, selectionOutcomeSelected, + ).Scan(&previousKey, &previousSelectedAt) + if err == nil { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO selection_preferences (target_host_fingerprint, selected_key_fingerprint, selected_at_ns) + VALUES (?, ?, ?) + ON CONFLICT(target_host_fingerprint) DO UPDATE SET + selected_key_fingerprint = excluded.selected_key_fingerprint, + selected_at_ns = excluded.selected_at_ns`, + targetHost, previousKey, previousSelectedAt, + ); err != nil { + return fmt.Errorf("restore previous host preference: %w", err) + } + } else if !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("find previous host preference: %w", err) + } + } + } + } + if _, err := tx.ExecContext(ctx, `DELETE FROM selection_events WHERE id = ?`, eventID); err != nil { + return fmt.Errorf("delete selection history event: %w", err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit selection history delete: %w", err) + } + return nil +} + +// ListPage returns a stable request-time page and its total row count. +func (s *Store) ListPage(ctx context.Context, page, pageSize int) ([]Event, int, error) { + return s.listEvents(ctx, page, pageSize, false) +} + +// ListAll returns one consistent snapshot for sorting the complete history in the GUI. +func (s *Store) ListAll(ctx context.Context) ([]Event, error) { + events, _, err := s.listEvents(ctx, 0, 0, true) + return events, err +} + +func (s *Store) listEvents(ctx context.Context, page, pageSize int, all bool) ([]Event, int, error) { + if s == nil || s.db == nil { + return nil, 0, errors.New("selection history database is unavailable") + } + release, err := s.Retain() + if err != nil { + return nil, 0, err + } + defer release() + if !all && (page < 0 || pageSize < 1 || pageSize > pageSizeLimit) { + return nil, 0, errors.New("invalid selection history page") + } + tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return nil, 0, fmt.Errorf("begin selection history read: %w", err) + } + defer tx.Rollback() + var total int + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM selection_events`).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count selection history events: %w", err) + } + query := ` + WITH page_events AS ( + SELECT id, connection_id, requested_at_ns, dialog_opened_at_ns, resolved_at_ns, selected_at_ns, + outcome, target_host_fingerprint, selected_key_fingerprint, + selected_key_algorithm, selected_key_blob, selected_key_comment + FROM selection_events + ORDER BY requested_at_ns DESC, id DESC` + var args []any + if !all { + query += ` LIMIT ? OFFSET ?` + args = append(args, pageSize, page*pageSize) + } + query += ` + ) + SELECT e.id, e.connection_id, e.requested_at_ns, e.dialog_opened_at_ns, e.resolved_at_ns, + e.selected_at_ns, e.outcome, e.target_host_fingerprint, e.selected_key_fingerprint, + e.selected_key_algorithm, e.selected_key_blob, e.selected_key_comment, + h.ordinal, h.key_algorithm, h.host_key_fingerprint, h.is_forwarding, h.known_hosts_hints + FROM page_events e + LEFT JOIN selection_host_hops h ON h.event_id = e.id + ORDER BY e.requested_at_ns DESC, e.id DESC, h.ordinal` + rows, err := tx.QueryContext(ctx, query, args...) + if err != nil { + return nil, 0, fmt.Errorf("list selection history events: %w", err) + } + var events []Event + var current *Event + for rows.Next() { + var event Event + var requestedAt, resolvedAt int64 + var dialogOpenedAt, selectedAt sql.NullInt64 + var hopOrdinal, isForwarding sql.NullInt64 + var hopAlgorithm, hopFingerprint, hints sql.NullString + if err := rows.Scan( + &event.ID, &event.ConnectionID, &requestedAt, &dialogOpenedAt, &resolvedAt, &selectedAt, + &event.Outcome, &event.TargetHostFingerprint, &event.SelectedKeyFingerprint, + &event.SelectedKeyAlgorithm, &event.SelectedKeyBlob, &event.SelectedKeyComment, + &hopOrdinal, &hopAlgorithm, &hopFingerprint, &isForwarding, &hints, + ); err != nil { + _ = rows.Close() + return nil, 0, fmt.Errorf("read selection history event: %w", err) + } + if current == nil || current.ID != event.ID { + event.RequestedAt = time.Unix(0, requestedAt).UTC() + event.ResolvedAt = time.Unix(0, resolvedAt).UTC() + if dialogOpenedAt.Valid { + event.DialogOpenedAt = time.Unix(0, dialogOpenedAt.Int64).UTC() + } + if selectedAt.Valid { + event.SelectedAt = time.Unix(0, selectedAt.Int64).UTC() + } + event.HostHops = make([]HostHop, 0) + events = append(events, event) + current = &events[len(events)-1] + } + if hopOrdinal.Valid { + var knownHosts []string + if err := json.Unmarshal([]byte(hints.String), &knownHosts); err != nil { + _ = rows.Close() + return nil, 0, fmt.Errorf("decode selection host hints: %w", err) + } + current.HostHops = append(current.HostHops, HostHop{ + Algorithm: hopAlgorithm.String, Fingerprint: hopFingerprint.String, + IsForwarding: isForwarding.Int64 != 0, KnownHosts: knownHosts, + }) + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, 0, fmt.Errorf("read selection history events: %w", err) + } + if err := rows.Close(); err != nil { + return nil, 0, fmt.Errorf("close selection history event rows: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, 0, fmt.Errorf("finish selection history read: %w", err) + } + return events, total, nil +} + +// ExportCSV writes every event in request-time order, including its full host path as JSON. +func (s *Store) ExportCSV(ctx context.Context, destination io.Writer) error { + if s == nil || s.db == nil { + return errors.New("selection history database is unavailable") + } + release, err := s.Retain() + if err != nil { + return err + } + defer release() + tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return fmt.Errorf("begin selection history export: %w", err) + } + defer tx.Rollback() + rows, err := tx.QueryContext(ctx, ` + SELECT e.id, e.connection_id, e.requested_at_ns, e.dialog_opened_at_ns, e.resolved_at_ns, + e.selected_at_ns, e.outcome, e.target_host_fingerprint, e.selected_key_fingerprint, + e.selected_key_algorithm, e.selected_key_blob, e.selected_key_comment, + h.ordinal, h.key_algorithm, h.host_key_fingerprint, h.is_forwarding, h.known_hosts_hints + FROM selection_events e + LEFT JOIN selection_host_hops h ON h.event_id = e.id + ORDER BY e.requested_at_ns DESC, e.id DESC, h.ordinal`, + ) + if err != nil { + return fmt.Errorf("query selection history export: %w", err) + } + writer := csv.NewWriter(destination) + if err := writer.Write([]string{ + "Requested (Local)", "Target host", "Target host key", "Forwarded", "Key comment", "Key", + "Fingerprint", "Selected at (Local)", "Result", "Event ID", "Connection ID", + "Dialog opened (Local)", "Resolved (Local)", "Target host fingerprint", "Host path (JSON)", + "Selected key algorithm", "Selected public key (Base64)", + }); err != nil { + _ = rows.Close() + return fmt.Errorf("write selection history CSV header: %w", err) + } + var current *Event + flush := func() error { + if current == nil { + return nil + } + path, err := json.Marshal(current.HostHops) + if err != nil { + return fmt.Errorf("encode exported host path: %w", err) + } + return writer.Write([]string{ + csvHistoryTime(current.RequestedAt), csvTargetHostName(*current), csvTargetHostKey(*current), + csvForwardedLabel(current.HostHops), csvSelectedKeyComment(*current), csvSelectedKey(*current), + csvHistoryValue(current.SelectedKeyFingerprint), csvHistoryTime(current.SelectedAt), + csvOutcomeLabel(current.Outcome), strconv.FormatInt(current.ID, 10), + csvHistoryValue(current.ConnectionID), csvHistoryTime(current.DialogOpenedAt), + csvHistoryTime(current.ResolvedAt), csvHistoryValue(current.TargetHostFingerprint), + string(path), csvHistoryValue(current.SelectedKeyAlgorithm), csvSelectedKeyBase64(*current), + }) + } + for rows.Next() { + var event Event + var requestedAt, resolvedAt int64 + var dialogOpenedAt, selectedAt sql.NullInt64 + var hopOrdinal sql.NullInt64 + var hopAlgorithm, hopFingerprint, hints sql.NullString + var isForwarding sql.NullInt64 + if err := rows.Scan( + &event.ID, &event.ConnectionID, &requestedAt, &dialogOpenedAt, &resolvedAt, + &selectedAt, &event.Outcome, &event.TargetHostFingerprint, &event.SelectedKeyFingerprint, + &event.SelectedKeyAlgorithm, &event.SelectedKeyBlob, &event.SelectedKeyComment, &hopOrdinal, &hopAlgorithm, + &hopFingerprint, &isForwarding, &hints, + ); err != nil { + _ = rows.Close() + return fmt.Errorf("read selection history export row: %w", err) + } + if current == nil || current.ID != event.ID { + if err := flush(); err != nil { + _ = rows.Close() + return fmt.Errorf("write selection history CSV row: %w", err) + } + event.RequestedAt = time.Unix(0, requestedAt).UTC() + event.ResolvedAt = time.Unix(0, resolvedAt).UTC() + if dialogOpenedAt.Valid { + event.DialogOpenedAt = time.Unix(0, dialogOpenedAt.Int64).UTC() + } + if selectedAt.Valid { + event.SelectedAt = time.Unix(0, selectedAt.Int64).UTC() + } + event.HostHops = make([]HostHop, 0) + current = &event + } + if hopOrdinal.Valid { + var knownHosts []string + if err := json.Unmarshal([]byte(hints.String), &knownHosts); err != nil { + _ = rows.Close() + return fmt.Errorf("decode exported host hints: %w", err) + } + current.HostHops = append(current.HostHops, HostHop{ + Algorithm: hopAlgorithm.String, Fingerprint: hopFingerprint.String, + IsForwarding: isForwarding.Int64 != 0, KnownHosts: knownHosts, + }) + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return fmt.Errorf("read selection history export: %w", err) + } + if err := rows.Close(); err != nil { + return fmt.Errorf("close selection history export rows: %w", err) + } + if err := flush(); err != nil { + return fmt.Errorf("write final selection history CSV row: %w", err) + } + writer.Flush() + if err := writer.Error(); err != nil { + return fmt.Errorf("flush selection history CSV: %w", err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("finish selection history export: %w", err) + } + return nil +} + +func formatCSVTime(value time.Time) string { + if value.IsZero() { + return "" + } + return value.Local().Format(time.RFC3339Nano) +} + +func csvHistoryTime(value time.Time) string { + if value.IsZero() { + return "-" + } + return formatCSVTime(value) +} + +func csvHistoryValue(value string) string { + if safe := identity.DisplayText(value); safe != "" { + return csvSafeText(safe) + } + return "-" +} + +func csvTargetHostName(event Event) string { + if event.TargetHostFingerprint == "" || len(event.HostHops) == 0 { + return "-" + } + target := event.HostHops[len(event.HostHops)-1] + if target.IsForwarding { + return "-" + } + var names []string + for _, name := range target.KnownHosts { + if safe := identity.DisplayText(name); safe != "" { + names = append(names, safe) + } + } + if len(names) == 0 { + return "-" + } + return csvSafeText(strings.Join(names, ", ")) +} + +func csvTargetHostKey(event Event) string { + if event.TargetHostFingerprint == "" { + return "-" + } + fingerprint := identity.DisplayText(event.TargetHostFingerprint) + for index := len(event.HostHops) - 1; index >= 0; index-- { + hop := event.HostHops[index] + if hop.IsForwarding || hop.Fingerprint != event.TargetHostFingerprint { + continue + } + if algorithm := identity.DisplayText(hop.Algorithm); algorithm != "" { + return csvSafeText(algorithm + " " + fingerprint) + } + break + } + return csvSafeText(fingerprint) +} + +func csvForwardedLabel(hops []HostHop) string { + var forwarded []string + for _, hop := range hops { + if !hop.IsForwarding { + continue + } + key := identity.DisplayText(hop.Fingerprint) + algorithm := identity.DisplayText(hop.Algorithm) + if key == "" { + key = "-" + } else if algorithm != "" { + key = algorithm + " " + key + } + var names []string + for _, name := range hop.KnownHosts { + if safe := identity.DisplayText(name); safe != "" { + names = append(names, safe) + } + } + label := key + if len(names) > 0 { + label = strings.Join(names, ", ") + if key != "-" { + label += " [" + key + "]" + } + } + forwarded = append(forwarded, csvSafeText(label)) + } + if len(forwarded) == 0 { + return "-" + } + return strings.Join(forwarded, " -> ") +} + +func csvSelectedKeyComment(event Event) string { + if event.SelectedKeyFingerprint == "" { + return "-" + } + return csvHistoryValue(event.SelectedKeyComment) +} + +func csvSelectedKey(event Event) string { + if event.SelectedKeyFingerprint == "" || len(event.SelectedKeyBlob) == 0 { + return "-" + } + algorithm := identity.DisplayText(event.SelectedKeyAlgorithm) + key := csvSelectedKeyBase64(event) + if algorithm == "" { + return key + } + return csvSafeText(algorithm + " " + key) +} + +func csvSelectedKeyBase64(event Event) string { + if event.SelectedKeyFingerprint == "" || len(event.SelectedKeyBlob) == 0 { + return "-" + } + return base64.StdEncoding.EncodeToString(event.SelectedKeyBlob) +} + +func csvOutcomeLabel(outcome Outcome) string { + switch outcome { + case OutcomeSelected: + return "Selected" + case OutcomeCancelled: + return "Cancelled" + case OutcomeTimedOut: + return "Timed out" + case OutcomeNoKeys: + return "No keys" + default: + return "Failed" + } +} + +// csvSafeText sanitizes display controls and neutralizes spreadsheet formula prefixes. +func csvSafeText(value string) string { + value = identity.DisplayText(value) + trimmed := strings.TrimLeft(value, " \t\r\n") + if trimmed != "" && strings.ContainsRune("=+-@", rune(trimmed[0])) { + return "'" + value + } + return value +} diff --git a/internal/selector/gui.go b/internal/selector/gui.go index 30831f4..9b5ee5e 100644 --- a/internal/selector/gui.go +++ b/internal/selector/gui.go @@ -9,6 +9,7 @@ import ( "context" "errors" "fmt" + "log/slog" "math" "runtime" "strings" @@ -21,6 +22,7 @@ import ( "github.com/jfut/ssh-keyselect/internal/branding" "github.com/jfut/ssh-keyselect/internal/guitable" "github.com/jfut/ssh-keyselect/internal/identity" + "github.com/jfut/ssh-keyselect/internal/selectionhistory" "github.com/jfut/ssh-keyselect/internal/upstream" ) @@ -33,10 +35,13 @@ type GUISelector struct { initOnce sync.Once stopOnce sync.Once - mu sync.RWMutex - refresh func(context.Context) ([]identity.Identity, error) - parent func() *mygo.Window - windows map[*mygo.Window]struct{} + mu sync.RWMutex + refresh func(context.Context) ([]identity.Identity, error) + parent func() *mygo.Window + windows map[*mygo.Window]struct{} + history *selectionhistory.Store + recordHistory bool + rememberSelection bool } // NewGUISelector creates a selector that is used after MyGo's application loop starts. @@ -58,6 +63,18 @@ func (s *GUISelector) SetWindowProvider(parent func() *mygo.Window) { s.mu.Unlock() } +// SetHistoryOptions controls event recording and per-host key remembrance independently. +func (s *GUISelector) SetHistoryOptions(history *selectionhistory.Store, recordHistory, rememberSelection bool) { + s.mu.Lock() + s.history = history + s.recordHistory = recordHistory + s.rememberSelection = rememberSelection + if !recordHistory && !rememberSelection { + s.history = nil + } + s.mu.Unlock() +} + // Stop cancels pending selection requests when the application is closing. func (s *GUISelector) Stop() { s.init() @@ -76,11 +93,90 @@ func (s *GUISelector) Stop() { } // Select displays the verified SSH host-key path and waits for one selected identity. -func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity, requestContext SelectionContext) ([]identity.Identity, error) { +func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity, requestContext SelectionContext) (selected []identity.Identity, selectionErr error) { + s.init() + s.mu.RLock() + parentProvider, refresh, history := s.parent, s.refresh, s.history + recordHistory, rememberSelection := s.recordHistory, s.rememberSelection + var releaseHistory func() + var historyErr error + if history != nil && (recordHistory || rememberSelection) { + releaseHistory, historyErr = history.Retain() + if historyErr != nil { + history = nil + } + } else { + history = nil + } + s.mu.RUnlock() + if releaseHistory != nil { + defer releaseHistory() + } + if historyErr != nil { + slog.Warn("could not retain GUI selection history", "error", historyErr) + } + event := selectionhistory.Event{ + ConnectionID: requestContext.ConnectionID, + RequestedAt: requestContext.RequestedAt, + Outcome: selectionhistory.OutcomeFailed, + HostHops: selectionHistoryHops(requestContext), + } + if event.RequestedAt.IsZero() { + event.RequestedAt = time.Now() + } + if history != nil { + defer func() { + event.ResolvedAt = time.Now() + selectedSuccessfully := selectionErr == nil && len(selected) > 0 + if selectedSuccessfully { + chosen := selected[0] + event.SelectedAt = event.ResolvedAt + event.SelectedKeyFingerprint = identity.Fingerprint(chosen.Blob) + event.SelectedKeyAlgorithm = chosen.Algorithm + event.SelectedKeyBlob = append([]byte(nil), chosen.Blob...) + event.SelectedKeyComment = chosen.Comment + } + if !recordHistory { + if selectedSuccessfully && rememberSelection { + target := selectionTargetFingerprint(requestContext) + if target != "" { + recordCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := history.RememberSelection(recordCtx, target, event.SelectedKeyFingerprint, event.SelectedAt); err != nil { + slog.Warn("could not remember GUI key selection", "error", err) + } + } + } + return + } + switch { + case selectedSuccessfully: + event.Outcome = selectionhistory.OutcomeSelected + case len(identities) == 0 && selectionErr == nil: + event.Outcome = selectionhistory.OutcomeNoKeys + case errors.Is(selectionErr, context.DeadlineExceeded): + event.Outcome = selectionhistory.OutcomeTimedOut + case errors.Is(selectionErr, context.Canceled), errors.Is(selectionErr, ErrCancelled), selectionErr == nil: + event.Outcome = selectionhistory.OutcomeCancelled + default: + event.Outcome = selectionhistory.OutcomeFailed + } + recordCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var err error + if rememberSelection { + err = history.Record(recordCtx, event) + } else { + err = history.RecordHistory(recordCtx, event) + } + if err != nil { + slog.Warn("could not record GUI selection history", "error", err) + } + }() + } if len(identities) == 0 { return nil, nil } - s.init() select { case <-s.stopped: return nil, ErrCancelled @@ -100,9 +196,6 @@ func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity default: } - s.mu.RLock() - parentProvider, refresh := s.parent, s.refresh - s.mu.RUnlock() var parent *mygo.Window if parentProvider != nil { parent = parentProvider() @@ -111,15 +204,22 @@ func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity defer releasePickerReturnWindow(returnWindow) shownAt := time.Now() offered := append([]identity.Identity(nil), identities...) + selectedIndex := 0 + if rememberSelection { + selectedIndex = guiPreferredSelectionIndex(ctx, history, requestContext, offered) + } picker := &guiPickerState{ ctx: ctx, identities: offered, offered: offered, requestContext: requestContext, detailsText: guiSelectionDetailsText(requestContext, shownAt), shownAt: shownAt, refresh: refresh, - selected: 0, focusFilter: true, + selected: selectedIndex, focusFilter: true, // The current target is the final entry in a multi-host path. detailsScroll: ui.ScrollState{Y: math.MaxFloat32}, } + if selectedIndex > 0 { + picker.tableState.ScrollIntoView(selectedIndex) + } title := fmt.Sprintf("%s [%s - %s]", identitySelectionPrompt, branding.Name, selectionDisplayTime(shownAt)) windowParent, windowModal := pickerWindowOwnership(parent) // Keep five full key rows visible with only a small strip of the sixth row. @@ -168,6 +268,7 @@ func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity s.windows[window] = struct{}{} s.mu.Unlock() } + event.DialogOpenedAt = time.Now() // Show the modal as soon as it is created so its parent cannot stay blocked // if the platform has already delivered MyGo's one-shot ready event. window.Show() @@ -252,6 +353,49 @@ func (s *GUISelector) Select(ctx context.Context, identities []identity.Identity return []identity.Identity{selection.identity}, nil } +func selectionHistoryHops(requestContext SelectionContext) []selectionhistory.HostHop { + hops := make([]selectionhistory.HostHop, len(requestContext.HostBindings)) + for index, binding := range requestContext.HostBindings { + hops[index] = selectionhistory.HostHop{ + Algorithm: binding.Algorithm, Fingerprint: binding.Fingerprint, + IsForwarding: binding.IsForwarding, KnownHosts: append([]string(nil), binding.KnownHosts...), + } + } + return hops +} + +func selectionTargetFingerprint(requestContext SelectionContext) string { + if len(requestContext.HostBindings) == 0 { + return "" + } + target := requestContext.HostBindings[len(requestContext.HostBindings)-1] + if target.IsForwarding { + return "" + } + return target.Fingerprint +} + +func guiPreferredSelectionIndex(ctx context.Context, history *selectionhistory.Store, requestContext SelectionContext, identities []identity.Identity) int { + target := selectionTargetFingerprint(requestContext) + if history == nil || target == "" { + return 0 + } + preferred, ok, err := history.PreferredSelection(ctx, target) + if err != nil { + slog.Warn("could not read GUI selection preference", "error", err) + return 0 + } + if !ok { + return 0 + } + for index, id := range identities { + if identity.Fingerprint(id.Blob) == preferred { + return index + } + } + return 0 +} + func (s *GUISelector) init() { s.initOnce.Do(func() { if s.queue == nil { diff --git a/internal/selector/selector.go b/internal/selector/selector.go index 880a0dc..856e01b 100644 --- a/internal/selector/selector.go +++ b/internal/selector/selector.go @@ -34,6 +34,8 @@ type HostBinding struct { // SelectionContext carries verified connection details to the identity picker. type SelectionContext struct { HostBindings []HostBinding + ConnectionID string + RequestedAt time.Time } type selectionDetail struct { diff --git a/scripts/generate-credits.sh b/scripts/generate-credits.sh index fc25801..4de865a 100644 --- a/scripts/generate-credits.sh +++ b/scripts/generate-credits.sh @@ -14,15 +14,23 @@ mkdir -p "$credits_workdir/bin" # Scan each released operating system with the GUI build tag so platform-specific MyGo dependencies are included. GOBIN="$credits_workdir/bin" go install github.com/google/go-licenses@v1.6.0 go_licenses="$credits_workdir/bin/go-licenses" +sqlite_wasm_module="github.com/ncruces/go-sqlite3-wasm/v6" +sqlite_wasm_version="$(go list -m -f '{{.Version}}' "$sqlite_wasm_module")" +gomodcache="$(go env GOMODCACHE)" +license_ignores=(--ignore "$sqlite_wasm_module") for target_os in linux darwin windows; do - GOOS="$target_os" GOFLAGS=-tags=gui "$go_licenses" csv ./... > "$credits_workdir/$target_os.csv" - GOOS="$target_os" GOFLAGS=-tags=gui "$go_licenses" save ./... --save_path="$credits_workdir/save-$target_os" --force + GOOS="$target_os" GOFLAGS=-tags=gui "$go_licenses" csv ./... "${license_ignores[@]}" > "$credits_workdir/$target_os.csv" + GOOS="$target_os" GOFLAGS=-tags=gui "$go_licenses" save ./... --save_path="$credits_workdir/save-$target_os" --force "${license_ignores[@]}" done root_module="$(go list -m)" GOFLAGS=-tags=gui go list -m -f '{{printf "%s\t%s" .Path .Version}}' all > "$credits_workdir/modules.tsv" -cat "$credits_workdir/linux.csv" "$credits_workdir/darwin.csv" "$credits_workdir/windows.csv" | +cat "$credits_workdir/linux.csv" "$credits_workdir/darwin.csv" "$credits_workdir/windows.csv" > "$credits_workdir/licenses.csv" +printf '%s,%s,%s\n' "$sqlite_wasm_module" "https://github.com/ncruces/go-sqlite3-wasm/blob/$sqlite_wasm_version/LICENSE" "MIT-0" >> "$credits_workdir/licenses.csv" +sort -u "$credits_workdir/licenses.csv" > "$credits_workdir/sorted-licenses.csv" + +cat "$credits_workdir/sorted-licenses.csv" | sort -u > "$credits_workdir/licenses.csv" # Collapse platform-specific package imports to one entry per Go module. @@ -73,13 +81,17 @@ awk -v root="$root_module" ' while IFS=$'\t' read -r module version license url; do printf '\n\n%s %s: %s\n%s\n----------------------------------------------------------------\n' "$module" "$version" "$license" "$url" license_file="" - for target_os in linux darwin windows; do - module_dir="$credits_workdir/save-$target_os/$module" - if [[ -d "$module_dir" ]]; then - license_file="$(find "$module_dir" -type f \( -iname 'LICENSE' -o -iname 'LICENSE.*' -o -iname 'COPYING' -o -iname 'COPYING.*' \) -print | sort | head -n 1)" - if [[ -n "$license_file" ]]; then break; fi - fi - done + if [[ "$module" == "$sqlite_wasm_module" ]]; then + license_file="$gomodcache/$module@$version/LICENSE" + else + for target_os in linux darwin windows; do + module_dir="$credits_workdir/save-$target_os/$module" + if [[ -d "$module_dir" ]]; then + license_file="$(find "$module_dir" -type f \( -iname 'LICENSE' -o -iname 'LICENSE.*' -o -iname 'COPYING' -o -iname 'COPYING.*' \) -print | sort | head -n 1)" + if [[ -n "$license_file" ]]; then break; fi + fi + done + fi if [[ -z "$license_file" ]]; then printf 'Could not find license text for %s\n' "$module" >&2 exit 1