|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/charmbracelet/log" |
| 13 | + "github.com/gorilla/websocket" |
| 14 | + |
| 15 | + "github.com/profullstack/agentbbs/internal/games" |
| 16 | +) |
| 17 | + |
| 18 | +// serveGameWS exposes the AgentGames protocol over WebSocket at /play, the |
| 19 | +// browser/SDK-friendly twin of the game@ SSH route. It speaks the exact same |
| 20 | +// JSON messages (see internal/games/protocol.go) and shares the matchmaker, so |
| 21 | +// an SSH agent and a WebSocket agent can be paired against each other. |
| 22 | +// |
| 23 | +// Auth is a bearer API token (mint with `agentbbs mint-token <user>`), passed |
| 24 | +// as `Authorization: Bearer <token>` or `?token=`. The listener is loopback; |
| 25 | +// Caddy terminates TLS and proxies wss://host/play to it. |
| 26 | +func (a *app) serveGameWS(addr string) { |
| 27 | + mux := http.NewServeMux() |
| 28 | + mux.HandleFunc("/play", a.handleGameWS) |
| 29 | + mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }) |
| 30 | + log.Info("agentgames ws listening", "addr", addr) |
| 31 | + srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} |
| 32 | + if err := srv.ListenAndServe(); err != nil { |
| 33 | + log.Error("game ws server", "err", err) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +var wsUpgrader = websocket.Upgrader{ |
| 38 | + // The listener is loopback behind Caddy; origin is enforced at the edge. |
| 39 | + CheckOrigin: func(*http.Request) bool { return true }, |
| 40 | +} |
| 41 | + |
| 42 | +func (a *app) handleGameWS(w http.ResponseWriter, r *http.Request) { |
| 43 | + token := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")) |
| 44 | + if token == "" { |
| 45 | + token = r.URL.Query().Get("token") |
| 46 | + } |
| 47 | + name, ok, err := a.st.UserByToken(token) |
| 48 | + if err != nil || !ok { |
| 49 | + http.Error(w, "invalid or missing token (mint: agentbbs mint-token <user>)", http.StatusUnauthorized) |
| 50 | + return |
| 51 | + } |
| 52 | + if u, found, _ := a.st.UserByName(name); !found || u.Banned { |
| 53 | + http.Error(w, "account unavailable", http.StatusForbidden) |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + c, err := wsUpgrader.Upgrade(w, r, nil) |
| 58 | + if err != nil { |
| 59 | + return // Upgrade already wrote the error |
| 60 | + } |
| 61 | + defer c.Close() |
| 62 | + p := &wsPlayer{name: name, c: c} |
| 63 | + |
| 64 | + gameID := strings.ToLower(r.URL.Query().Get("game")) |
| 65 | + if gameID == "" { |
| 66 | + if gameID, err = p.ReadJoin(time.Now().Add(30 * time.Second)); err != nil { |
| 67 | + _ = p.Send(errEnvelope("send {\"type\":\"join\",\"game\":\"<id>\"} first; games: " + strings.Join(a.gamesReg.IDs(), ", "))) |
| 68 | + return |
| 69 | + } |
| 70 | + } |
| 71 | + if _, known := a.gamesReg.Get(gameID); !known { |
| 72 | + _ = p.Send(errEnvelope("unknown game " + gameID + "; games: " + strings.Join(a.gamesReg.IDs(), ", "))) |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + sessID, _ := a.st.RecordSession(0, name, wsRemoteIP(r), "game-ws") |
| 77 | + defer func() { _ = a.st.EndSession(sessID) }() |
| 78 | + |
| 79 | + _ = p.Send(map[string]any{"type": "queued", "game": gameID}) |
| 80 | + if err := a.mm.Play(context.Background(), gameID, p); errors.Is(err, games.ErrNoOpponent) { |
| 81 | + _ = p.Send(errEnvelope("no opponent found — try again later")) |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +// wsPlayer adapts a gorilla WebSocket connection to games.PlayerIO. The match |
| 86 | +// runs in a single goroutine, so reads and writes are never concurrent. |
| 87 | +type wsPlayer struct { |
| 88 | + name string |
| 89 | + c *websocket.Conn |
| 90 | +} |
| 91 | + |
| 92 | +func (p *wsPlayer) Name() string { return p.name } |
| 93 | +func (p *wsPlayer) Send(v any) error { return p.c.WriteJSON(v) } |
| 94 | + |
| 95 | +type wsInbound struct { |
| 96 | + Type string `json:"type"` |
| 97 | + Move string `json:"move"` |
| 98 | + Game string `json:"game"` |
| 99 | +} |
| 100 | + |
| 101 | +func (p *wsPlayer) read(deadline time.Time) (wsInbound, error) { |
| 102 | + _ = p.c.SetReadDeadline(deadline) |
| 103 | + _, data, err := p.c.ReadMessage() |
| 104 | + if err != nil { |
| 105 | + var ne net.Error |
| 106 | + if errors.As(err, &ne) && ne.Timeout() { |
| 107 | + return wsInbound{}, games.ErrTimeout |
| 108 | + } |
| 109 | + return wsInbound{}, games.ErrClosed |
| 110 | + } |
| 111 | + var m wsInbound |
| 112 | + _ = json.Unmarshal(data, &m) |
| 113 | + return m, nil |
| 114 | +} |
| 115 | + |
| 116 | +func (p *wsPlayer) ReadJoin(deadline time.Time) (string, error) { |
| 117 | + for { |
| 118 | + m, err := p.read(deadline) |
| 119 | + if err != nil { |
| 120 | + return "", err |
| 121 | + } |
| 122 | + if m.Type == "join" && m.Game != "" { |
| 123 | + return m.Game, nil |
| 124 | + } |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +func (p *wsPlayer) ReadMove(deadline time.Time) (string, error) { |
| 129 | + for { |
| 130 | + m, err := p.read(deadline) |
| 131 | + if err != nil { |
| 132 | + return "", err |
| 133 | + } |
| 134 | + if m.Type == "move" && m.Move != "" { |
| 135 | + return m.Move, nil |
| 136 | + } |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +func wsRemoteIP(r *http.Request) string { |
| 141 | + if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { |
| 142 | + return host |
| 143 | + } |
| 144 | + return r.RemoteAddr |
| 145 | +} |
0 commit comments