Files
aeternalis/server/internal/transport/control.go
T
dingoandClaude Sonnet 5 5df2f1b681 Merge control portal work from RPGTheory/aeternalis-portal
RPGTheory/aeternalis-portal had diverged from this repo (the git/CI/CD
copy) with an in-progress control portal feature that was never synced
back here, so none of it had gone through CI or been deployed:

- New site/game/control routing split: index.html becomes a world
  directory landing page (site.ts), game.html is the renamed former
  index.html (main.ts), control.html is a new admin panel
  (control.ts, portal-shared.ts, portal.css).
- Server: new internal/store/portal.go (character/world registry,
  command queue, admin grants) and internal/transport/control.go
  (portal API routes), plus a new internal/gitops package that lets
  the portal provision new worlds via a GitOps repo commit.
- game.World gains BornAt/DiedAt/DeathReason and an operator Control()
  path (close/open admissions, awaken boss, end world, per-character
  rename/heal/unstuck/retire); death no longer reuses the same
  character id on rejoin, matching the "new life" permadeath model in
  Plan.md rather than the old bypass-prevention test's expectations.
- deploy/: new control-egress network policy and portal/control
  values (admin role, GitOps repo/branch/values file/CIDRs).
- New e2e coverage: tests/portal.spec.ts, tools/capture-world.mjs.

Verified this repo's own independent commits (800ms movement-staleness
window, 20s boss-attack poll, SRS/TLS deploy values, ubuntu-22.04
runner pin, DOCKER_HOST fix) were already present in the portal copy
before merging, so nothing here regresses them. `tsc --noEmit`, the
vite client build, and the protocol contract check all pass; no go.mod
changes. Could not run `go build`/`go test` locally (no Go toolchain
on PATH, Docker daemon not running) — every new/changed Go symbol was
manually cross-referenced and resolves, but this should still be built
and tested in CI before merging to master.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 11:08:44 -04:00

197 lines
5.6 KiB
Go

package transport
import (
"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. Sign in again with the configured Keycloak role.")
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 "create-world":
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" {
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" {
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" {
continue
}
request, cancel := context.WithTimeout(ctx, 45*time.Second)
result, err := h.Provisioner.CreateWorld(request, c.Target, c.Value)
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)
}
}
}
}