Add audited admin player item and title management

This commit is contained in:
dingo
2026-09-08 07:20:18 -04:00
parent ed55cd23ab
commit ece92fa65c
15 changed files with 512 additions and 8 deletions
+77
View File
@@ -0,0 +1,77 @@
package store
import (
"aeternalis/server/internal/game"
"context"
"database/sql"
"errors"
)
// World and character ownership rows are locked before changing player content.
// Business rejections are audited without freezing the owner. Database failures
// roll the entire command back and leave the live simulation untouched.
func (d *DB) applyContentCommand(ctx context.Context, tx *sql.Tx, w *game.World, command *Command) (string, error) {
c := w.Characters[command.Target]
if c == nil {
return "character not found", nil
}
if (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") || w.Phase == "lost" {
return "only a living character or survivor can be changed", nil
}
var account, world, state string
err := tx.QueryRowContext(ctx, d.q(`SELECT account_id,world_id,state FROM character_records WHERE character_id=?`), command.Target).Scan(&account, &world, &state)
if err != nil {
return "", err
}
if account != c.Account || world != w.ID || state != c.View.Entity.State {
return "character has moved to another world", nil
}
switch command.Op {
case "grant-item", "remove-item":
if err := w.AdminItems(c, command.Op, command.Value); err != nil {
return err.Error(), nil
}
case "grant-title":
award, err := w.AdminTitle(command.Value)
if err != nil {
return err.Error(), nil
}
// Restore the original award if revoked; never repurpose a first claim.
if _, err = tx.ExecContext(ctx, d.q(`DELETE FROM title_revocations WHERE account_id=? AND title_id=?`), c.Account, command.Value); err != nil {
return "", err
}
w.PendingTitles = append(w.PendingTitles, game.TitleCandidate{CharacterID: c.View.Entity.ID, Award: award})
case "revoke-title":
var found string
err := tx.QueryRowContext(ctx, d.q(`SELECT title_id FROM title_awards WHERE account_id=? AND title_id=?`), c.Account, command.Value).Scan(&found)
if errors.Is(err, sql.ErrNoRows) {
return "player does not own that title", nil
}
if err != nil {
return "", err
}
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO title_revocations(account_id,title_id,command_id) VALUES(?,?,?) ON CONFLICT(account_id,title_id) DO UPDATE SET command_id=excluded.command_id`), c.Account, command.Value, command.ID); err != nil {
return "", err
}
default:
return "unknown player content command", nil
}
return "", nil
}
func (d *DB) revokedTitles(ctx context.Context, tx *sql.Tx, account string) (map[string]bool, error) {
rows, err := tx.QueryContext(ctx, d.q(`SELECT title_id FROM title_revocations WHERE account_id=?`), account)
if err != nil {
return nil, err
}
defer rows.Close()
ids := map[string]bool{}
for rows.Next() {
var id string
if err = rows.Scan(&id); err != nil {
return nil, err
}
ids[id] = true
}
return ids, rows.Err()
}
+183
View File
@@ -0,0 +1,183 @@
package store
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
"context"
"encoding/json"
"path/filepath"
"testing"
"time"
)
func TestAdminContentTransactionsAndTitleRevocation(t *testing.T) {
ctx := context.Background()
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "admin-content.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, _ := content.Load()
b.Titles = append(b.Titles, content.Title{ID: "admin_trial", Name: "Admin Trial", Scope: "global", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 999}}, Effects: content.TitleEffects{Modifiers: []content.StatModifier{{Stat: "strength", Flat: 4, Percent: 50}}}})
w := game.New("admin-content", 1, time.Now(), b)
lease, _, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
defer lease.Release(ctx)
c, err := w.Join("account", "Admin target")
if err != nil {
t.Fatal(err)
}
c.DailySeconds = 123
c.View.Entity.HP = 20
if err = lease.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
run := func(op, value string) Command {
t.Helper()
cmd := Command{ID: game.ID(), WorldID: w.ID, Actor: "operator", Target: c.View.Entity.ID, Op: op, Value: value, Reason: "Administration test"}
if err := db.Enqueue(ctx, cmd); err != nil {
t.Fatal(err)
}
if err := lease.SaveCommand(ctx, w, "", &cmd, ""); err != nil {
t.Fatal(err)
}
commands, err := db.Commands(ctx, w.ID, false)
if err != nil {
t.Fatal(err)
}
for _, result := range commands {
if result.ID == cmd.ID {
return result
}
}
t.Fatal("missing audit")
return Command{}
}
if cmd := run("grant-item", "spear:2"); cmd.Status != "completed" {
t.Fatal(cmd)
}
var spear string
count := 0
for _, i := range c.View.Items {
if i.DefinitionID == "spear" {
spear = i.ID
count++
}
}
if count != 2 {
t.Fatal("wrong grant quantity")
}
c.View.Equipment["weapon"] = spear
w.RefreshStats(c)
before := c.View.Stats["meleeDamage"].Final
if cmd := run("remove-item", spear+":1"); cmd.Status != "completed" {
t.Fatal(cmd)
}
if c.View.Equipment["weapon"] != "" || c.View.Stats["meleeDamage"].Final >= before {
t.Fatal("removed equipment still active")
}
cmd := run("grant-item", "wood:3")
if c.View.Inventory["wood"] != 3 {
t.Fatal("stack grant missing")
}
if err := lease.SaveCommand(ctx, w, "", &cmd, ""); err == nil || c.View.Inventory["wood"] != 3 {
t.Fatal("replayed command duplicated items")
}
if cmd := run("remove-item", "wood:4"); cmd.Status != "rejected" || c.View.Inventory["wood"] != 3 {
t.Fatal("over-removal accepted", cmd)
}
if cmd := run("grant-item", "invented:1"); cmd.Status != "rejected" {
t.Fatal("unknown item accepted", cmd)
}
if cmd := run("grant-title", "admin_trial"); cmd.Status != "completed" || c.View.Stats["strength"].Final != 6 {
t.Fatal("admin title requirement bypass failed", cmd)
}
award := c.View.Titles[0]
for _, a := range c.View.Titles {
if a.ID == "admin_trial" {
award = a
}
}
ring := p.ItemInstance{ID: game.ID(), DefinitionID: "trial_ring", Name: "Trial ring", Slot: "ring", Weight: 1, Requirements: p.ItemRequirements{Level: 1, Titles: []string{"admin_trial"}}, Modifiers: []p.StatModifier{{Stat: "luck", Flat: 5}}}
c.View.Items = append(c.View.Items, ring)
c.View.Equipment["ring1"] = ring.ID
w.RefreshStats(c)
if cmd := run("revoke-title", "admin_trial"); cmd.Status != "completed" || c.View.Stats["strength"].Final != 0 || c.View.Equipment["ring1"] != "" {
t.Fatal("revocation did not remove effects/eligibility", cmd)
}
w.PendingTitles = []game.TitleCandidate{{CharacterID: c.View.Entity.ID, Award: award}}
if err = lease.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
for _, a := range c.View.Titles {
if a.ID == award.ID {
t.Fatal("revoked title automatically re-awarded")
}
}
other, err := w.Join("other-account", "Other")
if err != nil {
t.Fatal(err)
}
otherCommand := Command{ID: game.ID(), WorldID: w.ID, Actor: "operator", Target: other.View.Entity.ID, Op: "grant-title", Value: award.ID, Reason: "First claim test"}
if err = db.Enqueue(ctx, otherCommand); err != nil {
t.Fatal(err)
}
if err = lease.SaveCommand(ctx, w, "", &otherCommand, ""); err != nil {
t.Fatal(err)
}
if len(other.View.Titles) != 0 {
t.Fatal("revocation erased original first claim")
}
if cmd := run("grant-title", "admin_trial"); cmd.Status != "completed" || c.View.Stats["strength"].Final != 6 {
t.Fatal("restore did not retain original title", cmd)
}
if c.DailySeconds != 123 || c.View.Entity.HP != 20 {
t.Fatal("admin content changed budget or healed")
}
c.View.Entity.State = "eligible"
w.Phase = "won"
if cmd := run("grant-item", "wood:1"); cmd.Status != "completed" {
t.Fatal("survivor change failed", cmd)
}
survivor, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
if err != nil || survivor.View.Inventory["wood"] != 4 {
t.Fatal("survivor passage was not updated", err)
}
destination := game.New("admin-destination", 2, time.Now(), b)
dl, _, err := db.Acquire(ctx, destination)
if err != nil {
t.Fatal(err)
}
defer dl.Release(ctx)
if err = destination.Import(survivor); err != nil {
t.Fatal(err)
}
if err = dl.Save(ctx, destination, survivor.View.Entity.ID); err != nil {
t.Fatal(err)
}
if cmd := run("grant-item", "wood:1"); cmd.Status != "rejected" {
t.Fatal("stale source command accepted", cmd)
}
record, err := db.ActiveCharacter(ctx, c.Account)
if err != nil || record.Character.View.Inventory["wood"] != 4 {
t.Fatal("stale source changed destination", err)
}
raw, _ := json.Marshal(record.Character.View)
if err = dl.Release(ctx); err != nil {
t.Fatal(err)
}
failed := Command{ID: game.ID(), WorldID: destination.ID, Actor: "operator", Target: survivor.View.Entity.ID, Op: "remove-item", Value: "wood:1", Reason: "Rollback test"}
if err = db.Enqueue(ctx, failed); err != nil {
t.Fatal(err)
}
if err = dl.SaveCommand(ctx, destination, "", &failed, ""); err == nil {
t.Fatal("lost owner committed")
}
after, _ := json.Marshal(survivor.View)
if string(raw) != string(after) {
t.Fatal("failed transaction mutated live view")
}
}
+1
View File
@@ -66,6 +66,7 @@ func (d *DB) migrate(ctx context.Context) error {
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
`CREATE TABLE IF NOT EXISTS title_awards(account_id TEXT NOT NULL, title_id TEXT NOT NULL, scope TEXT NOT NULL, scope_key TEXT NOT NULL, character_id TEXT NOT NULL, award TEXT NOT NULL, PRIMARY KEY(account_id,title_id), UNIQUE(scope,scope_key,title_id))`,
`CREATE TABLE IF NOT EXISTS title_revocations(account_id TEXT NOT NULL,title_id TEXT NOT NULL,command_id TEXT NOT NULL,PRIMARY KEY(account_id,title_id))`,
`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)`,
+17
View File
@@ -179,9 +179,26 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
return err
}
if command != nil && outcome == "" && game.IsContentCommand(command.Op) {
outcome, err = d.applyContentCommand(ctx, tx, w, command)
if err != nil {
return err
}
}
if err = d.syncTitles(ctx, tx, w); err != nil {
return err
}
if command != nil && outcome == "" && command.Op == "grant-title" {
found := false
for _, award := range w.Characters[command.Target].View.Titles {
if award.ID == command.Value {
found = true
}
}
if !found {
outcome = "title's first claim belongs to another player"
}
}
// Rewrite the final payloads after the immutable award claims have resolved.
// The transaction already holds the owner, passage and character row locks.
data, err = json.Marshal(w)
+18 -1
View File
@@ -21,6 +21,7 @@ func stageTitleWorld(w *game.World) *game.World {
copy := *c
copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...)
copy.View.Items = append([]p.ItemInstance{}, c.View.Items...)
copy.View.Inventory = maps.Clone(c.View.Inventory)
copy.View.Equipment = maps.Clone(c.View.Equipment)
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
copy.View.Stats = maps.Clone(c.View.Stats)
@@ -33,6 +34,7 @@ func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
// syncCharacters has already locked these rows. A stale source world may
// checkpoint itself, but it cannot grant titles for a transferred character.
owned := make(map[string]bool, len(w.Characters))
revoked := map[string]map[string]bool{}
for id, c := range w.Characters {
var account, world string
err := tx.QueryRowContext(ctx, d.q(`SELECT account_id,world_id FROM character_records WHERE character_id=?`), id).Scan(&account, &world)
@@ -40,6 +42,13 @@ func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
return err
}
owned[id] = account == c.Account && world == w.ID
if owned[id] && revoked[c.Account] == nil {
ids, err := d.revokedTitles(ctx, tx, c.Account)
if err != nil {
return err
}
revoked[c.Account] = ids
}
}
candidates := append([]game.TitleCandidate{}, w.PendingTitles...)
// All owners lock title IDs in the same order, even with different catalogs.
@@ -52,6 +61,9 @@ func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
continue
}
award := candidate.Award
if revoked[c.Account][award.ID] {
continue
}
if award.ID == "" || award.WorldID != w.ID {
return errors.New("invalid title candidate identity")
}
@@ -100,7 +112,12 @@ func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
byAccount[c.Account] = awards
}
if c.View.Entity.State != "dead" {
c.View.Titles = append([]p.TitleAward{}, awards...)
c.View.Titles = []p.TitleAward{}
for _, award := range awards {
if !revoked[c.Account][award.ID] {
c.View.Titles = append(c.View.Titles, award)
}
}
w.RefreshStats(c)
continue
}