commit 8266ca4000b3f0fd25a1f5364a4ff7e6b4018fe0 Author: Aleksey Shakhmatov Date: Fri Oct 30 15:05:18 2026 +0300 Add ysm: TUI for managing SSH keys with YubiKey support Lists keys in ~/.ssh, generates regular and FIDO2 (YubiKey) keys, imports resident keys, manages ssh-agent, copies/installs public keys. Passphrases and PINs are handled by ssh-keygen in the handed-over terminal. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..287cdbb --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +ysm diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f772996 --- /dev/null +++ b/go.mod @@ -0,0 +1,30 @@ +module ysm + +go 1.27.3 + +require ( + github.com/charmbracelet/bubbles v0.21.0 + github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/lipgloss v1.1.0 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/x/ansi v0.10.1 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.36.0 // indirect + golang.org/x/text v0.3.8 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..ee425d3 --- /dev/null +++ b/go.sum @@ -0,0 +1,47 @@ +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs= +github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= +github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= +golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= diff --git a/keys.go b/keys.go new file mode 100644 index 0000000..dce57cc --- /dev/null +++ b/keys.go @@ -0,0 +1,140 @@ +package main + +import ( + "encoding/base64" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" +) + +// Key is one public key in the ssh dir, plus its private half if present. +type Key struct { + Name string + Path string // private key path + PubPath string + HasPrivate bool + Bits string + Fingerprint string + Comment string + Type string // e.g. ED25519, RSA, ED25519-SK + InAgent bool +} + +func (k Key) Hardware() bool { return strings.HasSuffix(k.Type, "-SK") } + +func sshDir() string { + if d := os.Getenv("YSM_SSH_DIR"); d != "" { + return d + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".ssh") +} + +// parseFingerprint parses `ssh-keygen -l` / `ssh-add -l` lines: +// "256 SHA256:abc user@host (ED25519)". +func parseFingerprint(line string) (bits, fp, comment, typ string, ok bool) { + f := strings.Fields(line) + if len(f) < 3 { + return "", "", "", "", false + } + return f[0], f[1], strings.Join(f[2:len(f)-1], " "), strings.Trim(f[len(f)-1], "()"), true +} + +func agentFingerprints() map[string]bool { + out, _ := exec.Command("ssh-add", "-l").Output() // exits 1 when agent is empty + m := map[string]bool{} + for _, l := range strings.Split(string(out), "\n") { + if _, fp, _, _, ok := parseFingerprint(l); ok { + m[fp] = true + } + } + return m +} + +func loadKeys(dir string) ([]Key, error) { + pubs, err := filepath.Glob(filepath.Join(dir, "*.pub")) + if err != nil { + return nil, err + } + agent := agentFingerprints() + var keys []Key + for _, pub := range pubs { + out, err := exec.Command("ssh-keygen", "-l", "-f", pub).Output() + if err != nil { + continue // not a key file + } + bits, fp, comment, typ, ok := parseFingerprint(strings.TrimSpace(string(out))) + if !ok { + continue + } + priv := strings.TrimSuffix(pub, ".pub") + _, perr := os.Stat(priv) + keys = append(keys, Key{ + Name: filepath.Base(priv), Path: priv, PubPath: pub, HasPrivate: perr == nil, + Bits: bits, Fingerprint: fp, Comment: comment, Type: typ, InAgent: agent[fp], + }) + } + sort.Slice(keys, func(i, j int) bool { return keys[i].Name < keys[j].Name }) + return keys, nil +} + +func validateName(dir, name string) error { + if name == "" || name != filepath.Base(name) || strings.HasPrefix(name, ".") { + return errors.New("name must be a plain file name") + } + if strings.HasSuffix(name, ".pub") { + return errors.New("name must not end in .pub") + } + for _, p := range []string{name, name + ".pub"} { + if _, err := os.Stat(filepath.Join(dir, p)); err == nil { + return fmt.Errorf("%s already exists", p) + } + } + return nil +} + +// yubikeyStatus returns a description of the first attached YubiKey, or "". +func yubikeyStatus() string { + if _, err := exec.LookPath("ykman"); err == nil { + out, _ := exec.Command("ykman", "list").Output() + return strings.TrimSpace(strings.SplitN(string(out), "\n", 2)[0]) + } + out, _ := exec.Command("lsusb").Output() + for _, l := range strings.Split(string(out), "\n") { + if strings.Contains(strings.ToLower(l), "yubico") { + return "YubiKey (" + strings.TrimSpace(l[strings.Index(l, "ID "):]) + ")" + } + } + return "" +} + +// interactive wraps a command so its output stays visible when it fails; +// the TUI hands the terminal over so ssh-keygen can prompt for passphrase/PIN/touch. +func interactive(dir, name string, args ...string) *exec.Cmd { + script := `"$@" || { s=$?; printf '\nPress Enter to return to ysm…'; read _; exit $s; }` + c := exec.Command("sh", append([]string{"-c", script, "sh", name}, args...)...) + c.Dir = dir + // The terminal is ours to hand over, so prompt there instead of in a GUI askpass popup. + c.Env = append(os.Environ(), "SSH_ASKPASS_REQUIRE=never") + return c +} + +func copyToClipboard(text string) string { + for _, c := range [][]string{{"wl-copy"}, {"xclip", "-selection", "clipboard"}, {"xsel", "-ib"}, {"pbcopy"}} { + if _, err := exec.LookPath(c[0]); err != nil { + continue + } + cmd := exec.Command(c[0], c[1:]...) + cmd.Stdin = strings.NewReader(text) + if cmd.Run() == nil { + return c[0] + } + } + // OSC 52: asks the terminal itself to set the clipboard (works over ssh too). + fmt.Fprintf(os.Stdout, "\x1b]52;c;%s\a", base64.StdEncoding.EncodeToString([]byte(text))) + return "terminal (OSC 52)" +} diff --git a/keys_test.go b/keys_test.go new file mode 100644 index 0000000..e16f3a6 --- /dev/null +++ b/keys_test.go @@ -0,0 +1,42 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestParseFingerprint(t *testing.T) { + bits, fp, comment, typ, ok := parseFingerprint("256 SHA256:abc me@box two (ED25519-SK)") + if !ok || bits != "256" || fp != "SHA256:abc" || comment != "me@box two" || typ != "ED25519-SK" { + t.Fatalf("got %q %q %q %q %v", bits, fp, comment, typ, ok) + } + if _, _, _, _, ok := parseFingerprint(""); ok { + t.Fatal("empty line parsed") + } +} + +func TestLoadKeysAndValidate(t *testing.T) { + dir := t.TempDir() + out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "test@ysm", "-f", filepath.Join(dir, "id_test")).CombinedOutput() + if err != nil { + t.Fatalf("%v: %s", err, out) + } + os.WriteFile(filepath.Join(dir, "junk.pub"), []byte("not a key"), 0o600) + + keys, err := loadKeys(dir) + if err != nil || len(keys) != 1 { + t.Fatalf("keys=%v err=%v", keys, err) + } + k := keys[0] + if k.Name != "id_test" || k.Type != "ED25519" || k.Comment != "test@ysm" || !k.HasPrivate || k.Hardware() { + t.Fatalf("bad key %+v", k) + } + + for name, wantErr := range map[string]bool{"id_test": true, "": true, "../x": true, "a.pub": true, ".hidden": true, "id_new": false} { + if err := validateName(dir, name); (err != nil) != wantErr { + t.Errorf("validateName(%q) = %v", name, err) + } + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..1f5a7f3 --- /dev/null +++ b/main.go @@ -0,0 +1,548 @@ +package main + +import ( + "fmt" + "os" + "os/exec" + "os/user" + "path/filepath" + "strings" + "time" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +var ( + accent = lipgloss.AdaptiveColor{Light: "#5A3FD9", Dark: "#A78BFA"} + muted = lipgloss.AdaptiveColor{Light: "#6B7280", Dark: "#9CA3AF"} + good = lipgloss.AdaptiveColor{Light: "#047857", Dark: "#34D399"} + bad = lipgloss.AdaptiveColor{Light: "#B91C1C", Dark: "#F87171"} + titleSt = lipgloss.NewStyle().Bold(true).Foreground(accent) + mutedSt = lipgloss.NewStyle().Foreground(muted) + goodSt = lipgloss.NewStyle().Foreground(good) + badSt = lipgloss.NewStyle().Foreground(bad) + selSt = lipgloss.NewStyle().Bold(true).Foreground(accent) + badgeSt = lipgloss.NewStyle().Foreground(lipgloss.Color("#FFFFFF")).Background(accent).Padding(0, 1) + boxSt = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(accent).Padding(1, 2) + keyHelpS = lipgloss.NewStyle().Foreground(accent).Bold(true) +) + +type mode int + +const ( + listMode mode = iota + detailMode + formMode + confirmMode +) + +type ( + keysMsg struct { + keys []Key + err error + } + ykMsg string + tickMsg struct{} + detailMsg string + execMsg struct { + what string + err error + } +) + +// field is a text input, or a choice when options is set. +type field struct { + label string + input textinput.Model + options []string + sel int +} + +func (f field) value() string { + if f.options != nil { + return f.options[f.sel] + } + return strings.TrimSpace(f.input.Value()) +} + +type form struct { + kind, title, hint string + fields []field + focus int + err string +} + +func textField(label, placeholder, value string) field { + ti := textinput.New() + ti.Placeholder = placeholder + ti.SetValue(value) + ti.Prompt = "" + ti.CharLimit = 128 + ti.Width = 40 + return field{label: label, input: ti} +} + +func (f *form) setFocus(i int) { + f.focus = (i + len(f.fields)) % len(f.fields) + for j := range f.fields { + if f.fields[j].options != nil { + continue // choice fields have no initialised textinput + } + if j == f.focus { + f.fields[j].input.Focus() + } else { + f.fields[j].input.Blur() + } + } +} + +type model struct { + dir string + keys []Key + cursor int + mode mode + form *form + detail string + yubikey string + busy bool // an external command owns the terminal / YubiKey + status string + statusB bool // status is an error + width int +} + +func defaultComment() string { + u, _ := user.Current() + h, _ := os.Hostname() + if u == nil { + return h + } + return u.Username + "@" + h +} + +func (m model) loadCmd() tea.Cmd { + return func() tea.Msg { k, err := loadKeys(m.dir); return keysMsg{k, err} } +} + +func ykCmd() tea.Msg { return ykMsg(yubikeyStatus()) } + +func tick() tea.Cmd { return tea.Tick(2*time.Second, func(time.Time) tea.Msg { return tickMsg{} }) } + +func (m model) Init() tea.Cmd { return tea.Batch(m.loadCmd(), ykCmd, tick()) } + +func (m *model) setStatus(s string, isErr bool) { m.status, m.statusB = s, isErr } + +func (m model) selected() *Key { + if m.cursor < len(m.keys) { + return &m.keys[m.cursor] + } + return nil +} + +func (m *model) run(what string, c *exec.Cmd) tea.Cmd { + m.busy = true + m.setStatus(what+"…", false) + return tea.ExecProcess(c, func(err error) tea.Msg { return execMsg{what, err} }) +} + +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + case keysMsg: + if msg.err != nil { + m.setStatus(msg.err.Error(), true) + } + m.keys = msg.keys + m.cursor = min(m.cursor, max(len(m.keys)-1, 0)) + case tickMsg: + if m.busy { // don't poke the YubiKey while ssh-keygen waits for touch + return m, tick() + } + return m, tea.Batch(ykCmd, tick()) + case ykMsg: + was := m.yubikey + m.yubikey = string(msg) + if was == "" && m.yubikey != "" { + m.setStatus("YubiKey attached — press y to create a key on it", false) + } else if was != "" && m.yubikey == "" { + m.setStatus("YubiKey removed", false) + } + case detailMsg: + m.detail, m.mode = string(msg), detailMode + case execMsg: + m.busy = false + if msg.err != nil { + m.setStatus("✗ "+msg.what+" failed", true) + } else { + m.setStatus("✓ "+msg.what+" done", false) + } + return m, m.loadCmd() + case tea.KeyMsg: + if msg.String() == "ctrl+c" { + return m, tea.Quit + } + switch m.mode { + case formMode: + return m.updateForm(msg) + case confirmMode: + return m.updateConfirm(msg) + case detailMode: + switch msg.String() { + case "esc", "q", "enter", "backspace": + m.mode = listMode + case "c": + m.copyPub() + } + return m, nil + } + return m.updateList(msg) + } + return m, nil +} + +func (m *model) copyPub() { + k := m.selected() + if k == nil { + return + } + b, err := os.ReadFile(k.PubPath) + if err != nil { + m.setStatus(err.Error(), true) + return + } + m.setStatus("✓ copied "+k.Name+".pub via "+copyToClipboard(strings.TrimSpace(string(b))), false) +} + +func (m model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + k := m.selected() + needKey := func() bool { + if k == nil { + m.setStatus("no key selected", true) + } + return k != nil + } + needPriv := func() bool { + if needKey() && !k.HasPrivate { + m.setStatus(k.Name+" has no private key file here", true) + return false + } + return k != nil + } + switch msg.String() { + case "q", "esc": + return m, tea.Quit + case "up", "k": + m.cursor = max(m.cursor-1, 0) + case "down", "j": + m.cursor = min(m.cursor+1, max(len(m.keys)-1, 0)) + case "home", "g": + m.cursor = 0 + case "end", "G": + m.cursor = max(len(m.keys)-1, 0) + case "r": + m.setStatus("refreshed", false) + return m, tea.Batch(m.loadCmd(), ykCmd) + case "enter": + if needKey() { + pub := k.PubPath + return m, func() tea.Msg { + out, _ := exec.Command("ssh-keygen", "-lv", "-f", pub).CombinedOutput() + b, _ := os.ReadFile(pub) + return detailMsg(string(out) + "\n" + strings.TrimSpace(string(b))) + } + } + case "n": + m.form = &form{kind: "new", title: "New SSH key", hint: "ssh-keygen will ask for a passphrase next (recommended).", + fields: []field{ + {label: "Type", options: []string{"ed25519", "rsa", "ecdsa"}}, + textField("Name", "id_ed25519", ""), + textField("Comment", "", defaultComment()), + }} + m.form.setFocus(0) + m.mode = formMode + case "y": + if m.yubikey == "" { + m.setStatus("insert your YubiKey first", true) + break + } + m.form = &form{kind: "yubikey", title: "New key on YubiKey " + badgeSt.Render(m.yubikey), + hint: "Next: enter your FIDO2 PIN if asked, then touch the YubiKey when it blinks.\n" + + "Resident keys live on the YubiKey and can be restored on any machine with i.\n" + + "ed25519-sk needs firmware 5.2.3+; use ecdsa-sk on older keys.", + fields: []field{ + {label: "Type", options: []string{"ed25519-sk", "ecdsa-sk"}}, + textField("Name", "id_ed25519_sk", ""), + textField("Comment", "", defaultComment()), + {label: "Store on YubiKey (resident)", options: []string{"yes", "no"}}, + {label: "Require PIN on every use", options: []string{"no", "yes"}}, + }} + m.form.setFocus(0) + m.mode = formMode + case "i": + if m.yubikey == "" { + m.setStatus("insert your YubiKey first", true) + break + } + // -K writes id_*_sk_rk_* files into the working directory. + return m, m.run("import keys from YubiKey", interactive(m.dir, "ssh-keygen", "-K")) + case "a": + if needPriv() { + return m, m.run("add "+k.Name+" to agent", interactive(m.dir, "ssh-add", k.Path)) + } + case "x": + if needKey() { + return m, m.run("remove "+k.Name+" from agent", interactive(m.dir, "ssh-add", "-d", k.PubPath)) + } + case "c": + m.copyPub() + case "p": + if needPriv() { + return m, m.run("change passphrase of "+k.Name, interactive(m.dir, "ssh-keygen", "-p", "-f", k.Path)) + } + case "s": + if needKey() { + m.form = &form{kind: "copyid", title: "Install " + k.Name + ".pub on a server", + hint: "Runs ssh-copy-id; you'll log in once with your current credentials.", + fields: []field{textField("Server (user@host)", "user@example.com", "")}} + m.form.setFocus(0) + m.mode = formMode + } + case "d": + if needKey() { + m.mode = confirmMode + } + } + return m, nil +} + +func (m model) updateConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + m.mode = listMode + if msg.String() != "y" { + m.setStatus("delete cancelled", false) + return m, nil + } + k := m.selected() + for _, p := range []string{k.Path, k.PubPath} { + if err := os.Remove(p); err != nil && !os.IsNotExist(err) { + m.setStatus(err.Error(), true) + return m, m.loadCmd() + } + } + m.setStatus("✓ deleted "+k.Name, false) + return m, m.loadCmd() +} + +func (m model) updateForm(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + f := m.form + cur := &f.fields[f.focus] + switch msg.String() { + case "esc": + m.mode, m.form = listMode, nil + return m, nil + case "tab", "down": + f.setFocus(f.focus + 1) + return m, nil + case "shift+tab", "up": + f.setFocus(f.focus - 1) + return m, nil + case "enter": + return m.submit() + } + if cur.options != nil { + switch msg.String() { + case "left", "h": + cur.sel = (cur.sel - 1 + len(cur.options)) % len(cur.options) + case "right", "l", " ": + cur.sel = (cur.sel + 1) % len(cur.options) + } + return m, nil + } + var cmd tea.Cmd + cur.input, cmd = cur.input.Update(msg) + return m, cmd +} + +func (m model) submit() (tea.Model, tea.Cmd) { + f := m.form + v := make([]string, len(f.fields)) + for i, fl := range f.fields { + v[i] = fl.value() + } + switch f.kind { + case "new", "yubikey": + typ, name, comment := v[0], v[1], v[2] + if name == "" { + name = "id_" + strings.ReplaceAll(typ, "-", "_") + } + if err := validateName(m.dir, name); err != nil { + f.err = err.Error() + return m, nil + } + args := []string{"-t", typ, "-C", comment, "-f", filepath.Join(m.dir, name)} + if typ == "rsa" { + args = append(args, "-b", "4096") + } + if f.kind == "yubikey" { + if v[3] == "yes" { + args = append(args, "-O", "resident", "-O", "application=ssh:"+name) + } + if v[4] == "yes" { + args = append(args, "-O", "verify-required") + } + } + m.mode, m.form = listMode, nil + return m, m.run("generate "+name, interactive(m.dir, "ssh-keygen", args...)) + case "copyid": + if v[0] == "" || strings.HasPrefix(v[0], "-") { + f.err = "enter a server like user@host" + return m, nil + } + k := m.selected() + m.mode, m.form = listMode, nil + return m, m.run("install "+k.Name+" on "+v[0], interactive(m.dir, "ssh-copy-id", "-i", k.PubPath, v[0])) + } + return m, nil +} + +func (m model) View() string { + var b strings.Builder + yk := badSt.Render("○ no YubiKey") + if m.yubikey != "" { + yk = goodSt.Render("● " + m.yubikey) + } + b.WriteString(titleSt.Render("🔑 ysm") + mutedSt.Render(" — SSH keys in "+m.dir) + " " + yk + "\n\n") + + switch m.mode { + case detailMode: + k := m.selected() + b.WriteString(boxSt.Render(titleSt.Render(k.Name) + "\n" + mutedSt.Render(k.Path) + "\n\n" + + lipgloss.NewStyle().Width(max(m.width-8, 40)).Render(m.detail))) + b.WriteString("\n" + help("c", "copy public key", "esc", "back")) + return b.String() + case formMode: + b.WriteString(m.viewForm()) + return b.String() + } + + if len(m.keys) == 0 { + b.WriteString(mutedSt.Render(" No keys yet. Press n to create one, or y to create one on your YubiKey.") + "\n") + } + nameW := 4 + for _, k := range m.keys { + nameW = max(nameW, len(k.Name)) + } + for i, k := range m.keys { + cursor, st := " ", lipgloss.NewStyle() + if i == m.cursor { + cursor, st = selSt.Render("▸ "), selSt + } + flags := "" + if k.Hardware() { + flags += badgeSt.Render("YubiKey") + " " + } + if k.InAgent { + flags += goodSt.Render("● agent") + " " + } + if !k.HasPrivate { + flags += mutedSt.Render("pub only") + } + fmt.Fprintf(&b, "%s%s %s %s %s %s\n", cursor, + st.Render(fmt.Sprintf("%-*s", nameW, k.Name)), + fmt.Sprintf("%-11s", k.Type+" "+bitsIfRSA(k)), + mutedSt.Render(shortFP(k.Fingerprint)), + mutedSt.Render(fmt.Sprintf("%-22.22s", k.Comment)), + flags) + } + if m.mode == confirmMode { + b.WriteString("\n" + badSt.Render(fmt.Sprintf("Delete %s and %s.pub permanently? (y/N)", m.selected().Name, m.selected().Name)) + "\n") + } else if m.status != "" { + st := goodSt + if m.statusB { + st = badSt + } + b.WriteString("\n" + st.Render(m.status) + "\n") + } else { + b.WriteString("\n\n") + } + ykHelp := mutedSt.Render("y new YubiKey key • i import from YubiKey") + if m.yubikey != "" { + ykHelp = help("y", "new YubiKey key", "i", "import from YubiKey") + } + b.WriteString("\n" + help("↑↓", "move", "enter", "details", "n", "new key") + " • " + ykHelp + "\n" + + help("a", "add to agent", "x", "remove from agent", "c", "copy pub", "s", "send to server") + "\n" + + help("p", "passphrase", "d", "delete", "r", "refresh", "q", "quit")) + return b.String() +} + +func (m model) viewForm() string { + f := m.form + var b strings.Builder + b.WriteString(titleSt.Render(f.title) + "\n\n") + for i, fl := range f.fields { + label := fmt.Sprintf("%-28s", fl.label) + if i == f.focus { + label = selSt.Render("▸ " + label) + } else { + label = mutedSt.Render(" " + label) + } + val := " " + fl.input.View() + if fl.options != nil { + var opts []string + for j, o := range fl.options { + if j == fl.sel { + opts = append(opts, badgeSt.Render(o)) + } else { + opts = append(opts, mutedSt.Render(" "+o+" ")) + } + } + val = strings.Join(opts, " ") + } + b.WriteString(label + val + "\n") + } + if f.err != "" { + b.WriteString("\n" + badSt.Render("✗ "+f.err)) + } + b.WriteString("\n" + mutedSt.Render(f.hint) + "\n\n" + + help("tab/↑↓", "next field", "←→/space", "change option", "enter", "create", "esc", "cancel")) + return boxSt.Render(b.String()) +} + +func help(pairs ...string) string { + var parts []string + for i := 0; i+1 < len(pairs); i += 2 { + parts = append(parts, keyHelpS.Render(pairs[i])+" "+mutedSt.Render(pairs[i+1])) + } + return strings.Join(parts, mutedSt.Render(" • ")) +} + +func shortFP(fp string) string { + if len(fp) > 19 { + return fp[:19] + "…" + } + return fmt.Sprintf("%-20s", fp) +} + +func bitsIfRSA(k Key) string { + if k.Type == "RSA" { + return k.Bits + } + return "" +} + +func main() { + if _, err := exec.LookPath("ssh-keygen"); err != nil { + fmt.Fprintln(os.Stderr, "ysm needs OpenSSH (ssh-keygen) installed") + os.Exit(1) + } + dir := sshDir() + if err := os.MkdirAll(dir, 0o700); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + if _, err := tea.NewProgram(model{dir: dir}, tea.WithAltScreen()).Run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +}