Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
182 lines
4.1 KiB
Go
182 lines
4.1 KiB
Go
package services
|
|
|
|
import (
|
|
"net/http"
|
|
"net/url"
|
|
"sync"
|
|
"time"
|
|
|
|
"adam-french.co.uk/backend/models"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
// The chat hub behind GET /ws: one process, one room, so package-level state.
|
|
|
|
// History replayed on connect, and rows kept in the database.
|
|
const maxMessages = 50
|
|
|
|
var allowedDomain string
|
|
|
|
// CheckOrigin is the only cross-origin defence: browsers send cookies on a
|
|
// WebSocket handshake with no preflight. Gorilla's same-host default would
|
|
// reject the apex/www split and the Vite dev server.
|
|
var Upgrader = websocket.Upgrader{
|
|
ReadBufferSize: 1024,
|
|
WriteBufferSize: 1024,
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
origin := r.Header.Get("Origin")
|
|
if origin == "" {
|
|
return false
|
|
}
|
|
u, err := url.Parse(origin)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
host := u.Hostname()
|
|
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
|
|
},
|
|
}
|
|
|
|
var (
|
|
clients = make(map[*websocket.Conn]bool)
|
|
// Also serialises write-then-broadcast so all clients see one order.
|
|
mu sync.Mutex
|
|
wsDB *gorm.DB
|
|
// Per-process connection number, not a user id; chat is pseudonymous.
|
|
nextAuthorID uint
|
|
)
|
|
|
|
// Per-socket flood limit (frames, not requests per IP).
|
|
const (
|
|
rateLimitWindow = time.Second
|
|
rateLimitMaxMsgs = 10
|
|
)
|
|
|
|
type wsIncoming struct {
|
|
Action string `json:"action,omitempty"`
|
|
ID uint `json:"id,omitempty"`
|
|
Text string `json:"text"`
|
|
FileURL string `json:"fileUrl,omitempty"`
|
|
Private bool `json:"private,omitempty"`
|
|
}
|
|
|
|
type wsDeleteEvent struct {
|
|
Action string `json:"action"`
|
|
ID uint `json:"id"`
|
|
}
|
|
|
|
// Sent as one batch so a reconnect replaces the list without blanking it.
|
|
type wsHistoryEvent struct {
|
|
Action string `json:"action"`
|
|
Messages []models.Message `json:"messages"`
|
|
}
|
|
|
|
func InitWebSocket(database *gorm.DB, domain string) {
|
|
wsDB = database
|
|
allowedDomain = domain
|
|
}
|
|
|
|
// isAdmin allows seeing, sending and deleting private messages.
|
|
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
|
defer conn.Close()
|
|
|
|
// Register and snapshot under one lock, so a concurrent broadcast is
|
|
// either in the history or delivered after it, never lost or reordered.
|
|
mu.Lock()
|
|
clients[conn] = isAdmin
|
|
nextAuthorID++
|
|
authorID := nextAuthorID
|
|
|
|
history := make([]models.Message, 0, maxMessages)
|
|
historyQuery := wsDB.Order("created_at ASC").Limit(maxMessages)
|
|
if !isAdmin {
|
|
historyQuery = historyQuery.Where("private = ?", false)
|
|
}
|
|
historyQuery.Find(&history)
|
|
|
|
if err := conn.WriteJSON(wsHistoryEvent{Action: "history", Messages: history}); err != nil {
|
|
delete(clients, conn)
|
|
mu.Unlock()
|
|
return
|
|
}
|
|
mu.Unlock()
|
|
|
|
// Over-limit frames are dropped silently.
|
|
msgCount := 0
|
|
windowStart := time.Now()
|
|
|
|
for {
|
|
var incoming wsIncoming
|
|
if err := conn.ReadJSON(&incoming); err != nil {
|
|
break
|
|
}
|
|
|
|
now := time.Now()
|
|
if now.Sub(windowStart) > rateLimitWindow {
|
|
msgCount = 0
|
|
windowStart = now
|
|
}
|
|
msgCount++
|
|
if msgCount > rateLimitMaxMsgs {
|
|
continue
|
|
}
|
|
|
|
if incoming.Action == "delete" {
|
|
if isAdmin && incoming.ID != 0 {
|
|
deleteMessage(incoming.ID)
|
|
}
|
|
continue
|
|
}
|
|
|
|
msg := models.Message{
|
|
Content: incoming.Text,
|
|
FileURL: incoming.FileURL,
|
|
AuthorID: authorID,
|
|
Private: incoming.Private && isAdmin,
|
|
}
|
|
|
|
mu.Lock()
|
|
wsDB.Create(&msg)
|
|
// Soft delete, so the table still grows; the chat does not.
|
|
wsDB.Where("id NOT IN (?)",
|
|
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
|
|
).Delete(&models.Message{})
|
|
|
|
for client, clientAdmin := range clients {
|
|
if msg.Private && !clientAdmin {
|
|
continue
|
|
}
|
|
if err := client.WriteJSON(msg); err != nil {
|
|
client.Close()
|
|
delete(clients, client)
|
|
}
|
|
}
|
|
mu.Unlock()
|
|
}
|
|
|
|
mu.Lock()
|
|
delete(clients, conn)
|
|
mu.Unlock()
|
|
}
|
|
|
|
// deleteMessage soft-deletes and broadcasts; clients ignore unknown ids.
|
|
func deleteMessage(id uint) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
res := wsDB.Delete(&models.Message{}, id)
|
|
if res.Error != nil || res.RowsAffected == 0 {
|
|
return
|
|
}
|
|
|
|
event := wsDeleteEvent{Action: "delete", ID: id}
|
|
for client := range clients {
|
|
if err := client.WriteJSON(event); err != nil {
|
|
client.Close()
|
|
delete(clients, client)
|
|
}
|
|
}
|
|
}
|