Build playable Aeternalis foundation and GitOps deployment pipeline

This commit is contained in:
dingo
2026-09-05 12:52:51 -04:00
parent 93703b20bc
commit ff87b8a544
66 changed files with 6567 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
package game
import (
"fmt"
"math"
"math/rand/v2"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"github.com/ojrac/opensimplex-go"
)
const GeneratorVersion = 1
type Terrain struct {
Seed int64
B content.Balance
noise opensimplex.Noise
}
func NewTerrain(seed int64, b content.Balance) *Terrain {
return &Terrain{seed, b, opensimplex.New(seed)}
}
func (t *Terrain) rawHeight(x, z float64) float64 {
// A low, flat arrival clearing blends into broad hills and fine detail.
d := math.Min(1, math.Hypot(x, z)/55)
return (t.noise.Eval2(x/220, z/220)*17 + t.noise.Eval2(x/55, z/55)*3) * d
}
func ChunkCoord(v, size float64) int { return int(math.Floor(v / size)) }
func Key(x, z int) string { return fmt.Sprintf("%d:%d", x, z) }
// Height uses the same triangle split as the transmitted terrain mesh.
func (t *Terrain) Height(x, z float64) float64 {
step := t.B.ChunkSize / float64(t.B.TerrainResolution)
ix, iz := math.Floor(x/step), math.Floor(z/step)
fx, fz := x/step-ix, z/step-iz
a, b := t.rawHeight(ix*step, iz*step), t.rawHeight((ix+1)*step, iz*step)
c, d := t.rawHeight(ix*step, (iz+1)*step), t.rawHeight((ix+1)*step, (iz+1)*step)
if fx+fz <= 1 {
return a + (b-a)*fx + (c-a)*fz
}
return d + (c-d)*(1-fx) + (b-d)*(1-fz)
}
func (t *Terrain) Position(x, z float64) p.Vec3 { return p.Vec3{X: x, Y: t.Height(x, z), Z: z} }
func (t *Terrain) Chunk(x, z int) p.Chunk {
c := p.Chunk{Key: Key(x, z), X: int64(x), Z: int64(z), Size: t.B.ChunkSize, Resolution: int64(t.B.TerrainResolution), Biome: "highlands", Heights: []float64{}, Resources: []p.Entity{}}
for iz := 0; iz <= t.B.TerrainResolution; iz++ {
for ix := 0; ix <= t.B.TerrainResolution; ix++ {
c.Heights = append(c.Heights, t.rawHeight(float64(x)*c.Size+float64(ix)*c.Size/float64(c.Resolution), float64(z)*c.Size+float64(iz)*c.Size/float64(c.Resolution)))
}
}
rng := rand.New(rand.NewPCG(uint64(t.Seed)^uint64(int64(x)*73856093), uint64(int64(z)*19349663)^0xa341316c))
kinds := []string{"tree", "ore", "herb"}
for i := 0; i < t.B.ResourcesPerChunk; i++ {
px, pz := (float64(x)+0.08+rng.Float64()*0.84)*c.Size, (float64(z)+0.08+rng.Float64()*0.84)*c.Size
if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 10 {
continue
}
kind := kinds[i%len(kinds)]
c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%d", x, z, i), Kind: kind, Name: kind, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"})
}
// Arrival resources make the first crafting loop reachable without aimless travel.
if x == 0 && z == 0 {
for i, k := range kinds {
c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + k, Kind: k, Name: k, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"})
}
}
return c
}
+648
View File
@@ -0,0 +1,648 @@
package game
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"math"
"sort"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
)
type Character struct {
View p.Character `json:"view"`
Account string `json:"account"`
Day string `json:"day"`
DailySeconds float64 `json:"dailySeconds"`
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
Sheltered bool `json:"sheltered"`
LastAttack float64 `json:"lastAttack"`
LastGather float64 `json:"lastGather"`
Online bool `json:"-"`
MoveX float64 `json:"-"`
MoveZ float64 `json:"-"`
LastMove time.Time `json:"-"`
Message string `json:"-"`
}
type Corpse struct {
Entity p.Entity `json:"entity"`
Inventory map[string]int64 `json:"inventory"`
}
type Mob struct {
Entity p.Entity `json:"entity"`
HomeX int `json:"homeX"`
HomeZ int `json:"homeZ"`
LastAttack float64 `json:"lastAttack"`
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
}
func ID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
return hex.EncodeToString(b[:])
}
func New(id string, seed int64, now time.Time, b content.Balance) *World {
w := &World{Version: GeneratorVersion, ID: id, Seed: seed, CreatedAt: now, Phase: "gathering", BossHP: b.BossHp, Characters: map[string]*Character{}, Corpses: map[string]*Corpse{}, Depleted: map[string]float64{}, Mobs: map[string]*Mob{}, Balance: b}
_ = w.Restore(now)
return w
}
func (w *World) Restore(now time.Time) error {
if w.Version != GeneratorVersion {
return errors.New("unsupported persisted generator version")
}
if err := w.Balance.Validate(); err != nil {
return err
}
if w.Characters == nil || w.Mobs == nil || w.Corpses == nil || w.Depleted == nil {
return errors.New("invalid world snapshot")
}
w.terrain = NewTerrain(w.Seed, w.Balance)
w.chunks = map[string]p.Chunk{}
w.now = now
for _, c := range w.Characters {
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.View.ACK = 0
}
return nil
}
func (w *World) Age() float64 {
now := w.now
if w.EndedAt != nil {
now = *w.EndedAt
}
return math.Max(0, now.Sub(w.CreatedAt).Seconds())
}
func (w *World) Dirty() bool { return w.dirty }
func (w *World) Saved() { w.dirty = false }
func (w *World) SafeRadius() float64 {
if w.Phase == "gathering" {
return w.Balance.WorldRadius
}
if w.Phase == "lost" {
return 0
}
return math.Max(0, w.Balance.WorldRadius*(1-(w.Age()-w.Balance.SeasonSeconds)/w.Balance.CollapseSeconds))
}
func (w *World) Info() p.WorldInfo {
online := int64(0)
for _, c := range w.Characters {
if c.Online {
online++
}
}
return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp}
}
func (w *World) ForAccount(account string) *Character {
for _, c := range w.Characters {
if c.Account == account {
return c
}
}
return nil
}
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 {
break
}
clear := true
for id, c := range w.Characters {
if id != exclude && c.View.Entity.State != "dead" && distance(pos, c.View.Entity.Position) < w.Balance.SpawnSeparation {
clear = false
break
}
}
if clear {
return pos, nil
}
}
return p.Vec3{}, errors.New("no separated spawn available")
}
func (w *World) Join(account, name string) (*Character, error) {
if c := w.ForAccount(account); c != nil {
return c, nil
}
if w.Phase != "gathering" {
return nil, errors.New("this world is closed to new arrivals")
}
if len(w.Characters) >= w.Balance.MaxPlayers {
return nil, errors.New("world capacity reached")
}
pos, err := w.spawn("")
if err != nil {
return nil, err
}
c := &Character{Account: account, Day: w.now.UTC().Format(time.DateOnly), View: p.Character{Entity: p.Entity{ID: ID(), Kind: "player", Name: name, Position: pos, HP: w.Balance.PlayerHp, MaxHP: w.Balance.PlayerHp, State: "alive"}, Inventory: map[string]int64{}, Skills: map[string]int64{}, RemainingSeconds: w.Balance.DailyPlaySeconds}}
for k, v := range w.Balance.StartingKit {
c.View.Inventory[k] = v
}
w.Characters[c.View.Entity.ID] = c
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 {
return errors.New("destination cannot accept character")
}
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
return errors.New("character is not a living survivor")
}
pos, err := w.spawn("")
if err != nil {
return err
}
c.View.Entity.Position = pos
c.View.Entity.State = "alive"
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.View.ACK = 0
c.LastAttack = 0
c.LastGather = 0
c.ReturnPosition = nil
c.Sheltered = false
c.View.HasKeystone = false
w.resetDay(c)
w.Characters[c.View.Entity.ID] = c
w.dirty = true
return nil
}
func (w *World) resetDay(c *Character) {
day := w.now.UTC().Format(time.DateOnly)
if c.Day != day {
c.Day = day
c.DailySeconds = 0
w.dirty = true
}
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
}
func (w *World) Connect(id string) error {
c := w.Characters[id]
if c == nil {
return errors.New("character not found")
}
w.resetDay(c)
if c.View.Entity.State == "dead" {
return errors.New("this character has died permanently")
}
if c.View.RemainingSeconds <= 0 {
return errors.New("daily play limit reached; resets at 00:00 UTC")
}
if c.Online {
return errors.New("character already connected")
}
c.Online = true
c.View.ACK = 0
c.MoveX = 0
c.MoveZ = 0
return nil
}
func (w *World) Disconnect(id string) {
if c := w.Characters[id]; c != nil {
c.Online = false
c.MoveX = 0
c.MoveZ = 0
}
}
func distance(a, b p.Vec3) float64 { return math.Hypot(a.X-b.X, a.Z-b.Z) }
func (w *World) chunk(x, z int) p.Chunk {
key := Key(x, z)
if c, ok := w.chunks[key]; ok {
return c
}
c := w.terrain.Chunk(x, z)
w.chunks[key] = c
return c
}
func (w *World) neighbors(pos p.Vec3) []p.Chunk {
x, z := ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize)
chunks := make([]p.Chunk, 0, 9)
for dz := -1; dz <= 1; dz++ {
for dx := -1; dx <= 1; dx++ {
chunks = append(chunks, w.chunk(x+dx, z+dz))
}
}
return chunks
}
func (w *World) Intent(id string, i p.Intent) error {
c := w.Characters[id]
if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" {
return errors.New("character cannot act")
}
if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 {
return errors.New("invalid input sequence")
}
if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 {
return errors.New("invalid intent")
}
c.View.ACK = i.Seq
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) {
c.Sheltered = false
w.dirty = true
}
switch i.Op {
case "move":
n := math.Max(1, math.Hypot(i.X, i.Z))
c.MoveX = i.X / n
c.MoveZ = i.Z / n
c.LastMove = w.now
return nil
case "gather":
return w.gather(c, i.Target)
case "craft":
return w.craft(c, i.Target)
case "attack":
return w.attack(c, i.Target)
case "heal":
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
return errors.New("no bandage needed or available")
}
c.View.Inventory["bandage"]--
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
w.dirty = true
case "return":
if c.ReturnPosition == nil {
return errors.New("no keystone destination")
}
if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() {
return errors.New("keystone destination has been destroyed")
}
c.View.Entity.Position = *c.ReturnPosition
c.ReturnPosition = nil
c.View.HasKeystone = false
w.dirty = true
case "loot":
corpse := w.Corpses[i.Target]
if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange {
return errors.New("corpse out of reach")
}
for k, v := range corpse.Inventory {
c.View.Inventory[k] += v
}
delete(w.Corpses, i.Target)
w.dirty = true
default:
return errors.New("unknown intent")
}
return nil
}
func (w *World) gather(c *Character, target string) error {
if w.Age()-c.LastGather < w.Balance.GatherCooldown {
return errors.New("gathering cooldown")
}
if until := w.Depleted[target]; until > w.Age() {
return errors.New("resource depleted")
}
for _, chunk := range w.neighbors(c.View.Entity.Position) {
for _, r := range chunk.Resources {
if r.ID != target {
continue
}
if distance(c.View.Entity.Position, r.Position) > w.Balance.GatherRange {
return errors.New("resource out of reach")
}
item := map[string]string{"tree": "wood", "ore": "ore", "herb": "herb"}[r.Kind]
if item == "" {
return errors.New("not gatherable")
}
c.View.Inventory[item]++
c.View.Skills["gathering"] += w.Balance.SkillXpPerAction
c.LastGather = w.Age()
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
w.dirty = true
c.Message = "Gathered " + item
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) craft(c *Character, name string) error {
r, ok := w.Balance.Recipes[name]
if !ok {
return errors.New("unknown recipe")
}
for k, v := range r.Inputs {
if c.View.Inventory[k] < v {
return errors.New("missing crafting materials")
}
}
for k, v := range r.Inputs {
c.View.Inventory[k] -= v
}
for k, v := range r.Outputs {
c.View.Inventory[k] += v
}
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
c.Message = "Crafted " + name
w.dirty = true
return nil
}
func (w *World) attack(c *Character, target string) error {
if w.Age()-c.LastAttack < w.Balance.AttackCooldown {
return errors.New("attack cooldown")
}
damage := w.Balance.PlayerDamage
if c.View.Inventory["spear"] > 0 {
damage = w.Balance.SpearDamage
}
if target == "boss" {
if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 {
return errors.New("boss out of reach")
}
w.BossHP = math.Max(0, w.BossHP-damage)
if w.BossHP == 0 {
w.Phase = "won"
ended := w.now
w.EndedAt = &ended
for _, survivor := range w.Characters {
if survivor.View.Entity.State == "alive" {
survivor.View.Entity.State = "eligible"
survivor.MoveX = 0
survivor.MoveZ = 0
survivor.Message = "The world is saved. Passage is open."
}
}
}
} else {
m := w.Mobs[target]
if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange {
return errors.New("target out of reach")
}
m.Entity.HP = math.Max(0, m.Entity.HP-damage)
if m.Entity.HP == 0 {
m.Entity.State = "dead"
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
c.View.Kills++
c.View.Inventory["herb"]++
}
}
c.LastAttack = w.Age()
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
w.dirty = true
return nil
}
func (w *World) kill(c *Character, reason string) {
if c.View.Entity.State != "alive" {
return
}
e := c.View.Entity
e.ID = "corpse:" + e.ID
e.Kind = "corpse"
e.State = "dead"
e.HP = 0
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory}
c.View.Inventory = map[string]int64{}
c.View.Entity.HP = 0
c.View.Entity.State = "dead"
c.MoveX = 0
c.MoveZ = 0
c.ReturnPosition = nil
c.View.HasKeystone = false
c.Message = reason
w.dirty = true
}
func (w *World) Advance(now time.Time, dt float64) {
playedDT := math.Max(0, dt)
w.now = now
w.Tick++
dt = math.Max(0, math.Min(dt, 0.25))
if w.Phase == "won" || w.Phase == "lost" {
return
}
if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds {
w.Phase = "cataclysm"
w.dirty = true
}
active := map[string]bool{}
for _, c := range w.Characters {
if c.View.Entity.State != "alive" {
continue
}
w.resetDay(c)
if c.Online {
midnight := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC)
c.DailySeconds += math.Min(playedDT, now.Sub(midnight).Seconds())
c.View.PlayedSeconds += playedDT
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
if c.View.RemainingSeconds <= 0 {
pos := c.View.Entity.Position
c.ReturnPosition = &pos
c.Sheltered = true
c.View.HasKeystone = true
c.View.Entity.Position = w.terrain.Position(0, 0)
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, math.Max(50, c.View.Entity.HP))
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.Message = "Daily limit reached. Your keystone is ready for tomorrow."
w.dirty = true
}
}
if c.Online {
if now.Sub(c.LastMove) > 250*time.Millisecond {
c.MoveX = 0
c.MoveZ = 0
}
pos := c.View.Entity.Position
nx, nz := pos.X+c.MoveX*w.Balance.PlayerSpeed*dt, pos.Z+c.MoveZ*w.Balance.PlayerSpeed*dt
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
c.View.Entity.Position = w.terrain.Position(nx, nz)
}
for _, ch := range w.neighbors(c.View.Entity.Position) {
active[ch.Key] = true
w.ensureMob(ch)
}
}
if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() {
c.View.Entity.HP -= w.Balance.StormDamagePerSecond * dt
w.dirty = true
}
if c.View.Entity.HP <= 0 {
w.kill(c, "The encroaching ruin claimed this character.")
}
}
w.updateMobs(active, dt)
if w.Phase == "cataclysm" {
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
for _, c := range w.Characters {
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
c.View.Entity.HP -= w.Balance.BossDamage
w.dirty = true
if c.View.Entity.HP <= 0 {
w.kill(c, "The Harbinger ended this character's journey.")
}
}
}
w.BossLastAttack = w.Age()
}
alive := 0
for _, c := range w.Characters {
if c.View.Entity.State == "alive" {
alive++
}
}
if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) {
for _, c := range w.Characters {
w.kill(c, "The world has been destroyed.")
}
w.Phase = "lost"
ended := w.now
w.EndedAt = &ended
w.dirty = true
}
}
// Keep CPU/GPU working sets bounded to subscribed chunks. Persistent deltas survive eviction.
for key := range w.chunks {
if !active[key] {
delete(w.chunks, key)
}
}
for key, until := range w.Depleted {
if until <= w.Age() {
delete(w.Depleted, key)
}
}
}
func (w *World) ensureMob(ch p.Chunk) {
id := "m:" + ch.Key
if _, ok := w.Mobs[id]; ok {
return
}
x, z := (float64(ch.X)+0.55)*ch.Size, (float64(ch.Z)+0.55)*ch.Size
if math.Hypot(x, z) > w.Balance.WorldRadius {
return
}
hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)}
}
func (w *World) updateMobs(active map[string]bool, dt float64) {
for id, m := range w.Mobs {
key := Key(m.HomeX, m.HomeZ)
if !active[key] {
if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) {
delete(w.Mobs, id)
}
continue
}
if m.Entity.HP <= 0 {
if w.Age() >= m.RespawnAt {
m.Entity.HP = w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
m.Entity.MaxHP = m.Entity.HP
m.Entity.State = "alive"
}
continue
}
var target *Character
nearest := w.Balance.MobAggroRange
for _, c := range w.Characters {
if !c.Online || c.View.Entity.State != "alive" || c.Sheltered {
continue
}
d := distance(c.View.Entity.Position, m.Entity.Position)
if d < nearest {
nearest = d
target = c
}
}
if target == nil {
continue
}
if nearest <= w.Balance.MobAttackRange {
if w.Age()-m.LastAttack >= w.Balance.MobCooldown {
target.View.Entity.HP -= w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
m.LastAttack = w.Age()
w.dirty = true
if target.View.Entity.HP <= 0 {
w.kill(target, "An ash sentinel ended this character's journey.")
}
}
} else {
pos, to := m.Entity.Position, target.View.Entity.Position
step := math.Min(nearest, w.Balance.MobSpeed*dt)
x, z := pos.X+(to.X-pos.X)/nearest*step, pos.Z+(to.Z-pos.Z)/nearest*step
if ChunkCoord(x, w.Balance.ChunkSize) == m.HomeX && ChunkCoord(z, w.Balance.ChunkSize) == m.HomeZ {
m.Entity.Position = w.terrain.Position(x, z)
}
}
}
}
func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
c := w.Characters[id]
s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}}
allowed := map[string]bool{}
for _, ch := range w.neighbors(c.View.Entity.Position) {
allowed[ch.Key] = true
s.ChunkKeys = append(s.ChunkKeys, ch.Key)
if !known[ch.Key] {
s.Chunks = append(s.Chunks, ch)
}
for _, r := range ch.Resources {
if w.Depleted[r.ID] > w.Age() {
s.UnavailableResources = append(s.UnavailableResources, r.ID)
}
}
}
visible := func(pos p.Vec3) bool {
return allowed[Key(ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize))]
}
for _, other := range w.Characters {
if other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) {
s.Entities = append(s.Entities, other.View.Entity)
}
}
for _, m := range w.Mobs {
if m.Entity.HP > 0 && visible(m.Entity.Position) {
s.Entities = append(s.Entities, m.Entity)
}
}
for _, corpse := range w.Corpses {
if visible(corpse.Entity.Position) {
s.Entities = append(s.Entities, corpse.Entity)
}
}
if w.Phase == "cataclysm" && visible(w.terrain.Position(0, 0)) {
s.Entities = append(s.Entities, p.Entity{ID: "boss", Kind: "boss", Name: "The Harbinger", HP: w.BossHP, MaxHP: w.Balance.BossHp, Position: w.terrain.Position(0, 0), State: "alive"})
}
sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID })
return s
}
func (w *World) TriggerBoss() error {
if w.Phase != "gathering" {
return fmt.Errorf("boss event already started")
}
w.CreatedAt = w.now.Add(-time.Duration(w.Balance.SeasonSeconds * float64(time.Second)))
w.Phase = "cataclysm"
w.dirty = true
return nil
}
+305
View File
@@ -0,0 +1,305 @@
package game
import (
"encoding/json"
"math"
"reflect"
"testing"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
)
func fixture(t *testing.T) (*World, *Character) {
t.Helper()
b, err := content.Load()
if err != nil {
t.Fatal(err)
}
w := New("test", 123, time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC), b)
c, err := w.Join("account", "Traveler")
if err != nil {
t.Fatal(err)
}
if err = w.Connect(c.View.Entity.ID); err != nil {
t.Fatal(err)
}
return w, c
}
func TestTerrainDeterministicAndSeamless(t *testing.T) {
b, _ := content.Load()
a := NewTerrain(123, b)
other := NewTerrain(456, b)
if !reflect.DeepEqual(a.Chunk(-1, 0), NewTerrain(123, b).Chunk(-1, 0)) {
t.Fatal("same seed changed")
}
if reflect.DeepEqual(a.Chunk(0, 0), other.Chunk(0, 0)) {
t.Fatal("different seeds identical")
}
left, right := a.Chunk(-1, 0), a.Chunk(0, 0)
n := b.TerrainResolution + 1
for z := 0; z < n; z++ {
if left.Heights[z*n+n-1] != right.Heights[z*n] {
t.Fatal("chunk seam")
}
}
if ChunkCoord(-0.1, 128) != -1 || ChunkCoord(-128, 128) != -1 {
t.Fatal("negative coordinates")
}
for _, r := range left.Resources {
if math.Abs(r.Position.Y-a.Height(r.Position.X, r.Position.Z)) > 1e-8 {
t.Fatal("floating resource")
}
}
}
func TestMovementAuthorityAndInterest(t *testing.T) {
w, c := fixture(t)
id := c.View.Entity.ID
w.now = w.now.Add(time.Second)
for _, intent := range []p.Intent{{Op: "move", Seq: 1, X: 2}, {Op: "move", Seq: 1, X: math.NaN()}, {Op: "move", Seq: 1, Z: math.Inf(1)}} {
if w.Intent(id, intent) == nil {
t.Fatal("invalid movement accepted")
}
}
if err := w.Intent(id, p.Intent{Op: "move", Seq: 1, X: 1, Z: 1}); err != nil {
t.Fatal(err)
}
before := c.View.Entity.Position
w.Advance(w.now.Add(50*time.Millisecond), 0.05)
if got := distance(before, c.View.Entity.Position); math.Abs(got-w.Balance.PlayerSpeed*0.05) > 1e-8 {
t.Fatalf("diagonal speed: %v", got)
}
if w.Intent(id, p.Intent{Op: "move", Seq: 1}) == nil {
t.Fatal("replayed sequence")
}
s := w.Snapshot(id, map[string]bool{})
if len(s.Chunks) != 9 || len(s.ChunkKeys) != 9 {
t.Fatal("interest area not 3x3")
}
known := map[string]bool{}
for _, key := range s.ChunkKeys {
known[key] = true
}
if len(w.Snapshot(id, known).Chunks) != 0 {
t.Fatal("resent known terrain")
}
far, _ := w.Join("far", "Far")
far.View.Entity.Position = w.terrain.Position(700, 700)
far.Online = true
for _, e := range w.Snapshot(id, known).Entities {
if e.ID == far.View.Entity.ID {
t.Fatal("remote entity leaked outside interest")
}
}
w.Advance(w.now.Add(time.Second), 0.05)
if c.MoveX != 0 || c.MoveZ != 0 {
t.Fatal("stale input did not stop")
}
}
func TestGatherCraftAndPermanentDeath(t *testing.T) {
w, c := fixture(t)
id := c.View.Entity.ID
w.now = w.now.Add(2 * time.Second)
if w.Intent(id, p.Intent{Op: "gather", Seq: 1, Target: "arrival:ore"}) == nil {
t.Fatal("remote gather accepted")
}
c.View.Entity.Position = w.terrain.Position(17, 12)
if err := w.Intent(id, p.Intent{Op: "gather", Seq: 2, Target: "arrival:ore"}); err != nil {
t.Fatal(err)
}
if c.View.Inventory["ore"] != 1 {
t.Fatal("gather failed")
}
if w.Intent(id, p.Intent{Op: "gather", Seq: 3, Target: "arrival:ore"}) == nil {
t.Fatal("double gather")
}
if w.Intent(id, p.Intent{Op: "craft", Seq: 4, Target: "spear"}) == nil {
t.Fatal("free craft")
}
c.View.Inventory["wood"] = 3
c.View.Inventory["ore"] = 2
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
t.Fatal(err)
}
if c.View.Inventory["spear"] != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
t.Fatal("recipe not atomic")
}
w.kill(c, "test death")
w.Disconnect(id)
if w.Connect(id) == nil {
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 len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 {
t.Fatal("corpse inventory")
}
raw, _ := json.Marshal(w)
var restored World
if err = json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err = restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if restored.Connect(id) == nil {
t.Fatal("restart resurrected character")
}
}
func TestStaticResourcesAreNotReplicatedEverySnapshot(t *testing.T) {
w, c := fixture(t)
w.Depleted["arrival:ore"] = w.Age() + 60
s := w.Snapshot(c.View.Entity.ID, map[string]bool{})
if len(s.UnavailableResources) != 1 || s.UnavailableResources[0] != "arrival:ore" {
t.Fatal("missing authoritative resource availability")
}
for _, e := range s.Entities {
if e.Kind == "tree" || e.Kind == "ore" || e.Kind == "herb" {
t.Fatal("static resource repeated in dynamic entity snapshot")
}
}
resources := 0
for _, ch := range s.Chunks {
resources += len(ch.Resources)
}
if resources == 0 {
t.Fatal("initial chunk does not carry resources")
}
}
func TestDailyLimitAndKeystone(t *testing.T) {
w, c := fixture(t)
w.Balance.DailyPlaySeconds = 1
c.DailySeconds = .9
c.View.Entity.HP = 20
c.View.Entity.Position = w.terrain.Position(40, 40)
w.Advance(w.now.Add(200*time.Millisecond), .2)
if c.Online || c.ReturnPosition == nil || !c.View.HasKeystone || c.View.Entity.HP != 50 || distance(c.View.Entity.Position, p.Vec3{}) != 0 {
t.Fatalf("cap not enforced: %+v", c)
}
if w.Connect(c.View.Entity.ID) == nil {
t.Fatal("same-day cap bypass")
}
w.now = w.now.Add(24 * time.Hour)
if err := w.Connect(c.View.Entity.ID); err != nil {
t.Fatal(err)
}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "return", Seq: 1}); err != nil {
t.Fatal(err)
}
if c.View.Entity.Position.X != 40 || c.ReturnPosition != nil || c.View.HasKeystone {
t.Fatal("keystone failed")
}
}
func TestDailyBudgetUsesWallTimeDuringLag(t *testing.T) {
w, c := fixture(t)
w.Balance.DailyPlaySeconds = 2
w.Advance(w.now.Add(3*time.Second), 3)
if c.Online || c.View.RemainingSeconds != 0 {
t.Fatal("simulation lag bypassed wall-clock play cap")
}
}
func TestKeystoneCannotGrantRoamingInvulnerability(t *testing.T) {
w, c := fixture(t)
c.Sheltered = true
c.ReturnPosition = &p.Vec3{X: 40, Z: 40}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
t.Fatal(err)
}
if c.Sheltered || c.ReturnPosition == nil {
t.Fatal("leaving sanctuary must remove protection while preserving keystone")
}
}
func TestBossVictoryAndCollapse(t *testing.T) {
t.Run("victory includes offline survivors and excludes dead", func(t *testing.T) {
w, c := fixture(t)
dead, _ := w.Join("dead", "Dead")
w.kill(dead, "test")
offline, _ := w.Join("offline", "Offline")
w.now = w.now.Add(time.Second)
_ = w.TriggerBoss()
w.BossHP = 1
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil {
t.Fatal(err)
}
if w.Phase != "won" || c.View.Entity.State != "eligible" || offline.View.Entity.State != "eligible" || dead.View.Entity.State != "dead" {
t.Fatal("incorrect survivor selection")
}
radius := w.SafeRadius()
w.Advance(w.now.Add(20*24*time.Hour), .05)
if w.SafeRadius() != radius {
t.Fatal("world kept collapsing after boss death")
}
if c.View.Entity.State != "eligible" {
t.Fatal("victory not terminal")
}
if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) == nil {
t.Fatal("survivor mutated frozen world")
}
})
t.Run("collapse kills offline and capped characters", func(t *testing.T) {
w, c := fixture(t)
c.Online = false
c.ReturnPosition = &p.Vec3{X: 40}
w.Advance(w.CreatedAt.Add(time.Duration((w.Balance.SeasonSeconds+w.Balance.CollapseSeconds+1)*float64(time.Second))), .05)
if w.Phase != "lost" || c.View.Entity.State != "dead" {
t.Fatal("world destruction bypass")
}
})
t.Run("boss schedule survives downtime", func(t *testing.T) {
w, _ := fixture(t)
w.Advance(w.CreatedAt.Add(7*24*time.Hour+5*time.Minute), .05)
if w.Phase != "cataclysm" || w.SafeRadius() >= w.Balance.WorldRadius {
t.Fatal("deadline did not advance")
}
})
}
func TestSpawnAndTransferPreserveBudget(t *testing.T) {
w, c := fixture(t)
other, _ := w.Join("other", "Other")
if distance(c.View.Entity.Position, other.View.Entity.Position) < w.Balance.SpawnSeparation {
t.Fatal("spawns overlap")
}
c.View.Entity.State = "eligible"
c.DailySeconds = 123
c.View.PlayedSeconds = 456
c.View.Skills["combat"] = 9
c.View.Inventory["spear"] = 1
next := New("next", 999, w.now, w.Balance)
if err := next.Import(c); err != nil {
t.Fatal(err)
}
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || c.View.Inventory["spear"] != 1 {
t.Fatal("transfer changed progress or budget")
}
if err := next.Import(c); err == nil {
t.Fatal("duplicate import")
}
}
func BenchmarkSnapshot100Players(b *testing.B) {
balance, _ := content.Load()
w := New("bench", 123, time.Now(), balance)
ids := []string{}
for i := 0; i < 100; i++ {
c, err := w.Join(ID(), "Traveler")
if err != nil {
b.Fatal(err)
}
c.Online = true
ids = append(ids, c.View.Entity.ID)
}
w.Advance(time.Now(), .05)
known := map[string]bool{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
s := w.Snapshot(ids[i%len(ids)], known)
if _, err := json.Marshal(s); err != nil {
b.Fatal(err)
}
}
}
+81
View File
@@ -0,0 +1,81 @@
// Code generated from schemas/protocol.json. DO NOT EDIT.
package protocol
type Protocol struct {
Intent Intent `json:"intent"`
Snapshot Snapshot `json:"snapshot"`
}
type Intent struct {
Op string `json:"op"`
Seq int64 `json:"seq"`
Target string `json:"target"`
X float64 `json:"x"`
Z float64 `json:"z"`
}
type Snapshot struct {
ChunkKeys []string `json:"chunkKeys"`
Chunks []Chunk `json:"chunks"`
Entities []Entity `json:"entities"`
Message string `json:"message"`
Self Character `json:"self"`
Tick int64 `json:"tick"`
Type string `json:"type"`
UnavailableResources []string `json:"unavailableResources"`
Version int64 `json:"version"`
World WorldInfo `json:"world"`
}
type Chunk struct {
Biome string `json:"biome"`
Heights []float64 `json:"heights"`
Key string `json:"key"`
Resolution int64 `json:"resolution"`
Resources []Entity `json:"resources"`
Size float64 `json:"size"`
X int64 `json:"x"`
Z int64 `json:"z"`
}
type Entity struct {
HP float64 `json:"hp"`
ID string `json:"id"`
Kind string `json:"kind"`
MaxHP float64 `json:"maxHp"`
Name string `json:"name"`
Position Vec3 `json:"position"`
State string `json:"state"`
}
type Vec3 struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Z float64 `json:"z"`
}
type Character struct {
ACK int64 `json:"ack"`
Entity Entity `json:"entity"`
HasKeystone bool `json:"hasKeystone"`
Inventory map[string]int64 `json:"inventory"`
Kills int64 `json:"kills"`
PlayedSeconds float64 `json:"playedSeconds"`
RemainingSeconds float64 `json:"remainingSeconds"`
Skills map[string]int64 `json:"skills"`
}
type WorldInfo struct {
AgeSeconds float64 `json:"ageSeconds"`
BossHP float64 `json:"bossHp"`
BossInSeconds float64 `json:"bossInSeconds"`
BossMaxHP float64 `json:"bossMaxHp"`
Capacity int64 `json:"capacity"`
CollapseInSeconds float64 `json:"collapseInSeconds"`
ID string `json:"id"`
Online int64 `json:"online"`
Phase string `json:"phase"`
Radius float64 `json:"radius"`
SafeRadius float64 `json:"safeRadius"`
Seed int64 `json:"seed"`
}
+245
View File
@@ -0,0 +1,245 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"aeternalis/server/internal/game"
_ "github.com/jackc/pgx/v5/stdlib"
_ "modernc.org/sqlite"
)
var ErrOwnership = errors.New("world ownership or revision lost")
type DB struct {
sql *sql.DB
postgres bool
}
type Lease struct {
DB *DB
WorldID string
Owner string
Revision int64
}
type Passage struct {
CharacterID string `json:"characterId"`
SourceWorld string `json:"sourceWorld"`
Name string `json:"name"`
}
func Open(ctx context.Context, dsn string) (*DB, error) {
postgres := strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://")
driver := "sqlite"
if postgres {
driver = "pgx"
}
conn, err := sql.Open(driver, dsn)
if err != nil {
return nil, err
}
conn.SetMaxOpenConns(8)
if !postgres {
conn.SetMaxOpenConns(1)
}
db := &DB{conn, postgres}
if err = conn.PingContext(ctx); err != nil {
conn.Close()
return nil, err
}
if !postgres {
if _, err = conn.ExecContext(ctx, "PRAGMA journal_mode=WAL"); err != nil {
conn.Close()
return nil, err
}
_, _ = conn.ExecContext(ctx, "PRAGMA busy_timeout=5000")
}
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS worlds(id TEXT PRIMARY KEY, owner TEXT NOT NULL, lease_until BIGINT NOT NULL, revision BIGINT NOT NULL, snapshot TEXT NOT NULL)`,
`CREATE TABLE IF NOT EXISTS passages(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, source_world TEXT NOT NULL, character TEXT NOT NULL, claimed_world TEXT)`,
`CREATE INDEX IF NOT EXISTS passages_account ON passages(account_id)`,
`CREATE TABLE IF NOT EXISTS sessions(token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL, expires BIGINT NOT NULL)`,
`CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires)`,
} {
if _, err = conn.ExecContext(ctx, stmt); err != nil {
conn.Close()
return nil, err
}
}
return db, nil
}
func (d *DB) Close() error { return d.sql.Close() }
func (d *DB) q(query string) string {
if !d.postgres {
return query
}
i := 0
var b strings.Builder
for _, c := range query {
if c == '?' {
i++
fmt.Fprintf(&b, "$%d", i)
} else {
b.WriteRune(c)
}
}
return b.String()
}
func (d *DB) now() string {
if d.postgres {
return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) AS BIGINT)"
}
return "unixepoch()"
}
func (d *DB) Acquire(ctx context.Context, w *game.World) (*Lease, []byte, error) {
data, err := json.Marshal(w)
if err != nil {
return nil, nil, err
}
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return nil, nil, err
}
defer tx.Rollback()
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO worlds(id,owner,lease_until,revision,snapshot) VALUES(?,'',0,0,?) ON CONFLICT(id) DO NOTHING`), w.ID, string(data))
if err != nil {
return nil, nil, err
}
owner := game.ID()
result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET owner=?,lease_until=`+d.now()+`+30 WHERE id=? AND (owner='' OR lease_until<`+d.now()+`)`), owner, w.ID)
if err != nil {
return nil, nil, err
}
n, _ := result.RowsAffected()
if n != 1 {
return nil, nil, ErrOwnership
}
var snapshot string
var revision int64
if err = tx.QueryRowContext(ctx, d.q(`SELECT revision,snapshot FROM worlds WHERE id=?`), w.ID).Scan(&revision, &snapshot); err != nil {
return nil, nil, err
}
if err = tx.Commit(); err != nil {
return nil, nil, err
}
return &Lease{d, w.ID, owner, revision}, []byte(snapshot), nil
}
func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
data, err := json.Marshal(w)
if err != nil {
return err
}
d := l.DB
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=?,revision=revision+1,lease_until=`+d.now()+`+30 WHERE id=? AND owner=? AND revision=? AND lease_until>=`+d.now()), string(data), l.WorldID, l.Owner, l.Revision)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n != 1 {
return ErrOwnership
}
if claimID != "" {
c := w.Characters[claimID]
if c == nil {
return errors.New("claimed character absent from target")
}
result, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND claimed_world IS NULL AND source_world<>?`), w.ID, claimID, c.Account, w.ID)
if err != nil {
return err
}
n, _ = result.RowsAffected()
if n != 1 {
return errors.New("passage already redeemed or unavailable")
}
}
if w.Phase == "won" {
for _, c := range w.Characters {
if c.View.Entity.State != "eligible" {
continue
}
encoded, err := json.Marshal(c)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
if err != nil {
return err
}
}
}
if err = tx.Commit(); err != nil {
return err
}
l.Revision++
w.Saved()
return nil
}
func (l *Lease) Release(ctx context.Context) error {
_, err := l.DB.sql.ExecContext(ctx, l.DB.q(`UPDATE worlds SET owner='',lease_until=0 WHERE id=? AND owner=?`), l.WorldID, l.Owner)
return err
}
func (d *DB) Passages(ctx context.Context, account string) ([]Passage, error) {
rows, err := d.sql.QueryContext(ctx, d.q(`SELECT character_id,source_world,character FROM passages WHERE account_id=? AND claimed_world IS NULL`), account)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Passage{}
for rows.Next() {
var p Passage
var raw string
if err = rows.Scan(&p.CharacterID, &p.SourceWorld, &raw); err != nil {
return nil, err
}
var c game.Character
if err = json.Unmarshal([]byte(raw), &c); err != nil {
return nil, err
}
p.Name = c.View.Entity.Name
out = append(out, p)
}
return out, rows.Err()
}
func (d *DB) ReadPassage(ctx context.Context, id, account string) (*game.Character, error) {
var raw string
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character FROM passages WHERE character_id=? AND account_id=? AND claimed_world IS NULL`), id, account).Scan(&raw)
if err != nil {
return nil, err
}
var c game.Character
if err = json.Unmarshal([]byte(raw), &c); err != nil {
return nil, err
}
return &c, nil
}
func (d *DB) CreateSession(ctx context.Context, hash, account string) error {
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.ExecContext(ctx, `DELETE FROM sessions WHERE expires<`+d.now()); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO sessions(token_hash,account_id,expires) VALUES(?,?,`+d.now()+`+86400)`), hash, account); err != nil {
return err
}
return tx.Commit()
}
func (d *DB) Session(ctx context.Context, hash string) (string, error) {
var account string
err := d.sql.QueryRowContext(ctx, d.q(`SELECT account_id FROM sessions WHERE token_hash=? AND expires>`+d.now()), hash).Scan(&account)
return account, err
}
func (d *DB) DeleteSession(ctx context.Context, hash string) error {
_, err := d.sql.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE token_hash=?`), hash)
return err
}
+210
View File
@@ -0,0 +1,210 @@
package store
import (
"context"
"encoding/json"
"os"
"path/filepath"
"sync"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
)
func TestStoreLifecycle(t *testing.T) {
runStoreTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "world.db")))
}
func TestConcurrentPassageRedemption(t *testing.T) {
ctx := context.Background()
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "race.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
now := time.Now().UTC()
source := game.New("source", 1, now, b)
lease, _, err := db.Acquire(ctx, source)
if err != nil {
t.Fatal(err)
}
c, _ := source.Join("account", "Survivor")
c.View.Entity.State = "eligible"
source.Phase = "won"
if err = lease.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
targets := []*game.World{game.New("target-a", 2, now, b), game.New("target-b", 3, now, b)}
leases := make([]*Lease, 2)
for i, w := range targets {
leases[i], _, err = db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
copy, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
if err != nil {
t.Fatal(err)
}
if err = w.Import(copy); err != nil {
t.Fatal(err)
}
}
var wg sync.WaitGroup
results := make(chan error, 2)
for i := range targets {
wg.Add(1)
go func(i int) { defer wg.Done(); results <- leases[i].Save(ctx, targets[i], c.View.Entity.ID) }(i)
}
wg.Wait()
close(results)
successes := 0
for err := range results {
if err == nil {
successes++
}
}
if successes != 1 {
t.Fatalf("expected one successful redemption, got %d", successes)
}
durableCopies := 0
for _, w := range targets {
var raw string
if err := db.sql.QueryRowContext(ctx, db.q("SELECT snapshot FROM worlds WHERE id=?"), w.ID).Scan(&raw); err != nil {
t.Fatal(err)
}
var restored game.World
if err := json.Unmarshal([]byte(raw), &restored); err != nil {
t.Fatal(err)
}
if restored.Characters[c.View.Entity.ID] != nil {
durableCopies++
}
}
if durableCopies != 1 {
t.Fatal("failed redemption left a durable duplicate")
}
}
func TestPostgresLifecycle(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not configured")
}
runStoreTests(t, dsn)
}
func runStoreTests(t *testing.T, dsn string) {
ctx := context.Background()
db, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
balance, _ := content.Load()
prefix := game.ID()
now := time.Now().UTC()
source := game.New(prefix+"-source", 123, now, balance)
lease, _, err := db.Acquire(ctx, source)
if err != nil {
t.Fatal(err)
}
if _, _, err = db.Acquire(ctx, source); err == nil {
t.Fatal("two simultaneous world owners")
}
c, _ := source.Join("account:"+prefix, "Traveler")
c.View.Inventory["spear"] = 1
c.DailySeconds = 123
c.View.Entity.State = "eligible"
source.Phase = "won"
if err = lease.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
if err = lease.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
passages, err := db.Passages(ctx, c.Account)
if err != nil || len(passages) != 1 {
t.Fatalf("idempotent survivor grant %v %v", passages, err)
}
if _, err = db.ReadPassage(ctx, c.View.Entity.ID, "attacker"); err == nil {
t.Fatal("another account stole transfer")
}
target := game.New(prefix+"-target", 456, now, balance)
targetLease, _, err := db.Acquire(ctx, target)
if err != nil {
t.Fatal(err)
}
survivor, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
if err != nil {
t.Fatal(err)
}
if err = target.Import(survivor); err != nil {
t.Fatal(err)
}
if err = targetLease.Save(ctx, target, c.View.Entity.ID); err != nil {
t.Fatal(err)
}
if _, err = db.ReadPassage(ctx, c.View.Entity.ID, c.Account); err == nil {
t.Fatal("passage can be redeemed twice")
}
third := game.New(prefix+"-third", 789, now, balance)
thirdLease, _, err := db.Acquire(ctx, third)
if err != nil {
t.Fatal(err)
}
copy := *survivor
copy.View.Entity.State = "eligible"
if err = third.Import(&copy); err != nil {
t.Fatal(err)
}
if err = thirdLease.Save(ctx, third, c.View.Entity.ID); err == nil {
t.Fatal("duplicate transfer committed")
}
if err = targetLease.Release(ctx); err != nil {
t.Fatal(err)
}
freshLease, raw, err := db.Acquire(ctx, target)
if err != nil {
t.Fatal(err)
}
var restored game.World
if err = json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
loaded := restored.Characters[c.View.Entity.ID]
if loaded == nil || loaded.DailySeconds != 123 || loaded.View.Inventory["spear"] != 1 {
t.Fatal("transfer not durable")
}
if err = targetLease.Save(ctx, target, ""); err == nil {
t.Fatal("stale owner wrote state")
}
// A subsequent victory grants a fresh passage for the same permanent character ID.
loaded.View.Entity.State = "eligible"
restored.Phase = "won"
if err = freshLease.Save(ctx, &restored, ""); err != nil {
t.Fatal(err)
}
if err = lease.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
passages, err = db.Passages(ctx, c.Account)
if err != nil || len(passages) != 1 || passages[0].SourceWorld != target.ID {
t.Fatal("old world overwrote next passage")
}
if err = db.CreateSession(ctx, "hash:"+prefix, c.Account); err != nil {
t.Fatal(err)
}
if account, err := db.Session(ctx, "hash:"+prefix); err != nil || account != c.Account {
t.Fatal("session roundtrip")
}
if err = db.DeleteSession(ctx, "hash:"+prefix); err != nil {
t.Fatal(err)
}
if _, err = db.Session(ctx, "hash:"+prefix); err == nil {
t.Fatal("revoked session remains valid")
}
_ = lease.Release(ctx)
_ = freshLease.Release(ctx)
_ = thirdLease.Release(ctx)
}
+149
View File
@@ -0,0 +1,149 @@
package transport
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"net/url"
"strings"
"sync"
"time"
"aeternalis/server/internal/game"
"aeternalis/server/internal/store"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
type Auth struct {
db *store.DB
dev bool
base string
oauth *oauth2.Config
verifier *oidc.IDTokenVerifier
mu sync.Mutex
flows map[string]flow
}
type flow struct {
verifier string
expires time.Time
}
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{}}
if dev {
return a, nil
}
if !strings.HasPrefix(base, "https://") || !strings.HasPrefix(issuer, "https://") || client == "" {
return nil, errors.New("production requires HTTPS PUBLIC_URL, OIDC_ISSUER, and OIDC_CLIENT_ID")
}
provider, err := oidc.NewProvider(ctx, issuer)
if err != nil {
return nil, err
}
a.oauth = &oauth2.Config{ClientID: client, ClientSecret: secret, Endpoint: provider.Endpoint(), RedirectURL: base + "/auth/callback", Scopes: []string{oidc.ScopeOpenID}}
a.verifier = provider.Verifier(&oidc.Config{ClientID: client})
return a, nil
}
func hash(s string) string { b := sha256.Sum256([]byte(s)); return hex.EncodeToString(b[:]) }
func (a *Auth) cookieName() string {
if a.dev {
return "aeternalis_session"
}
return "__Host-aeternalis_session"
}
func (a *Auth) account(r *http.Request) (string, error) {
c, err := r.Cookie(a.cookieName())
if err != nil || len(c.Value) != 64 {
return "", errors.New("not authenticated")
}
return a.db.Session(r.Context(), hash(c.Value))
}
func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error {
token := game.ID() + game.ID()
if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil {
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)
return
}
state := game.ID() + game.ID()
v := oauth2.GenerateVerifier()
a.mu.Lock()
for key, f := range a.flows {
if time.Now().After(f.expires) {
delete(a.flows, key)
}
}
if len(a.flows) >= 4096 {
a.mu.Unlock()
fail(w, 503, "login capacity reached")
return
}
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)}
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)
}
func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
if a.dev {
fail(w, 404, "not enabled")
return
}
state := r.URL.Query().Get("state")
cookie, err := r.Cookie("__Host-aeternalis_login")
if err != nil || state == "" || cookie.Value != state {
fail(w, 400, "invalid login state")
return
}
a.mu.Lock()
f, ok := a.flows[state]
delete(a.flows, state)
a.mu.Unlock()
if !ok || time.Now().After(f.expires) {
fail(w, 400, "login expired")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
token, err := a.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(f.verifier))
if err != nil {
fail(w, 401, "login exchange failed")
return
}
raw, ok := token.Extra("id_token").(string)
if !ok {
fail(w, 401, "identity token missing")
return
}
identity, err := a.verifier.Verify(ctx, raw)
if err != nil || identity.Nonce != state {
fail(w, 401, "invalid identity token")
return
}
if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); 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)
}
func validOrigin(r *http.Request, base string) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return false
}
expected, err := url.Parse(base)
if err != nil {
return false
}
actual, err := url.Parse(origin)
return err == nil && actual.Scheme == expected.Scheme && actual.Host == expected.Host && actual.Path == "" && actual.RawQuery == "" && actual.User == nil
}
+408
View File
@@ -0,0 +1,408 @@
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()
}
}
+139
View File
@@ -0,0 +1,139 @@
package transport
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
"aeternalis/server/internal/store"
"github.com/coder/websocket"
)
func TestHTTPAndSocketSecurity(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "http.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
w := game.New("test", 123, 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", "", "", "")
server := httptest.NewServer(NewHTTP(svc, auth, t.TempDir(), nil).Handler())
defer server.Close()
auth.base = server.URL
go svc.Run(ctx)
defer func() { cancel(); <-svc.done; _ = svc.Stop(context.Background()) }()
request := func(path, origin, body string, cookie *http.Cookie) *http.Response {
t.Helper()
req, _ := http.NewRequest(http.MethodPost, server.URL+path, strings.NewReader(body))
if origin != "" {
req.Header.Set("Origin", origin)
}
req.Header.Set("Content-Type", "application/json")
if cookie != nil {
req.AddCookie(cookie)
}
response, err := server.Client().Do(req)
if err != nil {
t.Fatal(err)
}
return response
}
for _, origin := range []string{"", "https://evil.example", "null", server.URL + ".evil"} {
r := request("/auth/dev", origin, "{}", nil)
r.Body.Close()
if r.StatusCode != 403 {
t.Fatalf("accepted origin %q", origin)
}
}
r := request("/auth/dev", server.URL, "{}", nil)
cookies := r.Cookies()
r.Body.Close()
if len(cookies) != 1 || !cookies[0].HttpOnly {
t.Fatal("missing HttpOnly session")
}
cookie := cookies[0]
r = request("/api/join", server.URL, `{"name":"Traveler","passage":"","hp":999}`, cookie)
r.Body.Close()
if r.StatusCode != 400 {
t.Fatal("unknown join field accepted")
}
r = request("/api/join", server.URL, `{"name":"Traveler","passage":""}`, cookie)
raw, _ := io.ReadAll(r.Body)
r.Body.Close()
if r.StatusCode != 200 {
t.Fatalf("join %d %s", r.StatusCode, raw)
}
var character p.Character
if err = json.Unmarshal(raw, &character); err != nil {
t.Fatal(err)
}
wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws"
badCtx, stop := context.WithTimeout(ctx, time.Second)
_, response, err := websocket.Dial(badCtx, wsURL, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{"https://evil.example"}, "Cookie": []string{cookie.String()}}})
stop()
if err == nil || response.StatusCode != 403 {
t.Fatal("cross-origin websocket accepted")
}
socketCtx, stopSocket := context.WithTimeout(ctx, 5*time.Second)
defer stopSocket()
conn, _, err := websocket.Dial(socketCtx, wsURL, &websocket.DialOptions{HTTPHeader: http.Header{"Origin": []string{server.URL}, "Cookie": []string{cookie.String()}}})
if err != nil {
t.Fatal(err)
}
defer conn.CloseNow()
conn.SetReadLimit(2 << 20)
_, data, err := conn.Read(socketCtx)
if err != nil {
t.Fatal(err)
}
var s p.Snapshot
if err = json.Unmarshal(data, &s); err != nil {
t.Fatal(err)
}
if len(s.Chunks) != 9 {
t.Fatal("missing chunk snapshot")
}
if bytes.Contains(data, []byte(`"account"`)) {
t.Fatal("account identity leaked")
}
intent := p.Intent{Op: "move", Seq: 1, X: 1}
payload, _ := json.Marshal(intent)
if err = conn.Write(socketCtx, websocket.MessageText, payload); err != nil {
t.Fatal(err)
}
if err = conn.Write(socketCtx, websocket.MessageText, []byte(`{"op":"move","seq":2,"x":1,"z":0,"target":"","hp":999}`)); err != nil {
t.Fatal(err)
}
for {
_, _, err = conn.Read(socketCtx)
if err != nil {
break
}
}
if err == nil {
t.Fatal("malformed intent was not disconnected")
}
}
func TestProductionAuthRequiresOIDC(t *testing.T) {
if _, err := NewAuth(context.Background(), nil, false, "http://insecure", "", "", ""); err == nil {
t.Fatal("insecure production auth accepted")
}
}
+149
View File
@@ -0,0 +1,149 @@
package transport
import (
"context"
"encoding/json"
"errors"
"log/slog"
"maps"
"sync"
"sync/atomic"
"time"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
"aeternalis/server/internal/store"
)
type peer struct {
character string
out chan []byte
known map[string]bool
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{}
}
func NewService(w *game.World, l *store.Lease) *Service {
s := &Service{world: w, lease: l, peers: map[string]*peer{}, lastSave: time.Now(), done: make(chan struct{})}
s.ready.Store(true)
return s
}
func (s *Service) persist(ctx context.Context, claim string) error {
err := s.lease.Save(ctx, s.world, claim)
if err != nil {
s.ready.Store(false)
slog.Error("world frozen: persistence failed", "error", err)
for _, p := range s.peers {
p.close()
}
return err
}
s.lastSave = time.Now()
return nil
}
func (s *Service) Run(ctx context.Context) {
defer close(s.done)
ticker := time.NewTicker(time.Second / time.Duration(s.world.Balance.TickHz))
defer ticker.Stop()
last := time.Now()
for {
select {
case <-ctx.Done():
return
case now := <-ticker.C:
s.mu.Lock()
if !s.ready.Load() {
s.mu.Unlock()
return
}
s.world.Advance(now, now.Sub(last).Seconds())
last = now
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := s.persist(saveCtx, "")
cancel()
if err != nil {
s.mu.Unlock()
return
}
}
if s.world.Tick%int64(s.world.Balance.TickHz/s.world.Balance.SnapshotHz) == 0 {
for id, p := range s.peers {
snapshot := s.world.Snapshot(id, p.known)
data, err := json.Marshal(snapshot)
if err != nil {
slog.Error("snapshot encoding failed", "error", err)
p.close()
continue
}
select {
case p.out <- data:
for key := range p.known {
delete(p.known, key)
}
for _, key := range snapshot.ChunkKeys {
p.known[key] = true
}
default:
p.close()
}
}
}
s.mu.Unlock()
}
}
}
func (s *Service) Stop(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
wasReady := s.ready.Swap(false)
for id, p := range s.peers {
s.world.Disconnect(id)
p.close()
}
if !wasReady {
return errors.New("world already frozen; lease will expire")
}
if err := s.lease.Save(ctx, s.world, ""); err != nil {
return err
}
return s.lease.Release(ctx)
}
func (s *Service) join(ctx context.Context, account, name, claim string) (p.Character, error) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.ready.Load() {
return p.Character{}, errors.New("world unavailable")
}
var c *game.Character
var err error
if claim != "" {
c, err = s.lease.DB.ReadPassage(ctx, claim, account)
if err != nil {
return p.Character{}, errors.New("passage unavailable")
}
if err = s.world.Import(c); err != nil {
return p.Character{}, err
}
} else {
c, err = s.world.Join(account, name)
if err != nil {
return p.Character{}, err
}
}
if err = s.persist(ctx, claim); err != nil {
return p.Character{}, errors.New("world persistence unavailable")
}
view := c.View
view.Inventory = maps.Clone(view.Inventory)
view.Skills = maps.Clone(view.Skills)
return view, nil
}