Files
Aleksey ShakhmatovandClaude Opus 5.5 f680bf3b9d Start ssh-agent when adding a key and none is running
ysm starts its own agent on $XDG_RUNTIME_DIR/ysm-agent.sock, reconnects
to it on later runs, and shows agent status in the header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:18:59 +03:00

577 lines
15 KiB
Go

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
agent bool
err error
}
agentMsg struct {
started bool
err error
key Key
}
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
agent bool
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, agentRunning(), 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, m.agent = msg.keys, msg.agent
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 agentMsg:
if msg.err != nil {
m.setStatus("✗ "+msg.err.Error(), true)
return m, nil
}
m.agent = true
what := "add " + msg.key.Name + " to agent"
if msg.started {
what = "start ssh-agent and " + what
}
return m, m.run(what, interactive(m.dir, "ssh-add", msg.key.Path))
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() {
key := *k
return m, func() tea.Msg { started, err := ensureAgent(); return agentMsg{started, err, key} }
}
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)
}
agent := badSt.Render("○ no ssh-agent") + mutedSt.Render(" (a starts one)")
if m.agent {
agent = goodSt.Render("● ssh-agent")
if sock := os.Getenv("SSH_AUTH_SOCK"); sock == agentSocket() {
// ysm's own agent: the user's shell needs this to use it.
agent += mutedSt.Render(" export SSH_AUTH_SOCK=" + sock)
}
}
b.WriteString(titleSt.Render("🔑 ysm") + mutedSt.Render(" — SSH keys in "+m.dir) + " " + yk + "\n" + agent + "\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)
}
connectAgent()
if _, err := tea.NewProgram(model{dir: dir}, tea.WithAltScreen()).Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}