Files
ysm/keys.go
T
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

199 lines
5.7 KiB
Go

package main
import (
"encoding/base64"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"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
}
// agentRunning reports whether SSH_AUTH_SOCK points at a live agent
// (ssh-add -l exits 1 for an empty agent, 2 when it can't connect).
func agentRunning() bool {
err := exec.Command("ssh-add", "-l").Run()
var ee *exec.ExitError
return err == nil || errors.As(err, &ee) && ee.ExitCode() == 1
}
// agentSocket is where ysm starts its own agent, so later runs can find it again.
func agentSocket() string {
dir := os.Getenv("XDG_RUNTIME_DIR")
if dir == "" {
dir = sshDir()
}
return filepath.Join(dir, "ysm-agent.sock")
}
// connectAgent uses the current agent, or falls back to ysm's own if it is alive.
func connectAgent() bool {
if agentRunning() {
return true
}
old, had := os.LookupEnv("SSH_AUTH_SOCK")
os.Setenv("SSH_AUTH_SOCK", agentSocket())
if agentRunning() {
return true
}
if had {
os.Setenv("SSH_AUTH_SOCK", old)
} else {
os.Unsetenv("SSH_AUTH_SOCK")
}
return false
}
// ensureAgent connects to an agent, starting ysm's own one if none is running.
func ensureAgent() (started bool, err error) {
if connectAgent() {
return false, nil
}
sock := agentSocket()
os.Remove(sock) // stale socket left by a dead agent; connectAgent proved nothing listens
out, err := exec.Command("ssh-agent", "-s", "-a", sock).Output()
if err != nil {
var ee *exec.ExitError
if errors.As(err, &ee) && len(ee.Stderr) > 0 {
err = errors.New(strings.TrimSpace(string(ee.Stderr)))
}
return false, fmt.Errorf("start ssh-agent: %w", err)
}
os.Setenv("SSH_AUTH_SOCK", sock)
if m := regexp.MustCompile(`SSH_AGENT_PID=(\d+)`).FindSubmatch(out); m != nil {
os.Setenv("SSH_AGENT_PID", string(m[1]))
}
return true, nil
}
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)"
}