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>
This commit is contained in:
dingo
2026-09-06 11:08:44 -04:00
co-authored by Claude Sonnet 5
parent b515c65aba
commit 5df2f1b681
32 changed files with 1871 additions and 100 deletions
+86 -23
View File
@@ -27,6 +27,9 @@ type Character struct {
MoveZ float64 `json:"-"`
LastMove time.Time `json:"-"`
Message string `json:"-"`
BornAt time.Time `json:"bornAt"`
DiedAt *time.Time `json:"diedAt,omitempty"`
DeathReason string `json:"deathReason,omitempty"`
}
type Corpse struct {
Entity p.Entity `json:"entity"`
@@ -40,24 +43,25 @@ type Mob struct {
RespawnAt float64 `json:"respawnAt"`
}
type World struct {
Version int `json:"version"`
ID string `json:"id"`
Seed int64 `json:"seed"`
CreatedAt time.Time `json:"createdAt"`
EndedAt *time.Time `json:"endedAt,omitempty"`
Phase string `json:"phase"`
Tick int64 `json:"tick"`
BossHP float64 `json:"bossHp"`
BossLastAttack float64 `json:"bossLastAttack"`
Characters map[string]*Character `json:"characters"`
Corpses map[string]*Corpse `json:"corpses"`
Depleted map[string]float64 `json:"depleted"`
Mobs map[string]*Mob `json:"mobs"`
Balance content.Balance `json:"balance"`
terrain *Terrain
chunks map[string]p.Chunk
now time.Time
dirty bool
Version int `json:"version"`
ID string `json:"id"`
Seed int64 `json:"seed"`
CreatedAt time.Time `json:"createdAt"`
EndedAt *time.Time `json:"endedAt,omitempty"`
Phase string `json:"phase"`
AdmissionsClosed bool `json:"admissionsClosed"`
Tick int64 `json:"tick"`
BossHP float64 `json:"bossHp"`
BossLastAttack float64 `json:"bossLastAttack"`
Characters map[string]*Character `json:"characters"`
Corpses map[string]*Corpse `json:"corpses"`
Depleted map[string]float64 `json:"depleted"`
Mobs map[string]*Mob `json:"mobs"`
Balance content.Balance `json:"balance"`
terrain *Terrain
chunks map[string]p.Chunk
now time.Time
dirty bool
}
func ID() string {
@@ -122,18 +126,27 @@ func (w *World) Info() p.WorldInfo {
}
func (w *World) ForAccount(account string) *Character {
for _, c := range w.Characters {
if c.Account == account {
if c.Account == account && c.View.Entity.State != "dead" {
return c
}
}
return nil
}
func (w *World) LivingCount() int {
n := 0
for _, c := range w.Characters {
if c.View.Entity.State != "dead" {
n++
}
}
return n
}
func (w *World) spawn(exclude string) (p.Vec3, error) {
for i := 0; i < 4096; i++ {
radius := math.Sqrt(float64(i)) * w.Balance.SpawnSeparation * 0.6
angle := float64(i) * 2.399963229728653
pos := w.terrain.Position(math.Cos(angle)*radius, math.Sin(angle)*radius)
if radius > w.Balance.WorldRadius-32 {
if radius > math.Max(0, math.Min(w.Balance.WorldRadius-32, w.SafeRadius()-8)) {
break
}
clear := true
@@ -153,10 +166,10 @@ func (w *World) Join(account, name string) (*Character, error) {
if c := w.ForAccount(account); c != nil {
return c, nil
}
if w.Phase != "gathering" {
if (w.Phase != "gathering" && w.Phase != "cataclysm") || w.AdmissionsClosed {
return nil, errors.New("this world is closed to new arrivals")
}
if len(w.Characters) >= w.Balance.MaxPlayers {
if w.LivingCount() >= w.Balance.MaxPlayers {
return nil, errors.New("world capacity reached")
}
pos, err := w.spawn("")
@@ -168,11 +181,12 @@ func (w *World) Join(account, name string) (*Character, error) {
c.View.Inventory[k] = v
}
w.Characters[c.View.Entity.ID] = c
c.BornAt = w.now
w.dirty = true
return c, nil
}
func (w *World) Import(c *Character) error {
if w.Phase != "gathering" || w.ForAccount(c.Account) != nil || len(w.Characters) >= w.Balance.MaxPlayers {
if w.Phase != "gathering" || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers {
return errors.New("destination cannot accept character")
}
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
@@ -430,8 +444,57 @@ func (w *World) kill(c *Character, reason string) {
c.ReturnPosition = nil
c.View.HasKeystone = false
c.Message = reason
died := w.now
c.DiedAt = &died
c.DeathReason = reason
w.dirty = true
}
// Operator changes use the same simulation and persistence path as gameplay.
func (w *World) Control(op, target, value, reason string) error {
switch op {
case "close-admissions", "open-admissions":
if w.Phase == "won" || w.Phase == "lost" {
return errors.New("world has ended")
}
w.AdmissionsClosed = op == "close-admissions"
case "awaken-boss":
return w.TriggerBoss()
case "end-world":
if w.Phase == "won" || w.Phase == "lost" {
return errors.New("world has already ended")
}
for _, c := range w.Characters {
w.kill(c, "World ended by an operator: "+reason)
}
w.Phase = "lost"
ended := w.now
w.EndedAt = &ended
default:
c := w.Characters[target]
if c == nil {
return errors.New("character not found")
}
if c.View.Entity.State != "alive" {
return errors.New("only living characters in an active world may be changed")
}
switch op {
case "rename":
c.View.Entity.Name = value
case "heal":
c.View.Entity.HP = c.View.Entity.MaxHP
case "unstuck":
c.View.Entity.Position = w.terrain.Position(0, 0)
c.MoveX, c.MoveZ = 0, 0
case "retire":
w.kill(c, "Character retired by an operator: "+reason)
default:
return errors.New("unknown control operation")
}
}
w.dirty = true
return nil
}
func (w *World) Advance(now time.Time, dt float64) {
playedDT := math.Max(0, dt)
w.now = now
+11 -2
View File
@@ -131,8 +131,17 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
t.Fatal("dead character reconnected")
}
same, err := w.Join(c.Account, "Replacement")
if err != nil || same.View.Entity.ID != id || same.View.Entity.State != "dead" {
t.Fatal("death bypass by rejoining")
if err != nil || same.View.Entity.ID == id || same.View.Entity.State != "alive" || c.View.Entity.State != "dead" {
t.Fatal("replacement must be a new life, not a resurrection")
}
if same.DailySeconds != 0 || same.View.Inventory["spear"] != 0 || w.LivingCount() != 1 {
t.Fatal("new life inherited old progress or incorrect capacity")
}
if again, _ := w.Join(c.Account, "Duplicate"); again.View.Entity.ID != same.View.Entity.ID {
t.Fatal("second living character")
}
if c.DiedAt == nil || c.DeathReason != "test death" {
t.Fatal("missing durable death record")
}
if len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 {
t.Fatal("corpse inventory")
+177
View File
@@ -0,0 +1,177 @@
package gitops
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"regexp"
"strings"
"time"
"go.yaml.in/yaml/v3"
)
type Config struct{ Repository, Branch, File, Token, PublicURL string }
type Client struct {
config Config
endpoint string
http *http.Client
}
var identifier = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
var seedPattern = regexp.MustCompile(`^[0-9]{1,15}$`)
func New(c Config) (*Client, error) {
if c.Repository == "" && c.Token == "" {
return nil, nil
}
u, err := url.Parse(c.Repository)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return nil, errors.New("CONTROL_GITOPS_REPOSITORY must be an HTTPS repository URL without credentials")
}
parts := strings.Split(strings.Trim(strings.TrimSuffix(u.Path, ".git"), "/"), "/")
if len(parts) != 2 {
return nil, errors.New("GitOps repository must have owner/repository path")
}
for _, p := range parts {
if p == "." || p == ".." || !regexp.MustCompile(`^[A-Za-z0-9_.-]+$`).MatchString(p) {
return nil, errors.New("invalid repository path")
}
}
if c.Token == "" || c.Branch == "" || c.File == "" || path.Clean(c.File) != c.File || strings.HasPrefix(c.File, "/") || strings.Contains(c.File, "\\") || strings.HasPrefix(c.File, "..") || !strings.HasSuffix(c.File, ".yaml") {
return nil, errors.New("GitOps requires token, branch, and repository-relative .yaml file")
}
public, err := url.Parse(c.PublicURL)
if err != nil || public.Scheme != "https" || public.Host == "" || public.Path != "" || public.RawQuery != "" || public.User != nil {
return nil, errors.New("GitOps requires an HTTPS public origin")
}
endpoint := u.Scheme + "://" + u.Host + "/api/v1/repos/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1]) + "/contents/"
for i, p := range strings.Split(c.File, "/") {
if i > 0 {
endpoint += "/"
}
endpoint += url.PathEscape(p)
}
return &Client{c, endpoint, &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
func (c *Client) request(ctx context.Context, method string, body any) ([]byte, int, error) {
var r io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, 0, err
}
r = bytes.NewReader(data)
}
u := c.endpoint
if method == http.MethodGet {
u += "?ref=" + url.QueryEscape(c.config.Branch)
}
req, err := http.NewRequestWithContext(ctx, method, u, r)
if err != nil {
return nil, 0, err
}
req.Header.Set("Authorization", "token "+c.config.Token)
req.Header.Set("Content-Type", "application/json")
res, err := c.http.Do(req)
if err != nil {
return nil, 0, errors.New("GitOps service unavailable")
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 2<<20))
if err != nil {
return nil, res.StatusCode, errors.New("GitOps response unavailable")
}
return raw, res.StatusCode, nil
}
func mapping(n *yaml.Node, key string) *yaml.Node {
if n.Kind != yaml.MappingNode {
return nil
}
for i := 0; i < len(n.Content); i += 2 {
if n.Content[i].Value == key {
return n.Content[i+1]
}
}
return nil
}
func scalar(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v} }
// Only the worlds sequence is changed; image pins, comments and runtime settings
// stay intact. Gitea's content SHA rejects concurrent image-promotion overwrites.
func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, error) {
if !identifier.MatchString(id) || !seedPattern.MatchString(seed) {
return "", errors.New("invalid world ID or seed")
}
for attempt := 0; attempt < 3; attempt++ {
raw, status, err := c.request(ctx, http.MethodGet, nil)
if err != nil {
return "", err
}
if status != 200 {
return "", fmt.Errorf("GitOps values could not be read (HTTP %d)", status)
}
var file struct {
SHA string `json:"sha"`
Content string `json:"content"`
}
if json.Unmarshal(raw, &file) != nil || file.SHA == "" {
return "", errors.New("invalid GitOps file response")
}
data, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(file.Content, "\n", ""))
if err != nil {
return "", errors.New("invalid GitOps file encoding")
}
var doc yaml.Node
if yaml.Unmarshal(data, &doc) != nil || len(doc.Content) != 1 {
return "", errors.New("invalid GitOps YAML")
}
root := doc.Content[0]
worlds := mapping(root, "worlds")
portal := mapping(root, "portal")
public, _ := url.Parse(c.config.PublicURL)
if portal == nil || mapping(portal, "host") == nil || mapping(portal, "host").Value != public.Host {
return "", errors.New("GitOps portal.host must match PUBLIC_URL before provisioning")
}
if worlds == nil || worlds.Kind != yaml.SequenceNode {
return "", errors.New("GitOps values must contain a worlds list")
}
for _, world := range worlds.Content {
key := mapping(world, "id")
if key != nil && key.Value == id {
existing := mapping(world, "seed")
if existing != nil && existing.Value == seed {
return "World definition already committed; waiting for ArgoCD readiness.", nil
}
return "", errors.New("world ID already exists with a different seed")
}
}
if len(worlds.Content) >= 50 {
return "", errors.New("operator world limit reached (50)")
}
worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host)}})
encoded, err := yaml.Marshal(&doc)
if err != nil {
return "", err
}
body := map[string]string{"branch": c.config.Branch, "sha": file.SHA, "content": base64.StdEncoding.EncodeToString(encoded), "message": "Provision Aeternalis world " + id}
_, status, err = c.request(ctx, http.MethodPut, body)
if err != nil {
return "", err
}
if status == 200 || status == 201 {
return "World definition committed; waiting for ArgoCD readiness.", nil
}
if status != 409 && status != 422 {
return "", fmt.Errorf("GitOps commit rejected (HTTP %d)", status)
}
}
return "", errors.New("GitOps changed concurrently; retry the request")
}
+89
View File
@@ -0,0 +1,89 @@
package gitops
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go.yaml.in/yaml/v3"
)
func TestCreateWorldPreservesValuesAndRetries(t *testing.T) {
current := "# retained operator comment\nimage:\n digest: sha256:keep\nportal:\n host: srs.example.test\nworlds:\n - id: world-001\n seed: \"12\"\n host: srs.example.test\n"
puts := 0
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "token test-token" {
t.Error("missing token")
}
if r.URL.Path != "/api/v1/repos/owner/game/contents/deploy/values.yaml" {
t.Error("wrong path", r.URL.Path)
}
if r.Method == "GET" {
if r.URL.Query().Get("ref") != "master" {
t.Error("wrong branch")
}
_ = json.NewEncoder(w).Encode(map[string]string{"sha": "revision", "content": base64.StdEncoding.EncodeToString([]byte(current))})
return
}
var body map[string]string
_ = json.NewDecoder(r.Body).Decode(&body)
if body["sha"] != "revision" || body["branch"] != "master" {
t.Error("missing optimistic revision")
}
puts++
if puts == 1 {
w.WriteHeader(409)
return
}
raw, err := base64.StdEncoding.DecodeString(body["content"])
if err != nil {
t.Fatal(err)
}
current = string(raw)
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}))
defer server.Close()
c, err := New(Config{server.URL + "/owner/game.git", "master", "deploy/values.yaml", "test-token", "https://srs.example.test"})
if err != nil {
t.Fatal(err)
}
c.http = server.Client()
if _, err = c.CreateWorld(context.Background(), "world-002", "42"); err != nil {
t.Fatal(err)
}
if puts != 2 || !strings.Contains(current, "retained operator comment") || !strings.Contains(current, "sha256:keep") {
t.Fatal("unrelated values changed", current)
}
var values struct {
Worlds []struct{ ID, Seed, Host string }
}
if err = yaml.Unmarshal([]byte(current), &values); err != nil || len(values.Worlds) != 2 || values.Worlds[1].Seed != "42" {
t.Fatal("bad world definition", err, current)
}
if _, err = c.CreateWorld(context.Background(), "world-002", "42"); err != nil || puts != 2 {
t.Fatal("retry duplicated world", err)
}
if _, err = c.CreateWorld(context.Background(), "world-002", "43"); err == nil {
t.Fatal("existing ID reused")
}
if _, err = c.CreateWorld(context.Background(), "../bad", "42"); err == nil {
t.Fatal("invalid ID accepted")
}
}
func TestGitOpsConfigurationValidation(t *testing.T) {
for _, repository := range []string{"http://example.test/o/r", "https://token@example.test/o/r", "https://example.test/only-one", "https://example.test/../repo"} {
if _, err := New(Config{repository, "master", "deploy/values.yaml", "token", "https://srs.example.test"}); err == nil {
t.Fatal("unsafe repository accepted", repository)
}
}
for _, file := range []string{"../secret.yaml", "/absolute.yaml", "values.json", "a/../values.yaml"} {
if _, err := New(Config{"https://example.test/o/r", "master", file, "token", "https://srs.example.test"}); err == nil {
t.Fatal("unsafe file accepted", file)
}
}
}
+300
View File
@@ -0,0 +1,300 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
"aeternalis/server/internal/game"
)
var ErrLivingCharacter = errors.New("you already have a living character; continue that character or use its survivor passage")
type CharacterRecord struct {
ID string `json:"id"`
Account string `json:"account"`
WorldID string `json:"worldId"`
Name string `json:"name"`
State string `json:"state"`
Character *game.Character `json:"character"`
}
type WorldRecord struct {
ID string `json:"id"`
Phase string `json:"phase"`
Living int `json:"living"`
Dead int `json:"dead"`
Capacity int `json:"capacity"`
CreatedAt time.Time `json:"createdAt"`
BossAt time.Time `json:"bossAt"`
Closed bool `json:"closed"`
Available bool `json:"available"`
Revision int64 `json:"revision"`
}
type Command struct {
ID string `json:"id"`
WorldID string `json:"worldId"`
Actor string `json:"actor"`
Op string `json:"op"`
Target string `json:"target"`
Value string `json:"value"`
Reason string `json:"reason"`
Status string `json:"status"`
Result string `json:"result"`
CreatedAt int64 `json:"createdAt"`
CompletedAt int64 `json:"completedAt"`
}
// Versioned, transactional backfill. Conflicting legacy lives fail closed rather
// than choosing which player's character to destroy during an upgrade.
func (d *DB) migrate(ctx context.Context) error {
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if d.postgres {
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(7362771)`); err != nil {
return err
}
}
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
`CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`,
`CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`,
`CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`,
`CREATE TABLE IF NOT EXISTS admin_sessions(token_hash TEXT PRIMARY KEY, expires BIGINT NOT NULL)`,
`CREATE TABLE IF NOT EXISTS control_commands(id TEXT PRIMARY KEY, world_id TEXT NOT NULL, actor TEXT NOT NULL, op TEXT NOT NULL, target TEXT NOT NULL, value TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL, created_at BIGINT NOT NULL, completed_at BIGINT NOT NULL DEFAULT 0)`,
`CREATE INDEX IF NOT EXISTS commands_pending ON control_commands(world_id,status,created_at)`,
} {
if _, err = tx.ExecContext(ctx, stmt); err != nil {
return err
}
}
var version int
err = tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=1`).Scan(&version)
if err == nil {
return tx.Commit()
}
if !errors.Is(err, sql.ErrNoRows) {
return err
}
rows, err := tx.QueryContext(ctx, `SELECT snapshot FROM worlds ORDER BY id`)
if err != nil {
return err
}
var worlds []*game.World
for rows.Next() {
var raw string
if err = rows.Scan(&raw); err != nil {
rows.Close()
return err
}
var w game.World
if err = json.Unmarshal([]byte(raw), &w); err != nil {
rows.Close()
return err
}
worlds = append(worlds, &w)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, w := range worlds {
for _, c := range w.Characters {
var source string
var claimed sql.NullString
err = tx.QueryRowContext(ctx, d.q(`SELECT source_world,claimed_world FROM passages WHERE character_id=?`), c.View.Entity.ID).Scan(&source, &claimed)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if err == nil && ((claimed.Valid && claimed.String != w.ID) || (!claimed.Valid && source != w.ID)) {
continue
}
if err = d.writeCharacter(ctx, tx, w.ID, c, false); err != nil {
return fmt.Errorf("character migration conflict in world %s: %w; stop all old world pods and resolve duplicate living characters before upgrading", w.ID, err)
}
}
}
if _, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES(1)`); err != nil {
return err
}
return tx.Commit()
}
func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *game.Character, claim bool) error {
raw, err := json.Marshal(c)
if err != nil {
return err
}
where := "character_records.world_id=excluded.world_id"
if claim {
where = "character_records.account_id=excluded.account_id"
}
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET world_id=excluded.world_id,name=excluded.name,state=excluded.state,character=excluded.character WHERE `+where), c.View.Entity.ID, c.Account, world, c.View.Entity.Name, c.View.Entity.State, string(raw))
if err != nil && (strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "character_records.account_id")) {
return ErrLivingCharacter
}
return err
}
func (d *DB) syncCharacters(ctx context.Context, tx *sql.Tx, w *game.World, claim string) error {
// Release dead lives before reserving their replacements, independent of map order.
characters := make([]*game.Character, 0, len(w.Characters))
for _, c := range w.Characters {
characters = append(characters, c)
}
sort.Slice(characters, func(i, j int) bool {
a, b := characters[i], characters[j]
if (a.View.Entity.State == "dead") != (b.View.Entity.State == "dead") {
return a.View.Entity.State == "dead"
}
return a.View.Entity.ID < b.View.Entity.ID
})
for _, c := range characters {
if err := d.writeCharacter(ctx, tx, w.ID, c, c.View.Entity.ID == claim && claim != ""); err != nil {
return err
}
}
return nil
}
func (d *DB) ActiveCharacter(ctx context.Context, account string) (*CharacterRecord, error) {
var r CharacterRecord
var raw string
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
if err = json.Unmarshal([]byte(raw), &r.Character); err != nil {
return nil, err
}
return &r, nil
}
func (d *DB) Characters(ctx context.Context, account, world string) ([]CharacterRecord, error) {
query := `SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE 1=1`
args := []any{}
if account != "" {
query += " AND account_id=?"
args = append(args, account)
}
if world != "" {
query += " AND world_id=?"
args = append(args, world)
}
query += " ORDER BY world_id,name,character_id LIMIT 500"
rows, err := d.sql.QueryContext(ctx, d.q(query), args...)
if err != nil {
return nil, err
}
defer rows.Close()
out := []CharacterRecord{}
for rows.Next() {
var r CharacterRecord
var raw string
if err = rows.Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw); err != nil {
return nil, err
}
if err = json.Unmarshal([]byte(raw), &r.Character); err != nil {
return nil, err
}
out = append(out, r)
}
return out, rows.Err()
}
func (d *DB) Worlds(ctx context.Context) ([]WorldRecord, error) {
rows, err := d.sql.QueryContext(ctx, `SELECT snapshot,revision,CASE WHEN owner<>'' AND lease_until>=`+d.now()+` THEN 1 ELSE 0 END FROM worlds ORDER BY id LIMIT 200`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []WorldRecord{}
for rows.Next() {
var raw string
var r WorldRecord
var available int
if err = rows.Scan(&raw, &r.Revision, &available); err != nil {
return nil, err
}
var w game.World
if err = json.Unmarshal([]byte(raw), &w); err != nil {
return nil, err
}
r.ID = w.ID
r.Phase = w.Phase
r.Living = w.LivingCount()
r.Dead = len(w.Characters) - r.Living
r.Capacity = w.Balance.MaxPlayers
r.CreatedAt = w.CreatedAt
r.BossAt = w.CreatedAt.Add(time.Duration(w.Balance.SeasonSeconds) * time.Second)
r.Closed = w.AdmissionsClosed
r.Available = available == 1
out = append(out, r)
}
return out, rows.Err()
}
func (d *DB) GrantAdmin(ctx context.Context, token string, seconds int64) error {
_, err := d.sql.ExecContext(ctx, d.q(`INSERT INTO admin_sessions(token_hash,expires) VALUES(?,`+d.now()+`+?) ON CONFLICT(token_hash) DO UPDATE SET expires=excluded.expires`), token, seconds)
return err
}
func (d *DB) IsAdmin(ctx context.Context, token string) bool {
var n int
err := d.sql.QueryRowContext(ctx, d.q(`SELECT 1 FROM admin_sessions a JOIN sessions s ON s.token_hash=a.token_hash WHERE a.token_hash=? AND a.expires>`+d.now()+` AND s.expires>`+d.now()), token).Scan(&n)
return err == nil && n == 1
}
func (d *DB) Enqueue(ctx context.Context, c Command) error {
_, err := d.sql.ExecContext(ctx, d.q(`INSERT INTO control_commands(id,world_id,actor,op,target,value,reason,status,result,created_at) VALUES(?,?,?,?,?,?,?,'pending','',`+d.now()+`) ON CONFLICT(id) DO NOTHING`), c.ID, c.WorldID, c.Actor, c.Op, c.Target, c.Value, c.Reason)
if err != nil {
return err
}
var existing Command
err = d.sql.QueryRowContext(ctx, d.q(`SELECT actor,world_id,op,target,value,reason FROM control_commands WHERE id=?`), c.ID).Scan(&existing.Actor, &existing.WorldID, &existing.Op, &existing.Target, &existing.Value, &existing.Reason)
if err != nil {
return err
}
if existing.Actor != c.Actor || existing.WorldID != c.WorldID || existing.Op != c.Op || existing.Target != c.Target || existing.Value != c.Value || existing.Reason != c.Reason {
return errors.New("request ID already used")
}
return nil
}
func (d *DB) Commands(ctx context.Context, world string, pending bool) ([]Command, error) {
query := `SELECT id,world_id,actor,op,target,value,reason,status,result,created_at,completed_at FROM control_commands WHERE 1=1`
args := []any{}
if world != "" {
query += " AND world_id=?"
args = append(args, world)
}
if pending {
query += " AND status='pending' ORDER BY created_at,id LIMIT 10"
} else {
query += " ORDER BY created_at DESC,id LIMIT 100"
}
rows, err := d.sql.QueryContext(ctx, d.q(query), args...)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Command{}
for rows.Next() {
var c Command
if err = rows.Scan(&c.ID, &c.WorldID, &c.Actor, &c.Op, &c.Target, &c.Value, &c.Reason, &c.Status, &c.Result, &c.CreatedAt, &c.CompletedAt); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
func (d *DB) FinishProvision(ctx context.Context, id, result string, success bool) error {
status := "rejected"
if success {
status = "completed"
}
_, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op='create-world'`), status, result, id)
return err
}
+214
View File
@@ -0,0 +1,214 @@
package store
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
)
func TestGlobalLivingCharacter(t *testing.T) {
runGlobalLives(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "lives.db")))
}
func TestPostgresGlobalLivingCharacter(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not configured")
}
runGlobalLives(t, dsn)
}
func runGlobalLives(t *testing.T, dsn string) {
ctx := context.Background()
db, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
prefix := game.ID()
account := "lives:" + prefix
worlds := []*game.World{game.New(prefix+"-a", 1, time.Now(), b), game.New(prefix+"-b", 2, time.Now(), b)}
leases := make([]*Lease, 2)
for i, w := range worlds {
leases[i], _, err = db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
if _, err = w.Join(account, "Traveler"); err != nil {
t.Fatal(err)
}
}
var wg sync.WaitGroup
results := make([]error, 2)
for i := range worlds {
wg.Add(1)
go func(i int) { defer wg.Done(); results[i] = leases[i].Save(ctx, worlds[i], "") }(i)
}
wg.Wait()
winner := -1
loser := -1
for i, err := range results {
if err == nil {
if winner != -1 {
t.Fatal("two living characters committed")
}
winner = i
} else {
if !errors.Is(err, ErrLivingCharacter) {
t.Fatal(err)
}
loser = i
}
}
if winner < 0 || loser < 0 {
t.Fatal("expected exactly one committed life")
}
var raw string
if err = db.sql.QueryRowContext(ctx, db.q(`SELECT snapshot FROM worlds WHERE id=?`), worlds[loser].ID).Scan(&raw); err != nil {
t.Fatal(err)
}
var durable game.World
_ = json.Unmarshal([]byte(raw), &durable)
if len(durable.Characters) != 0 {
t.Fatal("failed join left a durable duplicate")
}
old := worlds[winner].ForAccount(account)
if err = worlds[winner].Control("retire", old.View.Entity.ID, "", "test retirement"); err != nil {
t.Fatal(err)
}
if err = leases[winner].Save(ctx, worlds[winner], ""); err != nil {
t.Fatal(err)
}
if err = leases[loser].Save(ctx, worlds[loser], ""); err != nil {
t.Fatal(err)
}
active, err := db.ActiveCharacter(ctx, account)
if err != nil || active == nil || active.WorldID != worlds[loser].ID {
t.Fatal("death did not release the living-character reservation")
}
if err = leases[winner].Save(ctx, worlds[winner], ""); err != nil {
t.Fatal("old dead world interfered with replacement", err)
}
history, err := db.Characters(ctx, account, "")
if err != nil || len(history) != 2 {
t.Fatal("death history missing", err)
}
for _, l := range leases {
_ = l.Release(ctx)
}
}
func TestCommandAuditAtomicity(t *testing.T) {
ctx := context.Background()
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "audit.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
w := game.New("audit", 1, time.Now(), b)
l, _, _ := db.Acquire(ctx, w)
c := Command{ID: game.ID(), WorldID: w.ID, Actor: "admin", Op: "close-admissions", Reason: "maintenance test"}
if err = db.Enqueue(ctx, c); err != nil {
t.Fatal(err)
}
if err = db.Enqueue(ctx, c); err != nil {
t.Fatal("retry not idempotent", err)
}
if err = w.Control(c.Op, "", "", c.Reason); err != nil {
t.Fatal(err)
}
if err = l.SaveCommand(ctx, w, "", &c, ""); err != nil {
t.Fatal(err)
}
commands, _ := db.Commands(ctx, w.ID, false)
if len(commands) != 1 || commands[0].Status != "completed" {
t.Fatal("audit not completed")
}
if err = l.SaveCommand(ctx, w, "", &c, ""); err == nil {
t.Fatal("command completed twice")
}
c.Actor = "different"
if err = db.Enqueue(ctx, c); err == nil {
t.Fatal("request ID could be reused")
}
}
func TestOldSurvivorSnapshotCannotReclaimReplacement(t *testing.T) {
ctx := context.Background()
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "old-source.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
source := game.New("source", 1, time.Now(), b)
sl, _, _ := db.Acquire(ctx, source)
c, _ := source.Join("account", "Survivor")
c.View.Entity.State = "eligible"
source.Phase = "won"
if err = sl.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
target := game.New("target", 2, time.Now(), b)
tl, _, _ := db.Acquire(ctx, target)
copy, _ := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
if err = target.Import(copy); err != nil {
t.Fatal(err)
}
if err = tl.Save(ctx, target, c.View.Entity.ID); err != nil {
t.Fatal(err)
}
if err = target.Control("retire", c.View.Entity.ID, "", "test death"); err != nil {
t.Fatal(err)
}
if err = tl.Save(ctx, target, ""); err != nil {
t.Fatal(err)
}
replacement, _ := target.Join(c.Account, "Replacement")
if err = tl.Save(ctx, target, ""); err != nil {
t.Fatal(err)
}
if err = sl.Save(ctx, source, ""); err != nil {
t.Fatal("old source blocked new life", err)
}
active, _ := db.ActiveCharacter(ctx, c.Account)
if active == nil || active.ID != replacement.View.Entity.ID {
t.Fatal("old survivor reclaimed character slot")
}
}
func TestLegacySnapshotBackfill(t *testing.T) {
ctx := context.Background()
dsn := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "legacy.db"))
db, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
b, _ := content.Load()
w := game.New("legacy", 1, time.Now(), b)
l, _, _ := db.Acquire(ctx, w)
c, _ := w.Join("account", "Legacy")
if err = l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
_ = l.Release(ctx)
_, _ = db.sql.ExecContext(ctx, `DELETE FROM character_records`)
_, _ = db.sql.ExecContext(ctx, `DELETE FROM schema_migrations`)
_ = db.Close()
db, err = Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
active, err := db.ActiveCharacter(ctx, c.Account)
if err != nil || active == nil || active.ID != c.View.Entity.ID {
t.Fatal("legacy living character not backfilled", err)
}
}
+29
View File
@@ -69,6 +69,10 @@ func Open(ctx context.Context, dsn string) (*DB, error) {
return nil, err
}
}
if err = db.migrate(ctx); err != nil {
conn.Close()
return nil, err
}
return db, nil
}
func (d *DB) Close() error { return d.sql.Close() }
@@ -128,6 +132,9 @@ func (d *DB) Acquire(ctx context.Context, w *game.World) (*Lease, []byte, error)
return &Lease{d, w.ID, owner, revision}, []byte(snapshot), nil
}
func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
return l.SaveCommand(ctx, w, claimID, nil, "")
}
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
data, err := json.Marshal(w)
if err != nil {
return err
@@ -175,6 +182,28 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
}
}
}
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
return err
}
if command != nil {
status := "completed"
if outcome != "" {
status = "rejected"
}
r, err := tx.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND world_id=? AND status='pending'`), status, outcome, command.ID, w.ID)
if err != nil {
return err
}
n, _ := r.RowsAffected()
if n != 1 {
return errors.New("command already processed")
}
if command.Op == "revoke-sessions" && outcome == "" {
if _, err = tx.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE account_id=?`), command.Target); err != nil {
return err
}
}
}
if err = tx.Commit(); err != nil {
return err
}
+70 -12
View File
@@ -7,6 +7,7 @@ import (
"errors"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
@@ -18,21 +19,24 @@ import (
)
type Auth struct {
db *store.DB
dev bool
base string
oauth *oauth2.Config
verifier *oidc.IDTokenVerifier
mu sync.Mutex
flows map[string]flow
db *store.DB
dev bool
base string
oauth *oauth2.Config
verifier *oidc.IDTokenVerifier
mu sync.Mutex
flows map[string]flow
AdminRole string
DevAdmin bool
}
type flow struct {
verifier string
expires time.Time
returnTo string
}
func NewAuth(ctx context.Context, db *store.DB, dev bool, base, issuer, client, secret string) (*Auth, error) {
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}}
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}, AdminRole: "aeternalis-admin"}
if dev {
return a, nil
}
@@ -62,16 +66,25 @@ func (a *Auth) account(r *http.Request) (string, error) {
return a.db.Session(r.Context(), hash(c.Value))
}
func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error {
return a.issueSession(w, r, account, false)
}
func (a *Auth) issueSession(w http.ResponseWriter, r *http.Request, account string, admin bool) error {
token := game.ID() + game.ID()
if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil {
return err
}
if admin {
if err := a.db.GrantAdmin(r.Context(), hash(token), 600); err != nil {
_ = a.db.DeleteSession(r.Context(), hash(token))
return err
}
}
http.SetCookie(w, &http.Cookie{Name: a.cookieName(), Value: token, Path: "/", HttpOnly: true, Secure: !a.dev, SameSite: http.SameSiteLaxMode, MaxAge: 86400})
return nil
}
func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
if a.dev {
http.Redirect(w, r, "/", http.StatusSeeOther)
http.Redirect(w, r, safeReturn(r.URL.Query().Get("return")), http.StatusSeeOther)
return
}
state := game.ID() + game.ID()
@@ -87,7 +100,7 @@ func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
fail(w, 503, "login capacity reached")
return
}
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)}
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute), safeReturn(r.URL.Query().Get("return"))}
a.mu.Unlock()
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Value: state, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 600})
http.Redirect(w, r, a.oauth.AuthCodeURL(state, oauth2.S256ChallengeOption(v), oidc.Nonce(state)), http.StatusSeeOther)
@@ -128,12 +141,57 @@ func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
fail(w, 401, "invalid identity token")
return
}
if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); err != nil {
var claims roleClaims
if err = identity.Claims(&claims); err != nil {
fail(w, 401, "invalid identity claims")
return
}
if err = a.issueSession(w, r, hash(identity.Issuer+"\x00"+identity.Subject), claims.admin(a.AdminRole, a.oauth.ClientID)); err != nil {
fail(w, 503, "session unavailable")
return
}
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1})
http.Redirect(w, r, "/", http.StatusSeeOther)
http.Redirect(w, r, f.returnTo, http.StatusSeeOther)
}
type roleSet struct {
Roles []string `json:"roles"`
}
type roleClaims struct {
Realm roleSet `json:"realm_access"`
Clients map[string]roleSet `json:"resource_access"`
}
func (c roleClaims) admin(role, client string) bool {
return role != "" && (slices.Contains(c.Realm.Roles, role) || slices.Contains(c.Clients[client].Roles, role))
}
func (a *Auth) isAdmin(r *http.Request) bool {
if _, err := a.account(r); err != nil {
return false
}
if a.dev && a.DevAdmin {
return true
}
c, err := r.Cookie(a.cookieName())
return err == nil && a.db.IsAdmin(r.Context(), hash(c.Value))
}
func safeReturn(raw string) string {
u, err := url.Parse(raw)
if err != nil || u.IsAbs() || u.Host != "" || u.User != nil || u.Fragment != "" {
return "/"
}
if u.Path == "/control" {
return "/control"
}
if u.Path == "/game" {
q := url.Values{}
if world := u.Query().Get("world"); worldIDPattern.MatchString(world) {
q.Set("world", world)
}
u.RawQuery = q.Encode()
return u.String()
}
return "/"
}
func validOrigin(r *http.Request, base string) bool {
origin := r.Header.Get("Origin")
+196
View File
@@ -0,0 +1,196 @@
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)
}
}
}
}
+117
View File
@@ -0,0 +1,117 @@
package transport
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
"aeternalis/server/internal/store"
)
func TestControlAuthorizationAndExecution(t *testing.T) {
ctx := context.Background()
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "control.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
w := game.New("control-test", 1, time.Now(), b)
lease, _, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
svc := NewService(w, lease)
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
assets := t.TempDir()
for _, f := range []string{"index.html", "game.html", "control.html"} {
if err = os.WriteFile(filepath.Join(assets, f), []byte("<!doctype html><title>"+f+"</title>"), 0600); err != nil {
t.Fatal(err)
}
}
server := httptest.NewServer(NewHTTP(svc, auth, assets, nil).Handler())
defer server.Close()
auth.base = server.URL
request := func(method, path, body, token, origin string) int {
t.Helper()
r, _ := http.NewRequest(method, server.URL+path, strings.NewReader(body))
if token != "" {
r.AddCookie(&http.Cookie{Name: auth.cookieName(), Value: token})
}
r.Header.Set("Origin", origin)
response, err := server.Client().Do(r)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
return response.StatusCode
}
for _, path := range []string{"/", "/game", "/control", "/worlds/control-test/api/config"} {
if status := request("GET", path, "", "", ""); status != 200 {
t.Fatal(path, status)
}
}
if status := request("GET", "/worlds/another/api/config", "", "", ""); status != 404 {
t.Fatal("wrong world routed", status)
}
if request("GET", "/api/control", "", "", "") != 401 {
t.Fatal("anonymous admin access")
}
token := game.ID() + game.ID()
_ = db.CreateSession(ctx, hash(token), "operator")
if request("GET", "/api/control", "", token, "") != 403 {
t.Fatal("player has admin access")
}
_ = db.GrantAdmin(ctx, hash(token), 600)
if request("GET", "/api/control", "", token, "") != 200 {
t.Fatal("admin denied")
}
body := `{"id":"` + game.ID() + `","worldId":"control-test","op":"close-admissions","reason":"maintenance window"}`
if request("POST", "/api/control/commands", body, token, "https://evil.example") != 403 {
t.Fatal("cross-origin admin command")
}
if request("POST", "/api/control/commands", body, token, server.URL) != 202 {
t.Fatal("command not queued")
}
if err = svc.controls(ctx); err != nil {
t.Fatal(err)
}
if !w.AdmissionsClosed {
t.Fatal("command not applied by world owner")
}
commands, _ := db.Commands(ctx, w.ID, false)
if len(commands) != 1 || commands[0].Status != "completed" {
t.Fatal("command not audited")
}
bad := `{"id":"` + game.ID() + `","worldId":"control-test","op":"end-world","reason":"maintenance window"}`
if request("POST", "/api/control/commands", bad, token, server.URL) != 400 {
t.Fatal("destructive action without confirmation")
}
_ = db.DeleteSession(ctx, hash(token))
if request("GET", "/api/control", "", token, "") != 401 {
t.Fatal("revoked admin session accepted")
}
}
func TestKeycloakRolesAndReturnURL(t *testing.T) {
var claims roleClaims
_ = json.Unmarshal([]byte(`{"realm_access":{"roles":["player"]},"resource_access":{"game":{"roles":["aeternalis-admin"]},"other":{"roles":["foreign-admin"]}}}`), &claims)
if !claims.admin("aeternalis-admin", "game") || claims.admin("foreign-admin", "game") || claims.admin("", "game") {
t.Fatal("role scope validation")
}
for _, raw := range []string{"https://evil.example", "//evil.example/game", "/\\evil", "/game#fragment", "/control?next=https://evil"} {
if result := safeReturn(raw); result != "/" && result != "/control" {
t.Fatal("unsafe return", raw, result)
}
}
if safeReturn("/game?world=world-002&evil=value") != "/game?world=world-002" {
t.Fatal("game return lost or untrusted query retained")
}
}
+39 -8
View File
@@ -15,6 +15,7 @@ import (
"time"
"aeternalis/server/internal/game"
"aeternalis/server/internal/gitops"
p "aeternalis/server/internal/protocol"
"github.com/coder/websocket"
)
@@ -24,12 +25,13 @@ type Destination struct {
URL string `json:"url"`
}
type HTTP struct {
s *Service
auth *Auth
assets string
worlds []Destination
mu sync.Mutex
rates map[string]*bucket
s *Service
auth *Auth
assets string
worlds []Destination
mu sync.Mutex
rates map[string]*bucket
Provisioner *gitops.Client
}
type bucket struct {
tokens float64
@@ -94,6 +96,7 @@ func (h *HTTP) allow(r *http.Request) bool {
}
func (h *HTTP) Handler() http.Handler {
mux := http.NewServeMux()
h.portalRoutes(mux)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
if !h.s.ready.Load() {
fail(w, 503, "world frozen")
@@ -164,13 +167,18 @@ func (h *HTTP) Handler() http.Handler {
fail(w, 401, "sign in required")
return
}
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
if err != nil {
fail(w, 503, "character registry unavailable")
return
}
h.s.mu.Lock()
defer h.s.mu.Unlock()
if c := h.s.world.ForAccount(account); c != nil {
if c := h.s.world.ForAccount(account); c != nil && active != nil && active.WorldID == h.s.world.ID && active.ID == c.View.Entity.ID {
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()})
respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info(), "active": active})
})
mux.HandleFunc("POST /api/join", func(w http.ResponseWriter, r *http.Request) {
account, err := h.auth.account(r)
@@ -237,6 +245,12 @@ func (h *HTTP) Handler() http.Handler {
respond(w, 200, map[string]bool{"ok": true})
})
mux.HandleFunc("GET /ws", h.socket)
for route, file := range map[string]string{"/{$}": "index.html", "/game": "game.html", "/control": "control.html"} {
mux.HandleFunc("GET "+route, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
http.ServeFile(w, r, filepath.Join(h.assets, file))
})
}
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))
@@ -258,6 +272,17 @@ func (h *HTTP) Handler() http.Handler {
files.ServeHTTP(w, r)
})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
prefix := "/worlds/" + h.s.world.ID
if strings.HasPrefix(r.URL.Path, prefix+"/") {
r = r.Clone(r.Context())
u := *r.URL
u.Path = strings.TrimPrefix(u.Path, prefix)
u.RawPath = ""
r.URL = &u
} else if strings.HasPrefix(r.URL.Path, "/worlds/") {
fail(w, 404, "unknown world route")
return
}
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Frame-Options", "DENY")
@@ -307,6 +332,12 @@ func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) {
return
}
id := c.View.Entity.ID
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
if err != nil || active == nil || active.WorldID != h.s.world.ID || active.ID != id {
h.s.mu.Unlock()
fail(w, 409, "character is not active in this world")
return
}
if h.s.peers[id] != nil {
h.s.mu.Unlock()
fail(w, 409, "character already connected")
+80 -8
View File
@@ -22,13 +22,14 @@ type peer struct {
close func()
}
type Service struct {
mu sync.Mutex
world *game.World
lease *store.Lease
peers map[string]*peer
ready atomic.Bool
lastSave time.Time
done chan struct{}
mu sync.Mutex
world *game.World
lease *store.Lease
peers map[string]*peer
ready atomic.Bool
lastSave time.Time
lastControl time.Time
done chan struct{}
}
func NewService(w *game.World, l *store.Lease) *Service {
@@ -66,6 +67,14 @@ func (s *Service) Run(ctx context.Context) {
}
s.world.Advance(now, now.Sub(last).Seconds())
last = now
if now.Sub(s.lastControl) >= time.Second {
if err := s.controls(ctx); err != nil {
s.ready.Store(false)
s.mu.Unlock()
return
}
s.lastControl = now
}
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := s.persist(saveCtx, "")
@@ -125,6 +134,18 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
}
var c *game.Character
var err error
active, err := s.lease.DB.ActiveCharacter(ctx, account)
if err != nil {
return p.Character{}, errors.New("character registry unavailable")
}
if active != nil {
transfer := claim != "" && active.ID == claim && active.State == "eligible" && active.WorldID != s.world.ID
resume := claim == "" && active.WorldID == s.world.ID
if !transfer && !resume {
return p.Character{}, store.ErrLivingCharacter
}
}
existing := s.world.ForAccount(account)
if claim != "" {
c, err = s.lease.DB.ReadPassage(ctx, claim, account)
if err != nil {
@@ -139,11 +160,62 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
return p.Character{}, err
}
}
if err = s.persist(ctx, claim); err != nil {
if err = s.lease.Save(ctx, s.world, claim); err != nil {
if errors.Is(err, store.ErrLivingCharacter) {
if existing == nil {
delete(s.world.Characters, c.View.Entity.ID)
}
return p.Character{}, err
}
s.ready.Store(false)
for _, peer := range s.peers {
peer.close()
}
return p.Character{}, errors.New("world persistence unavailable")
}
s.lastSave = time.Now()
view := c.View
view.Inventory = maps.Clone(view.Inventory)
view.Skills = maps.Clone(view.Skills)
return view, nil
}
func (s *Service) controls(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
commands, err := s.lease.DB.Commands(ctx, s.world.ID, true)
if err != nil {
return err
}
for _, command := range commands {
result := ""
if time.Now().Unix()-command.CreatedAt > 900 {
result = "command expired before execution"
} else if command.Op == "revoke-sessions" {
found := false
for id, c := range s.world.Characters {
if c.Account == command.Target {
found = true
s.world.Disconnect(id)
if p := s.peers[id]; p != nil {
p.close()
}
}
}
if !found {
result = "account not found in world"
}
} else if err = s.world.Control(command.Op, command.Target, command.Value, command.Reason); err != nil {
result = err.Error()
}
if err = s.lease.SaveCommand(ctx, s.world, "", &command, result); err != nil {
s.ready.Store(false)
for _, peer := range s.peers {
peer.close()
}
return err
}
s.lastSave = time.Now()
}
return nil
}