From 9984583dd27a987c98a860d424d91c4357caea2a Mon Sep 17 00:00:00 2001 From: juancwu <46619361+juancwu@users.noreply.github.com> Date: Sun, 7 Dec 2025 18:10:26 -0500 Subject: [PATCH] simple server relay with clients --- cmd/client/main.go | 183 ++++++++++++++++++++++++++++++++++++++++++ cmd/server/main.go | 83 +++++++++++++++++++ go.mod | 29 +++++++ go.sum | 55 +++++++++++++ main.go | 7 -- pkg/protocol/types.go | 8 ++ 6 files changed, 358 insertions(+), 7 deletions(-) create mode 100644 cmd/client/main.go create mode 100644 cmd/server/main.go create mode 100644 go.sum delete mode 100644 main.go create mode 100644 pkg/protocol/types.go diff --git a/cmd/client/main.go b/cmd/client/main.go new file mode 100644 index 0000000..4aa5a0f --- /dev/null +++ b/cmd/client/main.go @@ -0,0 +1,183 @@ +package main + +import ( + "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "log" + "strings" + + "gossip/pkg/protocol" + + "github.com/charmbracelet/bubbles/textarea" + "github.com/charmbracelet/bubbles/viewport" + tea "github.com/charmbracelet/bubbletea" + "github.com/gorilla/websocket" + "golang.org/x/crypto/nacl/box" +) + +type KeyPair struct { + Public *[32]byte + Private *[32]byte + PubHex string +} + +type model struct { + conn *websocket.Conn + keys KeyPair + targetHex string + targetPub *[32]byte + viewport viewport.Model + textarea textarea.Model + messages []string + err error +} + +type wsMsg protocol.Message + +func main() { + pub, priv, err := box.GenerateKey(rand.Reader) + if err != nil { + log.Fatal(err) + } + keys := KeyPair{Public: pub, Private: priv, PubHex: hex.EncodeToString(pub[:])} + + c, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil) + if err != nil { + log.Fatal("Could not connect to server:", err) + } + defer c.Close() + + loginMsg := protocol.Message{Type: "login", Sender: keys.PubHex} + c.WriteJSON(loginMsg) + + ta := textarea.New() + ta.Placeholder = "Type a message (or /connect )..." + ta.Focus() + ta.SetHeight(2) + ta.ShowLineNumbers = false + + vp := viewport.New(80, 20) + vp.SetContent(fmt.Sprintf("Your ID: %s\nTo start, type: /connect ", keys.PubHex)) + + m := model{ + conn: c, + keys: keys, + textarea: ta, + viewport: vp, + } + + p := tea.NewProgram(m) + + go func() { + for { + _, data, err := c.ReadMessage() + if err != nil { + return + } + var msg protocol.Message + json.Unmarshal(data, &msg) + p.Send(wsMsg(msg)) + } + }() + + if _, err := p.Run(); err != nil { + log.Fatal(err) + } +} + +func (m model) Init() tea.Cmd { + return textarea.Blink +} + +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + var ( + tiCmd tea.Cmd + vpCmd tea.Cmd + ) + + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.Type { + case tea.KeyCtrlC, tea.KeyEsc: + return m, tea.Quit + case tea.KeyEnter: + input := m.textarea.Value() + if input == "" { + return m, nil + } + + if dest, ok := strings.CutPrefix(input, "/connect "); ok { + m.targetHex = dest + + decoded, _ := hex.DecodeString(dest) + var keyArr [32]byte + copy(keyArr[:], decoded) + m.targetPub = &keyArr + + m.messages = append(m.messages, "System: Target set to "+dest[:8]+"...") + m.viewport.SetContent(strings.Join(m.messages, "\n")) + m.textarea.Reset() + m.viewport.GotoBottom() + return m, nil + } + + if m.targetPub == nil { + m.messages = append(m.messages, "System: No target set! Use /connect first.") + } else { + var nonce [24]byte + rand.Read(nonce[:]) + encrypted := box.Seal(nonce[:], []byte(input), &nonce, m.targetPub, m.keys.Private) + b64Content := base64.StdEncoding.EncodeToString(encrypted) + + outMsg := protocol.Message{ + Type: "msg", + Sender: m.keys.PubHex, + Target: m.targetHex, + Content: b64Content, + } + + m.conn.WriteJSON(outMsg) + + m.messages = append(m.messages, "Me: "+input) + } + + m.textarea.Reset() + m.viewport.SetContent(strings.Join(m.messages, "\n")) + m.viewport.GotoBottom() + } + + case wsMsg: + encBytes, _ := base64.StdEncoding.DecodeString(msg.Content) + + senderBytes, _ := hex.DecodeString(msg.Sender) + var senderKey [32]byte + copy(senderKey[:], senderBytes) + + var nonce [24]byte + copy(nonce[:], encBytes[:24]) + decrypted, ok := box.Open(nil, encBytes[24:], &nonce, &senderKey, m.keys.Private) + + if !ok { + m.messages = append(m.messages, "System: Failed to decrypt message from "+msg.Sender[:8]) + } else { + m.messages = append(m.messages, fmt.Sprintf("Friend (%s): %s", msg.Sender[:8], string(decrypted))) + } + m.viewport.SetContent(strings.Join(m.messages, "\n")) + m.viewport.GotoBottom() + } + + m.textarea, tiCmd = m.textarea.Update(msg) + m.viewport, vpCmd = m.viewport.Update(msg) + return m, tea.Batch(tiCmd, vpCmd) +} + +func (m model) View() string { + return fmt.Sprintf( + "%s\n\n%s", + m.viewport.View(), + m.textarea.View(), + ) + "\n\nPress Esc to quit." +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..ad3226b --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,83 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" + "sync" + + "gossip/pkg/protocol" + + "github.com/gorilla/websocket" +) + +type Server struct { + clients map[string]*websocket.Conn + mu sync.Mutex + upgrader websocket.Upgrader +} + +func main() { + srv := &Server{ + clients: make(map[string]*websocket.Conn), + upgrader: websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + CheckOrigin: func(r *http.Request) bool { return true }, + }, + } + + http.HandleFunc("/ws", srv.handleWS) + log.Println("Relay Server listening on :8080") + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func (s *Server) handleWS(w http.ResponseWriter, r *http.Request) { + conn, err := s.upgrader.Upgrade(w, r, nil) + if err != nil { + log.Println("Upgrade error:", err) + return + } + defer conn.Close() + + var myPubKey string + + for { + _, data, err := conn.ReadMessage() + if err != nil { + break + } + + var msg protocol.Message + if err := json.Unmarshal(data, &msg); err != nil { + continue + } + + switch msg.Type { + case "login": + s.mu.Lock() + s.clients[msg.Sender] = conn + s.mu.Unlock() + myPubKey = msg.Sender + log.Printf("Client connected: %s...", myPubKey[:8]) + case "msg": + s.mu.Lock() + targetConn, ok := s.clients[msg.Target] + s.mu.Unlock() + + if ok { + err = targetConn.WriteMessage(websocket.TextMessage, data) + if err != nil { + log.Printf("Failed to relay to %s", msg.Target[:8]) + } + } + } + } + + if myPubKey != "" { + s.mu.Lock() + delete(s.clients, myPubKey) + s.mu.Unlock() + log.Printf("Client disconnected: %s...", myPubKey[:8]) + } +} diff --git a/go.mod b/go.mod index a2494ea..70cbbf5 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,32 @@ module gossip go 1.25.1 + +require ( + github.com/charmbracelet/bubbles v0.21.0 + github.com/charmbracelet/bubbletea v1.3.10 + github.com/gorilla/websocket v1.5.3 + golang.org/x/crypto v0.45.0 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/lipgloss v1.1.0 // indirect + github.com/charmbracelet/x/ansi v0.10.1 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.38.0 // indirect + golang.org/x/text v0.31.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7396145 --- /dev/null +++ b/go.sum @@ -0,0 +1,55 @@ +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= +github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= +github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs= +github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= +github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= diff --git a/main.go b/main.go deleted file mode 100644 index 8a33282..0000000 --- a/main.go +++ /dev/null @@ -1,7 +0,0 @@ -package main - -import "fmt" - -func main() { - fmt.Println("Let the gossip start") -} diff --git a/pkg/protocol/types.go b/pkg/protocol/types.go new file mode 100644 index 0000000..ffbbb27 --- /dev/null +++ b/pkg/protocol/types.go @@ -0,0 +1,8 @@ +package protocol + +type Message struct { + Type string `json:"type"` + Sender string `json:"sender"` + Target string `json:"target"` + Content string `json:"content"` +}