Files

217 lines
6.3 KiB
Go

package transport
import (
"aeternalis/server/internal/game"
"context"
"errors"
"net/http"
"regexp"
"strings"
"time"
"aeternalis/server/internal/store"
)
var worldIDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
var namePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9 _-]{1,23}$`)
var requestIDPattern = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
func (h *HTTP) admin(w http.ResponseWriter, r *http.Request) (string, bool) {
account, err := h.auth.account(r)
if err != nil {
fail(w, 401, "sign in required")
return "", false
}
if !h.auth.isAdmin(r) {
fail(w, 403, "Administrator access required. Your Keycloak ID token must include the role \""+h.auth.AdminRole+"\". Sign in again after assigning it.")
return "", false
}
return account, true
}
func (h *HTTP) portalRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/worlds", func(w http.ResponseWriter, r *http.Request) {
worlds, err := h.auth.db.Worlds(r.Context())
if err != nil {
fail(w, 503, "world directory unavailable")
return
}
respond(w, 200, worlds)
})
mux.HandleFunc("GET /api/account", func(w http.ResponseWriter, r *http.Request) {
account, err := h.auth.account(r)
if err != nil {
fail(w, 401, "sign in required")
return
}
characters, err := h.auth.db.Characters(r.Context(), account, "")
if err != nil {
fail(w, 503, "character history unavailable")
return
}
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
if err != nil {
fail(w, 503, "character registry unavailable")
return
}
respond(w, 200, map[string]any{"characters": characters, "active": active, "admin": h.auth.isAdmin(r)})
})
mux.HandleFunc("GET /api/control", func(w http.ResponseWriter, r *http.Request) {
if _, ok := h.admin(w, r); !ok {
return
}
worlds, err := h.auth.db.Worlds(r.Context())
if err != nil {
fail(w, 503, "world directory unavailable")
return
}
characters, err := h.auth.db.Characters(r.Context(), "", r.URL.Query().Get("world"))
if err != nil {
fail(w, 503, "character registry unavailable")
return
}
commands, err := h.auth.db.Commands(r.Context(), "", false)
if err != nil {
fail(w, 503, "audit log unavailable")
return
}
respond(w, 200, map[string]any{"worlds": worlds, "characters": characters, "commands": commands, "provisioningEnabled": h.Provisioner != nil, "characterLimit": 500, "auditLimit": 100})
})
mux.HandleFunc("POST /api/control/commands", func(w http.ResponseWriter, r *http.Request) {
actor, ok := h.admin(w, r)
if !ok {
return
}
var req struct {
ID string `json:"id"`
WorldID string `json:"worldId"`
Op string `json:"op"`
Target string `json:"target"`
Value string `json:"value"`
Reason string `json:"reason"`
Confirm string `json:"confirm"`
}
if decode(w, r, &req) != nil {
fail(w, 400, "invalid command")
return
}
req.Reason = strings.TrimSpace(req.Reason)
req.Value = strings.TrimSpace(req.Value)
if !requestIDPattern.MatchString(req.ID) || !worldIDPattern.MatchString(req.WorldID) || len(req.Reason) < 5 || len(req.Reason) > 240 || len(req.Target) > 128 || len(req.Value) > 100 {
fail(w, 400, "a valid request ID, world ID, and 5-240 character reason are required")
return
}
switch req.Op {
case "spawn-mobs":
if _, _, _, err := game.ParseMobSpawn(req.Value); err != nil {
fail(w, 400, err.Error())
return
}
case "grant-item", "remove-item":
if _, _, err := game.ParseItemChange(req.Value); err != nil {
fail(w, 400, err.Error())
return
}
case "grant-title", "revoke-title":
if !regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`).MatchString(req.Value) {
fail(w, 400, "choose a title")
return
}
case "create-world", "create-hub":
if h.Provisioner == nil {
fail(w, 503, "GitOps provisioning is not configured")
return
}
if !regexp.MustCompile(`^[0-9]{1,15}$`).MatchString(req.Value) {
fail(w, 400, "seed must contain 1-15 digits")
return
}
case "close-admissions", "open-admissions", "awaken-boss", "end-world", "heal", "unstuck", "retire", "revoke-sessions":
case "rename":
if !namePattern.MatchString(req.Value) {
fail(w, 400, "name must be 2-24 letters, numbers, spaces or hyphens")
return
}
default:
fail(w, 400, "unknown command")
return
}
if req.Op == "end-world" || req.Op == "awaken-boss" || req.Op == "retire" {
expected := req.WorldID
if req.Op == "retire" {
expected = req.Target
}
if req.Confirm != expected {
fail(w, 400, "confirmation does not match the target")
return
}
}
if req.Op != "create-world" && req.Op != "create-hub" {
worlds, err := h.auth.db.Worlds(r.Context())
if err != nil {
fail(w, 503, "world directory unavailable")
return
}
found := false
for _, world := range worlds {
if world.ID == req.WorldID && world.Available {
found = true
}
}
if !found {
fail(w, 409, "world owner is not available")
return
}
}
command := store.Command{ID: req.ID, WorldID: req.WorldID, Actor: actor, Op: req.Op, Target: req.Target, Value: req.Value, Reason: req.Reason}
if req.Op == "create-world" || req.Op == "create-hub" {
command.Target = req.WorldID
command.WorldID = "_provision"
}
if err := h.auth.db.Enqueue(r.Context(), command); err != nil {
fail(w, 409, "command could not be queued; request ID may already be used")
return
}
respond(w, 202, map[string]string{"id": command.ID, "status": "pending"})
})
}
func (h *HTTP) RunProvisioning(ctx context.Context) {
if h.Provisioner == nil {
return
}
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if !h.s.ready.Load() {
return
}
commands, err := h.auth.db.Commands(ctx, "_provision", true)
if err != nil {
continue
}
for _, c := range commands {
if c.Op != "create-world" && c.Op != "create-hub" {
continue
}
request, cancel := context.WithTimeout(ctx, 45*time.Second)
kind := "survival"
if c.Op == "create-hub" {
kind = "hub"
}
result, err := h.Provisioner.CreateInstance(request, c.Target, c.Value, kind)
cancel()
if errors.Is(ctx.Err(), context.Canceled) {
return
}
if err != nil {
result = err.Error()
}
_ = h.auth.db.FinishProvision(ctx, c.ID, result, err == nil)
}
}
}
}