aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 06f2ca59b85909caf4188c4880461c7a7e04539d
parent f2e6b196cb8023866fba661f0fcafc2d7697d96f
Author: anon <anon@example.com>
Date:   Sun,  8 Nov 2026 06:17:40 +0000

Replace player YAML editor with plain HTML forms

Diffstat:
MDEVELOPERS.md | 9+++++----
Mdocs/admin.md | 7++++++-
Mdocs/combat-regeneration.md | 40++++++++++++++--------------------------
Mdocs/inventory.md | 2+-
Mdocs/nano-damage.md | 2+-
Mdocs/project-notes.md | 8++++----
Mserver/admin_browser_test.go | 6++++++
Mserver/admin_live_test.go | 2+-
Mserver/appearance.go | 35++++++-----------------------------
Mserver/appearance_test.go | 10++++------
Mserver/bank_storage_test.go | 14+++++++-------
Mserver/buddies_test.go | 9+--------
Mserver/character_editor.go | 14+++++++-------
Mserver/control.go | 20++++++--------------
Mserver/control_data_test.go | 99++++++++++++++++++++++++++++++++++---------------------------------------------
Mserver/control_equipment_slots_test.go | 6+++---
Mserver/control_inventory_test.go | 43++++++++++++++++++++++---------------------
Aserver/control_player_form.go | 453+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/control_player_form_test.go | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/database.go | 20++++++++++----------
Mserver/database_test.go | 36++++--------------------------------
Mserver/insurance_experience_test.go | 3+--
Mserver/insurance_test.go | 9++-------
Mserver/inventory_write_test.go | 24+++++-------------------
Mserver/item_import_test.go | 8++++----
Mserver/item_owner_test.go | 2+-
Mserver/item_pages.go | 16+++++++++++++++-
Mserver/item_store.go | 32++++++++++++++++----------------
Mserver/item_store_test.go | 4++--
Mserver/progression_test.go | 10+++++-----
Mserver/shop_control_edit_test.go | 4++--
Mserver/stats.go | 172++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mserver/users.go | 56++++++++++++++++++++------------------------------------
Mserver/users_test.go | 23+++++++++--------------
Mserver/zone_http_test.go | 23++++-------------------
Mserver/zoning.go | 6+++---
Mtools/client/test_admin.mjs | 20+++++++++++++++++++-
Mtools/client/test_pending_edit.mjs | 2+-
38 files changed, 985 insertions(+), 450 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -59,10 +59,11 @@ stop can lose simulation changes since the last checkpoint. Ctrl+C or SIGTERM flushes player positions and world state before closing the database; check `logs/server.log` for shutdown errors. -The admin dashboard's YAML is an editing format generated from the current state. -Saving it validates and writes the database; there are no per-player YAML -storage files. HTTPS key/certificate files are separate and use atomic file -replacement. +The admin player editor uses grouped HTML form fields. Saving validates the +character and item ownership before writing the database atomically. Player +export/import is not implemented; there are no per-player YAML storage files. +Item pages still use YAML as an editing format for individual item records. +HTTPS key/certificate files are separate and use atomic file replacement. ### Server ownership boundaries diff --git a/docs/admin.md b/docs/admin.md @@ -38,7 +38,12 @@ the admin interface's own authentication queries. Players at `/admin/players` provides character editors and separate Teleport and Change password pages; -players create accounts through the game. Items retains catalog creation, +players create accounts through the game. The player editor uses labeled form +fields grouped into character, appearance, skills, location, vitals and inventory +sections. Item slots refer to existing instance IDs; blank slots unassign their +items. Saves validate the complete ownership change and commit atomically. +Player IDs and browser credentials are not editable in this form. Player +export/import is not implemented. Items retains catalog creation, ownership, assignment and instance editing. Players, item instances, the item catalog, administrators and shop stock use 1,000-row pages. Click a column heading to sort ascending or descending; filters diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md @@ -12,31 +12,19 @@ server's scheduler is not established by those rules. ## Character data -The character editor at `/admin/players/<id>` shows one YAML document -with every field and its current value. The `stats` -section contains all six abilities and 69 skills under the -classic UI categories: abilities, body, melee, misc weapons, ranged, speed, -trade/repair, nano/aiding, spying and navigation. For example: - -```yaml -stats: - improvement_points: 1500 - abilities: - strength: 10 - agility: 10 - stamina: 60 - intelligence: 10 - sense: 10 - psychic: 120 - body: - martial_arts: 100 - body_development: 200 - nano_pool: 100 - speed: - physical_initiative: 600 -``` +The character editor at `/admin/players/<id>` uses labeled form fields with +current values. The stats groups contain all six abilities and 69 skills under +the classic UI categories: abilities, body, melee, misc weapons, ranged, speed, +trade/repair, nano/aiding, spying and navigation. The arithmetic example below +uses these form values: + +| Group | Values | +| --- | --- | +| Stats | Improvement points 1500 | +| Abilities | Strength 10, Agility 10, Stamina 60, Intelligence 10, Sense 10, Psychic 120 | +| Body | Martial arts 100, Body development 200, Nano pool 100 | +| Speed | Physical initiative 600 | -The editor expands this abbreviated example to include every other skill. Fresh characters use the original breed ability baselines, raw skills 5 including Run Speed, and 1500 IP. The raw skill/IP seeds remain reconstruction policy; native defaults alone do not establish historical character creation. @@ -75,8 +63,8 @@ float store before AggDef subtraction. At effective initiative 387 and AggDef -100, recharge truncates to 170 centiseconds; the algebraically simplified division would give 171. This boundary is covered by a regression test. -Omitted nested fields retain their current values; explicitly saved zero skills -remain zero. +Fields omitted from a submission retain their current values; explicitly saved +zero skills remain zero. QL 1 Kinetic Axe attacks use Melee Initiative; unequipping restores fists and Physical Initiative. Its requirements also use the effective 1h Edged, Brawling and Fast Attack values. diff --git a/docs/inventory.md b/docs/inventory.md @@ -28,7 +28,7 @@ unassigned instance at its exact catalog quality. Its assignment form offers only free compatible player/equipment/backpack slots. Admin equipment assignment bypasses gameplay skill requirements. -The character page at `/admin/players/<owner>` shows one editable YAML document +The character page at `/admin/players/<owner>` groups labeled form fields for the character, position, vitals and inventory, with all empty slots visible. Moving an ID preserves the instance; clearing its slot leaves it unassigned. Duplicate references and unknown IDs are rejected, including during startup. Native diff --git a/docs/nano-damage.md b/docs/nano-damage.md @@ -147,7 +147,7 @@ unpersisted synthetic actor. Admission commits available nano and its refundable `nano_reserved` amount in one update before action 18. The reservation is internal state, excluded from -the YAML editor. Routine vitals checkpoints and item effects preserve it along +the player editor. Routine vitals checkpoints and item effects preserve it along with the balance. Cancellation restores the current balance plus the reserved amount, capped at the current maximum, and clears the reservation in one update before action 108. Resource gains during execution are retained. Completion diff --git a/docs/project-notes.md b/docs/project-notes.md @@ -95,9 +95,9 @@ To quit, press X to sit, then choose OPT > Quit > To Windows. The original logout countdown takes 30 seconds. Pressing X to stand prevents logout, although the client's countdown bar currently remains visible. -Open http://127.0.0.1:8080/control to list all saved users, create a user, and -change the game time immediately. Follow a user's name to edit their character -in a YAML textarea or teleport them by selecting a location on their map. Offline +Open http://127.0.0.1:8080/admin to sign in, list saved players, and +change the game time immediately. Follow a player's name to edit their character +through grouped form fields or open their Teleport map. Offline users and users reconnecting during a teleport stay on the list. The page uses plain HTML forms and a small JavaScript canvas map. The world starts at 13:30. Rubi-Ka has a 27-hour day, running at 15 game seconds per real second. @@ -110,7 +110,7 @@ owns one character, with a stable ID. Walk/run mode is saved in the `running` field and supplied in the initial vehicle state on login and zone reconnect. Saving character data refreshes an online character through the native zone reconnect sequence. -Use the web editor while the server runs. Its YAML text represents database +Use the web editor while the server runs. Form submissions update database records. The database is local development data and is ignored by Git. To extract the control UI's map tiles from `anarchy-vanilla-14.9.1`, run from diff --git a/server/admin_browser_test.go b/server/admin_browser_test.go @@ -45,6 +45,12 @@ func TestAdminBrowser(t *testing.T) { t.Fatal(err) } + var title string + var rifle uint16 + if err := world.db.QueryRow("SELECT title,ranged_rifle FROM characters WHERE id=1").Scan(&title, &rifle); err != nil || title != "Form & field check" || rifle != 42 { + t.Fatal("player form edits were not persisted", title, rifle, err) + } + var weather int callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { state.advancePlayerMovement(time.Now().Add(5 * time.Minute)) diff --git a/server/admin_live_test.go b/server/admin_live_test.go @@ -32,7 +32,7 @@ func TestAdminCarriedItemChangesKeepSessionAndMovement(t *testing.T) { } connection.packets = nil - removed := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: null}\n"}}) + removed := postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_30: null}\n")) restarted = newTestInventoryServer(t) if removed.Code != http.StatusSeeOther || world.clients[1] != client || !client.ready || player.movement != movement || len(connection.packets) != 2 { t.Fatal("removal reloaded the player", removed.Code, removed.Body, connection.packets) diff --git a/server/appearance.go b/server/appearance.go @@ -3,8 +3,6 @@ package main import ( "ao/server/gamedata" "fmt" - - "go.yaml.in/yaml/v3" ) func (character *character) baseScale() uint16 { @@ -53,12 +51,12 @@ func (character *character) appearanceAssets() (uint32, [5]uint32) { } type appearanceFields struct { - Race uint16 `yaml:"race"` - Fatness uint16 `yaml:"fatness"` - Breed uint16 `yaml:"breed"` - Sex uint16 `yaml:"sex"` - Side uint16 `yaml:"side"` - Head uint16 `yaml:"head"` + Race uint16 + Fatness uint16 + Breed uint16 + Sex uint16 + Side uint16 + Head uint16 } func unpackAppearance(value uint16) appearanceFields { @@ -75,24 +73,3 @@ func (appearance appearanceFields) validate() error { } return nil } - -func (appearance appearanceFields) MarshalYAML() (any, error) { - // Annotate the editing document without storing presentation text in SQLite. - type fields appearanceFields - var node yaml.Node - if err := node.Encode(fields(appearance)); err != nil { - return nil, err - } - comments := []string{ - "Native race code: 1 default; Solitus skin variants also use 2 and 3.", - "Body build: 0 slim, 1 normal, 2 heavy; native field range 0-3.", - "Breed: 1 Solitus, 2 Opifex, 3 Nanomage, 4 Atrox, 6 creature; native range 0-7.", - "Sex: 2 male, 3 female; Atrox and creatures use 1. Native range 0-3.", - "Side: 0 neutral, 1 Clan, 2 Omni-Tek; native range 0-3.", - "Native face hint: 0-31; head_mesh selects the visible head independently.", - } - for index, comment := range comments { - node.Content[index*2].HeadComment = comment - } - return &node, nil -} diff --git a/server/appearance_test.go b/server/appearance_test.go @@ -93,9 +93,7 @@ func TestPlayerAppearancePersistsThroughControlEditAndRestart(t *testing.T) { world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Visitor"}}) - response := postControlForm(world, "/admin/players/1", url.Values{"data": { - "head_mesh: 40132\nheight: 110\nappearance: {race: 1, breed: 4, sex: 1, fatness: 2}\n", - }}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("head_mesh: 40132\nheight: 110\nappearance: {race: 1, breed: 4, sex: 1, fatness: 2}\n")) restored := newTestInventoryServer(t).characters[1] spawn := characterPacket(restored) @@ -118,7 +116,7 @@ func TestPlayerAppearanceFailedControlSaveLeavesMemoryAndDatabaseUnchanged(t *te t.Fatal(err) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("head_mesh: 40680\nheight: 110\n")) restored := newTestInventoryServer(t).characters[1] if response.Code != 500 || world.characters[1].headMesh != 0 || world.characters[1].height != 0 || restored.headMesh != 0 || restored.height != 0 { @@ -128,7 +126,7 @@ func TestPlayerAppearanceFailedControlSaveLeavesMemoryAndDatabaseUnchanged(t *te t.Fatal(err) } - response = postControlForm(world, "/admin/players/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) + response = postControlForm(world, "/admin/players/1", playerFixtureForm("head_mesh: 40680\nheight: 110\n")) restored = newTestInventoryServer(t).characters[1] if response.Code != 303 || restored.headMesh != 40680 || restored.height != 110 { @@ -144,7 +142,7 @@ func TestPlayerAppearanceRejectsUnrepresentableProfileFields(t *testing.T) { world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Visitor"}}) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(data)) restored := newTestInventoryServer(t).characters[1] if response.Code != 400 || world.characters[1].headMesh != 0 || world.characters[1].height != 0 || restored.headMesh != 0 || restored.height != 0 { diff --git a/server/bank_storage_test.go b/server/bank_storage_test.go @@ -14,7 +14,7 @@ import ( func TestBankStoragePreservesFilledBackpack(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n")) restarted := newServerForTest(t) page, bag := httptest.NewRecorder(), httptest.NewRecorder() adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) @@ -32,7 +32,7 @@ func TestBankStoragePreservesFilledBackpack(t *testing.T) { t.Fatal("bank storage lost ownership or duplicated an item") } if !strings.Contains(withoutItemIcons(page.Body.String()), "<h2>Bank</h2>") || - !strings.Contains(withoutItemIcons(page.Body.String()), "<tr><td>slot_102</td><td><a href='admin/items/3'>Small Backpack (ID 3)</a></td></tr>") || + !strings.Contains(withoutItemIcons(page.Body.String()), "<tr><td>slot_102</td><td></td><td><a href='admin/items/3'>Small Backpack (ID 3)</a></td></tr>") || !strings.Contains(withoutItemIcons(bag.Body.String()), "Bank, slot_102") { t.Fatal("control panel omitted bank ownership or its final slot") } @@ -55,7 +55,7 @@ func TestBankStorageRejectsInvalidOwnershipGraphs(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {document}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(document)) after, err := readTestItemStore(world) if response.Code != http.StatusBadRequest || err != nil || !bytes.Equal(before, after) { @@ -68,12 +68,12 @@ func TestBankStorageRejectsInvalidOwnershipGraphs(t *testing.T) { func TestBankStorageRejectsAnotherPlayersInstance(t *testing.T) { world := newControlInventoryWorld(t) postControlForm(world, "/admin/players", url.Values{"name": {"Other"}}) - placed := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory: {slots: {inventory_slot_1: null}}\nbank: {slot_1: 1}\n"}}) + placed := postControlForm(world, "/admin/players/1", playerFixtureForm("inventory: {slots: {inventory_slot_1: null}}\nbank: {slot_1: 1}\n")) if placed.Code != http.StatusSeeOther { t.Fatal(placed.Body.String()) } - response := postControlForm(world, "/admin/players/2", url.Values{"data": {"bank: {slot_1: 1}\n"}}) + response := postControlForm(world, "/admin/players/2", playerFixtureForm("bank: {slot_1: 1}\n")) restarted := newServerForTest(t) if response.Code != http.StatusBadRequest || len(restarted.characters[2].inventory.Bank) != 0 || @@ -93,7 +93,7 @@ func TestBankStorageFailurePreservesPlacement(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_1: 3}\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_1: 3}\n")) after, err := readTestItemStore(world) if response.Code != http.StatusInternalServerError || err != nil || !bytes.Equal(before, after) || @@ -116,7 +116,7 @@ func TestBankStorageSupportsEveryNativeSlot(t *testing.T) { document.WriteString(" slot_" + strconv.Itoa(id) + ": " + strconv.Itoa(id) + "\n") } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {document.String()}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(document.String())) restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || len(restarted.characters[1].inventory.Bank) != 102 || len(restarted.items) != 102 || diff --git a/server/buddies_test.go b/server/buddies_test.go @@ -8,13 +8,10 @@ import ( "net" "net/http" "net/http/httptest" - "net/url" "reflect" "strings" "testing" "time" - - "go.yaml.in/yaml/v3" ) func buddyTestWorld(t *testing.T) *server { @@ -286,11 +283,7 @@ func TestBuddyControlEditPreservesSavedList(t *testing.T) { world.clients[1].ready = false data := world.characters[1].editor() data.Level = 2 - contents, err := yaml.Marshal(data) - if err != nil { - t.Fatal(err) - } - request := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {string(contents)}}.Encode())) + request := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(playerEditorForm(t, data).Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") response := httptest.NewRecorder() diff --git a/server/character_editor.go b/server/character_editor.go @@ -1,13 +1,13 @@ package main -// YAML is only a presentation format; each section maps to native SQL fields. +// A detached editing snapshot combines character fields and item references. type characterEditor struct { - playerProfile `yaml:",inline"` - playerPosition `yaml:",inline"` - Vitals playerVitals `yaml:"vitals"` - Inventory inventoryReferences `yaml:"inventory"` - Equipment map[string]*uint32 `yaml:"equipment"` - Bank map[string]*uint32 `yaml:"bank"` + playerProfile + playerPosition + Vitals playerVitals + Inventory inventoryReferences + Equipment map[string]*uint32 + Bank map[string]*uint32 } func (character *character) editor() characterEditor { diff --git a/server/control.go b/server/control.go @@ -12,8 +12,6 @@ import ( "strconv" "strings" "time" - - "go.yaml.in/yaml/v3" ) func (server *server) userPage(w http.ResponseWriter, r *http.Request) { @@ -36,12 +34,6 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { data := player.userData() connected := server.clients[data.ID] != nil && server.clients[data.ID].ready - // One document exposes the complete editable character and all empty slots. - contents, err := yaml.Marshal(player.editor()) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } var itemTables strings.Builder server.inventoryTables(&itemTables, player.inventory) @@ -62,7 +54,7 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<p><a href='admin/players/%d/password'>Change password</a></p>", data.ID) } fmt.Fprint(w, "<h2>Character data</h2>") - fmt.Fprintf(w, "<form method='post' action='admin/players/%d'><p><label>Character:<br><textarea name='data' rows='40' cols='100' required>%s</textarea></label></p><button>Save</button></form>", data.ID, html.EscapeString(string(contents))) + renderPlayerForm(w, player.editor()) fmt.Fprint(w, itemTables.String()) fmt.Fprint(w, "</main></body></html>") } @@ -79,14 +71,14 @@ func (server *server) editUser(w http.ResponseWriter, r *http.Request) { return } - // Validate the document and ownership graph before starting the SQL transaction. + // Validate submitted fields and ownership before starting the SQL transaction. data := character.editor() - err = decodeUsers(strings.NewReader(r.FormValue("data")), &data) + err = r.ParseForm() + if err == nil { + err = data.readForm(r.PostForm) + } updated := data.character() updated.nextPositionSave = character.nextPositionSave - if err == nil && data.ID != character.id { - err = fmt.Errorf("player ID cannot change") - } if err == nil { err = data.Appearance.validate() } diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -3,15 +3,12 @@ package main import ( "bytes" "encoding/binary" - "html" "net/http" "net/http/httptest" "net/url" "regexp" "strings" "testing" - - "go.yaml.in/yaml/v3" ) func TestControlItemCatalogPaginatesAndFilters(t *testing.T) { @@ -94,7 +91,7 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing pistol := postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) bag := postControlForm(world, "/admin/items", url.Values{"template": {"99228"}}) contained := postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - placed := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1, inventory_slot_2: 2}\n"}}) + placed := postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: 1, inventory_slot_2: 2}\n")) filled := postControlForm(world, "/admin/items/2", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {slot_1: 3}\n"}}) restarted := newServerForTest(t) page := httptest.NewRecorder() @@ -123,8 +120,8 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing t.Fatalf("item properties: %d %s", details.Code, details.Body.String()) } contents, err := readTestItemStore(world) - if err != nil || !strings.Contains(string(contents), "slot_30: null") || !strings.Contains(string(contents), "slot_21: null") || strings.Contains(string(contents), "slot: 64") { - t.Fatalf("shared YAML is not slot-based: %s, %v", contents, err) + if err != nil || !strings.Contains(string(contents), `"inventory_slot_30":null`) || !strings.Contains(string(contents), `"slot_21":null`) || strings.Contains(string(contents), `"Slot":64`) { + t.Fatalf("item snapshot is not slot-based: %s, %v", contents, err) } } @@ -134,11 +131,11 @@ func TestControlItemCanBeUnassignedAndTransferredWithoutChangingID(t *testing.T) postControlForm(world, "/admin/players", url.Values{"name": {"First"}}) postControlForm(world, "/admin/players", url.Values{"name": {"Second"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: 1}\n")) - cleared := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}}) + cleared := postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: null}\n")) unassigned := newServerForTest(t) - transferred := postControlForm(world, "/admin/players/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}}) + transferred := postControlForm(world, "/admin/players/2", playerFixtureForm("inventory:\n slots: {inventory_slot_30: 1}\n")) restarted := newServerForTest(t) postControlForm(restarted, "/admin/items", url.Values{"template": {"121567"}}) @@ -167,13 +164,13 @@ func TestControlInventoryRejectsDuplicateUnknownAndInvalidSlotsAtomically(t *tes postControlForm(world, "/admin/players", url.Values{"name": {"Second"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: 1}\n")) before, err := readTestItemStore(world) if err != nil { t.Fatal(err) } - response := postControlForm(world, "/admin/players/2", url.Values{"data": {"inventory:\n " + contents}}) + response := postControlForm(world, "/admin/players/2", playerFixtureForm("inventory:\n "+contents)) after, readError := readTestItemStore(world) if response.Code != http.StatusBadRequest || readError != nil || !bytes.Equal(before, after) || len(world.characters[2].inventory.Items) != 0 || world.nextItem != 2 { @@ -200,37 +197,34 @@ func TestControlEditorShowsAllSkillCategoriesAndDefaultFields(t *testing.T) { world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) contents := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 1\nstats:\n body:\n martial_arts: 0\n" - if response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}); response.Code != http.StatusSeeOther { + if response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)); response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } page := httptest.NewRecorder() adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) - editors := regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindAllStringSubmatch(page.Body.String(), -1) + fields := playerPageValues(t, page.Body.String()) - if page.Code != http.StatusOK || len(editors) != 1 { - t.Fatalf("editors: %d %s", page.Code, page.Body.String()) - } - var profile map[string]any - if err := yaml.Unmarshal([]byte(html.UnescapeString(editors[0][1])), &profile); err != nil { - t.Fatal(err) + if page.Code != http.StatusOK || strings.Contains(page.Body.String(), "<textarea") { + t.Fatalf("form: %d %s", page.Code, page.Body.String()) } - stats := profile["stats"].(map[string]any) for category, count := range map[string]int{"abilities": 6, "body": 8, "melee": 10, "misc_weapons": 3, "ranged": 13, "speed": 9, "trade_repair": 10, "nano_aiding": 8, "spying": 4, "navigation": 4} { - if len(stats[category].(map[string]any)) != count { - t.Fatalf("incomplete %s category: %v", category, stats[category]) + actual := 0 + for name := range fields { + if strings.HasPrefix(name, "stats."+category+".") { + actual++ + } + } + if actual != count { + t.Fatalf("incomplete %s category: %d", category, actual) } } - if stats["improvement_points"] != 1500 || stats["body"].(map[string]any)["martial_arts"] != 0 || stats["abilities"].(map[string]any)["strength"] != 6 || stats["ranged"].(map[string]any)["rifle"] != 5 || stats["speed"].(map[string]any)["run_speed"] != 5 { - t.Fatalf("incorrect defaults: %v", stats) - } - var data characterEditor - if err := decodeUsers(strings.NewReader(html.UnescapeString(editors[0][1])), &data); err != nil { - t.Fatal(err) - } - if data.Inventory.Credits != 0 || len(data.Inventory.Slots) != 30 || len(data.Equipment) != 43 || data.Inventory.Slots["inventory_slot_1"] != nil || data.Inventory.Slots["inventory_slot_30"] != nil || !strings.Contains(editors[0][1], "return_door: null\n") { - t.Fatal("empty inventory slots or optional fields are hidden") + for name, expected := range map[string]string{"stats.improvement_points": "1500", "stats.body.martial_arts": "0", "stats.abilities.strength": "6", "stats.ranged.rifle": "5", "stats.speed.run_speed": "5", "inventory.credits": "0", "inventory.slots.inventory_slot_1": "", "inventory.slots.inventory_slot_30": "", "return_door.playfield": "0", "return_door.door": "0"} { + if value, exists := fields[name]; !exists || len(value) != 1 || value[0] != expected { + t.Fatalf("field %s: %v", name, value) + } } + } func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing.T) { @@ -239,7 +233,7 @@ func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) contents := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 1\nstats:\n improvement_points: 12345\n ranged:\n rifle: 42\n spying:\n concealment: 87\n" - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) restarted := newServerForTest(t) packet := fullCharacterPacket(restarted.characters[1]) values := make(map[uint32]uint32) @@ -271,7 +265,7 @@ func TestControlRoutesRequireAdminPrefix(t *testing.T) { } } -func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { +func TestControlCharacterFormSavesNativeFieldsAndNamedSlots(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) @@ -280,34 +274,27 @@ func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { } page := httptest.NewRecorder() adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) - document := html.UnescapeString(regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindStringSubmatch(page.Body.String())[1]) - var data characterEditor - if err := decodeUsers(strings.NewReader(document), &data); err != nil { - t.Fatal(err) - } - data.Name, data.Position, data.Appearance.Head = "Edited", [3]float32{53, 14, 60}, 31 - data.Stats.ImprovementPoints, data.Stats.Ranged.Rifle, data.Vitals.Health = 12345, 42, 31 - data.Inventory.Credits = 913 - pistol, armor, implant := uint32(1), uint32(2), uint32(3) - data.Inventory.Slots["inventory_slot_7"] = &pistol - data.Equipment["clothes_chest"], data.Equipment["implants_chest"] = &armor, &implant - contents, err := yaml.Marshal(data) - if err != nil { - t.Fatal(err) + fields := playerPageValues(t, page.Body.String()) + for name, value := range map[string]string{ + "name": "Edited", "position.x": "53", "position.y": "14", "position.z": "60", "appearance.head": "31", + "stats.improvement_points": "12345", "stats.ranged.rifle": "42", "vitals.health": "31", "inventory.credits": "913", + "inventory.slots.inventory_slot_7": "1", "equipment.clothes_chest": "2", "equipment.implants_chest": "3", + } { + fields.Set(name, value) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/players/1", fields) restarted := newServerForTest(t) var name string var x float32 var head, points, rifle, health, credits uint32 - err = restarted.db.QueryRow("SELECT name, position_x, appearance_head, improvement_points, ranged_rifle, health, credits FROM characters JOIN players USING(id) WHERE id=1").Scan(&name, &x, &head, &points, &rifle, &health, &credits) + err := restarted.db.QueryRow("SELECT name, position_x, appearance_head, improvement_points, ranged_rifle, health, credits FROM characters JOIN players USING(id) WHERE id=1").Scan(&name, &x, &head, &points, &rifle, &health, &credits) if response.Code != http.StatusSeeOther || err != nil || name != "Edited" || x != 53 || head != 31 || points != 12345 || rifle != 42 || health != 31 || credits != 913 { t.Fatalf("native character fields were not saved: %d %s, %v", response.Code, response.Body.String(), err) } - if !strings.Contains(document, "# Breed: 1 Solitus") || !strings.Contains(document, "# Sex: 2 male, 3 female") || strings.Count(page.Body.String(), "<textarea") != 1 { - t.Fatal("the unified editor lost its appearance documentation") + if !strings.Contains(page.Body.String(), "Breed: 1 Solitus") || !strings.Contains(page.Body.String(), "Sex: 2 male, 3 female") || strings.Contains(page.Body.String(), "<textarea") { + t.Fatal("the form lost its appearance documentation") } if restarted.characters[1].appearance != 64277 || restarted.characters[1].position != [3]float32{53, 14, 60} || restarted.characters[1].inventory.Credits != 913 { t.Fatal("the native row did not restore the edited character") @@ -320,7 +307,7 @@ func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { } } -func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) { +func TestControlCharacterFormRollsBackAllSections(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) @@ -331,7 +318,7 @@ func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) { } contents := "name: Changed\nposition: [53, 14, 60]\ninventory:\n credits: 913\n slots: {inventory_slot_7: 1}\nequipment: {clothes_head: 2}\n" - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) restarted := newServerForTest(t) var name string var credits, locations uint32 @@ -358,7 +345,7 @@ func TestControlAppearanceRejectsPackedScalarsAndOutOfRangeFields(t *testing.T) world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) if response.Code != http.StatusBadRequest || world.characters[1].appearance != 789 { t.Fatalf("invalid appearance changed the character: %d %s", response.Code, response.Body.String()) @@ -367,7 +354,7 @@ func TestControlAppearanceRejectsPackedScalarsAndOutOfRangeFields(t *testing.T) } } -func TestControlCharacterDocumentPreservesCastRefundAndExplicitNanoEdits(t *testing.T) { +func TestControlCharacterFormPreservesCastRefundAndExplicitNanoEdits(t *testing.T) { for _, contents := range []string{"name: Edited\n", "name: Edited\nvitals: {nano: 13}\n"} { t.Run(contents, func(t *testing.T) { t.Chdir(t.TempDir()) @@ -380,7 +367,7 @@ func TestControlCharacterDocumentPreservesCastRefundAndExplicitNanoEdits(t *test defer world.closeDatabase() world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) var nano, reserved uint32 err := world.db.QueryRow("SELECT nano,nano_reserved FROM characters WHERE id=1").Scan(&nano, &reserved) diff --git a/server/control_equipment_slots_test.go b/server/control_equipment_slots_test.go @@ -29,7 +29,7 @@ func TestControlClothingNamesMatchNativeArmorSlots(t *testing.T) { } data := fmt.Sprintf("equipment: {%s: 1}\n", scenario.name) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(data)) restarted := newTestInventoryServer(t) page := httptest.NewRecorder() adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) @@ -43,8 +43,8 @@ func TestControlClothingNamesMatchNativeArmorSlots(t *testing.T) { t.Fatal("named clothing placement changed the native identity or slot", item) } if !strings.Contains(withoutItemIcons(page.Body.String()), "<tr><td>"+scenario.name+"</td><td></td><td><a href='admin/items/1'>") || - !strings.Contains(withoutItemIcons(page.Body.String()), scenario.name+": 1") { - t.Fatal("equipment table or YAML editor uses a different clothing name") + !strings.Contains(withoutItemIcons(page.Body.String()), "name='equipment."+scenario.name+"' value='1'") { + t.Fatal("equipment table or form uses a different clothing name") } }) } diff --git a/server/control_inventory_test.go b/server/control_inventory_test.go @@ -1,15 +1,12 @@ package main import ( - "html" "net/http" "net/http/httptest" "net/url" "regexp" "strings" "testing" - - "go.yaml.in/yaml/v3" ) // Inventory assertions check text and structure; icon rendering has separate coverage. @@ -38,13 +35,13 @@ func newControlInventoryWorld(t *testing.T) *server { return world } -func TestControlCharacterDocumentSeparatesEquipment(t *testing.T) { +func TestControlCharacterFormSeparatesEquipment(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) postControlForm(world, "/admin/items", url.Values{"template": {"85557"}}) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"equipment: {clothes_head: 1}\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("equipment: {clothes_head: 1}\n")) restarted := newServerForTest(t) page := httptest.NewRecorder() adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) @@ -52,17 +49,17 @@ func TestControlCharacterDocumentSeparatesEquipment(t *testing.T) { if response.Code != http.StatusSeeOther { t.Fatalf("top-level equipment save: %d %s", response.Code, response.Body.String()) } - document := html.UnescapeString(regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindStringSubmatch(page.Body.String())[1]) - var data map[string]any - if err := yaml.Unmarshal([]byte(document), &data); err != nil { - t.Fatal(err) - } - if len(data["equipment"].(map[string]any)) != 43 || data["equipment"].(map[string]any)["clothes_head"] != 1 { - t.Fatal("equipment is not a complete top-level section") + fields := playerPageValues(t, page.Body.String()) + count := 0 + for name := range fields { + if strings.HasPrefix(name, "equipment.") { + count++ + } } - if _, nested := data["inventory"].(map[string]any)["equipment"]; nested { - t.Fatal("equipment is nested under ordinary inventory") + if count != 43 || fields.Get("equipment.clothes_head") != "1" { + t.Fatal("equipment form is incomplete") } + if len(restarted.characters[1].inventory.Items) != 1 || restarted.characters[1].inventory.Items[0].Slot != 18 { t.Fatal("the equipped instance did not survive restart") } @@ -77,7 +74,7 @@ func TestControlInventoryTablesShowInstancesContainersAndEmptySlots(t *testing.T body := withoutItemIcons(page.Body.String()) for _, expected := range []string{ - "<base href='/share/test/'>", "<textarea name='data'", "<h2>Inventory</h2>", "<h2>Equipment</h2>", "<h2>Bank</h2>", + "<base href='/share/test/'>", "<form class='player-editor'", "<h2>Inventory</h2>", "<h2>Equipment</h2>", "<h2>Bank</h2>", "<tr><td>inventory_slot_1</td><td></td><td><a href='admin/items/1'>Solar-Powered Pistol (ID 1)</a></td></tr>", "<tr><td>clothes_head</td><td></td><td><a href='admin/items/2'>Worn Metaplast Armor Helmet (ID 2)</a></td></tr>", "<h2>Container <a href='admin/items/3'>Small Backpack (ID 3)</a></h2>", @@ -115,7 +112,7 @@ func TestControlBackpackPagesLinkContentsAndParentContainer(t *testing.T) { func TestControlEquipmentClearUnassignsWithoutLosingItems(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"equipment: {clothes_head: null}\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("equipment: {clothes_head: null}\n")) restarted := newServerForTest(t) var placements int err := restarted.db.QueryRow("SELECT count(*) FROM item_locations").Scan(&placements) @@ -142,7 +139,7 @@ func TestControlEquipmentRejectsInvalidPlacementsAtomically(t *testing.T) { t.Run(name, func(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"name: Changed\n" + document}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("name: Changed\n"+document)) restarted := newServerForTest(t) if response.Code != http.StatusBadRequest || world.characters[1].name != "Explorer" || restarted.characters[1].name != "Explorer" { @@ -168,7 +165,7 @@ func TestControlEquipmentCannotTakeAnotherPlayersItem(t *testing.T) { t.Fatal(assigned.Body.String()) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"equipment: {clothes_head: 5}\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("equipment: {clothes_head: 5}\n")) var owner, slot uint32 err := world.db.QueryRow("SELECT player_id, slot FROM item_locations WHERE item_id=5").Scan(&owner, &slot) @@ -179,10 +176,14 @@ func TestControlEquipmentCannotTakeAnotherPlayersItem(t *testing.T) { func TestControlInventoryTablesIncludeReclaimAndItsBackpackContents(t *testing.T) { world := newControlInventoryWorld(t) - document := "inventory:\n slots: {inventory_slot_2: null}\n reclaim: [{id: 3, original_slot: inventory_slot_2, available_at: 2026-10-23T00:00:00Z}]\n" - prepared := postControlForm(world, "/admin/players/1", url.Values{"data": {document}}) + prepared := postControlForm(world, "/admin/players/1", url.Values{ + "inventory.slots.inventory_slot_2": {""}, + "reclaim.0.id": {"3"}, + "reclaim.0.original_slot": {"inventory_slot_2"}, + "reclaim.0.available_at": {"2026-10-23T00:00:00Z"}, + }) if prepared.Code != http.StatusSeeOther { - t.Fatal(prepared.Body.String()) + t.Fatal(prepared.Code, prepared.Body.String()) } page := httptest.NewRecorder() diff --git a/server/control_player_form.go b/server/control_player_form.go @@ -0,0 +1,453 @@ +package main + +import ( + "fmt" + "html" + "io" + "math" + "net/url" + "slices" + "strconv" + "strings" + "time" +) + +type playerFormField struct { + name string + value any +} + +type playerFormSlot struct { + slots map[string]*uint32 + name string +} + +// The same explicit fields render controls and parse submitted values. +func (data *characterEditor) formFields() []playerFormField { + if data.ReturnDoor == nil { + data.ReturnDoor = &doorOrigin{} + } else { + origin := *data.ReturnDoor + data.ReturnDoor = &origin + } + // One empty row allows adding a reclaim entry without a separate editor. + data.Inventory.Reclaim = append(slices.Clone(data.Inventory.Reclaim), reclaimReference{}) + fields := []playerFormField{ + {"name", &data.Name}, + {"title", &data.Title}, + {"level", &data.Level}, + {"profession", &data.Profession}, + {"experience", &data.Experience}, + {"insured_experience", &data.InsuredExperience}, + {"running", &data.Running}, + {"appearance.race", &data.Appearance.Race}, + {"appearance.fatness", &data.Appearance.Fatness}, + {"appearance.breed", &data.Appearance.Breed}, + {"appearance.sex", &data.Appearance.Sex}, + {"appearance.side", &data.Appearance.Side}, + {"appearance.head", &data.Appearance.Head}, + {"appearance.head_mesh", &data.HeadMesh}, + {"appearance.height", &data.Height}, + {"appearance.monster_data", &data.MonsterData}, + {"stats.improvement_points", &data.Stats.ImprovementPoints}, + {"stats.abilities.strength", &data.Stats.Abilities.Strength}, + {"stats.abilities.agility", &data.Stats.Abilities.Agility}, + {"stats.abilities.stamina", &data.Stats.Abilities.Stamina}, + {"stats.abilities.intelligence", &data.Stats.Abilities.Intelligence}, + {"stats.abilities.sense", &data.Stats.Abilities.Sense}, + {"stats.abilities.psychic", &data.Stats.Abilities.Psychic}, + {"stats.body.martial_arts", &data.Stats.Body.MartialArts}, + {"stats.body.brawling", &data.Stats.Body.Brawling}, + {"stats.body.riposte", &data.Stats.Body.Riposte}, + {"stats.body.dimach", &data.Stats.Body.Dimach}, + {"stats.body.adventuring", &data.Stats.Body.Adventuring}, + {"stats.body.swimming", &data.Stats.Body.Swimming}, + {"stats.body.body_development", &data.Stats.Body.BodyDevelopment}, + {"stats.body.nano_pool", &data.Stats.Body.NanoPool}, + {"stats.melee.one_hand_blunt", &data.Stats.Melee.OneHandBlunt}, + {"stats.melee.one_hand_edged", &data.Stats.Melee.OneHandEdged}, + {"stats.melee.piercing", &data.Stats.Melee.Piercing}, + {"stats.melee.two_hand_blunt", &data.Stats.Melee.TwoHandBlunt}, + {"stats.melee.two_hand_edged", &data.Stats.Melee.TwoHandEdged}, + {"stats.melee.melee_energy", &data.Stats.Melee.MeleeEnergy}, + {"stats.melee.parry", &data.Stats.Melee.Parry}, + {"stats.melee.sneak_attack", &data.Stats.Melee.SneakAttack}, + {"stats.melee.multi_melee", &data.Stats.Melee.MultiMelee}, + {"stats.melee.fast_attack", &data.Stats.Melee.FastAttack}, + {"stats.misc_weapons.sharp_objects", &data.Stats.MiscWeapons.SharpObjects}, + {"stats.misc_weapons.grenade", &data.Stats.MiscWeapons.Grenade}, + {"stats.misc_weapons.heavy_weapons", &data.Stats.MiscWeapons.HeavyWeapons}, + {"stats.ranged.bow", &data.Stats.Ranged.Bow}, + {"stats.ranged.pistol", &data.Stats.Ranged.Pistol}, + {"stats.ranged.assault_rifle", &data.Stats.Ranged.AssaultRifle}, + {"stats.ranged.submachine_gun", &data.Stats.Ranged.SubmachineGun}, + {"stats.ranged.shotgun", &data.Stats.Ranged.Shotgun}, + {"stats.ranged.rifle", &data.Stats.Ranged.Rifle}, + {"stats.ranged.ranged_energy", &data.Stats.Ranged.RangedEnergy}, + {"stats.ranged.fling_shot", &data.Stats.Ranged.FlingShot}, + {"stats.ranged.aimed_shot", &data.Stats.Ranged.AimedShot}, + {"stats.ranged.burst", &data.Stats.Ranged.Burst}, + {"stats.ranged.full_auto", &data.Stats.Ranged.FullAuto}, + {"stats.ranged.bow_special_attack", &data.Stats.Ranged.BowSpecialAttack}, + {"stats.ranged.multi_ranged", &data.Stats.Ranged.MultiRanged}, + {"stats.speed.melee_initiative", &data.Stats.Speed.MeleeInitiative}, + {"stats.speed.ranged_initiative", &data.Stats.Speed.RangedInitiative}, + {"stats.speed.physical_initiative", &data.Stats.Speed.PhysicalInitiative}, + {"stats.speed.nano_initiative", &data.Stats.Speed.NanoInitiative}, + {"stats.speed.dodge_ranged", &data.Stats.Speed.DodgeRanged}, + {"stats.speed.evade_close", &data.Stats.Speed.EvadeClose}, + {"stats.speed.duck_explosions", &data.Stats.Speed.DuckExplosions}, + {"stats.speed.nano_resist", &data.Stats.Speed.NanoResist}, + {"stats.speed.run_speed", &data.Stats.Speed.RunSpeed}, + {"stats.trade_repair.mechanical_engineering", &data.Stats.TradeRepair.MechanicalEngineering}, + {"stats.trade_repair.electrical_engineering", &data.Stats.TradeRepair.ElectricalEngineering}, + {"stats.trade_repair.quantum_field_technology", &data.Stats.TradeRepair.QuantumFieldTechnology}, + {"stats.trade_repair.weapon_smithing", &data.Stats.TradeRepair.WeaponSmithing}, + {"stats.trade_repair.pharmaceutical_technology", &data.Stats.TradeRepair.PharmaceuticalTechnology}, + {"stats.trade_repair.nano_programming", &data.Stats.TradeRepair.NanoProgramming}, + {"stats.trade_repair.computer_literacy", &data.Stats.TradeRepair.ComputerLiteracy}, + {"stats.trade_repair.psychology", &data.Stats.TradeRepair.Psychology}, + {"stats.trade_repair.chemistry", &data.Stats.TradeRepair.Chemistry}, + {"stats.trade_repair.tutoring", &data.Stats.TradeRepair.Tutoring}, + {"stats.nano_aiding.matter_metamorphosis", &data.Stats.NanoAiding.MatterMetamorphosis}, + {"stats.nano_aiding.biological_metamorphosis", &data.Stats.NanoAiding.BiologicalMetamorphosis}, + {"stats.nano_aiding.psychological_modification", &data.Stats.NanoAiding.PsychologicalModification}, + {"stats.nano_aiding.matter_creation", &data.Stats.NanoAiding.MatterCreation}, + {"stats.nano_aiding.time_and_space", &data.Stats.NanoAiding.TimeAndSpace}, + {"stats.nano_aiding.sensory_improvement", &data.Stats.NanoAiding.SensoryImprovement}, + {"stats.nano_aiding.first_aid", &data.Stats.NanoAiding.FirstAid}, + {"stats.nano_aiding.treatment", &data.Stats.NanoAiding.Treatment}, + {"stats.spying.concealment", &data.Stats.Spying.Concealment}, + {"stats.spying.breaking_and_entering", &data.Stats.Spying.BreakingAndEntering}, + {"stats.spying.trap_disarm", &data.Stats.Spying.TrapDisarm}, + {"stats.spying.perception", &data.Stats.Spying.Perception}, + {"stats.navigation.vehicle_air", &data.Stats.Navigation.VehicleAir}, + {"stats.navigation.vehicle_ground", &data.Stats.Navigation.VehicleGround}, + {"stats.navigation.vehicle_water", &data.Stats.Navigation.VehicleWater}, + {"stats.navigation.map_navigation", &data.Stats.Navigation.MapNavigation}, + {"location.playfield", &data.Playfield}, + {"position.x", &data.Position[0]}, + {"position.y", &data.Position[1]}, + {"position.z", &data.Position[2]}, + {"rotation.x", &data.Rotation[0]}, + {"rotation.y", &data.Rotation[1]}, + {"rotation.z", &data.Rotation[2]}, + {"rotation.w", &data.Rotation[3]}, + {"return_door.playfield", &data.ReturnDoor.Playfield}, + {"return_door.door", &data.ReturnDoor.Door}, + {"vitals.health", &data.Vitals.Health}, + {"vitals.nano", &data.Vitals.Nano}, + {"vitals.sitting", &data.Vitals.Sitting}, + {"vitals.agg_def", &data.Vitals.AggDef}, + {"vitals.recharge_until", &data.Vitals.RechargeUntil}, + {"vitals.nano_recharge_until", &data.Vitals.NanoRechargeUntil}, + {"vitals.regeneration_at", &data.Vitals.RegenerationAt}, + {"vitals.regeneration_seconds", &data.Vitals.RegenerationSeconds}, + {"vitals.resurrection_shock", &data.Vitals.ResurrectionShock}, + {"recovery.resurrection_terminal", &data.ResurrectionTerminal}, + {"recovery.implant_changes_until", &data.ImplantChangesUntil}, + {"inventory.credits", &data.Inventory.Credits}, + {"inventory.clan_tokens", &data.Inventory.ClanTokens}, + {"inventory.omni_tokens", &data.Inventory.OmniTokens}, + {"inventory.learned_nanos", &data.Inventory.LearnedNanos}, + {"inventory.map_flags.0", &data.Inventory.MapFlags[0]}, + {"inventory.map_flags.1", &data.Inventory.MapFlags[1]}, + {"inventory.map_flags.2", &data.Inventory.MapFlags[2]}, + } + // Slots retain instance references; item details are edited on their own pages. + for _, group := range []struct { + name string + slots map[string]*uint32 + }{ + {"inventory.slots", data.Inventory.Slots}, + {"equipment", data.Equipment}, + {"bank", data.Bank}, + } { + names := make([]string, 0, len(group.slots)) + for name := range group.slots { + names = append(names, name) + } + slices.SortFunc(names, func(a, b string) int { + // Numbered slots sort numerically; named equipment sorts alphabetically. + if len(a) != len(b) && (group.name == "bank" || group.name == "inventory.slots") { + return len(a) - len(b) + } + return strings.Compare(a, b) + }) + for _, name := range names { + fields = append(fields, playerFormField{group.name + "." + name, playerFormSlot{group.slots, name}}) + } + } + for index := range data.Inventory.Reclaim { + entry := &data.Inventory.Reclaim[index] + prefix := fmt.Sprintf("reclaim.%d.", index) + fields = append(fields, playerFormField{prefix + "id", &entry.ID}, playerFormField{prefix + "original_slot", &entry.Slot}, playerFormField{prefix + "available_at", &entry.AvailableAt}) + } + return fields +} + +func playerFieldLabel(name string) string { + label := strings.ReplaceAll(name, "_", " ") + return strings.ToUpper(label[:1]) + label[1:] +} + +func (field playerFormField) render(w io.Writer) { + name := html.EscapeString(field.name) + _, label, _ := strings.Cut(field.name, ".") + if label == "" { + label = field.name + } + if index := strings.LastIndex(label, "."); index >= 0 { + label = label[index+1:] + } + fmt.Fprintf(w, "<label>%s", html.EscapeString(playerFieldLabel(label))) + // Reclaim always refers to an ordinary inventory slot. + if strings.HasPrefix(field.name, "reclaim.") && strings.HasSuffix(field.name, ".original_slot") { + fmt.Fprintf(w, "<select name='%s'><option value=''", name) + if *field.value.(*string) == "" { + fmt.Fprint(w, " selected") + } + fmt.Fprint(w, ">Choose a slot</option>") + for index := 1; index <= 30; index++ { + value := fmt.Sprintf("inventory_slot_%d", index) + selected := "" + if value == *field.value.(*string) { + selected = " selected" + } + fmt.Fprintf(w, "<option value='%s'%s>Inventory slot %d</option>", value, selected, index) + } + fmt.Fprint(w, "</select></label>") + return + } + + // Named choices keep common appearance edits readable while retaining native codes. + var choices []string + firstChoice := 0 + switch field.name { + case "profession": + firstChoice = 1 + choices = []string{"Soldier", "Martial Artist", "Engineer", "Fixer", "Agent", "Adventurer", "Trader", "Bureaucrat", "Enforcer", "Doctor", "Nano-Technician", "Meta-Physicist"} + case "appearance.race": + choices = []string{"Unspecified", "Default", "Solitus skin variant", "Solitus skin variant"} + case "appearance.head": + for index := 0; index < 32; index++ { + choices = append(choices, strconv.Itoa(index)) + } + case "appearance.breed": + choices = []string{"Unspecified", "Solitus", "Opifex", "Nanomage", "Atrox", "Unknown", "Creature", "Unknown"} + case "appearance.sex": + choices = []string{"Unspecified", "Atrox / creature", "Male", "Female"} + case "appearance.side": + choices = []string{"Neutral", "Clan", "Omni-Tek", "Unknown"} + case "appearance.fatness": + choices = []string{"Slim", "Normal", "Heavy", "Unknown"} + } + if choices != nil { + fmt.Fprintf(w, "<select name='%s'>", name) + for index, choice := range choices { + selected := "" + if uint16(index+firstChoice) == *field.value.(*uint16) { + selected = " selected" + } + label := fmt.Sprintf("%s (%d)", choice, index+firstChoice) + if field.name == "appearance.head" { + label = choice + } + fmt.Fprintf(w, "<option value='%d'%s>%s</option>", index+firstChoice, selected, html.EscapeString(label)) + } + fmt.Fprint(w, "</select></label>") + return + } + kind, value, attributes := "number", "", " step='1' min='0'" + switch target := field.value.(type) { + case *string: + kind, value, attributes = "text", *target, "" + case *uint16: + value = fmt.Sprint(*target) + attributes += " max='65535' required" + case *uint32: + value = fmt.Sprint(*target) + attributes += " max='4294967295' required" + case *int32: + value, attributes = fmt.Sprint(*target), " step='1' min='-2147483648' max='2147483647' required" + case *float32: + value, attributes = strconv.FormatFloat(float64(*target), 'g', -1, 32), " step='any' required" + case *bool: + fmt.Fprintf(w, "<select name='%s'>", name) + for _, option := range []bool{false, true} { + selected := "" + if option == *target { + selected = " selected" + } + text := "No" + if option { + text = "Yes" + } + fmt.Fprintf(w, "<option value='%t'%s>%s</option>", option, selected, text) + } + fmt.Fprint(w, "</select></label>") + return + case *time.Time: + kind, attributes = "text", " placeholder='RFC3339 timestamp or blank'" + if !target.IsZero() { + value = target.Format(time.RFC3339Nano) + } + case *[]uint32: + kind, attributes = "text", " placeholder='Catalog IDs, separated by commas'" + values := make([]string, len(*target)) + for i, id := range *target { + values[i] = fmt.Sprint(id) + } + value = strings.Join(values, ", ") + case playerFormSlot: + attributes += " max='4294967295' placeholder='Empty'" + if target.slots[target.name] != nil { + value = fmt.Sprint(*target.slots[target.name]) + } + } + switch field.name { + case "name": + attributes = " maxlength='254' required" + case "title": + attributes = " maxlength='31'" + case "level": + attributes = " min='1' max='200' required" + } + fmt.Fprintf(w, "<input type='%s' name='%s' value='%s'%s></label>", kind, name, html.EscapeString(value), attributes) +} + +func renderPlayerForm(w io.Writer, data characterEditor) { + fmt.Fprint(w, `<style>.player-fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px}.player-fields label{display:flex;flex-direction:column;align-items:stretch;margin:0;min-width:0}.player-fields input,.player-fields select{width:100%}.player-editor h3{margin-top:0}</style>`) + fmt.Fprintf(w, "<form class='player-editor' method='post' action='admin/players/%d'>", data.ID) + group := "" + for _, field := range data.formFields() { + next := "Character" + if index := strings.LastIndex(field.name, "."); index >= 0 { + next = field.name[:index] + } + if next != group { + if group != "" { + fmt.Fprint(w, "</div></section>") + } + title := playerFieldLabel(strings.ReplaceAll(next, ".", " / ")) + if strings.HasPrefix(next, "reclaim.") { + index, _ := strconv.Atoi(strings.TrimPrefix(next, "reclaim.")) + title = fmt.Sprintf("Reclaim item %d", index+1) + } + fmt.Fprintf(w, "<section><h3>%s</h3>", html.EscapeString(title)) + if next == "appearance" { + fmt.Fprint(w, "<p>Breed: 1 Solitus, 2 Opifex, 3 Nanomage, 4 Atrox, 6 creature. Sex: 2 male, 3 female; 1 for Atrox and creatures. Side: 0 neutral, 1 Clan, 2 Omni-Tek. Body build (fatness): 0 slim, 1 normal, 2 heavy. Race: 1 default. Head: 0-31; head mesh selects the visible head.</p>") + } + if next == "inventory.slots" || next == "equipment" || next == "bank" { + fmt.Fprint(w, "<p>Item instance IDs. Leave a slot blank to unassign its item. Use the item links below to inspect or edit an instance.</p>") + } + if strings.HasPrefix(next, "reclaim.") { + fmt.Fprint(w, "<p>Set the item instance ID, original inventory slot and availability time. ID 0 leaves the entry empty or removes it from reclaim.</p>") + } + if next == "return_door" { + fmt.Fprint(w, "<p>Set both fields to zero to clear the return door.</p>") + } + fmt.Fprint(w, "<div class='player-fields'>") + group = next + } + field.render(w) + } + fmt.Fprint(w, "</div></section><button>Save</button></form>") +} + +func (field playerFormField) parse(text string) error { + switch target := field.value.(type) { + case *string: + *target = text + case *uint16: + value, err := strconv.ParseUint(text, 10, 16) + if err != nil { + return err + } + *target = uint16(value) + case *uint32: + value, err := strconv.ParseUint(text, 10, 32) + if err != nil { + return err + } + *target = uint32(value) + case *int32: + value, err := strconv.ParseInt(text, 10, 32) + if err != nil { + return err + } + *target = int32(value) + case *float32: + value, err := strconv.ParseFloat(text, 32) + if err != nil { + return err + } + if math.IsNaN(value) || math.IsInf(value, 0) { + return fmt.Errorf("must be a finite number") + } + *target = float32(value) + case *bool: + if text != "true" && text != "false" { + return fmt.Errorf("choose Yes or No") + } + *target = text == "true" + case *time.Time: + if text == "" { + *target = time.Time{} + return nil + } + value, err := time.Parse(time.RFC3339Nano, text) + if err != nil { + return err + } + *target = value + case *[]uint32: + var values []uint32 + if strings.TrimSpace(text) != "" { + for _, part := range strings.Split(text, ",") { + value, err := strconv.ParseUint(strings.TrimSpace(part), 10, 32) + if err != nil { + return err + } + values = append(values, uint32(value)) + } + } + *target = values + case playerFormSlot: + if text == "" { + target.slots[target.name] = nil + return nil + } + value, err := strconv.ParseUint(text, 10, 32) + if err != nil { + return err + } + id := uint32(value) + target.slots[target.name] = &id + } + return nil +} + +func (data *characterEditor) readForm(values url.Values) error { + fields := make(map[string]playerFormField) + for _, field := range data.formFields() { + fields[field.name] = field + } + for name, entries := range values { + field, exists := fields[name] + if !exists { + return fmt.Errorf("unknown player field %q", name) + } + if len(entries) != 1 { + return fmt.Errorf("expected one value for %s", name) + } + if err := field.parse(entries[0]); err != nil { + return fmt.Errorf("%s: %w", name, err) + } + } + data.Inventory.Reclaim = slices.DeleteFunc(data.Inventory.Reclaim, func(entry reclaimReference) bool { return entry.ID == 0 }) + if data.ReturnDoor.Playfield == 0 && data.ReturnDoor.Door == 0 { + data.ReturnDoor = nil + } + return nil +} diff --git a/server/control_player_form_test.go b/server/control_player_form_test.go @@ -0,0 +1,186 @@ +package main + +import ( + "fmt" + "html" + "net/http" + "net/http/httptest" + "net/url" + "regexp" + "strconv" + "strings" + "testing" + + "go.yaml.in/yaml/v3" +) + +// Existing gameplay fixtures use YAML for concise setup, then submit actual form fields. +func playerFixtureForm(document string) url.Values { + if document == "" { + return make(url.Values) + } + var node yaml.Node + if err := yaml.Unmarshal([]byte(document), &node); err != nil { + panic(err) + } + values := make(url.Values) + var visit func(string, *yaml.Node) + visit = func(path string, node *yaml.Node) { + if path == "id" || path == "browser_token_hash" { + return + } + if node.Kind == yaml.MappingNode { + for i := 0; i < len(node.Content); i += 2 { + name := node.Content[i].Value + if path != "" { + name = path + "." + name + } + visit(name, node.Content[i+1]) + } + return + } + if node.Kind == yaml.SequenceNode { + if path == "inventory.learned_nanos" { + parts := make([]string, len(node.Content)) + for i, n := range node.Content { + parts[i] = n.Value + } + values.Add(path, strings.Join(parts, ",")) + return + } + for i, n := range node.Content { + name := strconv.Itoa(i) + if path == "position" || path == "rotation" { + name = string("xyzw"[i]) + } + visit(path+"."+name, n) + } + return + } + if path == "return_door" && node.Tag == "!!null" { + values.Set("return_door.playfield", "0") + values.Set("return_door.door", "0") + return + } + if path == "inventory.reclaim" && node.Tag == "!!null" { + return + } + switch path { + case "playfield": + path = "location.playfield" + case "head_mesh", "height", "monster_data": + path = "appearance." + path + case "resurrection_terminal", "implant_changes_until": + path = "recovery." + path + } + path = strings.Replace(path, "inventory.reclaim.", "reclaim.", 1) + value := node.Value + if node.Tag == "!!null" { + value = "" + } + values.Add(path, value) + } + visit("", node.Content[0]) + return values +} + +func playerEditorForm(t *testing.T, data characterEditor) url.Values { + t.Helper() + var page strings.Builder + renderPlayerForm(&page, data) + return playerPageValues(t, page.String()) +} + +func playerPageValues(t *testing.T, markup string) url.Values { + t.Helper() + values := make(url.Values) + for _, match := range regexp.MustCompile(`<input type='[^']+' name='([^']+)' value='([^']*)'`).FindAllStringSubmatch(markup, -1) { + values.Set(html.UnescapeString(match[1]), html.UnescapeString(match[2])) + } + for _, match := range regexp.MustCompile(`(?s)<select name='([^']+)'>(.*?)</select>`).FindAllStringSubmatch(markup, -1) { + selected := regexp.MustCompile(`<option value='([^']*)' selected>`).FindStringSubmatch(match[2]) + if len(selected) != 2 { + t.Fatalf("missing selection: %s", match[0]) + } + values.Set(match[1], html.UnescapeString(selected[1])) + } + return values +} + +func TestPlayerFormRoundTripAndValidation(t *testing.T) { + world := newControlInventoryWorld(t) + page := httptest.NewRecorder() + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) + fields := playerPageValues(t, page.Body.String()) + fields.Set("name", "Edited Explorer") + fields.Set("title", "A & B") + fields.Set("stats.ranged.rifle", "42") + fields.Set("inventory.credits", "913") + fields.Set("running", "false") + + response := postControlForm(world, "/admin/players/1", fields) + restarted := newServerForTest(t) + + if response.Code != http.StatusSeeOther { + t.Fatal(response.Code, response.Body.String()) + } + player := restarted.characters[1] + if player.name != "Edited Explorer" || player.title != "A & B" || player.stats.Ranged.Rifle != 42 || player.inventory.Credits != 913 || player.running || len(player.inventory.Items) != 3 || len(player.inventory.Containers[3]) != 1 || player.returnDoor != nil { + t.Fatal("form did not preserve the player and item ownership", player.name, player.inventory) + } + if strings.Contains(page.Body.String(), "<textarea") || strings.Contains(page.Body.String(), "<details") || strings.Contains(page.Body.String(), "browser_token_hash") { + t.Fatal("player page exposes a document or credential field") + } +} + +func TestPlayerFormRejectsInvalidFieldsWithoutChangingState(t *testing.T) { + for _, fields := range []url.Values{ + {"level": {"65536"}}, {"stats.ranged.rifle": {"-1"}}, {"position.x": {"NaN"}}, + {"running": {"maybe"}}, {"recovery.implant_changes_until": {"yesterday"}}, + {"inventory.slots.inventory_slot_2": {"1"}}, {"name": {"First", "Second"}}, + {"data": {"name: Changed"}}, {"id": {"2"}}, {"browser_token_hash": {"changed"}}, + } { + t.Run(fmt.Sprint(fields), func(t *testing.T) { + world := newControlInventoryWorld(t) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + fields.Set("title", "Must not save") + + response := postControlForm(world, "/admin/players/1", fields) + restarted := newServerForTest(t) + after, err := readTestItemStore(restarted) + + if response.Code != http.StatusBadRequest || err != nil || string(before) != string(after) || world.characters[1].title != "" || restarted.characters[1].title != "" { + t.Fatal(response.Code, response.Body.String(), err) + } + }) + } +} + +func TestPlayerFormClearsReclaimWithoutDeletingTheItem(t *testing.T) { + world := newControlInventoryWorld(t) + prepared := postControlForm(world, "/admin/players/1", url.Values{ + "inventory.slots.inventory_slot_1": {""}, + "reclaim.0.id": {"1"}, + "reclaim.0.original_slot": {"inventory_slot_1"}, + "reclaim.0.available_at": {"2026-10-23T00:00:00Z"}, + }) + if prepared.Code != http.StatusSeeOther { + t.Fatal(prepared.Code, prepared.Body.String()) + } + page := httptest.NewRecorder() + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) + fields := playerPageValues(t, page.Body.String()) + fields.Set("reclaim.0.id", "0") + + response := postControlForm(world, "/admin/players/1", fields) + restarted := newServerForTest(t) + var placements int + err := restarted.db.QueryRow("SELECT count(*) FROM item_locations WHERE item_id=1").Scan(&placements) + + if response.Code != http.StatusSeeOther || err != nil || placements != 0 || len(restarted.characters[1].inventory.Reclaim) != 0 || len(restarted.items) != 4 { + t.Fatal("clearing reclaim lost the item or retained its placement", response.Code, response.Body.String(), placements, err) + } +} diff --git a/server/database.go b/server/database.go @@ -62,16 +62,16 @@ func (server *server) openDatabase() (*sql.DB, error) { } type playerVitals struct { - Health uint32 `yaml:"health"` - Nano uint32 `yaml:"nano"` - NanoReserved uint32 `yaml:"-"` - Sitting bool `yaml:"sitting"` - AggDef int32 `yaml:"agg_def"` - RechargeUntil time.Time `yaml:"recharge_until"` - NanoRechargeUntil time.Time `yaml:"nano_recharge_until"` - RegenerationAt time.Time `yaml:"regeneration_at"` - RegenerationSeconds uint32 `yaml:"regeneration_seconds"` - ResurrectionShock uint32 `yaml:"resurrection_shock"` + Health uint32 + Nano uint32 + NanoReserved uint32 + Sitting bool + AggDef int32 + RechargeUntil time.Time + NanoRechargeUntil time.Time + RegenerationAt time.Time + RegenerationSeconds uint32 + ResurrectionShock uint32 } func (character *character) profile() playerProfile { diff --git a/server/database_test.go b/server/database_test.go @@ -7,11 +7,8 @@ import ( "net/http" "net/url" "os" - "strings" "testing" "time" - - "go.yaml.in/yaml/v3" ) func TestWorldDatabaseInitializationRollsBackAndRetries(t *testing.T) { @@ -59,45 +56,20 @@ func readTestPlayerRecord(id uint32, name string) ([]byte, error) { } switch name { case "player": - return yaml.Marshal(record.Profile) + return json.Marshal(record.Profile) case "position": - return yaml.Marshal(record.Position.editor()) + return json.Marshal(record.Position.editor()) default: return nil, fmt.Errorf("unknown test record %q", name) } } -func writeTestPlayerRecord(id uint32, name string, contents []byte) error { - world := &server{} - db, err := world.openDatabase() - if err != nil { - return err - } - defer world.closeDatabase() - tx, err := db.Begin() - if err != nil { - return err - } - defer tx.Rollback() - var profile playerProfile - if name != "player" { - return fmt.Errorf("unknown test record %q", name) - } - if err := decodeUsers(strings.NewReader(string(contents)), &profile); err != nil { - return err - } - if err := updateRecord(tx, "characters", id, profileColumns, profile.fields()); err != nil { - return err - } - return tx.Commit() -} - func readTestItemStore(world *server) ([]byte, error) { store, err := world.readItems() if err != nil { return nil, err } - return yaml.Marshal(store) + return json.Marshal(store) } func readTestChatHistory(world *server, id uint32) ([]byte, error) { @@ -267,7 +239,7 @@ func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) { postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) world.characters[1].health, world.characters[1].nano = 30, 12 - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 2\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 2\n")) restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || restarted.characters[1].level != 2 || restarted.characters[1].health != 30 || restarted.characters[1].nano != 12 { diff --git a/server/insurance_experience_test.go b/server/insurance_experience_test.go @@ -7,7 +7,6 @@ import ( "fmt" "net" "net/http" - "net/url" "sync" "testing" "time" @@ -236,7 +235,7 @@ func TestInsuranceExperienceEditorRejectsImpossibleSnapshots(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) restored := newTestInventoryServer(t).characters[1] if response.Code != http.StatusBadRequest || player.experience != 50 || player.insuredExperience != 1490 || restored.insuredExperience != 1490 { diff --git a/server/insurance_test.go b/server/insurance_test.go @@ -191,18 +191,13 @@ func TestInsuranceUnknownSavedScannerFailsLoading(t *testing.T) { if err := world.saveUser(player); err != nil { t.Fatal(err) } - contents, err := readTestPlayerRecord(1, "player") - if err != nil { - t.Fatal(err) - } - contents = []byte(strings.Replace(string(contents), "resurrection_terminal: 0", "resurrection_terminal: 123", 1)) - if err := writeTestPlayerRecord(1, "player", contents); err != nil { + if _, err := world.db.Exec("UPDATE characters SET resurrection_terminal=123 WHERE id=1"); err != nil { t.Fatal(err) } loaded := &server{characters: make(map[uint32]*character)} openTestDatabase(t, loaded) - err = loaded.loadUsers() + err := loaded.loadUsers() if err == nil || !strings.Contains(err.Error(), "unknown resurrection terminal") { t.Fatalf("unknown scanner was accepted: %v", err) diff --git a/server/inventory_write_test.go b/server/inventory_write_test.go @@ -7,8 +7,6 @@ import ( "reflect" "testing" "time" - - "go.yaml.in/yaml/v3" ) func newInventoryWriteWorld(t *testing.T) (*server, *combatTestConn) { @@ -85,13 +83,9 @@ func TestInventoryMetadataRetainsUnchangedProgramsAndLocks(t *testing.T) { } data := world.characters[1].editor() data.Inventory.LearnedNanos = []uint32{29618, 43324} - contents, err := yaml.Marshal(data) - if err != nil { - t.Fatal(err) - } auditCheckpointWrites(t, world) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/players/1", playerEditorForm(t, data)) restored := newTestInventoryServer(t) if response.Code != http.StatusSeeOther || !reflect.DeepEqual(restored.characters[1].inventory.LearnedNanos, []uint32{29618, 43324}) || @@ -108,13 +102,9 @@ func TestInventoryMetadataWritesOnlyChangedCreditsAndPrograms(t *testing.T) { data := world.characters[1].editor() data.Inventory.Credits = 43 data.Inventory.LearnedNanos = []uint32{43324, 29618} - contents, err := yaml.Marshal(data) - if err != nil { - t.Fatal(err) - } auditCheckpointWrites(t, world) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/players/1", playerEditorForm(t, data)) restored := newTestInventoryServer(t) inventory := restored.characters[1].inventory @@ -133,7 +123,7 @@ func TestInventoryMetadataRemovalKeepsOtherPlayers(t *testing.T) { contents := "inventory:\n learned_nanos: []\n" auditCheckpointWrites(t, world) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) restored := newTestInventoryServer(t) inventory, other := restored.characters[1].inventory, restored.characters[2].inventory @@ -159,10 +149,6 @@ func TestInventoryMetadataFailureRollsBackWithOwnershipThenRetries(t *testing.T) data.Inventory.Credits, data.Inventory.LearnedNanos = 43, []uint32{29618} data.Inventory.Slots["inventory_slot_2"] = data.Inventory.Slots["inventory_slot_1"] data.Inventory.Slots["inventory_slot_1"] = nil - contents, err := yaml.Marshal(data) - if err != nil { - t.Fatal(err) - } before, err := readTestItemStore(world) if err != nil { t.Fatal(err) @@ -171,7 +157,7 @@ func TestInventoryMetadataFailureRollsBackWithOwnershipThenRetries(t *testing.T) t.Fatal(err) } - failed := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) + failed := postControlForm(world, "/admin/players/1", playerEditorForm(t, data)) after, err := readTestItemStore(world) if err != nil { t.Fatal(err) @@ -183,7 +169,7 @@ func TestInventoryMetadataFailureRollsBackWithOwnershipThenRetries(t *testing.T) if _, err := world.db.Exec("DROP TRIGGER reject_metadata_commit"); err != nil { t.Fatal(err) } - retry := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) + retry := postControlForm(world, "/admin/players/1", playerEditorForm(t, data)) restored := newTestInventoryServer(t) inventory := restored.characters[1].inventory diff --git a/server/item_import_test.go b/server/item_import_test.go @@ -26,7 +26,7 @@ func TestRoutedPlayerEditorTransfersUnassignedBagAtomically(t *testing.T) { t.Fatal(err) } - cleared := adminRequest(handler, "POST", "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null, inventory_slot_2: null}\n"}}.Encode(), nil) + cleared := adminRequest(handler, "POST", "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: null, inventory_slot_2: null}\n").Encode(), nil) first := &zoneTransferQuery{player: 1} if err := firstOwner.call(first); err != nil { t.Fatal(err) @@ -37,7 +37,7 @@ func TestRoutedPlayerEditorTransfersUnassignedBagAtomically(t *testing.T) { if _, err := fixture.db.Exec("CREATE TRIGGER reject_import BEFORE INSERT ON item_locations WHEN NEW.player_id=2 AND NEW.item_id=1 BEGIN SELECT RAISE(FAIL,'claim rejected'); END"); err != nil { t.Fatal(err) } - document := url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 3, inventory_slot_2: 1}\n"}}.Encode() + document := playerFixtureForm("inventory:\n slots: {inventory_slot_1: 3, inventory_slot_2: 1}\n").Encode() failed := adminRequest(handler, "POST", "/admin/players/2", document, nil) destination := &zoneTransferQuery{player: 2} if err := secondOwner.call(destination); err != nil { @@ -60,7 +60,7 @@ func TestRoutedPlayerEditorTransfersUnassignedBagAtomically(t *testing.T) { if accepted.Code != http.StatusSeeOther || !reflect.DeepEqual(destination.items, []uint32{1, 3, 4}) || destination.locations[4] != (itemPlacement{Backpack: 3}) { t.Fatal("bag import lost identity or contents", accepted.Code, accepted.Body.String(), destination) } - stolen := adminRequest(handler, "POST", "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 3}\n"}}.Encode(), nil) + stolen := adminRequest(handler, "POST", "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: 3}\n").Encode(), nil) if stolen.Code != http.StatusBadRequest { t.Fatal("another zone's assigned bag was accepted", stolen.Code, stolen.Body.String()) } @@ -76,7 +76,7 @@ func TestRoutedItemAssignmentClaimsOneOwnerAcrossConcurrentZones(t *testing.T) { fixture.world = newRoutedTestWorld(t, fixture) defer fixture.world.stop() handler := adminTestHandler(fixture) - cleared := adminRequest(handler, "POST", "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_2: null}\n"}}.Encode(), nil) + cleared := adminRequest(handler, "POST", "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_2: null}\n").Encode(), nil) if cleared.Code != http.StatusSeeOther { t.Fatal(cleared.Code, cleared.Body.String()) } diff --git a/server/item_owner_test.go b/server/item_owner_test.go @@ -26,7 +26,7 @@ func TestRoutedItemEditsPreserveAtomicBagOwnership(t *testing.T) { defer fixture.world.stop() handler := adminTestHandler(fixture) if mode == "unassigned" { - cleared := adminRequest(handler, "POST", "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_2: null}\n"}}.Encode(), nil) + cleared := adminRequest(handler, "POST", "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_2: null}\n").Encode(), nil) if cleared.Code != http.StatusSeeOther { t.Fatal(cleared.Code, cleared.Body.String()) } diff --git a/server/item_pages.go b/server/item_pages.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "html" + "io" "maps" "net/http" "slices" @@ -16,6 +17,19 @@ import ( "go.yaml.in/yaml/v3" ) +func decodeYAML(reader io.Reader, value any) error { + decoder := yaml.NewDecoder(reader) + decoder.KnownFields(true) + if err := decoder.Decode(value); err != nil { + return err + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + return fmt.Errorf("expected one YAML document") + } + return nil +} + type itemLocation struct { owner uint32 container uint32 @@ -306,7 +320,7 @@ func (state *server) editItemRecord(w http.ResponseWriter, r *http.Request, impo id, err := strconv.ParseUint(r.PathValue("item"), 10, 32) var record itemRecord if err == nil { - err = decodeUsers(strings.NewReader(r.FormValue("data")), &record) + err = decodeYAML(strings.NewReader(r.FormValue("data")), &record) } definition := gamedata.ItemTemplates[record.Template] if err != nil || definition == nil || record.Type != definition.HeaderWords[0] || !gamedata.ItemQualitySupported(record.Template, record.Quality) { diff --git a/server/item_store.go b/server/item_store.go @@ -21,25 +21,25 @@ type itemRecord struct { } type reclaimReference struct { - ID uint32 `yaml:"id"` - Slot string `yaml:"original_slot"` - AvailableAt time.Time `yaml:"available_at"` + ID uint32 + Slot string + AvailableAt time.Time } type inventoryReferences struct { - Credits uint32 `yaml:"credits"` - Slots map[string]*uint32 `yaml:"slots"` - Reclaim []reclaimReference `yaml:"reclaim"` - LearnedNanos []uint32 `yaml:"learned_nanos"` - MapFlags [3]uint32 `yaml:"map_flags,flow"` - ClanTokens uint32 `yaml:"clan_tokens"` - OmniTokens uint32 `yaml:"omni_tokens"` + Credits uint32 + Slots map[string]*uint32 + Reclaim []reclaimReference + LearnedNanos []uint32 + MapFlags [3]uint32 + ClanTokens uint32 + OmniTokens uint32 } type characterItemReferences struct { - inventoryReferences `yaml:",inline"` - Equipment map[string]*uint32 `yaml:"equipment"` - Bank map[string]*uint32 `yaml:"bank"` + inventoryReferences + Equipment map[string]*uint32 + Bank map[string]*uint32 } type playerVitalUpdate struct { @@ -49,9 +49,9 @@ type playerVitalUpdate struct { type itemStore struct { imported *itemImport - LastID uint32 `yaml:"last_id"` - Items map[uint32]itemRecord `yaml:"items"` - Players map[uint32]characterItemReferences `yaml:"players"` + LastID uint32 + Items map[uint32]itemRecord + Players map[uint32]characterItemReferences Corpses map[uint32][]ownedItem WorldItems map[uint32]worldItem DepletedResources map[uint32]bool diff --git a/server/item_store_test.go b/server/item_store_test.go @@ -55,7 +55,7 @@ func TestDatabaseRejectsSharedInstanceReferences(t *testing.T) { postControlForm(world, "/admin/players", url.Values{"name": {"Second"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}"}}) + postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: 1}")) _, err := world.db.Exec("INSERT INTO item_locations (item_id, player_id, slot) VALUES (1, 2, 65)") _, occupiedError := world.db.Exec("INSERT INTO item_locations (item_id, player_id, slot) VALUES (2, 1, 64)") @@ -75,7 +75,7 @@ func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) { world := newTestServer(t) postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/players/1", playerFixtureForm("inventory:\n slots: {inventory_slot_1: 1}\n")) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) page := httptest.NewRecorder() diff --git a/server/progression_test.go b/server/progression_test.go @@ -57,7 +57,7 @@ func TestExperienceEditAndCheckpointSurviveRestart(t *testing.T) { postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) postControlForm(world, "/admin/players", url.Values{"name": {"Observer"}}) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("level: 2\nexperience: 50\n")) player := world.characters[1] player.position[0]++ if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { @@ -93,7 +93,7 @@ func TestExperienceEditorRejectsInvalidProgressWithoutChangingState(t *testing.T t.Fatal(err) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) after, err := readTestPlayerRecord(1, "player") if err != nil || response.Code != http.StatusBadRequest || !bytes.Equal(before, after) || world.characters[1].experience != 0 || world.characters[1].level != 1 { @@ -116,7 +116,7 @@ func TestExperienceEditorAcceptsLevelEndpoints(t *testing.T) { postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) contents := fmt.Sprintf("level: %d\nexperience: %d\n", scenario.level, scenario.experience) - response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm(contents)) restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || restarted.characters[1].level != scenario.level || @@ -150,7 +150,7 @@ func TestExperienceEditFailureRollsBackThenRetries(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("level: 2\nexperience: 50\n")) restarted := newServerForTest(t) if response.Code != http.StatusInternalServerError || world.characters[1].level != 1 || world.characters[1].experience != 0 || @@ -162,7 +162,7 @@ func TestExperienceEditFailureRollsBackThenRetries(t *testing.T) { if _, err := world.db.Exec("DROP TRIGGER reject_xp"); err != nil { t.Fatal(err) } - response = postControlForm(world, "/admin/players/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response = postControlForm(world, "/admin/players/1", playerFixtureForm("level: 2\nexperience: 50\n")) retried := newServerForTest(t) if response.Code != http.StatusSeeOther || retried.characters[1].level != 2 || retried.characters[1].experience != 50 { t.Fatal("the rejected progression edit could not be retried") diff --git a/server/shop_control_edit_test.go b/server/shop_control_edit_test.go @@ -42,7 +42,7 @@ func TestShopControlEditRetiresDraftBeforeReconnection(t *testing.T) { } conn.packets = nil - path, fields := "/admin/players/1", url.Values{"data": {scenario.document}} + path, fields := "/admin/players/1", playerFixtureForm(scenario.document) if scenario.document == "" { path, fields = "/admin/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}} } @@ -147,7 +147,7 @@ func TestShopRejectedControlSavePreservesAcceptableDraft(t *testing.T) { } conn.packets = nil - response := postControlForm(world, "/admin/players/1", url.Values{"data": {"name: Changed\ninventory:\n credits: 17\n slots: {inventory_slot_1: null, inventory_slot_2: 1}\n"}}) + response := postControlForm(world, "/admin/players/1", playerFixtureForm("name: Changed\ninventory:\n credits: 17\n slots: {inventory_slot_1: null, inventory_slot_2: 1}\n")) restored := newTestInventoryServer(t) if response.Code != http.StatusInternalServerError || world.clients[1] != client || !client.ready || client.shop == nil || diff --git a/server/stats.go b/server/stats.go @@ -3,122 +3,122 @@ package main import "ao/server/gamedata" type characterStats struct { - ImprovementPoints uint32 `yaml:"improvement_points"` - Abilities characterAbilitiesStats `yaml:"abilities"` - Body characterBodyStats `yaml:"body"` - Melee characterMeleeStats `yaml:"melee"` - MiscWeapons characterMiscWeaponsStats `yaml:"misc_weapons"` - Ranged characterRangedStats `yaml:"ranged"` - Speed characterSpeedStats `yaml:"speed"` - TradeRepair characterTradeRepairStats `yaml:"trade_repair"` - NanoAiding characterNanoAidingStats `yaml:"nano_aiding"` - Spying characterSpyingStats `yaml:"spying"` - Navigation characterNavigationStats `yaml:"navigation"` + ImprovementPoints uint32 + Abilities characterAbilitiesStats + Body characterBodyStats + Melee characterMeleeStats + MiscWeapons characterMiscWeaponsStats + Ranged characterRangedStats + Speed characterSpeedStats + TradeRepair characterTradeRepairStats + NanoAiding characterNanoAidingStats + Spying characterSpyingStats + Navigation characterNavigationStats } type characterAbilitiesStats struct { - Strength uint16 `yaml:"strength"` - Agility uint16 `yaml:"agility"` - Stamina uint16 `yaml:"stamina"` - Intelligence uint16 `yaml:"intelligence"` - Sense uint16 `yaml:"sense"` - Psychic uint16 `yaml:"psychic"` + Strength uint16 + Agility uint16 + Stamina uint16 + Intelligence uint16 + Sense uint16 + Psychic uint16 } type characterBodyStats struct { - MartialArts uint16 `yaml:"martial_arts"` - Brawling uint16 `yaml:"brawling"` - Riposte uint16 `yaml:"riposte"` - Dimach uint16 `yaml:"dimach"` - Adventuring uint16 `yaml:"adventuring"` - Swimming uint16 `yaml:"swimming"` - BodyDevelopment uint16 `yaml:"body_development"` - NanoPool uint16 `yaml:"nano_pool"` + MartialArts uint16 + Brawling uint16 + Riposte uint16 + Dimach uint16 + Adventuring uint16 + Swimming uint16 + BodyDevelopment uint16 + NanoPool uint16 } type characterMeleeStats struct { - OneHandBlunt uint16 `yaml:"one_hand_blunt"` - OneHandEdged uint16 `yaml:"one_hand_edged"` - Piercing uint16 `yaml:"piercing"` - TwoHandBlunt uint16 `yaml:"two_hand_blunt"` - TwoHandEdged uint16 `yaml:"two_hand_edged"` - MeleeEnergy uint16 `yaml:"melee_energy"` - Parry uint16 `yaml:"parry"` - SneakAttack uint16 `yaml:"sneak_attack"` - MultiMelee uint16 `yaml:"multi_melee"` - FastAttack uint16 `yaml:"fast_attack"` + OneHandBlunt uint16 + OneHandEdged uint16 + Piercing uint16 + TwoHandBlunt uint16 + TwoHandEdged uint16 + MeleeEnergy uint16 + Parry uint16 + SneakAttack uint16 + MultiMelee uint16 + FastAttack uint16 } type characterMiscWeaponsStats struct { - SharpObjects uint16 `yaml:"sharp_objects"` - Grenade uint16 `yaml:"grenade"` - HeavyWeapons uint16 `yaml:"heavy_weapons"` + SharpObjects uint16 + Grenade uint16 + HeavyWeapons uint16 } type characterRangedStats struct { - Bow uint16 `yaml:"bow"` - Pistol uint16 `yaml:"pistol"` - AssaultRifle uint16 `yaml:"assault_rifle"` - SubmachineGun uint16 `yaml:"submachine_gun"` - Shotgun uint16 `yaml:"shotgun"` - Rifle uint16 `yaml:"rifle"` - RangedEnergy uint16 `yaml:"ranged_energy"` - FlingShot uint16 `yaml:"fling_shot"` - AimedShot uint16 `yaml:"aimed_shot"` - Burst uint16 `yaml:"burst"` - FullAuto uint16 `yaml:"full_auto"` - BowSpecialAttack uint16 `yaml:"bow_special_attack"` - MultiRanged uint16 `yaml:"multi_ranged"` + Bow uint16 + Pistol uint16 + AssaultRifle uint16 + SubmachineGun uint16 + Shotgun uint16 + Rifle uint16 + RangedEnergy uint16 + FlingShot uint16 + AimedShot uint16 + Burst uint16 + FullAuto uint16 + BowSpecialAttack uint16 + MultiRanged uint16 } type characterSpeedStats struct { - MeleeInitiative uint16 `yaml:"melee_initiative"` - RangedInitiative uint16 `yaml:"ranged_initiative"` - PhysicalInitiative uint16 `yaml:"physical_initiative"` - NanoInitiative uint16 `yaml:"nano_initiative"` - DodgeRanged uint16 `yaml:"dodge_ranged"` - EvadeClose uint16 `yaml:"evade_close"` - DuckExplosions uint16 `yaml:"duck_explosions"` - NanoResist uint16 `yaml:"nano_resist"` - RunSpeed uint16 `yaml:"run_speed"` + MeleeInitiative uint16 + RangedInitiative uint16 + PhysicalInitiative uint16 + NanoInitiative uint16 + DodgeRanged uint16 + EvadeClose uint16 + DuckExplosions uint16 + NanoResist uint16 + RunSpeed uint16 } type characterTradeRepairStats struct { - MechanicalEngineering uint16 `yaml:"mechanical_engineering"` - ElectricalEngineering uint16 `yaml:"electrical_engineering"` - QuantumFieldTechnology uint16 `yaml:"quantum_field_technology"` - WeaponSmithing uint16 `yaml:"weapon_smithing"` - PharmaceuticalTechnology uint16 `yaml:"pharmaceutical_technology"` - NanoProgramming uint16 `yaml:"nano_programming"` - ComputerLiteracy uint16 `yaml:"computer_literacy"` - Psychology uint16 `yaml:"psychology"` - Chemistry uint16 `yaml:"chemistry"` - Tutoring uint16 `yaml:"tutoring"` + MechanicalEngineering uint16 + ElectricalEngineering uint16 + QuantumFieldTechnology uint16 + WeaponSmithing uint16 + PharmaceuticalTechnology uint16 + NanoProgramming uint16 + ComputerLiteracy uint16 + Psychology uint16 + Chemistry uint16 + Tutoring uint16 } type characterNanoAidingStats struct { - MatterMetamorphosis uint16 `yaml:"matter_metamorphosis"` - BiologicalMetamorphosis uint16 `yaml:"biological_metamorphosis"` - PsychologicalModification uint16 `yaml:"psychological_modification"` - MatterCreation uint16 `yaml:"matter_creation"` - TimeAndSpace uint16 `yaml:"time_and_space"` - SensoryImprovement uint16 `yaml:"sensory_improvement"` - FirstAid uint16 `yaml:"first_aid"` - Treatment uint16 `yaml:"treatment"` + MatterMetamorphosis uint16 + BiologicalMetamorphosis uint16 + PsychologicalModification uint16 + MatterCreation uint16 + TimeAndSpace uint16 + SensoryImprovement uint16 + FirstAid uint16 + Treatment uint16 } type characterSpyingStats struct { - Concealment uint16 `yaml:"concealment"` - BreakingAndEntering uint16 `yaml:"breaking_and_entering"` - TrapDisarm uint16 `yaml:"trap_disarm"` - Perception uint16 `yaml:"perception"` + Concealment uint16 + BreakingAndEntering uint16 + TrapDisarm uint16 + Perception uint16 } type characterNavigationStats struct { - VehicleAir uint16 `yaml:"vehicle_air"` - VehicleGround uint16 `yaml:"vehicle_ground"` - VehicleWater uint16 `yaml:"vehicle_water"` - MapNavigation uint16 `yaml:"map_navigation"` + VehicleAir uint16 + VehicleGround uint16 + VehicleWater uint16 + MapNavigation uint16 } func defaultCharacterStats(breed uint16) characterStats { diff --git a/server/users.go b/server/users.go @@ -3,15 +3,12 @@ package main import ( "ao/server/gamedata" "fmt" - "io" "math" "math/rand/v2" "slices" "sort" "strings" "time" - - "go.yaml.in/yaml/v3" ) // User IDs are stable; each local user currently owns one character. @@ -38,29 +35,29 @@ type userData struct { } type playerProfile struct { - ID uint32 `yaml:"id"` - Name string `yaml:"name"` - Title string `yaml:"title"` - Appearance appearanceFields `yaml:"appearance"` - HeadMesh uint32 `yaml:"head_mesh"` - Height uint16 `yaml:"height"` - MonsterData uint32 `yaml:"monster_data"` - Level uint16 `yaml:"level"` - Experience uint32 `yaml:"experience"` - InsuredExperience uint32 `yaml:"insured_experience"` - Profession uint16 `yaml:"profession"` - Stats characterStats `yaml:"stats"` - Running bool `yaml:"running"` - BrowserTokenHash string `yaml:"browser_token_hash"` - ResurrectionTerminal uint32 `yaml:"resurrection_terminal"` - ImplantChangesUntil time.Time `yaml:"implant_changes_until"` + ID uint32 + Name string + Title string + Appearance appearanceFields + HeadMesh uint32 + Height uint16 + MonsterData uint32 + Level uint16 + Experience uint32 + InsuredExperience uint32 + Profession uint16 + Stats characterStats + Running bool + BrowserTokenHash string + ResurrectionTerminal uint32 + ImplantChangesUntil time.Time } type playerPosition struct { - Playfield uint32 `yaml:"playfield"` - Position [3]float32 `yaml:"position,flow"` - Rotation [4]float32 `yaml:"rotation,flow"` - ReturnDoor *doorOrigin `yaml:"return_door"` + Playfield uint32 + Position [3]float32 + Rotation [4]float32 + ReturnDoor *doorOrigin } func (character *character) userData() userData { @@ -141,19 +138,6 @@ func (data userData) validateFields() error { return nil } -func decodeUsers(reader io.Reader, value any) error { - decoder := yaml.NewDecoder(reader) - decoder.KnownFields(true) - if err := decoder.Decode(value); err != nil { - return err - } - var extra any - if err := decoder.Decode(&extra); err != io.EOF { - return fmt.Errorf("expected one YAML document") - } - return nil -} - func (server *server) loadUsers() error { if err := server.loadMissions(); err != nil { return err diff --git a/server/users_test.go b/server/users_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "encoding/hex" + "encoding/json" "fmt" "net" "net/http" @@ -12,8 +13,6 @@ import ( "strings" "testing" "time" - - "go.yaml.in/yaml/v3" ) func TestUserRowsAreSeparateAndOnlyUpdatedProfileChanges(t *testing.T) { @@ -65,7 +64,7 @@ monster_data: 0 level: 7 running: true ` - edition := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {data}}.Encode())) + edition := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(playerFixtureForm(data).Encode())) edition.Header.Set("Content-Type", "application/x-www-form-urlencoded") edited := httptest.NewRecorder() teleport := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=800")) @@ -124,12 +123,8 @@ func TestUserTitleEditingRespectsClientTextLimit(t *testing.T) { before := world.characters[1].title edited := world.characters[1].editor() edited.Title = scenario.title - data, err := yaml.Marshal(edited) - if err != nil { - t.Fatal(err) - } - response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(data)}}) + response := postControlForm(world, "/admin/players/1", playerEditorForm(t, edited)) restarted := newServerForTest(t) expected, status := before, http.StatusBadRequest @@ -227,7 +222,7 @@ func TestUserEditorRejectsUnknownFieldsWithoutChangingSavedData(t *testing.T) { if err != nil { t.Fatal(err) } - request := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {"id: 1\nname: Changed\nlevle: 7\n"}}.Encode())) + request := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(playerFixtureForm("id: 1\nname: Changed\nlevle: 7\n").Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") response := httptest.NewRecorder() @@ -284,11 +279,11 @@ func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) { request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) data := "id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nmonster_data: 0\nlevel: 7\n" - request = httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {data}}.Encode())) + request = httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(playerFixtureForm(data).Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") world.editUser(httptest.NewRecorder(), request) - request = httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {"playfield: 950\nposition: [53, 14, 60]\nrotation: [0, 0, 0, 1]\n"}}.Encode())) + request = httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(playerFixtureForm("playfield: 950\nposition: [53, 14, 60]\nrotation: [0, 0, 0, 1]\n").Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") world.editUser(httptest.NewRecorder(), request) @@ -408,12 +403,12 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) { if err != nil { t.Fatal(err) } - positionYAML, err := readTestPlayerRecord(1, "position") + positionJSON, err := readTestPlayerRecord(1, "position") if err != nil { t.Fatal(err) } var position playerPosition - if err := yaml.Unmarshal(positionYAML, &position); err != nil { + if err := json.Unmarshal(positionJSON, &position); err != nil { t.Fatal(err) } @@ -423,7 +418,7 @@ func TestPositionUpdatesDoNotRewritePlayerProfile(t *testing.T) { if !bytes.Equal(before, after) || !bytes.Equal(profile, savedProfile) { t.Fatal("a position update rewrote the stable player profile") } - if bytes.Contains(profile, []byte("position:")) || bytes.Contains(profile, []byte("rotation:")) || bytes.Contains(profile, []byte("playfield:")) { + if bytes.Contains(profile, []byte(`"Position":`)) || bytes.Contains(profile, []byte(`"Rotation":`)) || bytes.Contains(profile, []byte(`"Playfield":`)) { t.Fatalf("location data remains in the stable player profile: %s", profile) } if position.Playfield != 705 || position.Position != [3]float32{960, 16.375, 510} || position.Rotation != [4]float32{0, 0, 0, 1} || restarted.characters[1].position != [3]float32{960, 16.375, 510} { diff --git a/server/zone_http_test.go b/server/zone_http_test.go @@ -1,17 +1,12 @@ package main import ( - "html" "io" "net/http" "net/http/httptest" - "net/url" - "regexp" "strings" "testing" "time" - - "go.yaml.in/yaml/v3" ) func TestRoutedPlayerAdministrationEditsAndTransfersThroughOwners(t *testing.T) { @@ -23,21 +18,11 @@ func TestRoutedPlayerAdministrationEditsAndTransfersThroughOwners(t *testing.T) if page.Code != http.StatusOK { t.Fatal(page.Code, page.Body.String()) } - match := regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindStringSubmatch(page.Body.String()) - if len(match) != 2 { - t.Fatal("player editor was not rendered") - } - var editor characterEditor - if err := decodeUsers(strings.NewReader(html.UnescapeString(match[1])), &editor); err != nil { - t.Fatal(err) - } - editor.Name, editor.Inventory.Credits = "Edited", 913 - document, err := yaml.Marshal(editor) - if err != nil { - t.Fatal(err) - } + fields := playerPageValues(t, page.Body.String()) + fields.Set("name", "Edited") + fields.Set("inventory.credits", "913") - edited := adminRequest(handler, "POST", "/admin/players/1", url.Values{"data": {string(document)}}.Encode(), nil) + edited := adminRequest(handler, "POST", "/admin/players/1", fields.Encode(), nil) moved := adminRequest(handler, "POST", "/admin/players/1/teleport", "playfield=705", nil) if edited.Code != http.StatusSeeOther || moved.Code != http.StatusSeeOther { diff --git a/server/zoning.go b/server/zoning.go @@ -11,8 +11,8 @@ import ( ) type doorOrigin struct { - Playfield uint32 `yaml:"playfield"` - Door uint32 `yaml:"door"` + Playfield uint32 + Door uint32 } type zoneDoor struct { @@ -60,7 +60,7 @@ func readZoneLinks() (map[string]map[uint32]zoneLinks, error) { return nil, err } var links map[string]map[uint32]zoneLinks - if err := decodeUsers(bytes.NewReader(contents), &links); err != nil { + if err := decodeYAML(bytes.NewReader(contents), &links); err != nil { return nil, fmt.Errorf("zone links: %w", err) } return links, nil diff --git a/tools/client/test_admin.mjs b/tools/client/test_admin.mjs @@ -68,6 +68,24 @@ try { assert(page.url().endsWith('/admin/players/1')); assert.equal(await page.locator('canvas').count(), 0); assert((await page.getByRole('heading', {name: 'Character data'}).boundingBox()).y < 900); + // Save ordinary controls, then verify the returned form at desktop and phone widths. + assert.equal(await page.locator('textarea, .player-editor details').count(), 0); + assert.equal(await page.getByRole('combobox', {name: 'Profession', exact: true}).locator('option:checked').textContent(), 'Soldier (1)'); + assert.equal(await page.getByRole('combobox', {name: 'Breed', exact: true}).locator('option:checked').textContent(), 'Solitus (1)'); + await page.getByLabel('Title', {exact: true}).fill('Form & field check'); + await page.getByRole('button', {name: 'Save', exact: true}).click(); + assert.equal(await page.getByLabel('Title', {exact: true}).inputValue(), 'Form & field check'); + await page.getByRole('combobox', {name: 'Profession', exact: true}).selectOption('1'); + await page.getByRole('combobox', {name: 'Breed', exact: true}).selectOption('1'); + await page.getByLabel('Rifle', {exact: true}).fill('42'); + await page.getByRole('button', {name: 'Save', exact: true}).click(); + assert.equal(await page.getByLabel('Rifle', {exact: true}).inputValue(), '42'); + await page.screenshot({path: output + '/player-form.png', fullPage: true}); + await page.setViewportSize({width: 390, height: 844}); + await page.getByRole('heading', {name: 'Character data'}).scrollIntoViewIfNeeded(); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + await page.screenshot({path: output + '/mobile-player-form.png'}); + await page.setViewportSize({width: 1280, height: 900}); await page.getByRole('link', {name: 'Teleport', exact: true}).click(); assert(page.url().endsWith('/admin/players/1/teleport')); await page.waitForFunction(() => document.querySelector('[data-map-status]').textContent.includes('connected players')); @@ -173,7 +191,7 @@ try { response = await context.request.post(url + 'admin/items/' + itemId, {form: {action: 'assign', owner: '1', destination: '0:93'}}); assert(response.ok(), await response.text()); await game.wait('live inventory addition at selected slot', state => game.local(state).inventory.some(item => item.id === itemId && item.slot === 77)); - response = await context.request.post(url + 'admin/players/1', {form: {data: 'inventory:\n slots: {inventory_slot_30: null}\n'}}); + response = await context.request.post(url + 'admin/players/1', {form: {'inventory.slots.inventory_slot_30': ''}}); assert(response.ok(), await response.text()); await game.wait('live inventory removal', state => !game.local(state).inventory.some(item => item.id === itemId)); assert.equal(game.worldStream, originalStream); diff --git a/tools/client/test_pending_edit.mjs b/tools/client/test_pending_edit.mjs @@ -39,7 +39,7 @@ try { await game.save(output + '/pending'); const stream = game.worldStream, frame = game.state.frame; const edited = await page.request.post(url + '/test-edit/1', { - form: {data: 'name: Pending Edit Check\n'}, maxRedirects: 0}); + form: {name: 'Pending Edit Check'}, maxRedirects: 0}); assert.equal(edited.status(), 303); await game.wait('new world stream after live edit', () => game.worldStream !== stream); await game.ready();