From ece92fa65c83f8267bef9f2c738057eb0cc0aa13 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 8 Sep 2026 07:19:27 -0400 Subject: [PATCH] Add audited admin player item and title management --- client/src/content-editor.css | 1 + client/src/control.ts | 7 +- client/src/player-content.ts | 48 +++++ docs/ARCHITECTURE.md | 7 + docs/PROGRESSION.md | 29 +++- planning/VISION.md | 7 +- server/internal/game/admin_content.go | 85 +++++++++ server/internal/store/admin_content.go | 77 ++++++++ server/internal/store/admin_content_test.go | 183 ++++++++++++++++++++ server/internal/store/portal.go | 1 + server/internal/store/store.go | 17 ++ server/internal/store/titles.go | 19 +- server/internal/transport/control.go | 11 ++ server/internal/transport/service.go | 6 +- tests/player-content.spec.ts | 22 +++ 15 files changed, 512 insertions(+), 8 deletions(-) create mode 100644 client/src/player-content.ts create mode 100644 server/internal/game/admin_content.go create mode 100644 server/internal/store/admin_content.go create mode 100644 server/internal/store/admin_content_test.go create mode 100644 tests/player-content.spec.ts diff --git a/client/src/content-editor.css b/client/src/content-editor.css index 73e9962..5e05dc3 100644 --- a/client/src/content-editor.css +++ b/client/src/content-editor.css @@ -1 +1,2 @@ .catalog-editor{padding:20px;min-width:0}.catalog-heading,.catalog-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px}.catalog-heading h2{font-size:20px;margin-right:auto}.catalog-tabs button[aria-pressed=true]{background:#215944;color:white}.catalog-list{display:grid;gap:12px}.catalog-list>.button{justify-self:start}.catalog-definition{padding:14px;border:1px solid var(--line);border-radius:5px;min-width:0;overflow-wrap:anywhere;font-size:12px;line-height:1.7}.catalog-definition summary{cursor:pointer;font-size:13px;font-weight:600}.catalog-definition p{margin-top:10px}.catalog-form{margin-top:24px;padding-top:20px;border-top:1px solid var(--line);max-width:900px}.catalog-form>h3{margin-bottom:12px}.catalog-form label{display:flex;flex-direction:column;gap:8px;font-size:12px;margin:14px 0;min-width:0}.catalog-form input,.catalog-form select,.catalog-form textarea{width:100%;min-width:0}.catalog-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 14px}.catalog-fields label:has(textarea){grid-column:1/-1}.catalog-repeatable,.catalog-title-choices{padding:14px;min-width:0;border:1px solid var(--line);margin:20px 0}.catalog-repeatable legend,.catalog-title-choices legend{font-size:13px;padding:0 8px}.catalog-row{display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--line);margin-bottom:12px}.catalog-row>.catalog-fields{flex:1}.catalog-row>.button{font-size:11px;padding:8px}.catalog-title-choices{max-height:260px;overflow:auto}.catalog-title-choices label{flex-direction:row-reverse;justify-content:flex-end;align-items:center}.catalog-title-choices input{width:18px;height:18px}.catalog-form footer{display:flex;justify-content:flex-end;gap:12px;margin-top:20px}.catalog-form>.muted{line-height:1.7}.catalog-form details{margin:14px 0}.catalog-form .error{margin-top:14px}.table-tools[hidden]{display:none}@media(max-width:720px){.control-sidebar nav{grid-template-columns:repeat(4,minmax(0,1fr))}.catalog-editor{padding:12px}.catalog-fields{grid-template-columns:1fr}.catalog-row{align-items:flex-end}.catalog-tabs{gap:6px}.catalog-tabs button{padding:9px;font-size:11px}} +.player-content{padding:0 0 20px;border-bottom:1px solid var(--line)}.player-content form{display:grid;gap:12px}.player-content label{display:flex;flex-direction:column;gap:7px;font-size:12px;min-width:0}.player-content input,.player-content select,.player-content textarea{width:100%;min-width:0;max-width:100%}.player-content .muted{font-size:12px;line-height:1.7}.player-content [hidden]{display:none}.player-content .button{justify-self:start} diff --git a/client/src/control.ts b/client/src/control.ts index 1897ac6..9a03bcc 100644 --- a/client/src/control.ts +++ b/client/src/control.ts @@ -2,6 +2,7 @@ import './portal.css'; import { permanentTitles, progressionSummary } from './progression'; import { statsBreakdown, equipmentDetails } from './character-stats'; import { showCatalog, hasCatalogDraft } from './content-editor'; +import { playerContent } from './player-content'; import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type Command, type RecordCharacter, type World } from './portal-shared'; type Data = { worlds: World[]; characters: RecordCharacter[]; commands: Command[]; provisioningEnabled: boolean; characterLimit: number; auditLimit: number }; @@ -11,6 +12,7 @@ let tab = 'worlds'; let busy = false; let draft: Draft; const labels: Record = { 'create-world': 'New world', 'close-admissions': 'Close arrivals', 'open-admissions': 'Open arrivals', 'awaken-boss': 'Awaken Harbinger', 'end-world': 'End world permanently', rename: 'Rename character', heal: 'Restore health', unstuck: 'Return to sanctuary', retire: 'Retire character permanently', 'revoke-sessions': 'Revoke account sessions' }; +Object.assign(labels, { 'grant-item':'Add item', 'remove-item':'Remove item', 'grant-title':'Add / restore title', 'revoke-title':'Remove title' }); function notify(message: string) { $('control-message').textContent = message; $('control-message').hidden = false; } function openCommand(op: string, worldId = '', target = '', value = '') { draft = { id: crypto.randomUUID(), worldId, op, target, value }; @@ -43,6 +45,9 @@ function actions(world: string, options: string[], target = '', value = '', disa function detail(r: RecordCharacter) { $('detail-name').textContent = r.name; const parent = $('character-detail'); parent.replaceChildren(); + parent.append(playerContent(r,['alive','eligible'].includes(r.state)&&!!data.worlds.find(w=>w.id===r.worldId)?.available,()=>{ + $('character-dialog').close();notify('Player change queued. The audit log records its result.');void refresh(); + })); const list = el('dl', '', 'details'); const v = r.character.view; const pairs: [string, string][] = [['Character ID', r.id], ['Account ID', r.account], ['World', r.worldId], ['State', r.state], ['Health', `${v.entity.hp} / ${v.entity.maxHp}`], ['Position', `${Math.round(v.entity.position.x)}, ${Math.round(v.entity.position.y)}, ${Math.round(v.entity.position.z)}`], ['Played today', `${Math.floor(r.character.dailySeconds / 60)} min`], ['Born', date(r.character.bornAt)], ['Died', r.character.diedAt ? date(r.character.diedAt) : '-'], ['Cause', r.character.deathReason || '-']]; for (const [key,value] of pairs) list.append(el('dt', key), el('dd', value)); parent.append(list); @@ -81,7 +86,7 @@ function render() { } else { const { node, body } = table(['Requested', 'Action', 'World / target', 'Status', 'Reason / result']); for (const c of data.commands.filter(c => matches([c.id,c.actor,c.op,c.target,c.reason,c.result], c.worldId === '_provision' ? c.target : c.worldId,c.status))) { - const row = body.insertRow(); cell(row, date(c.createdAt)); const op = el('div', labels[c.op] || c.op); op.title = `Request ${c.id}\nActor ${c.actor}`; cell(row, op); const target = el('div', c.worldId === '_provision' ? c.target : c.worldId); if (c.target && c.worldId !== '_provision') target.append(el('small', c.target, 'muted block')); cell(row, target); cell(row, badge(c.status)); const reason = el('div', c.reason); if (c.result) reason.append(el('small', c.result, 'muted block')); cell(row, reason); count++; + const row = body.insertRow(); cell(row, date(c.createdAt)); const op = el('div', labels[c.op] || c.op); op.title = `Request ${c.id}\nActor ${c.actor}`; if (['grant-item','remove-item','grant-title','revoke-title'].includes(c.op)) op.append(el('small',c.value,'muted block')); cell(row, op); const target = el('div', c.worldId === '_provision' ? c.target : c.worldId); if (c.target && c.worldId !== '_provision') target.append(el('small', c.target, 'muted block')); cell(row, target); cell(row, badge(c.status)); const reason = el('div', c.reason); if (c.result) reason.append(el('small', c.result, 'muted block')); cell(row, reason); count++; } parent.append(node); $('table-note').textContent = `Latest ${data.auditLimit} actions. Completed provisioning means committed to Git; world availability confirms startup.`; } diff --git a/client/src/player-content.ts b/client/src/player-content.ts new file mode 100644 index 0000000..819c1bf --- /dev/null +++ b/client/src/player-content.ts @@ -0,0 +1,48 @@ +import { api, el, type RecordCharacter } from './portal-shared'; +import { statLabel } from './character-stats'; + +type Catalog={items:{id:string;name:string}[];titles:{id:string;name:string}[]}; +export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()=>void){ + const root=el('section','','player-content');root.append(el('h3','Manage items and titles')); + if(!enabled){root.append(el('p','A living character or survivor with an available world owner is required.','muted'));return root;} + const form=el('form'),operation=el('select'),choice=el('select'),quantity=el('input'),reason=el('textarea'),message=el('p','','error'),submit=el('button','Queue player change','button'); + message.setAttribute('role','alert');submit.type='submit';submit.disabled=true;quantity.type='number';quantity.min='1';quantity.max='100';quantity.step='1';quantity.value='1';quantity.required=true;reason.required=true;reason.minLength=5;reason.maxLength=240;reason.rows=2; + for(const [value,label] of [['grant-item','Add item'],['remove-item','Remove item'],['grant-title','Add / restore title'],['revoke-title','Remove title']])operation.append(new Option(label,value)); + function field(label:string,input:HTMLElement){const wrap=el('label',label);wrap.append(input);return wrap;} + const qtyLabel=field('Quantity',quantity),notice=el('p','','muted'); + form.append(field('Player change',operation),field('Item or title',choice),qtyLabel,notice,field('Reason for player change',reason),message,submit);root.append(form); + let catalog:Catalog,busy=false,requestID=crypto.randomUUID(),lastBody=''; + function updateQuantity(){const isItem=operation.value.endsWith('item'),instance=operation.value==='remove-item'&&record.character.view.items?.some(i=>i.id===choice.value);qtyLabel.hidden=!isItem;quantity.required=isItem;quantity.disabled=!!instance;if(instance)quantity.value='1';} + function options(){ + if(!catalog)return; + const v=record.character.view;choice.replaceChildren(); + switch(operation.value){ + case 'grant-item': + for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id)); + for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage'])choice.append(new Option(statLabel(id),id)); + notice.textContent='Items go into the bag. Equipment requirements still apply when equipping.';break; + case 'remove-item': + for(const i of v.items??[]){const slot=Object.entries(v.equipment??{}).find(([,id])=>id===i.id)?.[0];choice.append(new Option(`${i.name}${slot?` [${statLabel(slot)}]`:''} · ${i.id}`,i.id));} + for(const [id,n] of Object.entries(v.inventory??{}))if(n>0)choice.append(new Option(`${statLabel(id)} · ${n} held`,id)); + notice.textContent='Removes the selected instance or stack quantity. Equipped items are unequipped automatically.';break; + case 'grant-title': + for(const t of catalog.titles)choice.append(new Option(`${t.name} (${t.id})`,t.id)); + notice.textContent='Bypasses achievement requirements. Restores revoked titles with their original effects. First claims held by another player remain reserved.';break; + case 'revoke-title': + for(const t of v.titles??[])choice.append(new Option(`${t.name} (${t.id})`,t.id)); + notice.textContent='Admin exception to permanent titles: removes the account’s active title and effects, and blocks automatic re-awarding until an admin restores it.';break; + } + choice.required=true;choice.disabled=!choice.options.length;submit.disabled=!choice.options.length||busy;updateQuantity(); + } + operation.onchange=options;choice.onchange=updateQuantity; + form.onsubmit=async event=>{ + event.preventDefault();if(busy||!choice.value)return; + const value=operation.value.endsWith('item')?`${choice.value}:${quantity.value}`:choice.value; + const body={worldId:record.worldId,target:record.id,op:operation.value,value,reason:reason.value.trim()}; + const serialized=JSON.stringify(body);if(lastBody&&lastBody!==serialized)requestID=crypto.randomUUID();lastBody=serialized; + busy=true;submit.disabled=true;message.textContent=''; + try{await api('/api/control/commands',{id:requestID,...body});onQueued();}catch(e){message.textContent=(e as Error).message;}finally{busy=false;submit.disabled=!choice.options.length;} + }; + void api<{catalog:Catalog}>('/api/control/catalog').then(data=>{catalog=data.catalog;options()}).catch(e=>{message.textContent=e.message}); + return root; +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6f52952..d8cc66c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -112,6 +112,13 @@ This account inheritance is the initial interpretation of player-bound titles. Awarded names, descriptions, effects, and provenance are copied at grant time; later content changes do not remove or alter an earned title. +Audited administrator player commands are an exception to gameplay title permanence. +Revocation records suppress active ownership/effects and future automatic awards; +the original immutable award and first claim remain intact. Explicit admin restoration +reactivates that original award. Dead-life history is not rewritten. Item and title +commands stage their changes inside the owner-checked save transaction, after locking +character registry rows, and update survivor passages and audit results atomically. + All earned title effects are active once per title ID. Flat bonuses are summed, then combined percentage bonuses apply. Modified primaries feed the derived-stat formulas. Existing damage/movement effects remain compatible. None can alter death, diff --git a/docs/PROGRESSION.md b/docs/PROGRESSION.md index a7d4f6b..852493d 100644 --- a/docs/PROGRESSION.md +++ b/docs/PROGRESSION.md @@ -89,8 +89,9 @@ The world snapshot and title ledger commit atomically before effects become visi Every owned title is active once per ID forever. Flat and percentage modifiers may be positive or negative and target any stat. Legacy damage/moveSpeed effects remain -compatible. Titles cannot be removed, traded, revoked, or lost if requirements cease -to hold. Content edits do not alter earned awards. +compatible. Players cannot remove, trade, or lose titles if requirements cease +to hold. Content edits do not alter earned awards. Administrators have the audited +grant/revocation exception described below. ## Inventory and equipment @@ -115,7 +116,29 @@ stacks migrate once, including corpses. Control can set an equipment definition's per-sentinel-kill drop chance (0-100%). The player's drop-rate multiplier applies, capped at a guaranteed drop. Zero disables sentinel drops for that definition. Starting and crafted gear retains those existing -acquisition paths. There is no arbitrary browser inventory grant. +acquisition paths. Ordinary player intents cannot grant inventory. + +## Administrator player changes + +Open Control -> Characters -> a character -> Manage items and titles. An available +world owner and a living character or survivor are required. Each command records +the administrator, target, item/title value, reason, and completed/rejected result. + +- Add items from published definitions or existing stackable items, 1-100 per command. +- Remove an exact equipment instance (including equipped gear) or a stack quantity. +- Add a title without achievement requirements, or restore a revoked original award. +- Revoke the account's active title and its effects. Normal gameplay cannot + re-award it until an administrator restores it. + +Revocation keeps the original title ledger and first-world/first-ever claim reserved; +it does not release that claim to another player. Historical dead-life records stay +intact. Restoring a title keeps its original effects and provenance. Equipment that +loses a title prerequisite returns to the bag, rather than being deleted. + +Changes are staged and committed atomically with the audit, stats, character record, +and survivor passage. Replays cannot duplicate grants, stale source worlds cannot +edit transferred characters, and admin inventory changes do not heal or reset the +daily budget. The player receives the change on the next committed snapshot. ## Verification and limits diff --git a/planning/VISION.md b/planning/VISION.md index c547fbd..2c7b5b8 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -72,7 +72,10 @@ Tracked across: documented in `docs/PROGRESSION.md` and editable through Control. - Titles have configurable requirements, a name, and positive or negative effects. - Award scopes include personal achievements, first in a world, and first ever. -- Earned titles cannot be lost or transferred to another player. +- Earned titles cannot be lost through gameplay or transferred to another player. +- Administrators may grant or revoke titles as an audited exception. Revocation + suppresses active effects and automatic re-awarding until an admin restores the + original title; first-claim history remains reserved. - Initial implementation interprets player-bound titles as account-bound: they carry to a replacement character after permanent death. Levels, XP, and banked stat points belong to the individual character and survive survivor passage. @@ -89,6 +92,8 @@ Tracked across: positive or negative stat modifiers. Each equipment instance has its own ID. - Equipment transfers through dropping, corpse looting, and survivor passage. Equipment requirements are checked without other equipment bonuses. +- Administrators may add items or remove a specific instance/stack quantity, + with an audit reason and the same owner-controlled durable save path. - Weight and carrying capacity are displayed; encumbrance penalties and hard capacity enforcement remain undecided. diff --git a/server/internal/game/admin_content.go b/server/internal/game/admin_content.go new file mode 100644 index 0000000..85449f3 --- /dev/null +++ b/server/internal/game/admin_content.go @@ -0,0 +1,85 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "errors" + "strconv" + "strings" + "time" +) + +func IsContentCommand(op string) bool { + return op == "grant-item" || op == "remove-item" || op == "grant-title" || op == "revoke-title" +} + +// Commands identify a stack definition or one exact equipment instance. +func ParseItemChange(value string) (string, int64, error) { + id, amount, ok := strings.Cut(value, ":") + n, err := strconv.ParseInt(amount, 10, 64) + if !ok || id == "" || len(id) > 64 || err != nil || n < 1 || n > 100 { + return "", 0, errors.New("choose an item and a quantity from 1 to 100") + } + return id, n, nil +} + +// Called on the transaction's staged world, never through a player intent. +func (w *World) AdminItems(c *Character, op, value string) error { + id, n, err := ParseItemChange(value) + if err != nil { + return err + } + if op == "grant-item" { + known := false + for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} { + if key == id { + known = true + } + } + for _, definition := range w.Balance.Items { + if definition.ID == id { + known = true + } + } + if !known { + return errors.New("unknown item definition") + } + return w.grantItems(c, id, n) + } + if op != "remove-item" { + return errors.New("unknown item operation") + } + for index, item := range c.View.Items { + if item.ID != id { + continue + } + if n != 1 { + return errors.New("equipment removal requires one exact instance") + } + c.View.Items = append(c.View.Items[:index], c.View.Items[index+1:]...) + for slot, held := range c.View.Equipment { + if held == id { + delete(c.View.Equipment, slot) + } + } + w.RefreshStats(c) + return nil + } + if c.View.Inventory[id] < n { + return errors.New("player no longer holds that item quantity") + } + c.View.Inventory[id] -= n + if c.View.Inventory[id] == 0 { + delete(c.View.Inventory, id) + } + w.RefreshStats(c) + return nil +} + +func (w *World) AdminTitle(id string) (p.TitleAward, error) { + for _, title := range w.Balance.Titles { + if title.ID == id { + return p.TitleAward{ID: title.ID, Name: title.Name, Description: title.Description, Scope: title.Scope, WorldID: w.ID, EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed, Modifiers: protocolModifiers(title.Effects.Modifiers)}}, nil + } + } + return p.TitleAward{}, errors.New("unknown title definition") +} diff --git a/server/internal/store/admin_content.go b/server/internal/store/admin_content.go new file mode 100644 index 0000000..068d038 --- /dev/null +++ b/server/internal/store/admin_content.go @@ -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() +} diff --git a/server/internal/store/admin_content_test.go b/server/internal/store/admin_content_test.go new file mode 100644 index 0000000..be0e7e2 --- /dev/null +++ b/server/internal/store/admin_content_test.go @@ -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") + } +} diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go index 1c961ef..ff571d9 100644 --- a/server/internal/store/portal.go +++ b/server/internal/store/portal.go @@ -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)`, diff --git a/server/internal/store/store.go b/server/internal/store/store.go index 92c2b6b..413b9bf 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -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) diff --git a/server/internal/store/titles.go b/server/internal/store/titles.go index 6a9fdde..a93ef07 100644 --- a/server/internal/store/titles.go +++ b/server/internal/store/titles.go @@ -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 } diff --git a/server/internal/transport/control.go b/server/internal/transport/control.go index 9d01b3b..8f2c32c 100644 --- a/server/internal/transport/control.go +++ b/server/internal/transport/control.go @@ -1,6 +1,7 @@ package transport import ( + "aeternalis/server/internal/game" "context" "errors" "net/http" @@ -100,6 +101,16 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) { return } switch req.Op { + case "grant-item", "remove-item": + if _, _, err := game.ParseItemChange(req.Value); err != nil { + fail(w, 400, err.Error()) + return + } + case "grant-title", "revoke-title": + if !regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`).MatchString(req.Value) { + fail(w, 400, "choose a title") + return + } case "create-world": if h.Provisioner == nil { fail(w, 503, "GitOps provisioning is not configured") diff --git a/server/internal/transport/service.go b/server/internal/transport/service.go index a0039d5..8a9dc3a 100644 --- a/server/internal/transport/service.go +++ b/server/internal/transport/service.go @@ -216,8 +216,10 @@ func (s *Service) controls(ctx context.Context) error { 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() + } else if !game.IsContentCommand(command.Op) { + 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) diff --git a/tests/player-content.spec.ts b/tests/player-content.spec.ts new file mode 100644 index 0000000..57c0ac8 --- /dev/null +++ b/tests/player-content.spec.ts @@ -0,0 +1,22 @@ +import { test, expect } from '@playwright/test'; + +test('admin adds and removes items and restores revoked titles', async ({page})=>{ + const origin='http://127.0.0.1:18089'; + await page.request.post('/auth/dev',{data:{},headers:{Origin:origin}}); + const joined=await page.request.post('/worlds/e2e/api/join',{data:{name:'Managed player',passage:''},headers:{Origin:origin}});expect(joined.ok()).toBe(true); + const character=await joined.json();const current=async()=>((await (await page.request.get('/api/account')).json()).active.character.view); + await page.goto('/control');await page.getByRole('button',{name:'Characters',exact:true}).click(); + const open=async()=>{await page.getByRole('button',{name:'Refresh',exact:true}).click();await page.getByRole('button',{name:'Managed player',exact:true}).click();await expect(page.locator('.player-content button[type=submit]')).toBeEnabled();}; + const submit=async(op:string,value:string,quantity?:string)=>{ + const form=page.locator('.player-content');await form.getByRole('combobox',{name:'Player change'}).selectOption(op);await form.getByRole('combobox',{name:'Item or title'}).selectOption(value); + if(quantity)await form.getByRole('spinbutton',{name:'Quantity'}).fill(quantity); + await form.getByRole('textbox',{name:'Reason for player change'}).fill('Browser administration test');await form.getByRole('button',{name:'Queue player change'}).click(); + }; + await open();await submit('grant-item','spear','2');await expect.poll(async()=>(await current()).items.filter(i=>i.definitionId==='spear').length).toBe(2); + const spear=(await current()).items.find(i=>i.definitionId==='spear');await open();await submit('remove-item',spear.id);await expect.poll(async()=>(await current()).items.some(i=>i.id===spear.id)).toBe(false); + await open();await submit('grant-title','wayfarer');await expect.poll(async()=>(await current()).titles.some(t=>t.id==='wayfarer')).toBe(true); + await open();await submit('revoke-title','wayfarer');await expect.poll(async()=>(await current()).titles.some(t=>t.id==='wayfarer')).toBe(false); + await open();await submit('grant-title','wayfarer');await expect.poll(async()=>(await current()).titles.some(t=>t.id==='wayfarer')).toBe(true); + expect((await current()).entity.id).toBe(character.entity.id); + await page.getByRole('button',{name:'Audit log',exact:true}).click();await expect(page.locator('#records')).toContainText('Browser administration test'); +});