~james/core

core/cilogs/server.go -rw-r--r-- 1.5 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package cilogs

import (
	"context"
	"fmt"
	"log/slog"

	"github.com/charmbracelet/ssh"
	"github.com/charmbracelet/wish"
	tea "github.com/charmbracelet/wish/bubbletea"
)

type Config struct {
	ListenAddr  string
	HostKeyPath string
}

type Server struct {
	config   Config
	spindles *Spindles
	logger   *slog.Logger
}

func New(cfg Config, spindles *Spindles, logger *slog.Logger) *Server {
	return &Server{config: cfg, spindles: spindles, logger: logger}
}

func (s *Server) ListenAndServe(ctx context.Context) error {
	opts := []ssh.Option{
		wish.WithAddress(s.config.ListenAddr),
		wish.WithMiddleware(
			tea.Middleware(s.teaHandler),
			requirePty,
		),
	}

	if s.config.HostKeyPath != "" {
		opts = append(opts, wish.WithHostKeyPath(s.config.HostKeyPath))
	}

	srv, err := wish.NewServer(opts...)
	if err != nil {
		return err
	}

	go func() {
		<-ctx.Done()
		s.logger.Info("shutting down SSH log server")
		srv.Close()
	}()

	s.logger.Info("SSH log server listening", "address", s.config.ListenAddr)
	if err := srv.ListenAndServe(); err != ssh.ErrServerClosed {
		return err
	}
	s.logger.Info("SSH log server stopped")
	return nil
}

// requirePty is a middleware that rejects connections without a PTY and tells the user to pass -t.
func requirePty(next ssh.Handler) ssh.Handler {
	return func(sess ssh.Session) {
		_, _, ok := sess.Pty()
		if !ok {
			fmt.Fprintf(sess.Stderr(), "error: no terminal allocated\nhint: use `ssh -t` to force PTY allocation\n")
			sess.Exit(1)
			return
		}
		next(sess)
	}
}