aorecomp

Anarchy Online classic in the browser

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


commit 73848d93ab4abcabd25f2ee30a8eaa342ab14271
parent e4c27b1dfd2e042bec843651538086a2b8a3d823
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 06:17:56 +0000

Refine player administration and keep ordinary edits live

Diffstat:
Mdocs/admin.md | 18++++++++++++------
Mdocs/browser-accounts.md | 2+-
Mserver/admin_auth.go | 30++++++++++++++++++++----------
Aserver/admin_live.go | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_live_test.go | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/admin_map.go | 2+-
Mserver/admin_pages.go | 8++++----
Aserver/admin_player_password.go | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_player_password_test.go | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/admin_test.go | 9++++++---
Mserver/assets/map.js | 14+++++++++-----
Mserver/browser_account.go | 4++--
Mserver/browser_account_test.go | 2+-
Mserver/control.go | 34++++++++++++++++++++++++++--------
Mserver/http.go | 2++
Mserver/item_pages.go | 2+-
Mserver/map_test.js | 27++++++++++++++++++++++++++-
Mserver/maps.go | 2+-
Mserver/users.go | 2+-
Mtools/client/test_admin.mjs | 39++++++++++++++++++++++++++++++++++++---
20 files changed, 503 insertions(+), 48 deletions(-)

diff --git a/docs/admin.md b/docs/admin.md @@ -23,15 +23,19 @@ 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. -Users provides existing character editors; players create accounts through the -game. Items retains catalog creation, ownership, assignment and instance editing. -Saving a character or owned item reconnects the affected player. +Players provides existing character editors and a separate Change password page; +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 +without reconnecting. Profile, equipment, backpack and bank changes, or inventory +edits during an open shop/trade or equipment transition, reload the player. +Password changes preserve the current game session and take effect on the next login. ## Map 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. NPC and warp layers default on. NPC requests start at 0.3 +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. @@ -100,5 +104,7 @@ 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, navigation, SQL writes and CSV, mobile map gestures, -and weather delivery/rendering in the actual WASM client through `GameTest`. +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 +carried-item additions/removals, weather delivery and profiling opt-in in the +actual WASM client through `GameTest`. diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md @@ -37,7 +37,7 @@ and digits, capitalize the first letter and lowercase the rest, then require Letters cannot follow digits. NUL-containing input is rejected. Visitor-prefixed names are reserved, and names are unique without ASCII case distinctions. Original server profanity/reservation lists remain unknown. Login applies the -same normalization. Passwords are nonempty and limited to 1024 +same normalization. Passwords may be empty and are limited to 1024 bytes, without trimming, case folding or composition rules. Claiming a name commits its name, salt, hash and replacement browser credential diff --git a/server/admin_auth.go b/server/admin_auth.go @@ -66,22 +66,17 @@ func (server *server) adminLogin(w http.ResponseWriter, r *http.Request) { return } if r.Method != http.MethodPost { - title, action := "Administrator login", "Log in" - if setup { - title, action = "Set up administrator", "Create administrator" - } - server.adminPageStart(w, title, "") - fmt.Fprintf(w, "<section class='login'><h1>%s</h1><form method='post' action='admin/login'><label>Username<input name='username' autocomplete='username' maxlength='64' required></label><label>Password<input name='password' type='password' autocomplete='%s' maxlength='1024'></label><button>%s</button></form></section></main></body></html>", title, map[bool]string{true: "new-password", false: "current-password"}[setup], action) + server.adminLoginPage(w, setup, "", "", http.StatusOK) return } r.Body = http.MaxBytesReader(w, r.Body, 8192) if err := r.ParseForm(); err != nil { - http.Error(w, "Invalid login form", 400) + server.adminLoginPage(w, setup, "", "Invalid login form", http.StatusBadRequest) return } name, password := strings.TrimSpace(r.PostForm.Get("username")), r.PostForm.Get("password") if name == "" || len(name) > 64 || len(password) > 1024 { - http.Error(w, "Invalid username or password", 400) + server.adminLoginPage(w, setup, name, "Invalid username or password", http.StatusBadRequest) return } var id int64 @@ -105,7 +100,7 @@ func (server *server) adminLogin(w http.ResponseWriter, r *http.Request) { return } if count != 1 { - http.Error(w, "Administrator already created. Log in.", http.StatusConflict) + server.adminLoginPage(w, false, name, "Administrator already created. Log in.", http.StatusConflict) return } id, err = result.LastInsertId() @@ -124,7 +119,7 @@ func (server *server) adminLogin(w http.ResponseWriter, r *http.Request) { } hash := server.browserPassword(password, salt) if id == 0 || subtle.ConstantTimeCompare(hash, expected) != 1 { - http.Error(w, "Incorrect username or password", http.StatusUnauthorized) + server.adminLoginPage(w, false, name, "Incorrect username or password", http.StatusUnauthorized) return } } @@ -142,6 +137,21 @@ func (server *server) adminLogin(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, server.baseURL+"admin", http.StatusSeeOther) } +func (server *server) adminLoginPage(w http.ResponseWriter, setup bool, name, message string, status int) { + title, action := "Administrator login", "Log in" + if setup { + title, action = "Set up administrator", "Create administrator" + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + server.adminPageStart(w, title, "") + fmt.Fprintf(w, "<section class='login'><h1>%s</h1>", title) + if message != "" { + fmt.Fprintf(w, "<p class='error' role='alert'>%s</p>", html.EscapeString(message)) + } + fmt.Fprintf(w, "<form method='post' action='admin/login'><label>Username<input name='username' value='%s' autocomplete='username' maxlength='64' required></label><label>Password<input name='password' type='password' autocomplete='%s' maxlength='1024'></label><button>%s</button></form></section></main></body></html>", html.EscapeString(name), map[bool]string{true: "new-password", false: "current-password"}[setup], action) +} + func (server *server) adminAccountsPage(w http.ResponseWriter, r *http.Request) { db, err := server.database() if err != nil { diff --git a/server/admin_live.go b/server/admin_live.go @@ -0,0 +1,121 @@ +package main + +import ( + "maps" + "slices" + "time" +) + +func (server *server) liveInventoryEdit_locked(player, updated *character) bool { + // Appearance, equipment and open transactions still use full initialization. + if client := server.clients[player.id]; client != nil && (!client.ready || client.loading || client.trade != nil || client.shop != nil || client.equipment != nil) { + return false + } + if player.profile() != updated.profile() || player.vitals() != updated.vitals() || player.record().Position != updated.record().Position { + return false + } + a, b := player.inventory, updated.inventory + if a.Credits != b.Credits || a.MapFlags != b.MapFlags || a.ClanTokens != b.ClanTokens || a.OmniTokens != b.OmniTokens || + !slices.Equal(a.Bank, b.Bank) || !slices.Equal(a.Reclaim, b.Reclaim) || !slices.Equal(a.LearnedNanos, b.LearnedNanos) || + !maps.EqualFunc(a.Containers, b.Containers, slices.Equal[[]ownedItem]) { + return false + } + for _, pair := range [][2][]ownedItem{{a.Items, b.Items}, {b.Items, a.Items}} { + for _, item := range pair[0] { + if (item.Slot < 64 || item.isPortableContainer()) && !slices.Contains(pair[1], item) { + return false + } + } + } + return true +} + +func (server *server) applyInventoryEdit_locked(player, updated *character) { + // Keep movement, combat and the connection intact after the durable write. + previous := player.inventory.Items + player.inventory = updated.inventory + player.savedProfile, player.savedPosition, player.savedVitals = updated.savedProfile, updated.savedPosition, updated.savedVitals + client := server.clients[player.id] + updates := make(map[*worldClient][][]byte) + if client != nil { + var occupied [30]bool + for _, item := range previous { + if item.Slot < 64 { + continue + } + if slices.Contains(player.inventory.Items, item) { + occupied[item.Slot-64] = true + continue + } + updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{112, 104, item.Slot})) + if item.Type == 51018 { + updates[client] = append(updates[client], n3Packet(0x36510078, item.Type, item.ID, nil)) + } + } + // Native additions choose first-free; move each item to its saved slot. + items := slices.Clone(player.inventory.Items) + slices.SortFunc(items, func(a, b ownedItem) int { return int(a.Slot) - int(b.Slot) }) + for _, item := range items { + if item.Slot < 64 || slices.Contains(previous, item) { + continue + } + updates[client] = append(updates[client], inventoryAdditionPacket(player, item)) + slot := uint32(64) + for occupied[slot-64] { + slot++ + } + if slot != item.Slot { + updates[client] = append(updates[client], itemMovePacket(player.id, slot, item.Slot)) + } + occupied[item.Slot-64] = true + } + } + server.mutex.Unlock() + server.sendCombatUpdates(updates) +} + +func (server *server) teleportWithinPlayfield_locked(player *character, destination userData) error { + // Hold updateMutex and mutex; commit the destination before touching live state. + updated := *player + updated.anchorMovement_locked(time.Now()) + updated.placePosition(destination.Position) + updated.returnDoor = destination.ReturnDoor + if err := server.savePosition_locked(&updated); err != nil { + server.mutex.Unlock() + return err + } + updates := make(map[*worldClient][][]byte) + server.cancelCombat_locked(player.id, updates) + client := server.clients[player.id] + server.cancelPlayerTrade_locked(client) + player.position, player.rotation, player.returnDoor = updated.position, updated.rotation, updated.returnDoor + player.savedPosition = updated.savedPosition + // The owner's correction changes position only, preserving facing and held input. + player.movement, player.body, player.roomState = updated.movement, updated.body, updated.roomState + if player.followTarget != 0 { + player.movement.action(player, 2) + player.movement.action(player, 4) + } + player.followTarget = 0 + if client != nil && client.ready { + if client.shop != nil { + if err := server.abortShop_locked(client); err != nil { + client.disconnect(client.conn) + } + } + if client.bank != nil { + client.bank = nil + updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{106})) + } + client.lootCorpse, client.dialogue = 0, nil + for _, observer := range server.clients { + if observer.ready && !observer.loading && server.characters[observer.id].playfield == player.playfield { + updates[observer] = append(updates[observer], playerFollowPacket(player.id, 0), npcMovementPacket(player, 0x94)) + } + } + updates[client] = append(updates[client], server.updateNPCInterest_locked(client, time.Now())...) + } + server.mutex.Unlock() + server.sendCombatUpdates(updates) + return nil +} diff --git a/server/admin_live_test.go b/server/admin_live_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "encoding/binary" + "math" + "net/http" + "net/url" + "slices" + "testing" + "time" +) + +func TestAdminCarriedItemChangesKeepSessionAndMovement(t *testing.T) { + world := newControlInventoryWorld(t) + player := world.characters[1] + connection := &combatInterestConn{} + client := &worldClient{id: 1, ready: true, conn: connection, target: true} + world.clients[1] = client + player.movement = heldPlayerMovement(player, 1, time.Now()) + movement := player.movement + created := postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) + if created.Code != http.StatusSeeOther { + t.Fatal(created.Body) + } + assigned := postControlForm(world, "/admin/items/5", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:93"}}) + if assigned.Code != http.StatusSeeOther || world.clients[1] != client || !client.ready || player.movement != movement || len(connection.packets) != 2 || binary.BigEndian.Uint32(connection.packets[1][16:20]) != 0x47537a24 { + t.Fatal("assignment reloaded the player or lost its saved slot", assigned.Code, assigned.Body, connection.packets) + } + restarted := newTestInventoryServer(t) + if !slices.Contains(restarted.characters[1].inventory.Items, ownedItem{ID: 5, Type: 51018, Template: 121567, Quality: 1, Slot: 93, Count: 1}) { + t.Fatal("assignment did not persist") + } + + connection.packets = nil + removed := postControlForm(world, "/admin/users/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) + } + for _, state := range []*server{world, restarted} { + if len(state.characters[1].inventory.Items) != 3 || state.items[5].Template != 121567 { + t.Fatal("removal lost the unassigned instance", state.characters[1].inventory.Items) + } + } + for _, packet := range connection.packets { + if opcode := binary.BigEndian.Uint32(packet[16:20]); opcode == 0x43197d22 || opcode == 0x3c { + t.Fatal("inventory edit sent a reconnect") + } + } + connection.packets = nil + if _, err := world.db.Exec("CREATE TRIGGER reject_inventory BEFORE UPDATE ON characters BEGIN SELECT RAISE(FAIL, 'test inventory'); END"); err != nil { + t.Fatal(err) + } + rejected := postControlForm(world, "/admin/items/5", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:93"}}) + if rejected.Code != http.StatusInternalServerError || len(player.inventory.Items) != 3 || world.clients[1] != client || !client.ready || len(connection.packets) != 0 { + t.Fatal("rejected assignment changed live state", rejected.Code, rejected.Body) + } +} + +func TestAdminSameZoneTeleportPreservesConnectionAndNotifiesObservers(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + player, observer := world.newCharacter(), 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}} + ownerConnection, observerConnection := &combatInterestConn{}, &combatInterestConn{} + client := &worldClient{id: player.id, ready: true, conn: ownerConnection, target: true, npcs: make(map[uint32]bool)} + world.clients[player.id] = client + world.clients[observer.id] = &worldClient{id: observer.id, ready: true, conn: observerConnection, target: true} + player.rotation = [4]float32{0, 0.70710677, 0, 0.70710677} + player.movement = heldPlayerMovement(player, 1, time.Now()) + rotation := player.rotation + + response := postControlForm(world, "/admin/teleport/1", 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 { + t.Fatalf("same-zone teleport: status=%d connected=%t ready=%t moving=%t position=%v saved=%v rotation=%v expected=%v: %s", response.Code, world.clients[1] == client, client.ready, player.movement.active(), player.position, restarted.characters[1].position, player.rotation, rotation, response.Body) + } + for axis, value := range player.rotation { + if math.Abs(float64(value-rotation[axis])) > 0.000001 { + t.Fatal("teleport changed facing", player.rotation, rotation) + } + } + for _, connection := range []*combatInterestConn{ownerConnection, observerConnection} { + moved := false + for _, packet := range connection.packets { + opcode := binary.BigEndian.Uint32(packet[16:20]) + if opcode == 0x43197d22 || opcode == 0x3c { + t.Fatal("same-zone teleport sent a reconnect") + } + moved = moved || opcode == 0x54111123 + } + if !moved { + t.Fatal("client did not receive the new pose") + } + } +} + +func TestAdminRejectedSameZoneTeleportLeavesSessionUntouched(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + player := world.newCharacter() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + 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}} + connection := &combatInterestConn{} + client := &worldClient{id: 1, ready: true, conn: connection} + world.clients[1] = client + if _, err := world.db.Exec("CREATE TRIGGER reject_position BEFORE UPDATE ON characters BEGIN SELECT RAISE(FAIL, 'test position'); END"); err != nil { + t.Fatal(err) + } + + response := postControlForm(world, "/admin/teleport/1", 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 @@ -79,7 +79,7 @@ func (server *server) mapEntities(w http.ResponseWriter, r *http.Request) { result.NPCs = append(result.NPCs, mapMarker{Name: character.name, Point: *p}) } } - if r.URL.Query().Get("warps") == "1" { + if r.URL.Query().Get("warps") == "1" && bounds[2]-bounds[0] <= 6000 && bounds[3]-bounds[1] <= 6000 { for zone, links := range server.zoneLinks["target"] { add := func(name string, position [3]float32, destination uint32, arrival *[3]float32) { p := point(zone, position) diff --git a/server/admin_pages.go b/server/admin_pages.go @@ -21,7 +21,7 @@ func (server *server) adminPageStart(w http.ResponseWriter, title, section strin </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"}, {"Users", "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/users"}, {"Items", "admin/items"}, {"SQL", "admin/sql"}, {"Admins", "admin/admins"}} { current := "" if item.name == section { current = " aria-current='page'" @@ -63,7 +63,7 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { for _, stat := range []struct { label string value any - }{{"Users", players}, {"Connected", connected}, {"Item instances", items}, {"NPCs", npcs}, {"Database + WAL", fmt.Sprintf("%.1f MB", float64(size)/1048576)}} { + }{{"Players", players}, {"Connected", connected}, {"Item instances", items}, {"NPCs", npcs}, {"Database + WAL", fmt.Sprintf("%.1f MB", float64(size)/1048576)}} { fmt.Fprintf(w, "<div>%s<strong>%v</strong></div>", stat.label, stat.value) } fmt.Fprint(w, "<div>Database queries / second<strong id='query-rate'>-</strong></div></div><section><h2>Game time</h2>") @@ -92,8 +92,8 @@ func (server *server) usersPage(w http.ResponseWriter, r *http.Request) { connected[id] = client.ready } server.mutex.Unlock() - server.adminPageStart(w, "Users", "Users") - fmt.Fprint(w, "<h1>Users</h1><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th></tr>") + server.adminPageStart(w, "Players", "Players") + fmt.Fprint(w, "<h1>Players</h1><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th></tr>") for _, player := range players { status := "Offline" if connected[player.ID] { diff --git a/server/admin_player_password.go b/server/admin_player_password.go @@ -0,0 +1,62 @@ +package main + +import ( + "crypto/rand" + "fmt" + "html" + "net/http" + "strconv" +) + +func (server *server) changePlayerPassword(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) + if err != nil { + http.NotFound(w, r) + 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() + + message := "" + if r.Method == http.MethodPost { + r.Body = http.MaxBytesReader(w, r.Body, 8192) + if err := r.ParseForm(); err != nil || !r.PostForm.Has("password") || len(r.PostForm.Get("password")) > 1024 { + message = "Invalid password" + } else { + // Password changes preserve the player's current game session. + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + hash := server.browserPassword(r.PostForm.Get("password"), salt) + db, err := server.database() + if err == nil { + _, err = db.Exec("UPDATE characters SET password_salt=?, password_hash=? WHERE id=?", salt, hash, id) + } + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d?password=saved", server.baseURL, id), http.StatusSeeOther) + return + } + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if message != "" { + w.WriteHeader(http.StatusBadRequest) + } + server.adminPageStart(w, "Change player password", "Players") + fmt.Fprintf(w, "<section class='login'><h1>Change password</h1><p>%s</p>", html.EscapeString(name)) + 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) +} diff --git a/server/admin_player_password_test.go b/server/admin_player_password_test.go @@ -0,0 +1,51 @@ +package main + +import ( + "bytes" + "fmt" + "net/http" + "strings" + "testing" +) + +func TestAdminChangesPlayerPasswordWithoutDisconnecting(t *testing.T) { + world := newTestServer(t) + visitor := accountVisitor(t, world) + if response := accountRequest(world, visitor, "claim", "Alice", "old"); response.Code != 204 { + t.Fatal(response.Body) + } + connection := &combatInterestConn{} + client := &worldClient{id: 1, ready: true, conn: connection} + world.clients[1] = client + 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) + page := adminRequest(handler, "GET", path, "", cookie) + unauthorized := adminRequest(handler, "POST", path, "password=wrong", nil) + changed := adminRequest(handler, "POST", path, "password=", cookie) + var salt, hash []byte + if err := world.db.QueryRow("SELECT password_salt,password_hash FROM characters WHERE id=1").Scan(&salt, &hash); err != nil { + t.Fatal(err) + } + + 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" { + 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 { + t.Fatal("password change did not preserve the live session or store a salted hash") + } + + // Verify the saved credential through the ordinary login route after restart. + restored := newTestInventoryServer(t) + restored.baseURL = "/" + other := accountVisitor(t, restored) + old := accountRequest(restored, other, "login", "Alice", "old") + current := accountRequest(restored, other, "login", "Alice", "") + if old.Code != 401 || current.Code != 204 { + t.Fatal("new credential did not survive restart", old.Code, current.Code, current.Body) + } +} diff --git a/server/admin_test.go b/server/admin_test.go @@ -67,6 +67,9 @@ func TestAdminSetupLoginLogoutAndExpiry(t *testing.T) { if len(salt) != 16 || len(hash) != 32 { t.Fatal("password not hashed") } + if !strings.Contains(wrong.Header().Get("Content-Type"), "text/html") || !strings.Contains(wrong.Body.String(), "<section class='login'>") || !strings.Contains(wrong.Body.String(), "role='alert'>Incorrect username or password") || !strings.Contains(wrong.Body.String(), "value='Operator'") || strings.Contains(wrong.Body.String(), "incorrect-password") { + t.Fatal("failed login lost the form styling or exposed the password", wrong.Body) + } } func TestAdminChangePassword(t *testing.T) { @@ -263,7 +266,7 @@ func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { players := adminRequest(handler, "GET", "/admin/map-players", "", cookie) offline := adminRequest(handler, "GET", "/admin/map-players?offline=1", "", cookie) entities := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=0&bottom=0&right=100&top=100&npcs=1&warps=1", "", cookie) - wide := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=0&bottom=0&right=7000&top=7000&npcs=1", "", cookie) + wide := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=0&bottom=0&right=7000&top=7000&npcs=1&warps=1", "", cookie) invalid := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=NaN&bottom=0&right=1&top=1", "", cookie) var result struct { NPCs, Warps []mapMarker @@ -279,8 +282,8 @@ func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { if len(result.NPCs) != 500 || 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) } - if !strings.Contains(wide.Body.String(), `"npcs":[]`) || invalid.Code != 400 { - t.Fatal("unbounded NPC request accepted") + 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/assets/map.js b/server/assets/map.js @@ -124,11 +124,15 @@ 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; + } + 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.scale >= 0.3 && right - left <= 6000 && top - bottom <= 6000; + const npcs = this.element.querySelector("[data-map-npcs]").checked && this.detailVisible(); return new URLSearchParams({view: this.view.value, left, bottom, right, top, - npcs: npcs ? "1" : "0", warps: this.element.querySelector("[data-map-warps]").checked ? "1" : "0"}).toString(); + npcs: npcs ? "1" : "0", warps: this.element.querySelector("[data-map-warps]").checked && this.detailVisible() ? "1" : "0"}).toString(); } resize() { @@ -356,7 +360,7 @@ class AOMap { pick(x, y) { for (const marker of this.entities.warps) { - if (!this.element.querySelector("[data-map-warps]").checked) break; + if (!this.detailVisible() || !this.element.querySelector("[data-map-warps]").checked) break; const screen = this.toScreen(...marker.point); if (Math.hypot(x - screen[0], y - screen[1]) < 14) { this.location.textContent = `${marker.name}: ${marker.destination}`; @@ -464,10 +468,10 @@ class AOMap { } } - // Keep dense NPC markers at useful zoom; warp destinations are labelled on tap. + // 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.element.querySelector(`[data-map-${kind}]`)?.checked || (kind === "npcs" && this.scale < 0.3)) continue; + if (!this.detailVisible() || !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; diff --git a/server/browser_account.go b/server/browser_account.go @@ -67,8 +67,8 @@ func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) { } name, validName := browserPlayerName(r.PostForm.Get("name")) password := r.PostForm.Get("password") - if !validName || len(password) == 0 || len(password) > 1024 { - http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a nonempty password (up to 1024 bytes).", http.StatusBadRequest) + if !validName || len(password) > 1024 { + http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a password up to 1024 bytes.", http.StatusBadRequest) return } var created *character diff --git a/server/browser_account_test.go b/server/browser_account_test.go @@ -121,7 +121,7 @@ func TestBrowserAccountLoginSwitchesOnlyAfterCorrectPassword(t *testing.T) { func TestBrowserAccountRejectsInvalidClaimsWithoutChangingVisitor(t *testing.T) { for _, scenario := range []struct{ name, password string }{ {"", "password"}, {"123Alice", "password"}, {"Abc", "password"}, {"Al\x00ice", "password"}, {"Ali1ce", "password"}, - {strings.Repeat("a", 255), "password"}, {"Visitor42", "password"}, {"vIsItOrAlice", "password"}, {"Alice", ""}, {"Alice", strings.Repeat("a", 1025)}, + {strings.Repeat("a", 255), "password"}, {"Visitor42", "password"}, {"vIsItOrAlice", "password"}, {"Alice", strings.Repeat("a", 1025)}, } { t.Run(fmt.Sprintf("name=%q/length=%d", scenario.name, len(scenario.password)), func(t *testing.T) { world := newTestServer(t) diff --git a/server/control.go b/server/control.go @@ -19,7 +19,7 @@ import ( func (server *server) userPage(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) if err != nil { - http.Error(w, "Invalid user", http.StatusBadRequest) + http.Error(w, "Invalid player", http.StatusBadRequest) return } server.mutex.Lock() @@ -43,11 +43,15 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { server.inventoryTables_locked(&itemTables, player.inventory) server.mutex.Unlock() - server.adminPageStart(w, "User", "Users") - fmt.Fprintf(w, "<h1>%s</h1><p>User %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected) + server.adminPageStart(w, "Player", "Players") + if r.URL.Query().Get("password") == "saved" { + 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.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 and reconnect</button></form>", data.ID, html.EscapeString(string(contents))) + 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.Fprint(w, itemTables.String()) fmt.Fprint(w, "</main></body></html>") } @@ -55,7 +59,7 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { func (server *server) editUser(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) if err != nil { - http.Error(w, "Invalid user", http.StatusBadRequest) + http.Error(w, "Invalid player", http.StatusBadRequest) return } server.updateMutex.Lock() @@ -74,7 +78,7 @@ func (server *server) editUser(w http.ResponseWriter, r *http.Request) { updated := data.character() updated.nextPositionSave = character.nextPositionSave if err == nil && data.ID != character.id { - err = fmt.Errorf("user ID cannot change") + err = fmt.Errorf("player ID cannot change") } if err == nil { err = data.Appearance.validate() @@ -214,7 +218,14 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) { } destination.Rotation = [4]float32{0, 0, 0, 1} destination.ReturnDoor = nil - if err := server.updateUser_locked(destination); err != nil { + server.mutex.Lock() + if character.playfield == destination.Playfield && (server.clients[character.id] == nil || !server.clients[character.id].loading) { + err = server.teleportWithinPlayfield_locked(character, destination) + } else { + server.mutex.Unlock() + err = server.updateUser_locked(destination) + } + if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -233,7 +244,7 @@ func (server *server) updateUser_locked(destination userData) error { character := server.characters[destination.ID] if character == nil || character.npc { server.mutex.Unlock() - return fmt.Errorf("unknown user") + return fmt.Errorf("unknown player") } updated := destination.character() updated.inventory = character.inventory @@ -283,6 +294,9 @@ func (server *server) prepareUser_locked(character, updated *character) { updated.buddies = character.buddies updated.missions = character.missions updated.pets = character.pets + if server.liveInventoryEdit_locked(character, updated) { + return + } // Reconnection cancels a pending cast; preserve its refund unless nano was edited. if updated.nano == character.nano { updated.nano = min(character.maximumNano(), character.nano+character.nanoReserved) @@ -293,6 +307,10 @@ func (server *server) prepareUser_locked(character, updated *character) { } func (server *server) applyUser_locked(character, updated *character) error { + if server.liveInventoryEdit_locked(character, updated) { + server.applyInventoryEdit_locked(character, updated) + return nil + } // Hold updateMutex and mutex; release mutex before sending reconnect packets. previousPlayfield := character.playfield updates := make(map[*worldClient][][]byte) diff --git a/server/http.go b/server/http.go @@ -69,6 +69,8 @@ func (server *server) adminHandler() http.Handler { 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/items", server.itemsPage) admin.HandleFunc("GET /admin/items/catalog", server.itemCatalogPage) admin.HandleFunc("POST /admin/items", server.createItem) diff --git a/server/item_pages.go b/server/item_pages.go @@ -272,7 +272,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "</select></label> <button>Assign item</button></form>") } } - fmt.Fprintf(w, "<h2>Instance properties</h2><form method='post' action='admin/items/%d'><textarea name='data' rows='25' cols='80' required>%s</textarea><p><button>Save and reconnect owner</button></p></form>", id, html.EscapeString(string(contents))) + fmt.Fprintf(w, "<h2>Instance properties</h2><form method='post' action='admin/items/%d'><textarea name='data' rows='25' cols='80' required>%s</textarea><p><button>Save</button></p></form>", id, html.EscapeString(string(contents))) if contentsTable.Len() != 0 { fmt.Fprint(w, "<h2>Contents</h2>", contentsTable.String()) } diff --git a/server/map_test.js b/server/map_test.js @@ -10,7 +10,7 @@ const AOMap = vm.runInNewContext(mapSource, { function mapWithTiles(tileSize, count, fetch) { const MapClass = vm.runInNewContext(mapSource, { - document: {querySelectorAll: () => []}, fetch, setTimeout, clearTimeout, + document: {querySelectorAll: () => []}, fetch, setTimeout, clearTimeout, URLSearchParams, createImageBitmap: async () => ({width: tileSize, height: tileSize, close() {}}), }); const elements = { @@ -31,6 +31,31 @@ function mapWithTiles(tileSize, count, fetch) { return map; } +test('detail layers require their checkbox, sufficient zoom and a bounded viewport', () => { + const map = mapWithTiles(1000, 1, () => {}); + const npcs = {checked: false}, warps = {checked: true}; + map.element.querySelector = selector => selector === '[data-map-npcs]' ? npcs : warps; + map.scale = 0.2; + let query = new URLSearchParams(map.entityQuery()); + assert.equal(query.get('npcs'), '0'); + assert.equal(query.get('warps'), '0'); + + map.scale = 0.3; + query = new URLSearchParams(map.entityQuery()); + assert.equal(query.get('npcs'), '0'); + assert.equal(query.get('warps'), '1'); + npcs.checked = true; + 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; + query = new URLSearchParams(map.entityQuery()); + assert.equal(query.get('npcs'), '0'); + assert.equal(query.get('warps'), '0'); +}); + 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 @@ -10,7 +10,7 @@ import ( ) 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 checked>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, "<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) 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) } diff --git a/server/users.go b/server/users.go @@ -96,7 +96,7 @@ func (data userData) validate() error { func (data userData) validateFields() error { if data.ID == 0 || data.ID >= 1000000 { - return fmt.Errorf("user ID must be between 1 and 999999") + return fmt.Errorf("player ID must be between 1 and 999999") } if len(strings.TrimSpace(data.Name)) == 0 || len(data.Name) > 254 || strings.ContainsRune(data.Name, 0) { return fmt.Errorf("name must contain 1-254 bytes without a NUL") diff --git a/tools/client/test_admin.mjs b/tools/client/test_admin.mjs @@ -43,12 +43,22 @@ try { await page.screenshot({path: output + '/admins.png'}); await page.getByRole('button', {name: 'Log out', exact: true}).click(); await page.getByLabel('Username').fill('Reviewer'); + await page.getByLabel('Password', {exact: true}).fill('wrong'); + await page.getByRole('button', {name: 'Log in', exact: true}).click(); + await page.getByRole('alert').filter({hasText: 'Incorrect username or password'}).waitFor(); + assert.equal(await page.locator('section.login').count(), 1); + assert.equal(await page.getByLabel('Username').inputValue(), 'Reviewer'); await page.getByLabel('Password', {exact: true}).fill(''); await page.getByRole('button', {name: 'Log in', exact: true}).click(); await page.getByRole('heading', {name: 'General', exact: true}).waitFor(); - await page.getByRole('link', {name: 'Users', exact: true}).click(); + await page.getByRole('link', {name: 'Players', exact: true}).click(); 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(); + 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(); + await page.getByRole('status').filter({hasText: 'Password changed.'}).waitFor(); await page.getByRole('link', {name: 'SQL', exact: true}).click(); await page.getByLabel('Query', {exact: true}).fill("CREATE TABLE admin_browser_test (value TEXT); INSERT INTO admin_browser_test VALUES ('a,b'); SELECT * FROM admin_browser_test"); await page.getByRole('button', {name: 'Run query'}).click(); @@ -69,12 +79,13 @@ try { await page.getByRole('link', {name: 'Map', exact: true}).click(); await page.waitForFunction(() => document.querySelector('[data-map-status]').textContent.includes('connected players')); assert.equal(await page.getByLabel('Offline players', {exact: true}).isChecked(), false); - assert.equal(await page.getByLabel('NPCs', {exact: true}).isChecked(), true); + assert.equal(await page.getByLabel('NPCs', {exact: true}).isChecked(), false); assert.equal(await page.getByLabel('Warp zones', {exact: true}).isChecked(), true); const mapResponses = []; page.on('response', async response => { if (response.url().includes('admin/map-entities?') && response.ok()) mapResponses.push(await response.json()); }); + 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(); await page.waitForResponse(response => response.url().includes('admin/map-entities?') && response.ok()); @@ -112,6 +123,28 @@ try { game = await GameTest.attach(client); await client.goto(url); await game.ready(); + 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'}}); + 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); + const players = await (await context.request.get(url + 'admin/map-players')).json(); + const teleported = players.players.find(player => player.id === 1); + assert(teleported.rotation.every((value, axis) => Math.abs(value - originalRotation[axis]) < 0.01)); + assert(Math.abs(teleported.position[0] - 980) < 1 && Math.abs(teleported.position[2] - 510) < 1); + response = await context.request.post(url + 'admin/items', {form: {template: '121567'}}); + assert(response.ok(), await response.text()); + const itemId = Number(response.url().split('/').pop()); + 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'}}); + 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); + assert(!game.events.some(event => event.sequence > editSequence && event.direction === 'framereceived' && ['43197d22', '0000003c'].includes(event.opcode))); for (const [value, name, type] of [['1', 'clear', 3], ['2', 'rain', 0], ['3', 'clouds', 2], ['4', 'fog', 1]]) { const sequence = game.sequence; await page.getByLabel('Conditions', {exact: true}).selectOption(value); @@ -135,7 +168,7 @@ try { assert(mapResponses.every(response => response.npcs.length <= 500 && response.warps.length <= 500)); assert.deepEqual(errors, []); assert.equal(game.errors.length, 0); - console.log('PASS: admin account creation/password pages, login/logout, expanding SQL table/CSV, responsive touch map, native weather, profiling off by default and explicit opt-in'); + 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'); } finally { await browser.close(); }