1package sshutils23import (4 "bytes"5 "context"67 "github.com/charmbracelet/ssh"8 gossh "golang.org/x/crypto/ssh"9)1011// ParseAuthorizedKey parses an authorized key string into a public key.12func ParseAuthorizedKey(ak string) (gossh.PublicKey, string, error) {13 pk, c, _, _, err := gossh.ParseAuthorizedKey([]byte(ak))14 return pk, c, err15}1617// MarshalAuthorizedKey marshals a public key into an authorized key string.18//19// This is the inverse of ParseAuthorizedKey.20// This function is a copy of ssh.MarshalAuthorizedKey, but without the trailing newline.21// It returns an empty string if pk is nil.22func MarshalAuthorizedKey(pk gossh.PublicKey) string {23 if pk == nil {24 return ""25 }26 return string(bytes.TrimSuffix(gossh.MarshalAuthorizedKey(pk), []byte("\n")))27}2829// KeysEqual returns whether the two public keys are equal.30func KeysEqual(a, b gossh.PublicKey) bool {31 return ssh.KeysEqual(a, b)32}3334// PublicKeyFromContext returns the public key from the context.35func PublicKeyFromContext(ctx context.Context) gossh.PublicKey {36 if pk, ok := ctx.Value(ssh.ContextKeyPublicKey).(gossh.PublicKey); ok {37 return pk38 }39 return nil40}4142// ContextKeySession is the context key for the SSH session.43var ContextKeySession = &struct{ string }{"session"}4445// SessionFromContext returns the SSH session from the context.46func SessionFromContext(ctx context.Context) ssh.Session {47 if s, ok := ctx.Value(ContextKeySession).(ssh.Session); ok {48 return s49 }50 return nil51}