aorecomp

Anarchy Online classic in the browser

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


commit 1c019fa11882128f361a5b2eb7b3ff6c52e553ee
parent 73848d93ab4abcabd25f2ee30a8eaa342ab14271
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 06:29:58 +0000

Refine admin maps and player routes and log client addresses

Diffstat:
MDEVELOPERS.md | 5+++--
Mdocs/admin.md | 20+++++++++++++-------
Mdocs/combat-regeneration.md | 2+-
Mdocs/inventory.md | 2+-
Mserver/admin_fixture_test.go | 4++--
Mserver/admin_live_test.go | 6+++---
Mserver/admin_map.go | 27++++++++++++++++++---------
Mserver/admin_pages.go | 8++++----
Mserver/admin_player_password.go | 4++--
Mserver/admin_player_password_test.go | 4++--
Mserver/admin_test.go | 22+++++++++++++++-------
Mserver/appearance_test.go | 14+++++++-------
Mserver/assets/map.js | 17+++++++++--------
Mserver/bank_storage_test.go | 18+++++++++---------
Mserver/browser_socket.go | 18++++++++++++++++--
Mserver/browser_socket_test.go | 5+++++
Mserver/browser_stream.go | 7++++---
Mserver/browser_stream_test.go | 6++++++
Mserver/buddies_test.go | 2+-
Mserver/chat.go | 2+-
Mserver/checkpoint_test.go | 2+-
Mserver/combat_test.go | 4++++
Mserver/control.go | 9++++-----
Mserver/control_containers_test.go | 4++--
Mserver/control_data_test.go | 48++++++++++++++++++++++++------------------------
Mserver/control_equipment_slots_test.go | 6+++---
Mserver/control_inventory_test.go | 24++++++++++++------------
Mserver/control_test.go | 25+++++++++++++++++--------
Mserver/database_test.go | 8++++----
Mserver/http.go | 13+++++++------
Mserver/insurance_experience_test.go | 2+-
Mserver/inventory_write_test.go | 12++++++------
Mserver/item_pages.go | 4++--
Mserver/item_store_test.go | 14+++++++-------
Mserver/logging_test.go | 4++--
Mserver/main.go | 4++--
Mserver/main_test.go | 6+++---
Mserver/map_test.js | 12+++++++++++-
Mserver/maps.go | 33++++++++++++++++++++++++++++++---
Mserver/maps_test.go | 4++--
Mserver/progression_test.go | 20++++++++++----------
Mserver/shop_control_edit_test.go | 4++--
Mserver/target_protocol_test.go | 2+-
Mserver/users_test.go | 41++++++++++++++++++++++-------------------
Mtools/client/sweep_browser.py | 2+-
Mtools/client/sweep_playfields.py | 2+-
Mtools/client/test_admin.mjs | 32++++++++++++++++++++++++++++----
Mtools/client/verify_client_1491.py | 2+-
Mtools/client/verify_game.py | 2+-
49 files changed, 333 insertions(+), 205 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -21,8 +21,9 @@ run from an empty directory; static resources are served directly from the binary. Mutable world state is stored in `data/world.sqlite` and certificates in `data/https/`. Server logs go to `logs/server.log` and profiles to `logs/profiles/`. By default, the terminal and log file contain startup/shutdown, player connections -and errors. Pass `-trace` when debugging to also write packet, movement and HTTP -request traces to `logs/server.log`. +with peer IP and port, and errors. Browser connections retain the HTTP peer address; +when proxied, this is the proxy address. Pass `-trace` when debugging to also write +packet, movement and HTTP request traces to `logs/server.log`. Browser profiling is also off by default; open the game with `?profile=1` to collect and upload a diagnostic profile. Back up `data/` when moving servers. Paths are relative to the working directory. diff --git a/docs/admin.md b/docs/admin.md @@ -23,7 +23,8 @@ including prepared queries and console queries. SQLite's internal trigger work and transaction-control statements are not counted separately. Counts include the admin interface's own authentication queries. -Players provides existing character editors and a separate Change password page; +Players at `/admin/players` provides character editors and separate Teleport and +Change password pages; players create accounts through the game. Items retains catalog creation, ownership, assignment and instance editing. Same-zone map teleports and ordinary carried-item edits update connected players @@ -35,11 +36,16 @@ Password changes preserve the current game session and take effect on the next l The map fits the viewport and supports dragging, wheel/buttons, and two-finger pinch/pan. Offline players default off; the selected character remains visible -in its own editor. NPCs default off; warp zones default on. Both layers start at 0.3 -pixels per world unit and require a viewport no larger than 6000 units in either -direction. The server filters current live positions and returns at most 500 -NPCs and 500 warps per request. A limit message asks the operator to zoom in. -Hidden browser pages do not poll. +on its teleport page. NPCs default off and appear from 1.2 pixels per world unit +with a viewport no larger than 2000 units in either direction. Warp zones default +on, starting at 0.3 pixels per world unit with a maximum viewport span of 6000. +The server filters current live positions and returns at most 5000 NPCs and 5000 +warps per request. Bounded selections have stable ordering across refreshes. A +limit message asks the operator to zoom in. Hidden browser pages do not poll. + +The main map links player markers to their profiles. Only the separate +`/admin/players/<id>/teleport` page selects destinations; its action and map +controls sit above the canvas, with nothing beneath it. Warp markers use the target client's door and zone-border links. Tapping a marker shows its destination; closer zoom adds destination labels and lines @@ -105,6 +111,6 @@ AO_GAME_TEST=1 go test ./server -run '^TestAdminBrowser$' -count=1 -timeout=7m - The browser check owns and closes its temporary server and Chromium instance. It covers setup, login/logout and styled errors, admin and player password forms, -navigation, SQL writes and CSV, mobile map gestures, same-zone teleporting, live +navigation, SQL writes and CSV, mobile map gestures and teleport layout, same-zone teleporting, live carried-item additions/removals, weather delivery and profiling opt-in in the actual WASM client through `GameTest`. diff --git a/docs/combat-regeneration.md b/docs/combat-regeneration.md @@ -8,7 +8,7 @@ server's scheduler is not established by those rules. ## Character data -The character editor at `/admin/users/<id>` shows one YAML document +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, 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/users/<owner>` shows one editable YAML document +The character page at `/admin/players/<owner>` shows one editable YAML document 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/server/admin_fixture_test.go b/server/admin_fixture_test.go @@ -10,7 +10,7 @@ import ( // State-transition tests exercise handlers beneath the authentication boundary. // Admin authentication tests use httpHandler directly. func serveAdminTestRequest(world *server, w http.ResponseWriter, r *http.Request) { - if r.Method == "POST" && r.URL.Path == "/admin/users" { + if r.Method == "POST" && r.URL.Path == "/admin/players" { world.createUser(w, r) return } @@ -60,5 +60,5 @@ func (server *server) createUser(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d", server.baseURL, player.id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/players/%d", server.baseURL, player.id), http.StatusSeeOther) } 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/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: null}\n"}}) + removed := postControlForm(world, "/admin/players/1", url.Values{"data": {"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) @@ -70,7 +70,7 @@ func TestAdminSameZoneTeleportPreservesConnectionAndNotifiesObservers(t *testing player.movement = heldPlayerMovement(player, 1, time.Now()) rotation := player.rotation - response := postControlForm(world, "/admin/teleport/1", url.Values{"playfield": {"950"}, "x": {"52"}, "z": {"56"}}) + response := postControlForm(world, "/admin/players/1/teleport", url.Values{"playfield": {"950"}, "x": {"52"}, "z": {"56"}}) restarted := newTestInventoryServer(t) if response.Code != http.StatusSeeOther || world.clients[1] != client || !client.ready || !player.movement.active() || player.position != [3]float32{52, 26.5, 56} || restarted.characters[1].position != player.position { @@ -112,7 +112,7 @@ func TestAdminRejectedSameZoneTeleportLeavesSessionUntouched(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/teleport/1", url.Values{"playfield": {"950"}, "x": {"52"}, "z": {"56"}}) + response := postControlForm(world, "/admin/players/1/teleport", url.Values{"playfield": {"950"}, "x": {"52"}, "z": {"56"}}) if response.Code != http.StatusInternalServerError || player.position != before || world.clients[1] != client || !client.ready || len(connection.packets) != 0 { t.Fatal("rejected teleport changed live state", response.Code, response.Body) diff --git a/server/admin_map.go b/server/admin_map.go @@ -3,8 +3,10 @@ package main import ( "ao/server/gamedata" "encoding/json" + "maps" "math" "net/http" + "slices" "strconv" ) @@ -63,8 +65,9 @@ func (server *server) mapEntities(w http.ResponseWriter, r *http.Request) { Limited bool `json:"limited"` }{NPCs: []mapMarker{}, Warps: []mapMarker{}} server.mutex.Lock() - if r.URL.Query().Get("npcs") == "1" && bounds[2]-bounds[0] <= 6000 && bounds[3]-bounds[1] <= 6000 { - for _, character := range server.characters { + if r.URL.Query().Get("npcs") == "1" && bounds[2]-bounds[0] <= 2000 && bounds[3]-bounds[1] <= 2000 { + var visibleIDs []uint32 + for id, character := range server.characters { if !character.npc || character.health == 0 { continue } @@ -72,21 +75,27 @@ func (server *server) mapEntities(w http.ResponseWriter, r *http.Request) { if !visible(p) { continue } - if len(result.NPCs) == 500 { - result.Limited = true - break - } - result.NPCs = append(result.NPCs, mapMarker{Name: character.name, Point: *p}) + visibleIDs = append(visibleIDs, id) + } + slices.Sort(visibleIDs) + if len(visibleIDs) > 5000 { + result.Limited = true + visibleIDs = visibleIDs[:5000] + } + for _, id := range visibleIDs { + character := server.characters[id] + result.NPCs = append(result.NPCs, mapMarker{Name: character.name, Point: *point(character.playfield, character.position)}) } } if r.URL.Query().Get("warps") == "1" && bounds[2]-bounds[0] <= 6000 && bounds[3]-bounds[1] <= 6000 { - for zone, links := range server.zoneLinks["target"] { + for _, zone := range slices.Sorted(maps.Keys(server.zoneLinks["target"])) { + links := server.zoneLinks["target"][zone] add := func(name string, position [3]float32, destination uint32, arrival *[3]float32) { p := point(zone, position) if !visible(p) { return } - if len(result.Warps) == 500 { + if len(result.Warps) == 5000 { result.Limited = true return } diff --git a/server/admin_pages.go b/server/admin_pages.go @@ -17,11 +17,11 @@ import ( func (server *server) adminPageStart(w http.ResponseWriter, title, section string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprintf(w, `<!doctype html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><base href='%s'><title>%s - AO Admin</title><style> - *{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182634;font:15px system-ui,sans-serif}a{color:#175d8d;text-underline-offset:3px}header{background:#142c3e;color:white;padding:12px 24px;display:flex;align-items:center;gap:24px;flex-wrap:wrap}header strong{font-size:18px}nav{display:flex;gap:6px;flex-wrap:wrap}nav a{color:#d7e4ed;text-decoration:none;padding:10px 14px;border-radius:6px}nav a[aria-current=page],nav a:hover{background:#2b4d65;color:white}header form{margin-left:auto}main{padding:24px;max-width:1600px;margin:auto;overflow-x:auto}h1{font-size:26px;margin:0 0 20px}h2{font-size:19px;margin-top:26px}section,.cards>div{background:white;border:1px solid #d9e1e7;border-radius:8px;padding:20px;margin-bottom:20px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}.cards strong{display:block;font-size:28px;margin-top:8px}label{display:inline-flex;gap:8px;align-items:center;flex-wrap:wrap;margin:5px 10px 5px 0}input,select,textarea,button{font:inherit;border:1px solid #a7b8c5;border-radius:5px;padding:10px;max-width:100%%}input[type=checkbox]{width:20px;height:20px}button{background:#175d8d;color:white;border-color:#175d8d;cursor:pointer;min-height:44px}button:disabled{opacity:.5;cursor:default}input:focus-visible,select:focus-visible,textarea:focus-visible,button:focus-visible,a:focus-visible{outline:3px solid #e0a22a;outline-offset:2px}textarea{display:block;width:100%%;font:14px ui-monospace,monospace;line-height:1.5;background:white}table{border-collapse:collapse;background:white;width:100%%;margin:16px 0}th,td{text-align:left;padding:10px 12px;border-bottom:1px solid #dce3e9;vertical-align:top}th{background:#e7edf2;position:sticky;top:0}tr:hover td{background:#f0f6fa}.login{max-width:430px;margin:8vh auto}.login label{display:flex;align-items:stretch;flex-direction:column;margin:16px 0}.login input{width:100%%}.muted{color:#526777}.error{color:#a02121;white-space:pre-wrap}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas[data-map-canvas]{width:100%%;height:calc(100dvh - 310px);min-height:320px;display:block;touch-action:none;border-radius:8px}body:has(.map-page){height:100dvh;display:flex;flex-direction:column}body:has(.map-page) header{flex-shrink:0}body:has(.map-page) main{flex:1;min-height:0;margin:0;width:100%%;max-width:none;display:flex;flex-direction:column}.map-page,.map-page [data-world-map]{flex:1;min-height:0;display:flex;flex-direction:column}.map-page h2{margin:0 0 10px}.map-page p{margin:6px 0}.map-page canvas{flex:1;min-height:220px;height:0}details{margin:16px 0}summary{cursor:pointer;padding:10px 0}@media(max-width:600px){header{padding:12px;gap:10px}nav a{padding:10px}main{padding:14px}header form{margin-left:0}th,td{padding:8px}canvas[data-map-canvas]{height:60dvh}} + *{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182634;font:15px system-ui,sans-serif}a{color:#175d8d;text-underline-offset:3px}header{background:#142c3e;color:white;padding:12px 24px;display:flex;align-items:center;gap:24px;flex-wrap:wrap}header strong{font-size:18px}nav{display:flex;gap:6px;flex-wrap:wrap}nav a{color:#d7e4ed;text-decoration:none;padding:10px 14px;border-radius:6px}nav a[aria-current=page],nav a:hover{background:#2b4d65;color:white}header form{margin-left:auto}main{padding:24px;max-width:1600px;margin:auto;overflow-x:auto}h1{font-size:26px;margin:0 0 20px}h2{font-size:19px;margin-top:26px}section,.cards>div{background:white;border:1px solid #d9e1e7;border-radius:8px;padding:20px;margin-bottom:20px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}.cards strong{display:block;font-size:28px;margin-top:8px}label{display:inline-flex;gap:8px;align-items:center;flex-wrap:wrap;margin:5px 10px 5px 0}input,select,textarea,button{font:inherit;border:1px solid #a7b8c5;border-radius:5px;padding:10px;max-width:100%%}input[type=checkbox]{width:20px;height:20px}button{background:#175d8d;color:white;border-color:#175d8d;cursor:pointer;min-height:44px}button:disabled{opacity:.5;cursor:default}input:focus-visible,select:focus-visible,textarea:focus-visible,button:focus-visible,a:focus-visible{outline:3px solid #e0a22a;outline-offset:2px}textarea{display:block;width:100%%;font:14px ui-monospace,monospace;line-height:1.5;background:white}table{border-collapse:collapse;background:white;width:100%%;margin:16px 0}th,td{text-align:left;padding:10px 12px;border-bottom:1px solid #dce3e9;vertical-align:top}th{background:#e7edf2;position:sticky;top:0}tr:hover td{background:#f0f6fa}.login{max-width:430px;margin:8vh auto}.login label{display:flex;align-items:stretch;flex-direction:column;margin:16px 0}.login input{width:100%%}.muted{color:#526777}.error{color:#a02121;white-space:pre-wrap}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas[data-map-canvas]{width:100%%;height:calc(100dvh - 310px);min-height:320px;display:block;touch-action:none;border-radius:8px}body:has(.map-page){height:100dvh;display:flex;flex-direction:column}body:has(.map-page) header{flex-shrink:0}body:has(.map-page) main{flex:1;min-height:0;margin:0;width:100%%;max-width:none;display:flex;flex-direction:column}.map-page,.map-page [data-world-map]{flex:1;min-height:0;display:flex;flex-direction:column}.map-page h1{font-size:22px;margin:0}.map-page [hidden]{display:none}.map-page form{margin-bottom:8px}.map-page p{margin:6px 0}.map-page canvas{flex:1;min-height:200px;height:0}details{margin:16px 0}summary{cursor:pointer;padding:10px 0}@media(max-width:600px){header{padding:12px;gap:10px}nav a{padding:10px}main{padding:14px}header form{margin-left:0}th,td{padding:8px}canvas[data-map-canvas]{height:60dvh}} </style></head><body>`, html.EscapeString(server.baseURL), html.EscapeString(title)) if section != "" { fmt.Fprint(w, "<header><strong>AO Admin</strong><nav aria-label='Main navigation'>") - for _, item := range []struct{ name, path string }{{"General", "admin"}, {"Map", "admin/map"}, {"Players", "admin/users"}, {"Items", "admin/items"}, {"SQL", "admin/sql"}, {"Admins", "admin/admins"}} { + for _, item := range []struct{ name, path string }{{"General", "admin"}, {"Map", "admin/map"}, {"Players", "admin/players"}, {"Items", "admin/items"}, {"SQL", "admin/sql"}, {"Admins", "admin/admins"}} { current := "" if item.name == section { current = " aria-current='page'" @@ -99,14 +99,14 @@ func (server *server) usersPage(w http.ResponseWriter, r *http.Request) { if connected[player.ID] { status = "Connected" } - fmt.Fprintf(w, "<tr><td>%d</td><td><a href='admin/users/%d'>%s</a></td><td>%s</td><td>%s (%d)</td></tr>", player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield) + fmt.Fprintf(w, "<tr><td>%d</td><td><a href='admin/players/%d'>%s</a></td><td>%s</td><td>%s (%d)</td></tr>", player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield) } fmt.Fprint(w, "</table></main></body></html>") } func (server *server) mapPage(w http.ResponseWriter, r *http.Request) { server.adminPageStart(w, "Map", "Map") - fmt.Fprint(w, "<div class='map-page'>") + fmt.Fprint(w, "<div class='map-page'><h1>Map</h1>") controlMap(w, 0) fmt.Fprint(w, "</div></main></body></html>") } diff --git a/server/admin_player_password.go b/server/admin_player_password.go @@ -45,7 +45,7 @@ func (server *server) changePlayerPassword(w http.ResponseWriter, r *http.Reques http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d?password=saved", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/players/%d?password=saved", server.baseURL, id), http.StatusSeeOther) return } } @@ -58,5 +58,5 @@ func (server *server) changePlayerPassword(w http.ResponseWriter, r *http.Reques if message != "" { fmt.Fprintf(w, "<p class='error' role='alert'>%s</p>", message) } - fmt.Fprintf(w, "<form method='post' action='admin/users/%d/password'><label>New password<input name='password' type='password' autocomplete='new-password' maxlength='1024'></label><button>Save password</button> <a href='admin/users/%d'>Cancel</a></form></section></main></body></html>", id, id) + fmt.Fprintf(w, "<form method='post' action='admin/players/%d/password'><label>New password<input name='password' type='password' autocomplete='new-password' maxlength='1024'></label><button>Save password</button> <a href='admin/players/%d'>Cancel</a></form></section></main></body></html>", id, id) } diff --git a/server/admin_player_password_test.go b/server/admin_player_password_test.go @@ -20,7 +20,7 @@ func TestAdminChangesPlayerPasswordWithoutDisconnecting(t *testing.T) { handler := world.httpHandler() setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=", nil) cookie := setup.Result().Cookies()[0] - path := fmt.Sprintf("/admin/users/%d/password", client.id) + path := fmt.Sprintf("/admin/players/%d/password", client.id) page := adminRequest(handler, "GET", path, "", cookie) unauthorized := adminRequest(handler, "POST", path, "password=wrong", nil) changed := adminRequest(handler, "POST", path, "password=", cookie) @@ -32,7 +32,7 @@ func TestAdminChangesPlayerPasswordWithoutDisconnecting(t *testing.T) { if page.Code != 200 || !strings.Contains(page.Body.String(), "Alice") || !strings.Contains(page.Body.String(), "New password") || strings.Contains(page.Body.String(), "can be empty") { t.Fatal("password page", page.Code, page.Body) } - if unauthorized.Code != http.StatusUnauthorized || changed.Code != http.StatusSeeOther || changed.Header().Get("Location") != "/admin/users/1?password=saved" { + if unauthorized.Code != http.StatusUnauthorized || changed.Code != http.StatusSeeOther || changed.Header().Get("Location") != "/admin/players/1?password=saved" { t.Fatal(unauthorized.Code, changed.Code, changed.Body) } if len(salt) != 16 || !bytes.Equal(hash, world.browserPassword("", salt)) || world.clients[1] != client || !client.ready || len(connection.packets) != 0 { diff --git a/server/admin_test.go b/server/admin_test.go @@ -154,13 +154,13 @@ func TestAdminBoundaryAndCrossOriginWrites(t *testing.T) { created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) cookie := created.Result().Cookies()[0] - for _, path := range []string{"/admin", "/admin/", "/admin/admins", "/admin/admins/new", "/admin/admins/1", "/admin/users", "/admin/users/1", "/admin/items", "/admin/items/catalog", "/admin/items/1", "/admin/sql", "/admin/stats", "/admin/map", "/admin/map-players", "/admin/map-entities", "/admin/map-assets/manifest.json", "/admin/control-map.js"} { + for _, path := range []string{"/admin", "/admin/", "/admin/admins", "/admin/admins/new", "/admin/admins/1", "/admin/players", "/admin/players/1", "/admin/players/1/teleport", "/admin/items", "/admin/items/catalog", "/admin/items/1", "/admin/sql", "/admin/stats", "/admin/map", "/admin/map-players", "/admin/map-entities", "/admin/map-assets/manifest.json", "/admin/control-map.js"} { response := adminRequest(handler, "GET", path, "", nil) if response.Code != 303 || response.Header().Get("Location") != "/admin/login" { t.Fatalf("unprotected read: %s %d", path, response.Code) } } - for _, path := range []string{"/admin/time", "/admin/weather", "/admin/admins/new", "/admin/admins/1", "/admin/users/1", "/admin/items", "/admin/items/1", "/admin/teleport/1", "/admin/sql", "/admin/logout"} { + for _, path := range []string{"/admin/time", "/admin/weather", "/admin/admins/new", "/admin/admins/1", "/admin/players/1", "/admin/items", "/admin/items/1", "/admin/players/1/teleport", "/admin/sql", "/admin/logout"} { response := adminRequest(handler, "POST", path, "", nil) if response.Code != 401 { t.Fatalf("unprotected write: %s %d", path, response.Code) @@ -175,7 +175,7 @@ func TestAdminBoundaryAndCrossOriginWrites(t *testing.T) { t.Fatalf("cross-origin write: %s %d", path, response.Code) } } - removed := adminRequest(handler, "POST", "/admin/users", "name=Unexpected", cookie) + removed := adminRequest(handler, "POST", "/admin/players", "name=Unexpected", cookie) old := adminRequest(handler, "GET", "/control/items", "", cookie) var count int if err := world.db.QueryRow("SELECT count(*) FROM admin_users").Scan(&count); err != nil { @@ -254,10 +254,10 @@ func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { world.characters[1] = &character{id: 1, name: "Offline", playfield: 950} world.characters[2] = &character{id: 2, name: "Online", playfield: 950} world.clients[2] = &worldClient{ready: true} - for id := uint32(1000000); id < 1000600; id++ { - world.characters[id] = &character{id: id, npc: true, health: 100, playfield: 950, name: "NPC", position: [3]float32{10, 0, 10}} + for id := uint32(1000000); id < 1005001; id++ { + world.characters[id] = &character{id: id, npc: true, health: 100, playfield: 950, name: fmt.Sprintf("NPC %d", id), position: [3]float32{10, 0, 10}} } - world.characters[1000600] = &character{id: 1000600, npc: true, health: 100, playfield: 950, name: "Outside", position: [3]float32{300, 0, 300}} + world.characters[1005001] = &character{id: 1005001, npc: true, health: 100, playfield: 950, name: "Outside", position: [3]float32{300, 0, 300}} world.zoneLinks = map[string]map[uint32]zoneLinks{"target": {950: {Doors: []zoneDoor{{Position: [3]float32{20, 0, 20}, Destination: 800, Arrival: &zoneArrival{Position: [3]float32{40, 0, 40}}}}}}} handler := world.httpHandler() created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) @@ -279,9 +279,17 @@ func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { if strings.Contains(players.Body.String(), "Offline") || !strings.Contains(offline.Body.String(), "Offline") { t.Fatal("offline filter") } - if len(result.NPCs) != 500 || len(result.Warps) != 1 || !result.Limited || !strings.Contains(result.Warps[0].Destination, "800") || strings.Contains(entities.Body.String(), "Outside") { + if len(result.NPCs) != 5000 || len(result.Warps) != 1 || !result.Limited || !strings.Contains(result.Warps[0].Destination, "800") || strings.Contains(entities.Body.String(), "Outside") { t.Fatal("entity bounds", len(result.NPCs), len(result.Warps), result.Limited) } + repeated := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=0&bottom=0&right=100&top=100&npcs=1&warps=1", "", cookie) + if repeated.Body.String() != entities.Body.String() || result.NPCs[0].Name != "NPC 1000000" || result.NPCs[4999].Name != "NPC 1004999" { + t.Fatal("bounded NPC selection must stay stable across refreshes") + } + distant := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=0&bottom=0&right=3000&top=3000&npcs=1&warps=1", "", cookie) + if !strings.Contains(distant.Body.String(), `"npcs":[]`) || strings.Contains(distant.Body.String(), `"warps":[]`) { + t.Fatal("NPCs require a closer viewport than warp zones") + } if !strings.Contains(wide.Body.String(), `"npcs":[]`) || !strings.Contains(wide.Body.String(), `"warps":[]`) || invalid.Code != 400 { t.Fatal("unbounded entity request accepted") } diff --git a/server/appearance_test.go b/server/appearance_test.go @@ -91,9 +91,9 @@ func TestPlayerHeightReachesSpawnStatsAndPhysicalExtent(t *testing.T) { func TestPlayerAppearancePersistsThroughControlEditAndRestart(t *testing.T) { world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Visitor"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Visitor"}}) - response := postControlForm(world, "/admin/users/1", url.Values{"data": { + response := postControlForm(world, "/admin/players/1", url.Values{"data": { "head_mesh: 40132\nheight: 110\nappearance: {race: 1, breed: 4, sex: 1, fatness: 2}\n", }}) restored := newTestInventoryServer(t).characters[1] @@ -113,12 +113,12 @@ func TestPlayerAppearanceFailedControlSaveLeavesMemoryAndDatabaseUnchanged(t *te } { t.Run(failure.name, func(t *testing.T) { world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Visitor"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Visitor"}}) if _, err := world.db.Exec(failure.statement); err != nil { t.Fatal(err) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"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 +128,7 @@ func TestPlayerAppearanceFailedControlSaveLeavesMemoryAndDatabaseUnchanged(t *te t.Fatal(err) } - response = postControlForm(world, "/admin/users/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) + response = postControlForm(world, "/admin/players/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) restored = newTestInventoryServer(t).characters[1] if response.Code != 303 || restored.headMesh != 40680 || restored.height != 110 { @@ -142,9 +142,9 @@ func TestPlayerAppearanceRejectsUnrepresentableProfileFields(t *testing.T) { for _, data := range []string{"height: 65536", "height: -1", "head_mesh: 4294967296", "head_mesh: -1"} { t.Run(data, func(t *testing.T) { world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Visitor"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Visitor"}}) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {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/assets/map.js b/server/assets/map.js @@ -74,7 +74,6 @@ class AOMap { this.canvas.addEventListener("pointercancel", event => this.pointerEnd(event, true)); for (const toggle of this.element.querySelectorAll("input[type=checkbox]")) { toggle.addEventListener("change", () => { - this.entities = {npcs: [], warps: []}; this.renderSoon(); }); } @@ -124,13 +123,14 @@ class AOMap { if (clicked) this.pick(...this.pointer(event)); } - detailVisible() { - return this.scale >= 0.3 && this.width / this.scale <= 6000 && this.height / this.scale <= 6000; + detailVisible(kind) { + const span = kind === "npcs" ? 2000 : 6000; + return this.scale >= (kind === "npcs" ? 1.2 : 0.3) && this.width / this.scale <= span && this.height / this.scale <= span; } entityQuery() { const [left, top] = this.toWorld(0, 0), [right, bottom] = this.toWorld(this.width, this.height); - const npcs = this.element.querySelector("[data-map-npcs]").checked && this.detailVisible(); + const npcs = this.element.querySelector("[data-map-npcs]").checked && this.detailVisible("npcs"); return new URLSearchParams({view: this.view.value, left, bottom, right, top, npcs: npcs ? "1" : "0", warps: this.element.querySelector("[data-map-warps]").checked && this.detailVisible() ? "1" : "0"}).toString(); } @@ -374,10 +374,11 @@ class AOMap { if (!point) continue; const screen = this.toScreen(...point); if (Math.hypot(x - screen[0], y - screen[1]) < 9 && player.id !== this.character) { - window.location.href = new URL(`admin/users/${player.id}`, document.baseURI); + window.location.href = new URL(`admin/players/${player.id}`, document.baseURI); return; } } + if (!this.form) return; const point = this.toWorld(x, y); let zone; if (this.view.value === "world") { @@ -390,7 +391,7 @@ class AOMap { this.form.querySelector("[data-map-zone-choice]").hidden = candidates.length < 2; } if (candidates.length !== 1) { - this.location.textContent = candidates.length ? `Overlapping playfields: ${candidates.map(zone => zone.name).join(", ")}.${this.form ? " Choose the destination playfield below." : ""}` : "No mapped outdoor playfield at this location."; + this.location.textContent = candidates.length ? `Overlapping playfields: ${candidates.map(zone => zone.name).join(", ")}.${this.form ? " Choose the destination playfield." : ""}` : "No mapped outdoor playfield at this location."; if (this.form) this.form.querySelector("button").disabled = true; this.pendingPoint = point; this.selection = null; @@ -471,7 +472,7 @@ class AOMap { // Show detailed markers at useful zoom; warp destinations are labelled on tap. ctx.font = "12px sans-serif"; for (const [kind, color] of [["npcs", "#f4b942"], ["warps", "#bc8cff"]]) { - if (!this.detailVisible() || !this.element.querySelector(`[data-map-${kind}]`)?.checked) continue; + if (!this.detailVisible(kind) || !this.element.querySelector(`[data-map-${kind}]`)?.checked) continue; for (const marker of this.entities[kind]) { const [x, y] = this.toScreen(...marker.point); if (x < 0 || y < 0 || x > this.width || y > this.height) continue; @@ -542,7 +543,7 @@ class AOMap { const zone = this.zones.get(Number(this.view.value)); const detail = zone && (!zone.levels || !zone.levels.length) ? " No extracted imagery for this playfield yet." : ""; const failures = [...this.tiles.values()].filter(tile => tile.failed).length; - this.status.textContent = `${this.players.filter(player => player.connected).length} connected players. ${this.scale < 0.3 ? "Zoom in to see NPCs." : `${this.entities.npcs.length} NPCs in view.`}${this.entities.limited ? " Marker limit reached; zoom in." : ""}${detail}${failures ? ` ${failures} tiles failed to load.` : ""}`; + this.status.textContent = `${this.players.filter(player => player.connected).length} connected players. ${this.element.querySelector("[data-map-npcs]")?.checked ? (this.detailVisible("npcs") ? `${this.entities.npcs.length} NPCs in view.` : "Zoom in to see NPCs.") : ""}${this.entities.limited ? " Marker limit reached; zoom in." : ""}${detail}${failures ? ` ${failures} tiles failed to load.` : ""}`; } } diff --git a/server/bank_storage_test.go b/server/bank_storage_test.go @@ -14,10 +14,10 @@ import ( func TestBankStoragePreservesFilledBackpack(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"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/users/1", nil)) + adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) adminTestHandler(restarted).ServeHTTP(bag, httptest.NewRequest("GET", "/admin/items/3", nil)) if response.Code != http.StatusSeeOther { @@ -55,7 +55,7 @@ func TestBankStorageRejectsInvalidOwnershipGraphs(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {document}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {document}}) after, err := readTestItemStore(world) if response.Code != http.StatusBadRequest || err != nil || !bytes.Equal(before, after) { @@ -67,13 +67,13 @@ func TestBankStorageRejectsInvalidOwnershipGraphs(t *testing.T) { func TestBankStorageRejectsAnotherPlayersInstance(t *testing.T) { world := newControlInventoryWorld(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Other"}}) - placed := postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_1: null}}\nbank: {slot_1: 1}\n"}}) + 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"}}) if placed.Code != http.StatusSeeOther { t.Fatal(placed.Body.String()) } - response := postControlForm(world, "/admin/users/2", url.Values{"data": {"bank: {slot_1: 1}\n"}}) + response := postControlForm(world, "/admin/players/2", url.Values{"data": {"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/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_1: 3}\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"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) || @@ -105,7 +105,7 @@ func TestBankStorageFailurePreservesPlacement(t *testing.T) { func TestBankStorageSupportsEveryNativeSlot(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) var document strings.Builder document.WriteString("bank:\n") for id := 1; id <= 102; id++ { @@ -116,7 +116,7 @@ func TestBankStorageSupportsEveryNativeSlot(t *testing.T) { document.WriteString(" slot_" + strconv.Itoa(id) + ": " + strconv.Itoa(id) + "\n") } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {document.String()}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {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/browser_socket.go b/server/browser_socket.go @@ -3,11 +3,25 @@ package main import ( "context" "log" + "net" "net/http" "github.com/coder/websocket" ) +// Keep the HTTP peer address on WebSocket and resumable in-memory connections. +type browserPeerAddress string + +func (address browserPeerAddress) Network() string { return "tcp" } +func (address browserPeerAddress) String() string { return string(address) } + +type browserGameConn struct { + net.Conn + peer browserPeerAddress +} + +func (connection *browserGameConn) RemoteAddr() net.Addr { return connection.peer } + func (server *server) browserWorld(w http.ResponseWriter, r *http.Request) { server.browserConnection(w, r, false) } @@ -37,12 +51,12 @@ func (server *server) browserConnection(w http.ResponseWriter, r *http.Request, } defer socket.CloseNow() if socket.Subprotocol() == "ao-stream-v1" { - server.resumeBrowserStream(socket, id, credential, chat) + server.resumeBrowserStream(socket, id, credential, chat, r.RemoteAddr) return } // Preserve the TCP byte stream across arbitrary binary WebSocket boundaries. - connection := websocket.NetConn(context.Background(), socket, websocket.MessageBinary) + connection := &browserGameConn{Conn: websocket.NetConn(context.Background(), socket, websocket.MessageBinary), peer: browserPeerAddress(r.RemoteAddr)} if chat { if err := server.serveChatClient(&chatClient{conn: connection, id: id, browserTokenHash: credential}); err != nil { log.Printf("Browser chat connection: %v", err) diff --git a/server/browser_socket_test.go b/server/browser_socket_test.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -60,6 +61,10 @@ func TestBrowserWorldPreservesPacketStream(t *testing.T) { if world.clients[1] == nil || !world.clients[1].target { t.Fatal("browser did not enter the shared 14.9.1 session handler") } + peer, _, err := net.SplitHostPort(world.clients[1].conn.RemoteAddr().String()) + if err != nil || peer != "127.0.0.1" || !strings.HasPrefix(host.URL, "http://"+peer+":") { + t.Fatal("browser connection lost its HTTP peer address", world.clients[1].conn.RemoteAddr(), err) + } } func TestBrowserWorldRejectsUnrelatedOrigin(t *testing.T) { diff --git a/server/browser_stream.go b/server/browser_stream.go @@ -216,7 +216,7 @@ func (stream *browserStream) receive(socket *websocket.Conn, message []byte) boo return err == nil } -func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint32, credential string, chat bool) { +func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint32, credential string, chat bool, remoteAddr string) { socket.SetReadLimit(65536) // The cookie authenticates every attachment; offsets identify replayed bytes. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -264,6 +264,7 @@ func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint } if stream == nil { game, pipe := net.Pipe() + connection := &browserGameConn{Conn: game, peer: browserPeerAddress(remoteAddr)} stream = &browserStream{server: server, id: hello.Stream, character: character, chat: chat, pipe: pipe, changed: make(chan struct{})} server.browserStreams[hello.Stream] = stream @@ -272,9 +273,9 @@ func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint defer game.Close() var result error if chat { - result = server.serveChatClient(&chatClient{conn: game, stream: stream, id: character, browserTokenHash: credential}) + result = server.serveChatClient(&chatClient{conn: connection, stream: stream, id: character, browserTokenHash: credential}) } else { - result = server.serveWorldClient(&worldClient{conn: game, stream: stream, id: character, loading: true, browserTokenHash: credential}) + result = server.serveWorldClient(&worldClient{conn: connection, stream: stream, id: character, loading: true, browserTokenHash: credential}) } if result != nil && result != io.EOF { log.Printf("Browser session ended: %v", result) diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -11,6 +11,7 @@ import ( "net" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -161,6 +162,11 @@ func TestBrowserWorldResumesTheSameSessionWithoutLostOrDuplicatedBytes(t *testin t.Fatal("world session was not initialized") } + peer, _, err := net.SplitHostPort(client.conn.RemoteAddr().String()) + if err != nil || peer != "127.0.0.1" || !strings.HasPrefix(host.URL, "http://"+peer+":") { + t.Fatal("browser connection lost its HTTP peer address", client.conn.RemoteAddr(), err) + } + // Lose the browser before it acknowledges the initialization bytes. first.CloseNow() if err := client.send(n3Packet(0x12345678, 50000, 1, nil)); err != nil { diff --git a/server/buddies_test.go b/server/buddies_test.go @@ -296,7 +296,7 @@ func TestBuddyControlEditPreservesSavedList(t *testing.T) { if err != nil { t.Fatal(err) } - request := httptest.NewRequest("POST", "/admin/users/1", strings.NewReader(url.Values{"data": {string(contents)}}.Encode())) + request := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {string(contents)}}.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") response := httptest.NewRecorder() diff --git a/server/chat.go b/server/chat.go @@ -114,7 +114,7 @@ func (server *server) initializeChat(client *chatClient, id uint32) error { if err != nil { log.Printf("Restore chat history for character %d: %v", id, err) } - log.Printf("Chat connected: character %d", id) + log.Printf("Chat connected: character %d from %s", id, client.conn.RemoteAddr()) // Announce the player's name and public channel before displaying history. channel := binary.BigEndian.AppendUint32([]byte{0x87}, 1) diff --git a/server/checkpoint_test.go b/server/checkpoint_test.go @@ -12,7 +12,7 @@ func newCheckpointWorld(t *testing.T) *server { t.Helper() useNPCData(t, testNPCData()) world := newTestServer(t) - response := postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + response := postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) if response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } diff --git a/server/combat_test.go b/server/combat_test.go @@ -15,6 +15,10 @@ type combatTestConn struct { packets [][]byte } +func (conn *combatTestConn) RemoteAddr() net.Addr { + return &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1), Port: 4321} +} + func (conn *combatTestConn) SetWriteDeadline(time.Time) error { return nil } func (conn *combatTestConn) Write(packet []byte) (int, error) { diff --git a/server/control.go b/server/control.go @@ -48,10 +48,9 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "<p role='status'>Password changed.</p>") } fmt.Fprintf(w, "<h1>%s</h1><p>Player %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected) - fmt.Fprintf(w, "<p><a href='admin/users/%d/password'>Change password</a></p>", data.ID) - controlMap(w, data.ID) + fmt.Fprintf(w, "<p><a href='admin/players/%d/teleport'>Teleport</a> | <a href='admin/players/%d/password'>Change password</a></p>", data.ID, data.ID) fmt.Fprint(w, "<h2>Character data</h2>") - fmt.Fprintf(w, "<form method='post' action='admin/users/%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))) + 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))) fmt.Fprint(w, itemTables.String()) fmt.Fprint(w, "</main></body></html>") } @@ -126,7 +125,7 @@ func (server *server) editUser(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/players/%d", server.baseURL, id), http.StatusSeeOther) } func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) { @@ -229,7 +228,7 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/players/%d/teleport?saved=1", server.baseURL, id), http.StatusSeeOther) } func (server *server) updateUser(destination userData) error { diff --git a/server/control_containers_test.go b/server/control_containers_test.go @@ -15,7 +15,7 @@ func TestControlPortableContainerCatalog(t *testing.T) { t.Run(container.name, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) for _, template := range []uint32{container.template, 121567, 99241} { response := postControlForm(world, "/admin/items", url.Values{"template": {strconv.FormatUint(uint64(template), 10)}}) if response.Code != http.StatusSeeOther { @@ -27,7 +27,7 @@ func TestControlPortableContainerCatalog(t *testing.T) { filled := postControlForm(world, "/admin/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"1:20"}}) nested := postControlForm(world, "/admin/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"1:0"}}) page, child := httptest.NewRecorder(), httptest.NewRecorder() - adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) adminTestHandler(world).ServeHTTP(child, httptest.NewRequest("GET", "/admin/items/2", nil)) restarted := newTestInventoryServer(t) diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -79,12 +79,12 @@ func postControlForm(world *server, path string, fields url.Values) *httptest.Re func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) 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/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1, inventory_slot_2: 2}\n"}}) + placed := postControlForm(world, "/admin/players/1", url.Values{"data": {"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() @@ -121,14 +121,14 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing func TestControlItemCanBeUnassignedAndTransferredWithoutChangingID(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) - postControlForm(world, "/admin/users", url.Values{"name": {"Second"}}) + 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/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) - cleared := postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}}) + cleared := postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}}) unassigned := newServerForTest(t) - transferred := postControlForm(world, "/admin/users/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}}) + transferred := postControlForm(world, "/admin/players/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}}) restarted := newServerForTest(t) postControlForm(restarted, "/admin/items", url.Values{"template": {"121567"}}) @@ -153,17 +153,17 @@ func TestControlInventoryRejectsDuplicateUnknownAndInvalidSlotsAtomically(t *tes t.Run(contents, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) - postControlForm(world, "/admin/users", url.Values{"name": {"Second"}}) + 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/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) before, err := readTestItemStore(world) if err != nil { t.Fatal(err) } - response := postControlForm(world, "/admin/users/2", url.Values{"data": {"inventory:\n " + contents}}) + response := postControlForm(world, "/admin/players/2", url.Values{"data": {"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 { @@ -188,14 +188,14 @@ func TestControlItemCreationKeepsStateWhenSavingFails(t *testing.T) { func TestControlEditorShowsAllSkillCategoriesAndDefaultFields(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + 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/users/1", url.Values{"data": {contents}}); response.Code != http.StatusSeeOther { + if response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}); response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } page := httptest.NewRecorder() - adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) editors := regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindAllStringSubmatch(page.Body.String(), -1) if page.Code != http.StatusOK || len(editors) != 1 { @@ -226,10 +226,10 @@ func TestControlEditorShowsAllSkillCategoriesAndDefaultFields(t *testing.T) { func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + 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/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) restarted := newServerForTest(t) packet := fullCharacterPacket(restarted.characters[1]) values := make(map[uint32]uint32) @@ -263,12 +263,12 @@ func TestControlRoutesRequireAdminPrefix(t *testing.T) { func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) for _, template := range []string{"121567", "85686", "101173"} { postControlForm(world, "/admin/items", url.Values{"template": {template}}) } page := httptest.NewRecorder() - adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + 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 { @@ -285,7 +285,7 @@ func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) restarted := newServerForTest(t) var name string var x float32 @@ -312,7 +312,7 @@ func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) postControlForm(world, "/admin/items", url.Values{"template": {"85557"}}) if _, err := world.db.Exec("CREATE TRIGGER reject_editor BEFORE UPDATE OF name ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil { @@ -320,7 +320,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/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) restarted := newServerForTest(t) var name string var credits, locations uint32 @@ -345,9 +345,9 @@ func TestControlAppearanceRejectsPackedScalarsAndOutOfRangeFields(t *testing.T) t.Run(contents, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {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()) @@ -369,7 +369,7 @@ func TestControlCharacterDocumentPreservesCastRefundAndExplicitNanoEdits(t *test defer world.db.Close() world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {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 @@ -22,17 +22,17 @@ func TestControlClothingNamesMatchNativeArmorSlots(t *testing.T) { t.Run(scenario.name, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) created := postControlForm(world, "/admin/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) if created.Code != 303 { t.Fatal(created.Code, created.Body.String()) } data := fmt.Sprintf("equipment: {%s: 1}\n", scenario.name) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {data}}) restarted := newTestInventoryServer(t) page := httptest.NewRecorder() - adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) if response.Code != 303 || len(restarted.characters[1].inventory.Items) != 1 { t.Fatal("named clothing placement rejected compatible equipment", response.Code, response.Body.String()) diff --git a/server/control_inventory_test.go b/server/control_inventory_test.go @@ -16,7 +16,7 @@ func newControlInventoryWorld(t *testing.T) *server { t.Helper() useNPCData(t, testNPCData()) world := newTestServer(t) - if response := postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}); response.Code != http.StatusSeeOther { + if response := postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}); response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } for _, template := range []string{"121567", "85557", "99228", "121567"} { @@ -36,13 +36,13 @@ func newControlInventoryWorld(t *testing.T) *server { func TestControlCharacterDocumentSeparatesEquipment(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) postControlForm(world, "/admin/items", url.Values{"template": {"85557"}}) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"equipment: {clothes_head: 1}\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"equipment: {clothes_head: 1}\n"}}) restarted := newServerForTest(t) page := httptest.NewRecorder() - adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) if response.Code != http.StatusSeeOther { t.Fatalf("top-level equipment save: %d %s", response.Code, response.Body.String()) @@ -68,7 +68,7 @@ func TestControlInventoryTablesShowInstancesContainersAndEmptySlots(t *testing.T world.baseURL = "/share/test/" page := httptest.NewRecorder() - adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/share/test/admin/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/share/test/admin/players/1", nil)) body := page.Body.String() for _, expected := range []string{ @@ -99,7 +99,7 @@ func TestControlBackpackPagesLinkContentsAndParentContainer(t *testing.T) { if !strings.Contains(bag.Body.String(), "<h2>Contents</h2>") || !strings.Contains(bag.Body.String(), "<tr><td>slot_1</td><td><a href='admin/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>") || !strings.Contains(bag.Body.String(), "<tr><td>slot_21</td><td>Empty</td></tr>") || - !strings.Contains(bag.Body.String(), "<a href='admin/users/1'>Explorer (1)</a>") { + !strings.Contains(bag.Body.String(), "<a href='admin/players/1'>Explorer (1)</a>") { t.Fatal("backpack page lost its owner or readable contents") } if !strings.Contains(child.Body.String(), "<a href='admin/items/3'>Container 3, slot_1</a>") { @@ -110,7 +110,7 @@ func TestControlBackpackPagesLinkContentsAndParentContainer(t *testing.T) { func TestControlEquipmentClearUnassignsWithoutLosingItems(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"equipment: {clothes_head: null}\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"equipment: {clothes_head: null}\n"}}) restarted := newServerForTest(t) var placements int err := restarted.db.QueryRow("SELECT count(*) FROM item_locations").Scan(&placements) @@ -137,7 +137,7 @@ func TestControlEquipmentRejectsInvalidPlacementsAtomically(t *testing.T) { t.Run(name, func(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"name: Changed\n" + document}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"name: Changed\n" + document}}) restarted := newServerForTest(t) if response.Code != http.StatusBadRequest || world.characters[1].name != "Explorer" || restarted.characters[1].name != "Explorer" { @@ -156,14 +156,14 @@ func TestControlEquipmentRejectsInvalidPlacementsAtomically(t *testing.T) { func TestControlEquipmentCannotTakeAnotherPlayersItem(t *testing.T) { world := newControlInventoryWorld(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Other"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Other"}}) postControlForm(world, "/admin/items", url.Values{"template": {"85557"}}) assigned := postControlForm(world, "/admin/items/5", url.Values{"action": {"assign"}, "owner": {"2"}, "destination": {"0:18"}}) if assigned.Code != http.StatusSeeOther { t.Fatal(assigned.Body.String()) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"equipment: {clothes_head: 5}\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"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) @@ -175,13 +175,13 @@ 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/users/1", url.Values{"data": {document}}) + prepared := postControlForm(world, "/admin/players/1", url.Values{"data": {document}}) if prepared.Code != http.StatusSeeOther { t.Fatal(prepared.Body.String()) } page := httptest.NewRecorder() - adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/players/1", nil)) if !strings.Contains(page.Body.String(), "<h2>Reclaim</h2>") || !strings.Contains(page.Body.String(), "<tr><td>inventory_slot_2</td><td><a href='admin/items/3'>Small Backpack (ID 3)</a></td></tr>") || diff --git a/server/control_test.go b/server/control_test.go @@ -57,7 +57,7 @@ func TestSetGameTimeRejectsHourOutsideOriginalDay(t *testing.T) { } } -func TestUserPageHasMapTeleportAndZoneFinder(t *testing.T) { +func TestUserPageLinksToSeparateTeleportPage(t *testing.T) { world := newTestServer(t) player := world.newCharacter() world.clients[player.id] = &worldClient{ready: true} @@ -66,16 +66,25 @@ func TestUserPageHasMapTeleportAndZoneFinder(t *testing.T) { } response := httptest.NewRecorder() - request := httptest.NewRequest("GET", "/admin/users/1", nil) + request := httptest.NewRequest("GET", "/admin/players/1", nil) request.SetPathValue("character", "1") world.userPage(response, request) body := response.Body.String() - if !strings.Contains(body, "<select data-map-find>") || !strings.Contains(body, "data-map-teleport>") { - t.Fatalf("missing map controls") + if strings.Contains(body, "<canvas") || !strings.Contains(body, "href='admin/players/1/teleport'") || !strings.Contains(body, "<h2>Character data</h2>") { + t.Fatal("player page must expose character data and link to teleport") } - if strings.Count(body, "action='admin/teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") { - t.Fatalf("generic zone teleport is still present") + + request = httptest.NewRequest("GET", "/admin/players/1/teleport", nil) + request.SetPathValue("character", "1") + response = httptest.NewRecorder() + world.teleportPage(response, request) + body = response.Body.String() + if !strings.Contains(body, "<select data-map-find>") || !strings.Contains(body, "action='admin/players/1/teleport'") { + t.Fatal("missing teleport map controls") + } + if strings.Index(body, "Teleport here</button>") > strings.Index(body, "<canvas") || !strings.Contains(body, "</canvas></div><script") { + t.Fatal("teleport controls must precede the map, with nothing below it") } } @@ -83,8 +92,8 @@ func TestTeleportRejectsZoneWithoutOriginalAssets(t *testing.T) { world := newTestServer(t) player := world.newCharacter() mux := http.NewServeMux() - mux.HandleFunc("POST /admin/teleport/{character}", world.teleportPlayer) - request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=690")) + mux.HandleFunc("POST /admin/players/{character}/teleport", world.teleportPlayer) + request := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=690")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() diff --git a/server/database_test.go b/server/database_test.go @@ -99,7 +99,7 @@ func failDatabaseWrites(t *testing.T, world *server) { func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) player := world.characters[1] player.health, player.nano, player.sitting, player.aggDef = 27, 11, true, 33 player.inventory.Credits = 913 @@ -219,10 +219,10 @@ func TestWorldDatabaseRollsBackCorpseCashWithInventory(t *testing.T) { func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) world.characters[1].health, world.characters[1].nano = 30, 12 - response := postControlForm(world, "/admin/users/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", url.Values{"data": {"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 { @@ -255,7 +255,7 @@ func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) { func TestNPCCheckpointsSkipEmptyZonesAndLimitRoutineWrites(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) now := time.Now() if err := world.checkpointWorld(now); err != nil { t.Fatal(err) diff --git a/server/http.go b/server/http.go @@ -56,7 +56,7 @@ func (server *server) adminHandler() http.Handler { admin := http.NewServeMux() admin.HandleFunc("GET /admin", server.controlPage) admin.HandleFunc("GET /admin/{$}", server.controlPage) - admin.HandleFunc("GET /admin/users", server.usersPage) + admin.HandleFunc("GET /admin/players", server.usersPage) admin.HandleFunc("GET /admin/map", server.mapPage) admin.HandleFunc("GET /admin/stats", server.adminStats) admin.HandleFunc("GET /admin/sql", server.sqlPage) @@ -67,10 +67,10 @@ func (server *server) adminHandler() http.Handler { admin.HandleFunc("POST /admin/admins/new", server.createAdmin) admin.HandleFunc("GET /admin/admins/{admin}", server.changeAdminPassword) admin.HandleFunc("POST /admin/admins/{admin}", server.changeAdminPassword) - admin.HandleFunc("GET /admin/users/{character}", server.userPage) - admin.HandleFunc("POST /admin/users/{character}", server.editUser) - admin.HandleFunc("GET /admin/users/{character}/password", server.changePlayerPassword) - admin.HandleFunc("POST /admin/users/{character}/password", server.changePlayerPassword) + admin.HandleFunc("GET /admin/players/{character}", server.userPage) + admin.HandleFunc("POST /admin/players/{character}", server.editUser) + admin.HandleFunc("GET /admin/players/{character}/password", server.changePlayerPassword) + admin.HandleFunc("POST /admin/players/{character}/password", server.changePlayerPassword) admin.HandleFunc("GET /admin/items", server.itemsPage) admin.HandleFunc("GET /admin/items/catalog", server.itemCatalogPage) admin.HandleFunc("POST /admin/items", server.createItem) @@ -101,6 +101,7 @@ func (server *server) adminHandler() http.Handler { }) admin.HandleFunc("POST /admin/time", server.setGameTime) admin.HandleFunc("POST /admin/weather", server.setWeather) - admin.HandleFunc("POST /admin/teleport/{character}", server.teleportPlayer) + admin.HandleFunc("GET /admin/players/{character}/teleport", server.teleportPage) + admin.HandleFunc("POST /admin/players/{character}/teleport", server.teleportPlayer) return admin } diff --git a/server/insurance_experience_test.go b/server/insurance_experience_test.go @@ -230,7 +230,7 @@ func TestInsuranceExperienceEditorRejectsImpossibleSnapshots(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) restored := newTestInventoryServer(t).characters[1] if response.Code != http.StatusBadRequest || player.experience != 50 || player.insuredExperience != 1490 || restored.insuredExperience != 1490 { diff --git a/server/inventory_write_test.go b/server/inventory_write_test.go @@ -14,7 +14,7 @@ import ( func newInventoryWriteWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() world := newCheckpointWorld(t) - response := postControlForm(world, "/admin/users", url.Values{"name": {"Observer"}}) + response := postControlForm(world, "/admin/players", url.Values{"name": {"Observer"}}) if response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } @@ -91,7 +91,7 @@ func TestInventoryMetadataRetainsUnchangedProgramsAndLocks(t *testing.T) { } auditCheckpointWrites(t, world) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) restored := newTestInventoryServer(t) if response.Code != http.StatusSeeOther || !reflect.DeepEqual(restored.characters[1].inventory.LearnedNanos, []uint32{29618, 43324}) || @@ -114,7 +114,7 @@ func TestInventoryMetadataWritesOnlyChangedCreditsAndPrograms(t *testing.T) { } auditCheckpointWrites(t, world) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) restored := newTestInventoryServer(t) inventory := restored.characters[1].inventory @@ -133,7 +133,7 @@ func TestInventoryMetadataRemovalKeepsOtherPlayers(t *testing.T) { contents := "inventory:\n learned_nanos: []\n" auditCheckpointWrites(t, world) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) restored := newTestInventoryServer(t) inventory, other := restored.characters[1].inventory, restored.characters[2].inventory @@ -171,7 +171,7 @@ func TestInventoryMetadataFailureRollsBackWithOwnershipThenRetries(t *testing.T) t.Fatal(err) } - failed := postControlForm(world, "/admin/users/1", url.Values{"data": {string(contents)}}) + failed := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) after, err := readTestItemStore(world) if err != nil { t.Fatal(err) @@ -183,7 +183,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/users/1", url.Values{"data": {string(contents)}}) + retry := postControlForm(world, "/admin/players/1", url.Values{"data": {string(contents)}}) restored := newTestInventoryServer(t) inventory := restored.characters[1].inventory diff --git a/server/item_pages.go b/server/item_pages.go @@ -127,7 +127,7 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { if location.owner == 0 { fmt.Fprint(w, owner) } else { - fmt.Fprintf(w, "<a href='admin/users/%d'>%s (%d)</a>", location.owner, html.EscapeString(owner), location.owner) + fmt.Fprintf(w, "<a href='admin/players/%d'>%s (%d)</a>", location.owner, html.EscapeString(owner), location.owner) } fmt.Fprintf(w, "</td><td>%s</td></tr>", html.EscapeString(location.label)) } @@ -241,7 +241,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<h2>%s</h2><p>%s</p>", html.EscapeString(definition.Name), html.EscapeString(definition.Description)) } if location.owner != 0 { - fmt.Fprintf(w, "<p>Owner: <a href='admin/users/%d'>%s (%d)</a>. ", location.owner, html.EscapeString(ownerName), location.owner) + fmt.Fprintf(w, "<p>Owner: <a href='admin/players/%d'>%s (%d)</a>. ", location.owner, html.EscapeString(ownerName), location.owner) } else { fmt.Fprint(w, "<p>Unassigned. ") } diff --git a/server/item_store_test.go b/server/item_store_test.go @@ -51,11 +51,11 @@ func TestItemStoreLoadsUnassignedInstancesWithoutCharacters(t *testing.T) { func TestDatabaseRejectsSharedInstanceReferences(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) - postControlForm(world, "/admin/users", url.Values{"name": {"Second"}}) + 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/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}"}}) + postControlForm(world, "/admin/players/1", url.Values{"data": {"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)") @@ -73,9 +73,9 @@ func TestDatabaseRejectsSharedInstanceReferences(t *testing.T) { func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/players/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) page := httptest.NewRecorder() @@ -147,8 +147,8 @@ func TestControlConcurrentCreationAllocatesUniqueGlobalIDs(t *testing.T) { func TestControlConcurrentAssignmentCannotShareOneInstance(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) - postControlForm(world, "/admin/users", url.Values{"name": {"Second"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"First"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Second"}}) postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) responses := make(chan *httptest.ResponseRecorder, 2) diff --git a/server/logging_test.go b/server/logging_test.go @@ -37,8 +37,8 @@ func TestPlayerLogsStayHighLevelWithOptionalTraces(t *testing.T) { world.httpHandler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/missing", nil)) if strings.Count(operational.String(), "\n") != 2 || - !strings.Contains(operational.String(), `Player connected: "Explorer" (character 1)`) || - !strings.Contains(operational.String(), `Player disconnected: "Explorer" (character 1)`) { + !strings.Contains(operational.String(), `Player connected: "Explorer" (character 1) from 192.0.2.1:4321`) || + !strings.Contains(operational.String(), `Player disconnected: "Explorer" (character 1) from 192.0.2.1:4321`) { t.Fatal("unexpected operational log", operational.String()) } if tracing { diff --git a/server/main.go b/server/main.go @@ -360,8 +360,8 @@ func (server *server) serveWorldClient(client *worldClient) error { character.movement = playerMovement{} character.body = playerCollisionBody{} server.clients[character.id] = client - log.Printf("Player connected: %q (character %d)", character.name, character.id) - defer log.Printf("Player disconnected: %q (character %d)", character.name, character.id) + log.Printf("Player connected: %q (character %d) from %s", character.name, character.id, client.conn.RemoteAddr()) + defer log.Printf("Player disconnected: %q (character %d) from %s", character.name, character.id, client.conn.RemoteAddr()) now := time.Now() for index := range character.activeNanos { if character.activeNanos[index].expiresAt.IsZero() { diff --git a/server/main_test.go b/server/main_test.go @@ -115,12 +115,12 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) { t.Fatal(err) } mux := http.NewServeMux() - mux.HandleFunc("POST /admin/teleport/{character}", world.teleportPlayer) + mux.HandleFunc("POST /admin/players/{character}/teleport", world.teleportPlayer) response := httptest.NewRecorder() done := make(chan struct{}) go func() { - request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=800")) + request := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=800")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") mux.ServeHTTP(response, request) close(done) @@ -151,7 +151,7 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) { if response.Code != http.StatusSeeOther { t.Fatalf("teleport HTTP status: %d", response.Code) } - if !strings.Contains(page.Body.String(), "href='admin/users/1'>Local Explorer 1</a>") { + if !strings.Contains(page.Body.String(), "href='admin/players/1'>Local Explorer 1</a>") { t.Fatal("user disappeared while reconnecting") } if hex.EncodeToString(teleport[20:36]) != "43197d220000c3500000000100000000" || hex.EncodeToString(teleport[48:72]) != "00000001000000000000000000009c500000032000000000" { diff --git a/server/map_test.js b/server/map_test.js @@ -45,17 +45,27 @@ test('detail layers require their checkbox, sufficient zoom and a bounded viewpo assert.equal(query.get('npcs'), '0'); assert.equal(query.get('warps'), '1'); npcs.checked = true; + assert.equal(new URLSearchParams(map.entityQuery()).get('npcs'), '0'); + map.scale = 1.2; assert.equal(new URLSearchParams(map.entityQuery()).get('npcs'), '1'); warps.checked = false; assert.equal(new URLSearchParams(map.entityQuery()).get('warps'), '0'); warps.checked = true; - map.width = 2000; + map.width = 8000; query = new URLSearchParams(map.entityQuery()); assert.equal(query.get('npcs'), '0'); assert.equal(query.get('warps'), '0'); }); +test('the main map does not select a teleport destination on a background tap', () => { + const map = mapWithTiles(1000, 1, () => {}); + map.location.textContent = ''; + map.pick(500, 500); + assert.equal(map.selection, null); + assert.equal(map.location.textContent, ''); +}); + test('finding a zone focuses its boundary within the world map', () => { const map = mapWithTiles(128, 1, () => { throw new Error('Navigation must not make a request'); }); map.width = 1000; diff --git a/server/maps.go b/server/maps.go @@ -5,16 +5,43 @@ import ( "ao/server/gamedata" "encoding/json" "fmt" + "html" "net/http" + "strconv" "time" ) func controlMap(w http.ResponseWriter, character uint32) { - fmt.Fprintf(w, "<h2>Map</h2><div data-world-map data-character='%d'><p><label>View <select data-map-view><option value='world'>Rubi-Ka</option></select></label> <label>Find zone <select data-map-find><option value=''>Choose a zone</option></select></label> <button type='button' data-map-zoom='1'>Zoom in</button> <button type='button' data-map-zoom='-1'>Zoom out</button> <button type='button' data-map-center>Center</button></p><p><label><input type='checkbox' data-map-offline>Offline players</label><label><input type='checkbox' data-map-npcs>NPCs</label><label><input type='checkbox' data-map-warps checked>Warp zones</label></p><canvas data-map-canvas width='1000' height='480' aria-label='World and player map'></canvas><p data-map-status>Loading maps...</p><p data-map-location>Drag to pan. Pinch or scroll to zoom.</p>", character) + fmt.Fprintf(w, "<div data-world-map data-character='%d'><p><label>View <select data-map-view><option value='world'>Rubi-Ka</option></select></label> <label>Find zone <select data-map-find><option value=''>Choose a zone</option></select></label> <button type='button' data-map-zoom='1'>Zoom in</button> <button type='button' data-map-zoom='-1'>Zoom out</button> <button type='button' data-map-center>Center</button></p><p><label><input type='checkbox' data-map-offline>Offline players</label><label><input type='checkbox' data-map-npcs>NPCs</label><label><input type='checkbox' data-map-warps checked>Warp zones</label></p><p data-map-status>Loading maps...</p><p data-map-location>Drag to pan. Pinch or scroll to zoom.</p>", character) if character != 0 { - fmt.Fprintf(w, "<form method='post' action='admin/teleport/%d' data-map-teleport><label data-map-zone-choice hidden>Playfield <select name='playfield' required></select></label> <input type='hidden' name='x'><input type='hidden' name='z'><button disabled>Teleport here</button></form>", character) + fmt.Fprintf(w, "<form method='post' action='admin/players/%d/teleport' data-map-teleport><label data-map-zone-choice hidden>Playfield <select name='playfield' required></select></label> <input type='hidden' name='x'><input type='hidden' name='z'><button disabled>Teleport here</button></form>", character) } - fmt.Fprint(w, "</div><script src='admin/control-map.js' defer></script>") + fmt.Fprint(w, "<canvas data-map-canvas width='1000' height='480' aria-label='World and player map'></canvas></div><script src='admin/control-map.js' defer></script>") +} + +func (server *server) teleportPage(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) + if err != nil { + http.Error(w, "Invalid player", http.StatusBadRequest) + return + } + server.mutex.Lock() + player := server.characters[uint32(id)] + if player == nil || player.npc { + server.mutex.Unlock() + http.NotFound(w, r) + return + } + name := player.name + server.mutex.Unlock() + + server.adminPageStart(w, "Teleport", "Players") + fmt.Fprintf(w, "<div class='map-page'><p><a href='admin/players/%d'>Back to player</a></p><h1>Teleport %s</h1>", id, html.EscapeString(name)) + if r.URL.Query().Get("saved") == "1" { + fmt.Fprint(w, "<p role='status'>Player teleported.</p>") + } + controlMap(w, uint32(id)) + fmt.Fprint(w, "</div></main></body></html>") } func controlMapScript(w http.ResponseWriter, r *http.Request) { diff --git a/server/maps_test.go b/server/maps_test.go @@ -14,7 +14,7 @@ func TestMapTeleportUsesTerrainHeightAndPersists(t *testing.T) { world := newTestServer(t) world.newCharacter() world.terrain[950] = &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 128, scale: 1, heights: []byte{0, 64, 128, 0, 64, 128, 0, 64, 128}} - request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=950&x=52&z=56")) + request := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=950&x=52&z=56")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") response := httptest.NewRecorder() @@ -35,7 +35,7 @@ func TestMapTeleportRejectsInvalidCoordinatesWithoutChangingPlayer(t *testing.T) player := world.newCharacter() before := player.position world.terrain[950] = &terrain{width: 2, height: 2, boundsWidth: 2, boundsHeight: 2, spacing: 128, scale: 1, heights: []byte{0, 64, 128, 0, 64, 128, 0, 64, 128}} - request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=950&"+coordinates)) + request := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=950&"+coordinates)) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") response := httptest.NewRecorder() diff --git a/server/progression_test.go b/server/progression_test.go @@ -54,10 +54,10 @@ func TestExperienceInitializationUsesCumulativeNativeBoundaries(t *testing.T) { func TestExperienceEditAndCheckpointSurviveRestart(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) - postControlForm(world, "/admin/users", url.Values{"name": {"Observer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Observer"}}) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) player := world.characters[1] player.position[0]++ if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { @@ -87,13 +87,13 @@ func TestExperienceEditorRejectsInvalidProgressWithoutChangingState(t *testing.T t.Run(contents, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) before, err := readTestPlayerRecord(1, "player") if err != nil { t.Fatal(err) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {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 { @@ -113,10 +113,10 @@ func TestExperienceEditorAcceptsLevelEndpoints(t *testing.T) { t.Run(fmt.Sprintf("level%d/progress%d", scenario.level, scenario.experience), func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) contents := fmt.Sprintf("level: %d\nexperience: %d\n", scenario.level, scenario.experience) - response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {contents}}) restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || restarted.characters[1].level != scenario.level || @@ -145,12 +145,12 @@ func TestExperienceProfileUpdatePersistsImmediately(t *testing.T) { func TestExperienceEditFailureRollsBackThenRetries(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) if _, err := world.db.Exec("CREATE TRIGGER reject_xp BEFORE UPDATE OF experience ON characters BEGIN SELECT RAISE(ABORT, 'test XP failure'); END"); err != nil { t.Fatal(err) } - response := postControlForm(world, "/admin/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response := postControlForm(world, "/admin/players/1", url.Values{"data": {"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/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response = postControlForm(world, "/admin/players/1", url.Values{"data": {"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/users/1", url.Values{"data": {scenario.document}} + path, fields := "/admin/players/1", url.Values{"data": {scenario.document}} if scenario.document == "" { path, fields = "/admin/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}} } @@ -143,7 +143,7 @@ func TestShopRejectedControlSavePreservesAcceptableDraft(t *testing.T) { } conn.packets = nil - response := postControlForm(world, "/admin/users/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", url.Values{"data": {"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/target_protocol_test.go b/server/target_protocol_test.go @@ -319,7 +319,7 @@ func TestTargetTeleportIncludesFullPlayfieldProxy(t *testing.T) { binary.BigEndian.PutUint16(ping[2:4], 11) client.Write(ping) readPacket(client) - request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=800")) + request := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=800")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") done := make(chan struct{}) diff --git a/server/users_test.go b/server/users_test.go @@ -19,7 +19,7 @@ func TestUserRowsAreSeparateAndOnlyUpdatedProfileChanges(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) for _, name := range []string{"First", "Second"} { - postControlForm(world, "/admin/users", url.Values{"name": {name}}) + postControlForm(world, "/admin/players", url.Values{"name": {name}}) } before, err := readTestPlayerRecord(2, "player") if err != nil { @@ -50,10 +50,10 @@ func TestUserCreationEditingAndOfflineTeleportSurviveRestart(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) mux := http.NewServeMux() - mux.HandleFunc("POST /admin/users", world.createUser) - mux.HandleFunc("POST /admin/users/{character}", world.editUser) - mux.HandleFunc("POST /admin/teleport/{character}", world.teleportPlayer) - creation := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name=Explorer")) + mux.HandleFunc("POST /admin/players", world.createUser) + mux.HandleFunc("POST /admin/players/{character}", world.editUser) + mux.HandleFunc("POST /admin/players/{character}/teleport", world.teleportPlayer) + creation := httptest.NewRequest("POST", "/admin/players", strings.NewReader("name=Explorer")) creation.Header.Set("Content-Type", "application/x-www-form-urlencoded") created := httptest.NewRecorder() data := `id: 1 @@ -63,10 +63,10 @@ monster_data: 0 level: 7 running: true ` - edition := httptest.NewRequest("POST", "/admin/users/1", strings.NewReader(url.Values{"data": {data}}.Encode())) + edition := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {data}}.Encode())) edition.Header.Set("Content-Type", "application/x-www-form-urlencoded") edited := httptest.NewRecorder() - teleport := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=800")) + teleport := httptest.NewRequest("POST", "/admin/players/1/teleport", strings.NewReader("playfield=800")) teleport.Header.Set("Content-Type", "application/x-www-form-urlencoded") teleported := httptest.NewRecorder() @@ -80,16 +80,19 @@ running: true page := httptest.NewRecorder() restarted.usersPage(page, httptest.NewRequest("GET", "/admin", nil)) - for _, response := range []*httptest.ResponseRecorder{created, edited, teleported} { - if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/admin/users/1" { + for _, response := range []*httptest.ResponseRecorder{created, edited} { + if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/admin/players/1" { t.Fatalf("user form response: %d %s", response.Code, response.Body.String()) } } + if teleported.Code != http.StatusSeeOther || teleported.Header().Get("Location") != "/admin/players/1/teleport?saved=1" { + t.Fatal("teleport must return to its map", teleported.Code, teleported.Header()) + } player := restarted.characters[1] if player.name != "Edited Explorer" || player.playfield != 800 || player.level != 7 || player.appearance != 789 || player.position != [3]float32{679.625, 74.75, 537.875} || !player.running { t.Fatalf("saved character: %+v", player) } - if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='admin/users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") { + if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='admin/players/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") { t.Fatalf("offline user disappeared: %s", page.Body.String()) } contents, err := readTestPlayerRecord(1, "player") @@ -168,14 +171,14 @@ func TestMovementModePersistsAndIsSuppliedOnReconnect(t *testing.T) { func TestUserEditorRejectsUnknownFieldsWithoutChangingSavedData(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - creation := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name=Explorer")) + creation := httptest.NewRequest("POST", "/admin/players", strings.NewReader("name=Explorer")) creation.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), creation) before, err := readTestPlayerRecord(1, "player") if err != nil { t.Fatal(err) } - request := httptest.NewRequest("POST", "/admin/users/1", strings.NewReader(url.Values{"data": {"id: 1\nname: Changed\nlevle: 7\n"}}.Encode())) + request := httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {"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() @@ -195,7 +198,7 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) for _, name := range []string{"First", "Second"} { - request := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name="+name)) + request := httptest.NewRequest("POST", "/admin/players", strings.NewReader("name="+name)) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) } @@ -227,15 +230,15 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) { func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - request := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name=Explorer")) + request := httptest.NewRequest("POST", "/admin/players", strings.NewReader("name=Explorer")) 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/users/1", strings.NewReader(url.Values{"data": {data}}.Encode())) + request = httptest.NewRequest("POST", "/admin/players/1", strings.NewReader(url.Values{"data": {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/users/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(url.Values{"data": {"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) @@ -270,7 +273,7 @@ func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) { func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - request := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name=Explorer")) + request := httptest.NewRequest("POST", "/admin/players", strings.NewReader("name=Explorer")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) profile, err := readTestPlayerRecord(1, "player") @@ -418,7 +421,7 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) { world := newTestServer(t) created := time.Now() for _, name := range []string{"First", "Second"} { - request := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name="+name)) + request := httptest.NewRequest("POST", "/admin/players", strings.NewReader("name="+name)) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) } @@ -507,7 +510,7 @@ func TestOfflinePositionSaveWithSparsePlayerIDs(t *testing.T) { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - request := httptest.NewRequest("POST", "/admin/teleport/7", strings.NewReader("playfield=800")) + request := httptest.NewRequest("POST", "/admin/players/7/teleport", strings.NewReader("playfield=800")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() diff --git a/tools/client/sweep_browser.py b/tools/client/sweep_browser.py @@ -119,7 +119,7 @@ def tick(message): disconnect_started = None queue.pop(0) log_start = (fixture / 'logs/server.log').stat().st_size - request('/admin/teleport/73', {'playfield': zone['id']}) + request('/admin/players/73/teleport', {'playfield': zone['id']}) request('/admin/time', {'hour': 13, 'minute': 30}) active = dict(zone, phase=phase, started=time.time(), status='loading', server_log_start=log_start, cold_start=need_launch, user_agent=message['user_agent']) diff --git a/tools/client/sweep_playfields.py b/tools/client/sweep_playfields.py @@ -121,7 +121,7 @@ def run_zone(zone, phase): assert time.monotonic() < deadline, 'server did not observe client disconnect' time.sleep(.1) server_log_start = (fixture / 'logs/server.log').stat().st_size - request('/admin/teleport/73', {'playfield': zone['id']}) + request('/admin/players/73/teleport', {'playfield': zone['id']}) request('/admin/time', {'hour': 13, 'minute': 30}) started = time.monotonic() result = {'phase': phase, 'id': zone['id'], 'name': zone['name'], 'started': time.time(), 'status': 'timeout', 'previous_pid': previous_pid, 'run_started': metadata['started']} diff --git a/tools/client/test_admin.mjs b/tools/client/test_admin.mjs @@ -55,6 +55,30 @@ try { assert.equal(await page.getByRole('link', {name: 'Admin Browser', exact: true}).count(), 1); assert.equal(await page.getByText('Create user', {exact: true}).count(), 0); await page.getByRole('link', {name: 'Admin Browser', exact: true}).click(); + 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); + 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')); + await page.setViewportSize({width: 390, height: 844}); + const teleportMap = page.locator('canvas'); + const teleportBox = await teleportMap.boundingBox(); + const teleportButton = await page.getByRole('button', {name: 'Teleport here', exact: true}).boundingBox(); + assert(teleportButton.y + teleportButton.height <= teleportBox.y); + assert(teleportBox.y + teleportBox.height <= 844, JSON.stringify({teleportBox, teleportButton})); + assert.equal(await teleportMap.evaluate(element => element.nextElementSibling), null); + await page.screenshot({path: output + '/mobile-teleport.png'}); + await page.setViewportSize({width: 1280, height: 900}); + await page.screenshot({path: output + '/teleport.png'}); + await page.getByLabel("Warp zones", {exact: true}).uncheck(); + const desktopTeleport = await teleportMap.boundingBox(); + await teleportMap.click({position: {x: desktopTeleport.width / 2 + 15, y: desktopTeleport.height / 2}}); + const destination = page.locator('[data-map-zone-choice]'); + if (await destination.isVisible()) await page.locator('[data-map-teleport] select').selectOption('705'); + assert.equal(await page.getByRole('button', {name: 'Teleport here', exact: true}).isEnabled(), true, await page.locator("[data-map-location]").textContent()); + assert(Number(await page.locator('[data-map-teleport] input[name=x]').inputValue()) > 960); + await page.getByRole('link', {name: 'Back to player', exact: true}).click(); await page.getByRole('link', {name: 'Change password', exact: true}).click(); await page.getByLabel('New password', {exact: true}).fill('x'); await page.getByRole('button', {name: 'Save password', exact: true}).click(); @@ -87,7 +111,7 @@ try { }); await page.getByLabel('NPCs', {exact: true}).check(); await page.locator('[data-map-find]').selectOption('705'); - await page.getByRole('button', {name: 'Zoom in', exact: true}).click(); + for (let i = 0; i < 5; i++) await page.getByRole('button', {name: 'Zoom in', exact: true}).click(); await page.waitForResponse(response => response.url().includes('admin/map-entities?') && response.ok()); const before = await page.locator('canvas').boundingBox(); await page.screenshot({path: output + '/map.png'}); @@ -126,7 +150,7 @@ try { const originalStream = game.worldStream; const editSequence = game.sequence; const originalRotation = game.local().rotation; - let response = await context.request.post(url + 'admin/teleport/1', {form: {playfield: '705', x: '980', z: '510'}}); + let response = await context.request.post(url + 'admin/players/1/teleport', {form: {playfield: '705', x: '980', z: '510'}}); assert(response.ok(), await response.text()); await game.wait('same-zone teleport', state => Math.abs(game.local(state).position[0] - 980) < 1 && Math.abs(game.local(state).position[2] - 510) < 1); assert.deepEqual(game.local().rotation, originalRotation); @@ -140,7 +164,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/users/1', {form: {data: 'inventory:\n slots: {inventory_slot_30: null}\n'}}); + response = await context.request.post(url + 'admin/players/1', {form: {data: 'inventory:\n slots: {inventory_slot_30: null}\n'}}); 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); @@ -165,7 +189,7 @@ try { await uploaded; assert(profileRequests.length > 0); - assert(mapResponses.every(response => response.npcs.length <= 500 && response.warps.length <= 500)); + assert(mapResponses.every(response => response.npcs.length <= 5000 && response.warps.length <= 5000)); assert.deepEqual(errors, []); assert.equal(game.errors.length, 0); console.log('PASS: admin/player password pages, styled login errors, expanding SQL table/CSV, responsive touch map, live teleport and inventory edits, native weather, profiling opt-in'); diff --git a/tools/client/verify_client_1491.py b/tools/client/verify_client_1491.py @@ -30,7 +30,7 @@ with socket.create_connection(('127.0.0.1', 7510), timeout=10) as connection: character_id = struct.unpack_from('>I', body, 12)[0] # View Bronto Burger and the building behind it from street level to the southwest. -url = f'http://127.0.0.1:8081/admin/users/{character_id}' +url = f'http://127.0.0.1:8081/admin/players/{character_id}' page = admin.open(url).read().decode() data = html.unescape(re.search(r'<textarea[^>]*>(.*?)</textarea>', page, re.S)[1]) assert 'return_door: null' in data diff --git a/tools/client/verify_game.py b/tools/client/verify_game.py @@ -43,7 +43,7 @@ with socket.create_connection(("127.0.0.1", 7510), timeout=10) as connection: character_id = struct.unpack_from(">I", body, 12)[0] # Match the approved stock Bronto Burger view and suppress first-run tutorials. -url = f"http://127.0.0.1:8081/admin/users/{character_id}" +url = f"http://127.0.0.1:8081/admin/players/{character_id}" page = admin.open(url).read().decode() data = html.unescape(re.search(r"<textarea[^>]*>(.*?)</textarea>", page, re.S)[1]) assert "return_door: null" in data