package transport import ( "bytes" "context" "encoding/json" "io" "net" "net/http" "os" "path/filepath" "regexp" "strings" "sync" "time" "aeternalis/server/internal/game" p "aeternalis/server/internal/protocol" "github.com/coder/websocket" ) type Destination struct { ID string `json:"id"` URL string `json:"url"` } type HTTP struct { s *Service auth *Auth assets string worlds []Destination mu sync.Mutex rates map[string]*bucket } type bucket struct { tokens float64 updated time.Time } func NewHTTP(s *Service, a *Auth, assets string, worlds []Destination) *HTTP { return &HTTP{s: s, auth: a, assets: assets, worlds: worlds, rates: map[string]*bucket{}} } func respond(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } func fail(w http.ResponseWriter, status int, msg string) { respond(w, status, map[string]string{"error": msg}) } func decode(w http.ResponseWriter, r *http.Request, v any) error { r.Body = http.MaxBytesReader(w, r.Body, 4096) d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if err := d.Decode(v); err != nil { return err } var extra any if err := d.Decode(&extra); err != io.EOF { return io.ErrUnexpectedEOF } return nil } func (h *HTTP) allow(r *http.Request) bool { // RemoteAddr is authoritative here. Proxy headers are deliberately not trusted. key, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { key = r.RemoteAddr } h.mu.Lock() defer h.mu.Unlock() now := time.Now() b := h.rates[key] if b == nil { if len(h.rates) >= 4096 { for k, v := range h.rates { if now.Sub(v.updated) > time.Minute { delete(h.rates, k) } } if len(h.rates) >= 4096 { return false } } b = &bucket{60, now} h.rates[key] = b } b.tokens = min(60, b.tokens+now.Sub(b.updated).Seconds()*5) b.updated = now if b.tokens < 1 { return false } b.tokens-- return true } func (h *HTTP) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() { fail(w, 503, "world frozen") return } respond(w, 200, map[string]string{"status": "alive"}) }) mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() { fail(w, 503, "world unavailable") return } respond(w, 200, map[string]string{"status": "ready"}) }) mux.HandleFunc("GET /auth/login", h.auth.login) mux.HandleFunc("GET /auth/callback", h.auth.callback) mux.HandleFunc("POST /auth/dev", func(w http.ResponseWriter, r *http.Request) { if !h.auth.dev { fail(w, 404, "not enabled") return } if account, err := h.auth.account(r); err == nil { respond(w, 200, map[string]bool{"authenticated": account != ""}) return } if err := h.auth.session(w, r, "dev:"+game.ID()); err != nil { fail(w, 503, "session unavailable") return } respond(w, 200, map[string]bool{"authenticated": true}) }) mux.HandleFunc("POST /auth/logout", func(w http.ResponseWriter, r *http.Request) { account, _ := h.auth.account(r) if cookie, err := r.Cookie(h.auth.cookieName()); err == nil { _ = h.auth.db.DeleteSession(r.Context(), hash(cookie.Value)) } h.s.mu.Lock() if c := h.s.world.ForAccount(account); c != nil { if p := h.s.peers[c.View.Entity.ID]; p != nil { p.close() } } h.s.mu.Unlock() http.SetCookie(w, &http.Cookie{Name: h.auth.cookieName(), Path: "/", HttpOnly: true, Secure: !h.auth.dev, SameSite: http.SameSiteLaxMode, MaxAge: -1}) respond(w, 200, map[string]bool{"ok": true}) }) mux.HandleFunc("GET /api/config", func(w http.ResponseWriter, r *http.Request) { h.s.mu.Lock() defer h.s.mu.Unlock() b := h.s.world.Balance respond(w, 200, map[string]any{"worldId": h.s.world.ID, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz}) }) mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) { h.s.mu.Lock() defer h.s.mu.Unlock() t := game.NewTerrain(h.s.world.Seed, h.s.world.Balance) chunks := []p.Chunk{} for z := -1; z <= 1; z++ { for x := -1; x <= 1; x++ { chunks = append(chunks, t.Chunk(x, z)) } } respond(w, 200, chunks) }) mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) { account, err := h.auth.account(r) if err != nil { fail(w, 401, "sign in required") return } h.s.mu.Lock() defer h.s.mu.Unlock() if c := h.s.world.ForAccount(account); c != nil { respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()}) return } respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info()}) }) mux.HandleFunc("POST /api/join", func(w http.ResponseWriter, r *http.Request) { account, err := h.auth.account(r) if err != nil { fail(w, 401, "sign in required") return } var req struct { Name string `json:"name"` Passage string `json:"passage"` } if decode(w, r, &req) != nil { fail(w, 400, "invalid request") return } req.Name = strings.TrimSpace(req.Name) if req.Passage == "" && !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9 _-]{1,23}$`).MatchString(req.Name) { fail(w, 400, "Name must be 2-24 letters, numbers, spaces, or hyphens.") return } c, err := h.s.join(r.Context(), account, req.Name, req.Passage) if err != nil { fail(w, 409, err.Error()) return } respond(w, 200, c) }) mux.HandleFunc("GET /api/passages", func(w http.ResponseWriter, r *http.Request) { account, err := h.auth.account(r) if err != nil { fail(w, 401, "sign in required") return } passages, err := h.auth.db.Passages(r.Context(), account) if err != nil { fail(w, 503, "passages unavailable") return } respond(w, 200, passages) }) mux.HandleFunc("POST /api/dev/boss", func(w http.ResponseWriter, r *http.Request) { if !h.auth.dev { fail(w, 404, "not enabled") return } if _, err := h.auth.account(r); err != nil { fail(w, 401, "sign in required") return } h.s.mu.Lock() defer h.s.mu.Unlock() if !h.s.ready.Load() { fail(w, 503, "world unavailable") return } if err := h.s.world.TriggerBoss(); err != nil { fail(w, 409, err.Error()) return } if err := h.s.persist(r.Context(), ""); err != nil { fail(w, 503, "save failed") return } respond(w, 200, map[string]bool{"ok": true}) }) mux.HandleFunc("GET /ws", h.socket) files := http.FileServer(http.Dir(h.assets)) mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { clean := filepath.Clean(filepath.FromSlash(r.URL.Path)) if strings.HasPrefix(r.URL.Path, "/api/") { fail(w, 404, "not found") return } if r.URL.Path == "/" { w.Header().Set("Cache-Control", "no-cache") } if strings.Contains(clean, ".env") || strings.HasPrefix(r.URL.Path, "/.") { fail(w, 404, "not found") return } if _, err := os.Stat(filepath.Join(h.assets, strings.TrimPrefix(clean, string(filepath.Separator)))); err != nil { http.NotFound(w, r) return } files.ServeHTTP(w, r) }) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'") if !h.auth.dev { w.Header().Set("Strict-Transport-Security", "max-age=31536000") } if strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/auth/") { w.Header().Set("Cache-Control", "no-store") if !h.allow(r) { fail(w, 429, "too many requests") return } } if r.Method == "POST" && !validOrigin(r, h.auth.base) { fail(w, 403, "origin rejected") return } mux.ServeHTTP(w, r) }) } func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) { if !validOrigin(r, h.auth.base) { fail(w, 403, "origin rejected") return } if !h.allow(r) { fail(w, 429, "too many connections") return } account, err := h.auth.account(r) if err != nil { fail(w, 401, "sign in required") return } h.s.mu.Lock() if !h.s.ready.Load() { h.s.mu.Unlock() fail(w, 503, "world unavailable") return } c := h.s.world.ForAccount(account) if c == nil { h.s.mu.Unlock() fail(w, 403, "create a character first") return } id := c.View.Entity.ID if h.s.peers[id] != nil { h.s.mu.Unlock() fail(w, 409, "character already connected") return } if err = h.s.world.Connect(id); err != nil { h.s.mu.Unlock() fail(w, 403, err.Error()) return } conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) if err != nil { h.s.world.Disconnect(id) h.s.mu.Unlock() return } conn.SetReadLimit(1024) ctx, cancel := context.WithCancel(r.Context()) peer := &peer{character: id, out: make(chan []byte, 2), known: map[string]bool{}, close: func() { cancel(); _ = conn.CloseNow() }} h.s.peers[id] = peer h.s.mu.Unlock() defer func() { cancel() _ = conn.CloseNow() h.s.mu.Lock() delete(h.s.peers, id) h.s.world.Disconnect(id) h.s.mu.Unlock() }() go func() { for { select { case <-ctx.Done(): return case data := <-peer.out: writeCtx, stop := context.WithTimeout(ctx, 3*time.Second) err := conn.Write(writeCtx, websocket.MessageText, data) stop() if err != nil { peer.close() return } var snap p.Snapshot if json.Unmarshal(data, &snap) == nil && snap.Self.RemainingSeconds <= 0 { _ = conn.Close(websocket.StatusPolicyViolation, "daily play limit reached") peer.close() return } } } }() tokens := float64(40) last := time.Now() lastSessionCheck := last for { readCtx, stop := context.WithTimeout(ctx, 45*time.Second) kind, data, err := conn.Read(readCtx) stop() if err != nil { return } now := time.Now() tokens = min(40, tokens+now.Sub(last).Seconds()*30) last = now if tokens < 1 { _ = conn.Close(websocket.StatusPolicyViolation, "input rate exceeded") return } tokens-- if now.Sub(lastSessionCheck) > time.Minute { if _, err = h.auth.account(r); err != nil { return } lastSessionCheck = now } if kind != websocket.MessageText { return } var intent p.Intent d := json.NewDecoder(bytes.NewReader(data)) d.DisallowUnknownFields() if d.Decode(&intent) != nil { return } var extra any if d.Decode(&extra) != io.EOF { return } h.s.mu.Lock() if !h.s.ready.Load() { h.s.mu.Unlock() return } if err = h.s.world.Intent(id, intent); err != nil { c.Message = err.Error() } h.s.mu.Unlock() } }