aorecomp

Anarchy Online classic in the browser

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


commit f683e1508329a92bddf289b3670aa9b809dadfaa
parent c24e29258d97d457465f8ec4560c9d14509bee5d
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 05:14:16 +0000

Protect /admin and add launch administration tools

Diffstat:
MDEVELOPERS.md | 15++++++++-------
MREADME.md | 7++++---
MTODO.md | 7+++++--
Adocs/admin.md | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/alpha-readiness.md | 2+-
Mdocs/combat-regeneration.md | 2+-
Mdocs/inventory.md | 6+++---
Aserver/admin_auth.go | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_browser_test.go | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_fixture_test.go | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_map.go | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_pages.go | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_sql.go | 34++++++++++++++++++++++++++++++++++
Aserver/admin_test.go | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_weather.go | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/admin_weather_test.go | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/appearance_test.go | 14+++++++-------
Mserver/armor_quality_test.go | 6+++---
Mserver/assets/map.js | 144++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mserver/backpack_quality_test.go | 6+++---
Mserver/bank_storage_test.go | 24++++++++++++------------
Mserver/browser_pending_edit_test.go | 1+
Mserver/buddies_test.go | 2+-
Mserver/checkpoint_test.go | 2+-
Mserver/control.go | 69+++++++--------------------------------------------------------------
Mserver/control_containers_test.go | 20++++++++++----------
Mserver/control_data_test.go | 108++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mserver/control_equipment_slots_test.go | 10+++++-----
Mserver/control_inventory.go | 4++--
Mserver/control_inventory_test.go | 58+++++++++++++++++++++++++++++-----------------------------
Mserver/control_test.go | 16++++++++--------
Mserver/database.go | 7+------
Aserver/database_metrics.go | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/database_test.go | 10+++++-----
Mserver/embedded_resources_test.go | 4++--
Mserver/fling_crash_test.go | 4+---
Mserver/flying_vehicle_test.go | 2+-
Mserver/http.go | 89+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Mserver/http_test.go | 18+++++++++---------
Mserver/insurance_experience_test.go | 2+-
Mserver/inventory_write_test.go | 12++++++------
Mserver/item_pages.go | 37++++++++++++++++++++-----------------
Mserver/item_store_test.go | 52++++++++++++++++++++++++++--------------------------
Mserver/main.go | 4++--
Mserver/main_test.go | 8++++----
Mserver/map_test.js | 40++++++++++++++++++++++++++++++++++++++--
Mserver/maps.go | 9++++++---
Mserver/maps_test.go | 8++++----
Mserver/nano_reservation_test.go | 2+-
Mserver/nano_visibility_test.go | 4++--
Mserver/ncu_hacker_interface_test.go | 4++--
Mserver/player_follow_test.go | 4++--
Mserver/player_movement.go | 1+
Mserver/progression_test.go | 20++++++++++----------
Mserver/ranged_test.go | 8++++----
Mserver/shop_control_edit_test.go | 10+++++-----
Mserver/state.go | 26+++++++++++++++-----------
Mserver/target_protocol_test.go | 2+-
Mserver/users_test.go | 40++++++++++++++++++++--------------------
Mserver/vehicle_test.go | 2+-
Mserver/world.sql | 17+++++++++++++++++
Mserver/world_store.go | 3+++
Mtools/client/server_fixture.py | 27+++++++++++++++++++++++++++
Mtools/client/sweep_browser.py | 15+++++++++------
Mtools/client/sweep_playfields.py | 15+++++++++------
Atools/client/test_admin.mjs | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/client/test_pending_edit.mjs | 2+-
Mtools/client/verify_client_1491.py | 12++++++++----
Mtools/client/verify_game.py | 11+++++++----
Mtools/client/verify_linux_game.py | 2+-
70 files changed, 1960 insertions(+), 458 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -40,7 +40,7 @@ stop can lose simulation changes since the last checkpoint. Ctrl+C or SIGTERM flushes player positions and world state before closing the database; check `logs/server.log` for shutdown errors. -The control panel's YAML is an editing format generated from the current state. +The admin dashboard's YAML is an editing format generated from the current state. Saving it validates and writes the database; there are no per-player YAML storage files. HTTPS key/certificate files are separate and use atomic file replacement. @@ -55,13 +55,13 @@ on the server build machine. Rebuild the Go binary after updating resources. Requires Go 1.26 or newer. The server listens on all network interfaces. Default ports are login 7500, world 7501, chat 7502, HTTP 8080 and HTTPS 8443. Chat uses the port immediately after the world port. From another machine, -open `https://<server-address>:8443/` or `/control`. On first startup, Go +open `https://<server-address>:8443/` or `/admin`. On first startup, Go creates a self-signed certificate in `data/https/cert.pem` and a private key in `data/https/key.pem`; both stay out of Git. Trust the certificate on the client machine before playing: shared WebAssembly memory requires trusted HTTPS. The certificate covers the server hostname and current IP addresses for one year. If those change, remove both files and restart to generate a new certificate. -HTTP remains available, including `http://<server-address>:8080/control`. +HTTP remains available, including `http://<server-address>:8080/admin`. For an existing installation, move `local/https/` to `data/https/` before restarting to preserve the trusted certificate. Existing `local/profiles/` files can be moved to `logs/profiles/`. Server messages are appended to @@ -77,7 +77,8 @@ To serve the game under a prefix such as `/share/demo/`, pass `-base-url /share/demo/` to the server. Configure the reverse proxy to preserve that path and the Host header, forward WebSocket upgrades, and mark `ao_client` secure when using HTTPS. The cookie is scoped to the -prefix. Game and control pages have no login. +prefix. The admin dashboard requires a separate administrator login; initialize +the first account before public exposure. See [administration](docs/admin.md). Keep saved player data and logs outside the public static directory. @@ -179,8 +180,8 @@ limit applies to login replay. Back up `data/` to preserve both characters and chat. History errors are reported in the server log while live chat remains available. -[Server controls](http://127.0.0.1:8080/control) -provide character editing, teleporting and time controls. +[Administration](http://127.0.0.1:8080/admin) +provides character/item editing, map teleporting, time/weather controls and SQL. PvE combat is available against admitted creature profiles. Select an enemy with Tab or a click, approach within the weapon's range, then press Q (or the @@ -219,7 +220,7 @@ Bronto Burger, Lush Fields and Newland have passed browser rendering, movement, inventory/map, audio and connection checks. Performance work and broader gameplay validation continue. For native clients, keep the server running in a separate terminal and use the -commands below. Creating a character in server controls also works. +commands below. Players create accounts through the game. ### Build the browser client on Debian diff --git a/README.md b/README.md @@ -16,8 +16,9 @@ Replace them with your public deployment URLs. [Play ao](/share/demo/) in your browser. No installation is needed. The first load can take a few minutes. -The [control panel](/share/demo/control) lets you edit characters, -teleport, and adjust the time of day. +The [admin dashboard](/share/demo/admin) lets you edit characters, +teleport, control time and weather, and query the database. It requires an +administrator account. ## 2. Run your own server @@ -38,7 +39,7 @@ If macOS blocks the first launch, open **System Settings > Privacy & Security**, scroll down and click **Open Anyway**, then confirm **Open** in the prompt. Keep the server running and open [localhost:8080](http://localhost:8080/) to play, -or [localhost:8080/control](http://localhost:8080/control) for the control panel. +or [localhost:8080/admin](http://localhost:8080/admin) for the admin dashboard. Create the first administrator on first visit. See the [server setup guide](DEVELOPERS.md#server-build-and-operation) for access from other devices. diff --git a/TODO.md b/TODO.md @@ -110,8 +110,11 @@ research separately. More screenshots and test cases do not count as new gamepla Keep a compact matrix of passed paths and specific remaining failures. - [ ] **A8: Isolate administration before public hosting.** The current HTTP - and HTTPS listeners expose the same handler, including unauthenticated - character/item/time/teleport controls. Completion: a public client cannot + and HTTPS listeners share a handler. Administration now requires separate + admin credentials under `/admin`, with first-admin setup, expiring sessions + and cross-origin write protection. Remaining release check: decide access to + the public browser-profile upload endpoint and verify deployment provisioning. + Completion: a public client cannot read or mutate administrative state through those routes, while the intended local administration path still works. Verify the actual launch configuration and keep any test/debug endpoints out of the public server. diff --git a/docs/admin.md b/docs/admin.md @@ -0,0 +1,100 @@ +# Administration + +Open `/admin` or `/admin/`. On an empty `admin_users` table, the login page +creates the first administrator. Complete this setup before exposing the server +to other people. Later visits require that username and password. Passwords need +at least 12 characters and use the same salted Argon2id implementation as player +accounts. Admin accounts are separate from players; there is no recovery flow. + +Sessions expire after 12 hours, survive server restarts, and are revoked on +logout. Cookies are HttpOnly, SameSite=Strict, scoped to the mounted admin path, +and Secure on HTTPS. All admin pages, actions, map feeds and assets pass through +the same authentication boundary on both listeners. Cross-origin writes are +rejected. `/control` and its descendants no longer exist. Use HTTPS for remote +administration. The browser profile upload endpoint is outside this change and +still needs a public-release policy under TODO A8. + +General shows player, connection, instance, NPC and database-size counts, game +time and weather. Query rate samples driver executions over two seconds, +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. + +## 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 +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. + +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 +where both endpoints have map coordinates. Return doors have a player-dependent +entry destination. This layer does not enumerate generated mission instances. + +## SQL + +The SQL console runs reads and writes against `data/world.sqlite`, with starter +queries for tables, players, items, NPCs and administrators. It displays the +most recent result set as a table or CSV, switching without executing again. +Multiple statements use SQLite's own statement-completeness parser, including +quoted semicolons and trigger bodies. Statements run once, in order. Use an +explicit `BEGIN`/`COMMIT` batch for atomic multi-statement changes. An error stops +the batch; earlier autocommitted statements remain committed. + +Each submission gets a separate connection, so console PRAGMAs or unfinished +transactions cannot affect the game's connection. Closing that connection rolls +back unfinished transactions. Queries have a five-second deadline and displayed +output is limited to 1000 rows or approximately 2 MiB. The console is trusted +administrator access, including writes to administration tables. + +The game holds live characters, NPCs, items and settings in memory. SQL does not +reload that state. Checkpoints can overwrite direct changes; use the normal +editors for live changes, or restart to load SQL edits. Back up the database +before destructive queries. + +## Weather + +Automatic leaves the client's ordinary environment behavior alone. Clear, Rain, +Clouds, and Fog and clouds send the original `WeatherControlIIR_t` message to +connected 14.9.1 clients. The selection is stored in `admin_settings` and restored +on startup. The movement loop refreshes an override every five seconds. Each +spatial effect fades in for one second, holds for four, and fades out for one; +switching or returning to Automatic settles within six seconds. Joining or zoning +clients receive the override at the next refresh. + +These are explicit preview presets, not recovered historical weather schedules: +70% intensity, neutral white ambient light, temperature 20, no wind/earthquake, +and fog RGB 160/170/180 with 25% density only in the fog preset. The radius is +1,000,000 units around each recipient's global position. Short effects avoid +accumulating permanent weather events. Automatic restores the original behavior +when the last short effect expires. + +Protocol evidence is original `kkr.dll` SHA-256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`: +`WeatherControlIIR_t::Read` at `0x100dbe30`, activation at `0x100dc120`, field +conversion/queue at `0x100da960`, lifetime at `0x100dad00`, spatial attenuation at +`0x100dae90`, and rendering at `0x100db3f0`. Lifted equivalents are in +`client/game/kkr.dll/lifted-0063.c`. The N3 key is `0x0c5a5d6d`; its 43-byte payload +contains fade/hold durations, radius, weather/effect bytes, ambient and fog RGB, +global XYZ center, and initial age. Local debug-weather AFCM identifiers are not +network packet identifiers. + +## Focused checks + +```sh +go test ./server -run '^(TestAdmin|TestControl|TestHTTPHandler|TestSetGameTime|TestMapPlayers|TestMapTeleport)' -count=1 -timeout=5m +node --test server/map_test.js +AO_GAME_TEST=1 go test ./server -run '^TestAdminBrowser$' -count=1 -timeout=7m -v +``` + +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`. diff --git a/docs/alpha-readiness.md b/docs/alpha-readiness.md @@ -89,7 +89,7 @@ ownership/dependency problems justify the change. A separate public-launch issue is concrete: `main.go` binds HTTP/HTTPS on all interfaces using `httpHandler`, and that handler registers unauthenticated -`/control` character, inventory, time and teleport routes. The plan includes +`/admin` character, inventory, time and teleport routes. The plan includes isolating administration before public hosting. A reverse proxy might already restrict a deployment, but the source does not guarantee that isolation. 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 `/control/users/<id>` shows one YAML document +The character editor at `/admin/users/<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 @@ -19,16 +19,16 @@ its own `slots`, numbered 1 through 21. These reference item IDs too; backpacks cannot contain backpacks. Item properties and placement have one authoritative source rather than being duplicated in each player's save. -`/control/items` lists instances with names, qualities, counts, owners and +`/admin/items` lists instances with names, qualities, counts, owners and locations. Search matches instance IDs, templates, names and owners. Clicking an instance opens its editable YAML properties and read-only catalog record. Both lists show 500 matching rows per page and retain filters in navigation. -`/control/items/catalog` filters templates by name or ID. Each row creates an +`/admin/items/catalog` filters templates by name or ID. Each row creates an 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 `/control/users/<owner>` shows one editable YAML document +The character page at `/admin/users/<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_auth.go b/server/admin_auth.go @@ -0,0 +1,161 @@ +package main + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "database/sql" + "fmt" + "net/http" + "strings" + "time" +) + +func (server *server) adminAuth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Referrer-Policy", "same-origin") + if r.URL.Path == "/admin/login" { + server.adminLogin(w, r) + return + } + db, err := server.database() + if err != nil { + http.Error(w, err.Error(), 500) + return + } + var valid bool + if cookie, cookieErr := r.Cookie("ao_admin"); cookieErr == nil { + hash := sha256.Sum256([]byte(cookie.Value)) + err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM admin_sessions JOIN admin_users ON admin_users.id=admin_sessions.admin_id WHERE token_hash=? AND expires_at>?)", hash[:], time.Now().Unix()).Scan(&valid) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + } + if !valid { + if r.Method == http.MethodGet || r.Method == http.MethodHead { + http.Redirect(w, r, server.baseURL+"admin/login", http.StatusSeeOther) + } else { + http.Error(w, "Administrator login required", http.StatusUnauthorized) + } + return + } + next.ServeHTTP(w, r) + }) +} + +func (server *server) adminLogin(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodPost { + w.Header().Set("Allow", "GET, HEAD, POST") + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + db, err := server.database() + if err != nil { + http.Error(w, err.Error(), 500) + return + } + var setup bool + if err = db.QueryRow("SELECT NOT EXISTS(SELECT 1 FROM admin_users)").Scan(&setup); err != nil { + http.Error(w, err.Error(), 500) + 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' minlength='12' maxlength='1024' required></label><button>%s</button></form></section></main></body></html>", title, map[bool]string{true: "new-password", false: "current-password"}[setup], action) + return + } + r.Body = http.MaxBytesReader(w, r.Body, 8192) + if err := r.ParseForm(); err != nil { + http.Error(w, "Invalid login form", 400) + return + } + name, password := strings.TrimSpace(r.PostForm.Get("username")), r.PostForm.Get("password") + if name == "" || len(name) > 64 || len(password) < 12 || len(password) > 1024 { + http.Error(w, "Use a username and a password of at least 12 characters", 400) + return + } + var id int64 + var salt, expected []byte + if setup { + salt = make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + http.Error(w, err.Error(), 500) + return + } + hash := server.browserPassword(password, salt) + // A single conditional insert admits exactly one initial administrator. + result, err := db.Exec("INSERT INTO admin_users (username, password_salt, password_hash) SELECT ?, ?, ? WHERE NOT EXISTS(SELECT 1 FROM admin_users)", name, salt, hash) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + count, err := result.RowsAffected() + if err != nil { + http.Error(w, err.Error(), 500) + return + } + if count != 1 { + http.Error(w, "Administrator already created. Log in.", http.StatusConflict) + return + } + id, err = result.LastInsertId() + if err != nil { + http.Error(w, err.Error(), 500) + return + } + } else { + err = db.QueryRow("SELECT id, password_salt, password_hash FROM admin_users WHERE username=? COLLATE NOCASE", name).Scan(&id, &salt, &expected) + if err != nil && err != sql.ErrNoRows { + http.Error(w, err.Error(), 500) + return + } + if err == sql.ErrNoRows { + salt = make([]byte, 16) + } + hash := server.browserPassword(password, salt) + if id == 0 || subtle.ConstantTimeCompare(hash, expected) != 1 { + http.Error(w, "Incorrect username or password", http.StatusUnauthorized) + return + } + } + token := rand.Text() + hash := sha256.Sum256([]byte(token)) + if _, err := db.Exec("DELETE FROM admin_sessions WHERE expires_at<=?", time.Now().Unix()); err != nil { + http.Error(w, err.Error(), 500) + return + } + if _, err := db.Exec("INSERT INTO admin_sessions (token_hash, admin_id, expires_at) VALUES (?, ?, ?)", hash[:], id, time.Now().Add(12*time.Hour).Unix()); err != nil { + http.Error(w, err.Error(), 500) + return + } + http.SetCookie(w, &http.Cookie{Name: "ao_admin", Value: token, Path: server.baseURL + "admin", HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteStrictMode, MaxAge: 43200}) + http.Redirect(w, r, server.baseURL+"admin", http.StatusSeeOther) +} + +func (server *server) adminLogout(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("ao_admin") + if err != nil { + http.Error(w, "Administrator login required", 401) + return + } + db, err := server.database() + if err != nil { + http.Error(w, err.Error(), 500) + return + } + hash := sha256.Sum256([]byte(cookie.Value)) + if _, err := db.Exec("DELETE FROM admin_sessions WHERE token_hash=?", hash[:]); err != nil { + http.Error(w, err.Error(), 500) + return + } + http.SetCookie(w, &http.Cookie{Name: "ao_admin", Path: server.baseURL + "admin", HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteStrictMode, MaxAge: -1}) + http.Redirect(w, r, server.baseURL+"admin/login", http.StatusSeeOther) +} diff --git a/server/admin_browser_test.go b/server/admin_browser_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "ao/server/assets" + "context" + "crypto/sha256" + "fmt" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestAdminBrowser(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for admin UI and native weather verification") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + useNPCData(t, testNPCData()) + useResources(t, assets.Files) + world := newTestServer(t) + world.baseURL = "/share/test/" + player := world.newCharacter() + player.name = "Admin Browser" + player.playfield = 705 + player.position = [3]float32{960, 16.5, 510} + player.rotation = [4]float32{0, 0.9238795, 0, -0.3826834} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("admin-browser"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + host := httptest.NewServer(world.httpHandler()) + defer host.Close() + stop := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advancePlayerMovement(now) + case <-stop: + return + } + } + }() + defer func() { close(stop); <-done }() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_admin.mjs"), host.URL+world.baseURL, filepath.Join(root, "local/admin-browser")) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + + if err := command.Run(); err != nil { + t.Fatal(err) + } + + world.mutex.Lock() + defer world.mutex.Unlock() + if world.weather != 0 { + t.Fatal("automatic weather was not restored") + } + var count int + if err := world.db.QueryRow("SELECT count(*) FROM admin_users").Scan(&count); err != nil || count != 1 { + t.Fatal(count, err) + } +} diff --git a/server/admin_fixture_test.go b/server/admin_fixture_test.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" +) + +// 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" { + world.createUser(w, r) + return + } + path := strings.TrimPrefix(r.URL.Path, strings.TrimSuffix(world.baseURL, "/")) + if path == "/admin" || strings.HasPrefix(path, "/admin/") { + http.StripPrefix(strings.TrimSuffix(world.baseURL, "/"), world.adminHandler()).ServeHTTP(w, r) + return + } + world.httpHandler().ServeHTTP(w, r) +} + +func adminTestHandler(world *server) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { serveAdminTestRequest(world, w, r) }) +} + +func adminRequest(handler http.Handler, method, path, body string, cookie *http.Cookie) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if cookie != nil { + request.AddCookie(cookie) + } + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + return response +} + +// Create isolated characters for persistence and editor tests. +func (server *server) createUser(w http.ResponseWriter, r *http.Request) { + name := strings.TrimSpace(r.FormValue("name")) + server.mutex.Lock() + player := server.newCharacter_locked() + player.name = name + if err := player.userData().validate(); err != nil { + delete(server.characters, player.id) + server.nextCharacter-- + server.mutex.Unlock() + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + err := server.saveUser_locked(player) + if err != nil { + delete(server.characters, player.id) + server.nextCharacter-- + } + server.mutex.Unlock() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d", server.baseURL, player.id), http.StatusSeeOther) +} diff --git a/server/admin_map.go b/server/admin_map.go @@ -0,0 +1,132 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/json" + "math" + "net/http" + "strconv" +) + +type mapMarker struct { + Name string `json:"name"` + Point [2]float64 `json:"point"` + Destination string `json:"destination,omitempty"` + Target *[2]float64 `json:"target,omitempty"` +} + +func (server *server) mapEntities(w http.ResponseWriter, r *http.Request) { + // The client supplies a viewport, never an unbounded NPC enumeration. + var bounds [4]float64 + for index, name := range []string{"left", "bottom", "right", "top"} { + value, err := strconv.ParseFloat(r.URL.Query().Get(name), 64) + if err != nil || math.IsNaN(value) || math.IsInf(value, 0) { + http.Error(w, "Invalid viewport", 400) + return + } + bounds[index] = value + } + if bounds[2] <= bounds[0] || bounds[3] <= bounds[1] || bounds[2]-bounds[0] > 100000 || bounds[3]-bounds[1] > 100000 { + http.Error(w, "Invalid viewport", 400) + return + } + view := r.URL.Query().Get("view") + playfield := uint64(0) + if view != "world" { + var err error + playfield, err = strconv.ParseUint(view, 10, 32) + if err != nil || playfield == 0 { + http.Error(w, "Invalid playfield", 400) + return + } + } + point := func(zone uint32, position [3]float32) *[2]float64 { + result := [2]float64{float64(position[0]), float64(position[2])} + if view == "world" { + origin, known := gamedata.MapCoordinates.Playfields[zone] + if !known { + return nil + } + result[0] += float64(origin[0]) + result[1] += float64(origin[1]) + } else if zone != uint32(playfield) { + return nil + } + return &result + } + visible := func(p *[2]float64) bool { + return p != nil && p[0] >= bounds[0] && p[0] <= bounds[2] && p[1] >= bounds[1] && p[1] <= bounds[3] + } + result := struct { + NPCs []mapMarker `json:"npcs"` + Warps []mapMarker `json:"warps"` + 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 !character.npc || character.health == 0 { + continue + } + p := point(character.playfield, character.position) + if !visible(p) { + continue + } + if len(result.NPCs) == 500 { + result.Limited = true + break + } + result.NPCs = append(result.NPCs, mapMarker{Name: character.name, Point: *p}) + } + } + if r.URL.Query().Get("warps") == "1" { + for zone, links := range server.zoneLinks["target"] { + 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 { + result.Limited = true + return + } + marker := mapMarker{Name: name, Point: *p, Destination: gamedata.Playfields[destination].Name + " (" + strconv.FormatUint(uint64(destination), 10) + ")"} + if name == "Return door" { + marker.Destination = "Entry point" + } else if destination == 0 { + marker.Destination = "Dynamic destination" + } else if arrival != nil { + marker.Target = point(destination, *arrival) + } + result.Warps = append(result.Warps, marker) + } + for _, door := range links.Doors { + var arrival *[3]float32 + if door.Arrival != nil { + arrival = &door.Arrival.Position + } else { + for _, target := range server.zoneLinks["target"][door.Destination].Doors { + if target.ID == door.DestinationDoor { + p := target.Position + arrival = &p + break + } + } + } + name := "Door" + if door.Return { + name = "Return door" + } + add(name, door.Position, door.Destination, arrival) + } + for _, wall := range links.Walls { + position := [3]float32{(wall.Start[0] + wall.End[0]) / 2, (wall.Start[1] + wall.End[1]) / 2, (wall.Start[2] + wall.End[2]) / 2} + arrival := [3]float32{(wall.ArrivalStart[0] + wall.ArrivalEnd[0]) / 2, (wall.ArrivalStart[1] + wall.ArrivalEnd[1]) / 2, (wall.ArrivalStart[2] + wall.ArrivalEnd[2]) / 2} + add("Zone border", position, wall.Destination, &arrival) + } + } + } + server.mutex.Unlock() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(result) +} diff --git a/server/admin_pages.go b/server/admin_pages.go @@ -0,0 +1,222 @@ +package main + +import ( + "ao/server/gamedata" + "context" + "database/sql" + "encoding/csv" + "encoding/json" + "fmt" + "html" + "net/http" + "os" + "strings" + "time" +) + +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}.scroll{overflow:auto;max-height:65vh}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}} + </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"}} { + current := "" + if item.name == section { + current = " aria-current='page'" + } + fmt.Fprintf(w, "<a href='%s'%s>%s</a>", item.path, current, item.name) + } + fmt.Fprint(w, "</nav><form method='post' action='admin/logout'><button>Log out</button></form></header>") + } + fmt.Fprint(w, "<main>") +} + +func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { + server.mutex.Lock() + seconds := int(server.gameSeconds_locked()) + weather := server.weather + players, connected, npcs := 0, 0, 0 + for _, character := range server.characters { + if character.npc { + npcs++ + } else { + players++ + } + } + for _, client := range server.clients { + if client.ready { + connected++ + } + } + items := len(server.items) + server.mutex.Unlock() + var size int64 + for _, path := range []string{"data/world.sqlite", "data/world.sqlite-wal"} { + if info, err := os.Stat(path); err == nil { + size += info.Size() + } + } + server.adminPageStart(w, "General", "General") + fmt.Fprint(w, "<h1>General</h1><div class='cards'>") + 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)}} { + 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>") + fmt.Fprintf(w, "<p>Game time: %02d:%02d</p><form method='post' action='admin/time'><label>Hour (0-26)<input type='number' name='hour' min='0' max='26' value='%d' required></label><label>Minute<input type='number' name='minute' min='0' max='59' value='%d' required></label><button>Set time</button></form></section>", seconds/3600, seconds/60%60, seconds/3600, seconds/60%60) + fmt.Fprint(w, "<section><h2>Weather</h2><form method='post' action='admin/weather'><label>Conditions<select name='weather' aria-label='Conditions'>") + for value, name := range []string{"Automatic", "Clear", "Rain", "Clouds", "Fog and clouds"} { + selected := "" + if value == weather { + selected = " selected" + } + fmt.Fprintf(w, "<option value='%d'%s>%s</option>", value, selected, name) + } + fmt.Fprint(w, "</select></label><button>Set weather</button></form><small class='muted'>Transitions take up to 6 seconds.</small></section><script>let sample;async function stats(){try{if(!document.hidden){const response=await fetch('admin/stats');if(!response.ok)throw new Error();const next=await response.json();if(sample)document.querySelector('#query-rate').textContent=((next.queries-sample.queries)/(next.time-sample.time)).toFixed(1);sample=next;}}catch{document.querySelector('#query-rate').textContent='Unavailable';}setTimeout(stats,2000)}stats();</script></main></body></html>") + +} + +func (server *server) usersPage(w http.ResponseWriter, r *http.Request) { + server.mutex.Lock() + players := server.users_locked() + connected := make(map[uint32]bool) + for id, client := range server.clients { + 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>") + for _, player := range players { + status := "Offline" + 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.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'>") + controlMap(w, 0) + fmt.Fprint(w, "</div></main></body></html>") +} + +func (server *server) sqlPage(w http.ResponseWriter, r *http.Request) { + query := "SELECT name, type, sql FROM sqlite_schema ORDER BY type, name;" + var columns []string + var values [][]string + var queryError error + truncated := false + if r.Method == http.MethodPost { + r.Body = http.MaxBytesReader(w, r.Body, 65536) + if err := r.ParseForm(); err != nil { + http.Error(w, "Query is too large", 400) + return + } + query = r.PostForm.Get("query") + // Bound query duration and retained output, including queries with RETURNING. + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + _, err := server.database() + queryError = err + if err == nil { + // Isolate console transactions and PRAGMAs from the live game's connection. + db := sql.OpenDB(databaseConnector{&server.databaseQueries}) + defer db.Close() + db.SetMaxOpenConns(1) + for _, statement := range sqlStatements(query) { + rows, err := db.QueryContext(ctx, statement) + queryError = err + if err != nil { + break + } + names, err := rows.Columns() + queryError = err + // Keep the most recent result set when trailing comments or writes follow it. + if len(names) > 0 { + columns = names + values = nil + truncated = false + } + bytes := 0 + for queryError == nil && rows.Next() { + row := make([]any, len(names)) + destinations := make([]any, len(names)) + for index := range row { + destinations[index] = &row[index] + } + if queryError = rows.Scan(destinations...); queryError != nil { + break + } + if len(values) >= 1000 || bytes >= 2*1024*1024 { + truncated = true + continue + } + cells := make([]string, len(row)) + for index, value := range row { + switch value := value.(type) { + case nil: + cells[index] = "NULL" + case []byte: + cells[index] = fmt.Sprintf("%x", value) + default: + cells[index] = fmt.Sprint(value) + } + bytes += len(cells[index]) + } + values = append(values, cells) + } + if err := rows.Err(); queryError == nil { + queryError = err + } + rows.Close() + if queryError != nil { + break + } + } + } + } + server.adminPageStart(w, "SQL", "SQL") + fmt.Fprint(w, `<h1>SQL</h1><p class='muted'>Direct database access. Live game state may overwrite edits; restart to reload it.</p><form method='post' action='admin/sql'><label>Starter query<select id='preset'><option value=''>Choose...</option>`) + for _, preset := range []struct{ name, query string }{{"Tables", "SELECT name, type, sql FROM sqlite_schema ORDER BY type, name;"}, {"Players", "SELECT characters.* FROM characters JOIN players USING(id) ORDER BY id;"}, {"Items", "SELECT * FROM items ORDER BY id;"}, {"NPCs", "SELECT * FROM npcs ORDER BY id;"}, {"Administrators", "SELECT id, username FROM admin_users ORDER BY id;"}} { + fmt.Fprintf(w, "<option value='%s'>%s</option>", html.EscapeString(preset.query), preset.name) + } + fmt.Fprintf(w, "</select></label><label for='query'>Query</label><textarea id='query' name='query' rows='8' required spellcheck='false'>%s</textarea><p><button>Run query</button></p></form>", html.EscapeString(query)) + if queryError != nil { + fmt.Fprintf(w, "<p role='alert' class='error'>%s</p>", html.EscapeString(queryError.Error())) + } else if r.Method == http.MethodPost { + fmt.Fprintf(w, "<p role='status'>Query completed. %d rows displayed%s.</p>", len(values), map[bool]string{true: " (output limited)", false: ""}[truncated]) + if len(columns) > 0 { + fmt.Fprint(w, "<label>Output<select id='format' aria-label='Output'><option value='table'>Table</option><option value='csv'>CSV</option></select></label><div id='result-table' class='scroll'><table><thead><tr>") + for _, column := range columns { + fmt.Fprintf(w, "<th>%s</th>", html.EscapeString(column)) + } + fmt.Fprint(w, "</tr></thead><tbody>") + for _, row := range values { + fmt.Fprint(w, "<tr>") + for _, cell := range row { + fmt.Fprintf(w, "<td>%s</td>", html.EscapeString(cell)) + } + fmt.Fprint(w, "</tr>") + } + fmt.Fprint(w, "</tbody></table></div>") + var output strings.Builder + writer := csv.NewWriter(&output) + writer.Write(columns) + writer.WriteAll(values) + fmt.Fprintf(w, "<div id='result-csv' hidden><textarea readonly rows='16' aria-label='CSV output'>%s</textarea></div>", html.EscapeString(output.String())) + } + } + fmt.Fprint(w, `<script>document.querySelector('#preset').addEventListener('change',event=>{if(event.target.value)document.querySelector('#query').value=event.target.value});document.querySelector('#format')?.addEventListener('change',event=>{document.querySelector('#result-table').hidden=event.target.value!=='table';document.querySelector('#result-csv').hidden=event.target.value!=='csv'});</script></main></body></html>`) +} + +func (server *server) adminStats(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{"queries": server.databaseQueries.Load(), "time": float64(time.Now().UnixMilli()) / 1000}) +} diff --git a/server/admin_sql.go b/server/admin_sql.go @@ -0,0 +1,34 @@ +package main + +/* +#include <stdlib.h> +// Use the SQLite parser linked by go-sqlite3, including trigger bodies and quotes. +int sqlite3_complete(const char *sql); +*/ +import "C" + +import ( + "strings" + "unsafe" +) + +func sqlStatements(query string) []string { + var statements []string + start := 0 + for index, character := range query { + if character != ';' { + continue + } + text := C.CString(query[start : index+1]) + complete := C.sqlite3_complete(text) != 0 + C.free(unsafe.Pointer(text)) + if complete { + statements = append(statements, query[start:index+1]) + start = index + 1 + } + } + if strings.TrimSpace(query[start:]) != "" { + statements = append(statements, query[start:]) + } + return statements +} diff --git a/server/admin_test.go b/server/admin_test.go @@ -0,0 +1,283 @@ +package main + +import ( + "crypto/sha256" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" +) + +func newAdminTestServer(t *testing.T) *server { + t.Helper() + t.Chdir(t.TempDir()) + world := &server{baseURL: "/", characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), clockStarted: time.Now()} + registerTestDatabaseCleanup(t, world) + return world +} + +func TestAdminSetupLoginLogoutAndExpiry(t *testing.T) { + world := newAdminTestServer(t) + world.baseURL = "/share/demo/" + handler := world.httpHandler() + credentials := "username=Operator&password=long-test-password" + + setup := adminRequest(handler, "GET", "/share/demo/admin/login", "", nil) + created := adminRequest(handler, "POST", "https://example.test/share/demo/admin/login", credentials, nil) + if created.Code != 303 || len(created.Result().Cookies()) != 1 { + t.Fatalf("setup: %d %s", created.Code, created.Body) + } + cookie := created.Result().Cookies()[0] + general := adminRequest(handler, "GET", "/share/demo/admin", "", cookie) + slash := adminRequest(handler, "GET", "/share/demo/admin/", "", cookie) + loggedOut := adminRequest(handler, "POST", "/share/demo/admin/logout", "", cookie) + revoked := adminRequest(handler, "GET", "/share/demo/admin/sql", "", cookie) + wrong := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Operator&password=incorrect-password", nil) + login := adminRequest(handler, "POST", "/share/demo/admin/login", credentials, nil) + if len(login.Result().Cookies()) != 1 { + t.Fatalf("login: %s", login.Body) + } + expiredCookie := login.Result().Cookies()[0] + if _, err := world.db.Exec("UPDATE admin_sessions SET expires_at=0"); err != nil { + t.Fatal(err) + } + expired := adminRequest(handler, "GET", "/share/demo/admin", "", expiredCookie) + var salt, hash []byte + if err := world.db.QueryRow("SELECT password_salt,password_hash FROM admin_users").Scan(&salt, &hash); err != nil { + t.Fatal(err) + } + + if !strings.Contains(setup.Body.String(), "Create administrator") || cookie.Path != "/share/demo/admin" || !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode { + t.Fatal("setup form or cookie scope", cookie) + } + if general.Code != 200 || slash.Code != 200 || !strings.Contains(general.Body.String(), "href='admin/sql'") || strings.Contains(general.Body.String(), "Create user") { + t.Fatal("general navigation") + } + if loggedOut.Code != 303 || revoked.Code != 303 || expired.Code != 303 || wrong.Code != 401 || login.Code != 303 { + t.Fatal("session lifecycle", loggedOut.Code, revoked.Code, expired.Code, wrong.Code, login.Code) + } + if len(salt) != 16 || len(hash) != 32 || string(hash) == "long-test-password" { + t.Fatal("password not hashed") + } +} + +func TestAdminBoundaryAndCrossOriginWrites(t *testing.T) { + world := newAdminTestServer(t) + handler := world.httpHandler() + 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/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"} { + 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/users/1", "/admin/items", "/admin/items/1", "/admin/teleport/1", "/admin/sql", "/admin/logout"} { + response := adminRequest(handler, "POST", path, "", nil) + if response.Code != 401 { + t.Fatalf("unprotected write: %s %d", path, response.Code) + } + request := httptest.NewRequest("POST", "https://example.test"+path, strings.NewReader("hour=1&minute=0")) + request.Header.Set("Origin", "https://attacker.test") + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + request.AddCookie(cookie) + response = httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != 403 { + t.Fatalf("cross-origin write: %s %d", path, response.Code) + } + } + removed := adminRequest(handler, "POST", "/admin/users", "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 { + t.Fatal(err) + } + + if removed.Code != 405 || old.Code != 404 || count != 1 { + t.Fatal("removed routes", removed.Code, old.Code, count) + } + if strings.Contains(adminRequest(handler, "GET", "/admin/login", "", nil).Body.String(), "Create administrator") { + t.Fatal("setup still available") + } +} + +func TestAdminConcurrentSetupCreatesOneAccount(t *testing.T) { + world := newAdminTestServer(t) + handler := world.httpHandler() + var wait sync.WaitGroup + responses := make([]*httptest.ResponseRecorder, 2) + + for index := range responses { + wait.Go(func() { + responses[index] = adminRequest(handler, "POST", "/admin/login", "username="+[]string{"First", "Second"}[index]+"&password=long-test-password", nil) + }) + } + wait.Wait() + var count int + if err := world.db.QueryRow("SELECT count(*) FROM admin_users").Scan(&count); err != nil { + t.Fatal(err) + } + + if count != 1 || (responses[0].Code == 303) == (responses[1].Code == 303) { + t.Fatal("multiple initial administrators", count, responses[0].Code, responses[1].Code) + } +} + +func TestAdminSQLWritesReadsEscapesAndBoundsOutput(t *testing.T) { + world := newAdminTestServer(t) + handler := world.httpHandler() + created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + cookie := created.Result().Cookies()[0] + run := func(query string) *httptest.ResponseRecorder { + return adminRequest(handler, "POST", "/admin/sql", url.Values{"query": {query}}.Encode(), cookie) + } + + table := run("CREATE TABLE admin_test (value TEXT)") + inserted := run("INSERT INTO admin_test VALUES ('<script>,\"quoted\"')") + selected := run("SELECT value FROM admin_test") + updated := run("UPDATE admin_test SET value='changed' RETURNING value") + invalid := run("SELECT missing FROM admin_test") + batch := run("CREATE TABLE admin_batch (value TEXT); CREATE TRIGGER admin_insert AFTER INSERT ON admin_batch BEGIN UPDATE admin_batch SET value=NEW.value || 'suffix;'; END; INSERT INTO admin_batch VALUES ('prefix;'); SELECT value FROM admin_batch; -- trailing comment") + bounded := run("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<1005) SELECT x FROM n") + var value string + if err := world.db.QueryRow("SELECT value FROM admin_test").Scan(&value); err != nil { + t.Fatal(err) + } + + for _, response := range []*httptest.ResponseRecorder{table, inserted, selected, updated, bounded} { + if !strings.Contains(response.Body.String(), "Query completed.") { + t.Fatal(response.Body) + } + } + if !strings.Contains(batch.Body.String(), "prefix;suffix;") { + t.Fatal("SQL batch or trigger parser", batch.Body) + } + if value != "changed" || !strings.Contains(selected.Body.String(), "&lt;script&gt;") || strings.Contains(selected.Body.String(), "<script>,") || !strings.Contains(selected.Body.String(), "id='result-csv'") { + t.Fatal("SQL values or output", selected.Body) + } + if !strings.Contains(invalid.Body.String(), "no such column") || !strings.Contains(bounded.Body.String(), "1000 rows displayed (output limited)") { + t.Fatal("SQL errors or limit") + } +} + +func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { + world := newAdminTestServer(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}} + } + world.characters[1000600] = &character{id: 1000600, 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) + cookie := created.Result().Cookies()[0] + + 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) + invalid := adminRequest(handler, "GET", "/admin/map-entities?view=950&left=NaN&bottom=0&right=1&top=1", "", cookie) + var result struct { + NPCs, Warps []mapMarker + Limited bool + } + if err := json.Unmarshal(entities.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + + 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") { + 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") + } +} + +func TestAdminSessionSurvivesDatabaseReopen(t *testing.T) { + world := newAdminTestServer(t) + created := adminRequest(world.httpHandler(), "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + cookie := created.Result().Cookies()[0] + hash := sha256.Sum256([]byte(cookie.Value)) + + if err := world.db.Close(); err != nil { + t.Fatal(err) + } + world.db = nil + response := adminRequest(world.httpHandler(), "GET", "/admin", "", cookie) + var count int + if err := world.db.QueryRow("SELECT count(*) FROM admin_sessions WHERE token_hash=?", hash[:]).Scan(&count); err != nil { + t.Fatal(err) + } + + if response.Code != 200 || count != 1 { + t.Fatal("session lost on reopen", response.Code, count) + } +} + +func TestAdminSQLDoesNotChangeGameConnectionTransactionOrPragmas(t *testing.T) { + world := newAdminTestServer(t) + handler := world.httpHandler() + created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + cookie := created.Result().Cookies()[0] + + adminRequest(handler, "POST", "/admin/sql", url.Values{"query": {"PRAGMA foreign_keys=OFF; BEGIN; UPDATE world SET game_seconds=100"}}.Encode(), cookie) + var foreignKeys int + var seconds float64 + if err := world.db.QueryRow("PRAGMA foreign_keys").Scan(&foreignKeys); err != nil { + t.Fatal(err) + } + if err := world.db.QueryRow("SELECT game_seconds FROM world").Scan(&seconds); err != nil { + t.Fatal(err) + } + + if foreignKeys != 1 || seconds != 48600 { + t.Fatal("console leaked connection state", foreignKeys, seconds) + } +} + +func TestAdminDatabaseCountsPreparedAndDirectExecutions(t *testing.T) { + world := newAdminTestServer(t) + db, err := world.database() + if err != nil { + t.Fatal(err) + } + statement, err := db.Prepare("SELECT game_seconds FROM world") + if err != nil { + t.Fatal(err) + } + defer statement.Close() + before := world.databaseQueries.Load() + + var seconds int + if err := statement.QueryRow().Scan(&seconds); err != nil { + t.Fatal(err) + } + if _, err := db.Exec("UPDATE world SET game_seconds=0"); err != nil { + t.Fatal(err) + } + tx, err := db.Begin() + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec("UPDATE world SET game_seconds=1"); err != nil { + t.Fatal(err) + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + + if world.databaseQueries.Load()-before != 3 { + t.Fatal("query count", world.databaseQueries.Load()-before) + } +} diff --git a/server/admin_weather.go b/server/admin_weather.go @@ -0,0 +1,73 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "math" + "net/http" + "strconv" + "time" +) + +// WeatherControlIIR_t::Read (kkr.dll 0x100dbe30) and the environment queue +// (0x100da960) define these fields; see docs/admin.md for the preset policy. +func weatherPacket(player *character, weather int) []byte { + body := make([]byte, 43) + binary.BigEndian.PutUint16(body, 1) + binary.BigEndian.PutUint32(body[2:], 4) + binary.BigEndian.PutUint16(body[6:], 1) + binary.BigEndian.PutUint32(body[8:], math.Float32bits(1000000)) + body[12] = []byte{3, 3, 0, 2, 1}[weather] + body[13] = 70 + body[15] = 20 + copy(body[20:26], []byte{255, 255, 255, 160, 170, 180}) + if weather == 4 { + body[26] = 25 + } + origin := gamedata.Playfields[player.playfield].Origin + position := [3]float32{player.position[0] + float32(origin[0]), player.position[1], player.position[2] + float32(origin[1])} + for index, value := range position { + binary.BigEndian.PutUint32(body[27+index*4:], math.Float32bits(value)) + } + return n3Packet(0x0c5a5d6d, 50000, player.id, body) +} + +func (server *server) setWeather(w http.ResponseWriter, r *http.Request) { + weather, err := strconv.Atoi(r.FormValue("weather")) + if err != nil || weather < 0 || weather > 4 { + http.Error(w, "Invalid weather", 400) + return + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + db, err := server.database() + if err == nil { + _, err = db.Exec("UPDATE admin_settings SET weather=? WHERE id=1", weather) + } + if err != nil { + server.mutex.Unlock() + http.Error(w, err.Error(), 500) + return + } + server.weather = weather + server.nextWeather = time.Time{} + updates := make(map[*worldClient][][]byte) + server.weatherUpdates_locked(time.Now(), updates) + server.mutex.Unlock() + server.sendCombatUpdates(updates) + http.Redirect(w, r, server.baseURL+"admin", http.StatusSeeOther) +} + +func (server *server) weatherUpdates_locked(now time.Time, updates map[*worldClient][][]byte) { + if server.weather == 0 || now.Before(server.nextWeather) { + return + } + server.nextWeather = now.Add(5 * time.Second) + for id, client := range server.clients { + if !client.ready || client.loading || !client.target { + continue + } + updates[client] = append(updates[client], weatherPacket(server.characters[id], server.weather)) + } +} diff --git a/server/admin_weather_test.go b/server/admin_weather_test.go @@ -0,0 +1,57 @@ +package main + +import ( + "encoding/binary" + "net/url" + "strings" + "testing" +) + +func TestAdminWeatherPersistsAndSendsOriginalTargetPacket(t *testing.T) { + world := newAdminTestServer(t) + player := &character{id: 1, playfield: 705, position: [3]float32{960, 16.5, 510}, health: 100} + world.characters[1] = player + connection := &combatTestConn{} + world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: connection} + handler := world.httpHandler() + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + cookie := setup.Result().Cookies()[0] + + selected := adminRequest(handler, "POST", "/admin/weather", url.Values{"weather": {"2"}}.Encode(), cookie) + var weather int + if err := world.db.QueryRow("SELECT weather FROM admin_settings").Scan(&weather); err != nil { + t.Fatal(err) + } + invalid := adminRequest(handler, "POST", "/admin/weather", "weather=8", cookie) + automatic := adminRequest(handler, "POST", "/admin/weather", "weather=0", cookie) + page := adminRequest(handler, "GET", "/admin", "", cookie) + + if selected.Code != 303 || weather != 2 || invalid.Code != 400 || automatic.Code != 303 || world.weather != 0 || len(connection.packets) != 1 { + t.Fatal("weather state", selected.Code, weather, invalid.Code, len(connection.packets)) + } + packet := connection.packets[0] + if len(packet) != 72 || binary.BigEndian.Uint32(packet[16:20]) != 0x0c5a5d6d || packet[41] != 0 || packet[42] != 70 || packet[49] != 255 || packet[50] != 255 || packet[51] != 255 { + t.Fatalf("native weather packet %x", packet) + } + if binary.BigEndian.Uint16(packet[29:31]) != 1 || binary.BigEndian.Uint32(packet[31:35]) != 4 || binary.BigEndian.Uint16(packet[35:37]) != 1 { + t.Fatalf("weather lifetime %x", packet) + } + if !strings.Contains(page.Body.String(), "value='0' selected>Automatic") { + t.Fatal("weather setting not reflected") + } +} + +func TestAdminWeatherRestoresAfterRestart(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + handler := world.httpHandler() + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + cookie := setup.Result().Cookies()[0] + + response := adminRequest(handler, "POST", "/admin/weather", "weather=4", cookie) + restarted := newServerForTest(t) + + if response.Code != 303 || restarted.weather != 4 { + t.Fatal("weather not restored", response.Code, restarted.weather) + } +} 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, "/control/users", url.Values{"name": {"Visitor"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Visitor"}}) - response := postControlForm(world, "/control/users/1", url.Values{"data": { + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Visitor"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Visitor"}}) if _, err := world.db.Exec(failure.statement); err != nil { t.Fatal(err) } - response := postControlForm(world, "/control/users/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {"head_mesh: 40680\nheight: 110\n"}}) + response = postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Visitor"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Visitor"}}) - response := postControlForm(world, "/control/users/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/users/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/armor_quality_test.go b/server/armor_quality_test.go @@ -177,14 +177,14 @@ func TestControlMetaplastIntermediateQualityAndNames(t *testing.T) { t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) + postControlForm(world, "/admin/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) data := fmt.Sprintf("type: 51022\ntemplate: %d\nquality: %d\ncount: 1\n", scenario.template, scenario.quality) before, _ := readTestItemStore(world) - response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/items/1", url.Values{"data": {data}}) after, err := readTestItemStore(world) page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/items/1", nil)) if response.Code != scenario.status || err != nil { t.Fatal(response.Code, response.Body.String(), err) diff --git a/server/assets/map.js b/server/assets/map.js @@ -11,6 +11,8 @@ class AOMap { this.form = element.querySelector("[data-map-teleport]"); this.character = Number(element.dataset.character); this.players = []; + this.entities = {npcs: [], warps: []}; + this.pointers = new Map(); this.tiles = new Map(); this.tileBytes = 0; this.loadingTiles = 0; @@ -23,7 +25,7 @@ class AOMap { } async start() { - const response = await fetch("control/map-assets/manifest.json"); + const response = await fetch("admin/map-assets/manifest.json"); if (!response.ok) { this.status.textContent = "Map data is missing. Run tools/data/extract_maps.py from the repository root."; return; @@ -66,37 +68,69 @@ class AOMap { const point = this.pointer(event); this.zoom(Math.exp(-event.deltaY * 0.0015), ...point); }, {passive: false}); - this.canvas.addEventListener("pointerdown", event => { - if (event.button !== 0) return; - this.drag = {point: this.pointer(event), center: [...this.center], moved: false}; - this.canvas.setPointerCapture(event.pointerId); - }); - this.canvas.addEventListener("pointermove", event => { - const point = this.pointer(event); - if (this.drag) { - const dx = point[0] - this.drag.point[0]; - const dy = point[1] - this.drag.point[1]; - if (Math.hypot(dx, dy) > 4) this.drag.moved = true; - if (this.drag.moved) { - this.center = [this.drag.center[0] - dx / this.scale, this.drag.center[1] + dy / this.scale]; - this.renderSoon(); - } - } - }); - this.canvas.addEventListener("pointerup", event => { - if (!this.drag) return; - const clicked = !this.drag.moved; - this.drag = null; - if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId); - if (clicked) this.pick(...this.pointer(event)); - }); - this.canvas.addEventListener("pointercancel", () => { this.drag = null; }); + this.canvas.addEventListener("pointerdown", event => this.pointerDown(event)); + this.canvas.addEventListener("pointermove", event => this.pointerMove(event)); + this.canvas.addEventListener("pointerup", event => this.pointerEnd(event)); + 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(); + }); + } new ResizeObserver(() => this.resize()).observe(this.canvas); this.resize(); this.fit(this.bounds()); await this.poll(); } + pointerDown(event) { + if (event.button !== 0) return; + const point = this.pointer(event); + this.pointers.set(event.pointerId, point); + this.drag = {point, center: [...this.center], moved: this.pointers.size > 1}; + this.canvas.setPointerCapture(event.pointerId); + } + + pointerMove(event) { + if (!this.pointers.has(event.pointerId)) return; + const before = [...this.pointers.values()]; + const point = this.pointer(event); + this.pointers.set(event.pointerId, point); + const after = [...this.pointers.values()]; + if (after.length === 2) { + // Keep the world position beneath the midpoint while pinching and panning. + const midpoint = points => [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2]; + const distance = points => Math.hypot(points[0][0] - points[1][0], points[0][1] - points[1][1]); + const oldMid = midpoint(before), newMid = midpoint(after); + this.zoom(distance(after) / Math.max(1, distance(before)), ...oldMid); + this.center[0] -= (newMid[0] - oldMid[0]) / this.scale; + this.center[1] += (newMid[1] - oldMid[1]) / this.scale; + this.drag.moved = true; + } else if (after.length === 1 && this.drag) { + const dx = point[0] - this.drag.point[0], dy = point[1] - this.drag.point[1]; + if (Math.hypot(dx, dy) > 4) this.drag.moved = true; + if (this.drag.moved) this.center = [this.drag.center[0] - dx / this.scale, this.drag.center[1] + dy / this.scale]; + } + this.renderSoon(); + } + + pointerEnd(event, cancelled = false) { + if (!this.pointers.has(event.pointerId)) return; + const clicked = !cancelled && this.pointers.size === 1 && !this.drag.moved; + this.pointers.delete(event.pointerId); + if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId); + this.drag = this.pointers.size ? {point: [...this.pointers.values()][0], center: [...this.center], moved: true} : null; + if (clicked) this.pick(...this.pointer(event)); + } + + 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; + 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(); + } + resize() { this.width = this.canvas.clientWidth; this.height = this.canvas.clientHeight; @@ -119,6 +153,7 @@ class AOMap { } fit(bounds) { + this.entities = {npcs: [], warps: []}; const [left, bottom, right, top] = bounds; this.center = [(left + right) / 2, (bottom + top) / 2]; this.scale = Math.min(this.width / (right - left), this.height / (top - bottom)) * 0.9; @@ -227,13 +262,19 @@ class AOMap { async poll() { try { if (!document.hidden) { - const response = await fetch("control/map-players", {cache: "no-store"}); + const offline = this.element.querySelector("[data-map-offline]").checked; + const response = await fetch(`admin/map-players?offline=${offline ? 1 : 0}&character=${this.character}`, {cache: "no-store"}); if (!response.ok) throw new Error(`Player feed returned HTTP ${response.status}`); this.players = (await response.json()).players; if (!this.initialized) { this.initialized = true; this.centerPlayer(); } + const query = this.entityQuery(); + const entities = await fetch(`admin/map-entities?${query}`, {cache: "no-store"}); + if (!entities.ok) throw new Error(`Map feed returned HTTP ${entities.status}`); + const data = await entities.json(); + if (query === this.entityQuery()) this.entities = data; this.renderSoon(); } } catch (error) { @@ -263,7 +304,7 @@ class AOMap { if (tile.bitmap || tile.failed || tile.loading) continue; tile.loading = true; this.loadingTiles++; - fetch(`control/map-assets/${path}`, {cache: "force-cache"}).then(response => { + fetch(`admin/map-assets/${path}`, {cache: "force-cache"}).then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.blob(); }).then(blob => createImageBitmap(blob)).then(bitmap => { @@ -314,13 +355,22 @@ class AOMap { } pick(x, y) { + for (const marker of this.entities.warps) { + if (!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}`; + return; + } + } // Player markers navigate to their existing character editor. for (const player of this.players) { + if (!player.connected && player.id !== this.character && !this.element.querySelector("[data-map-offline]")?.checked) continue; const point = this.playerPoint(player); 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(`control/users/${player.id}`, document.baseURI); + window.location.href = new URL(`admin/users/${player.id}`, document.baseURI); return; } } @@ -362,7 +412,7 @@ class AOMap { selectDestination(zone, point) { this.selection = {zone, point}; - this.location.textContent = `${zone.name} (${zone.id}): X ${point[0].toFixed(2)}, Z ${point[1].toFixed(2)}. The server calculates terrain height; obstacles and buildings are not checked.`; + this.location.textContent = `${zone.name} (${zone.id}): X ${point[0].toFixed(2)}, Z ${point[1].toFixed(2)}.`; if (this.form) { this.form.elements.playfield.value = zone.id; this.form.elements.x.value = point[0].toFixed(3); @@ -414,16 +464,34 @@ class AOMap { } } - // Draw player markers above imagery; offline markers have an empty centre. + // Keep dense NPC markers at useful zoom; warp destinations are labelled on tap. ctx.font = "12px sans-serif"; - for (const player of this.players) { - if (!this.character) { - const placement = document.querySelector(`[data-map-player="${player.id}"] [data-map-placement]`); - if (placement) { - placement.textContent = this.zones.get(player.playfield)?.origin ? "World map" : - (this.zones.get(player.entrance?.playfield)?.origin ? "At entrance" : "No world position"); + for (const [kind, color] of [["npcs", "#f4b942"], ["warps", "#bc8cff"]]) { + if (!this.element.querySelector(`[data-map-${kind}]`)?.checked || (kind === "npcs" && this.scale < 0.3)) 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; + ctx.fillStyle = color; + ctx.strokeStyle = color; + if (kind === "warps") { + ctx.strokeRect(x - 5, y - 5, 10, 10); + if (marker.target && this.scale >= 0.3) { + const target = this.toScreen(...marker.target); + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(...target); ctx.stroke(); + ctx.beginPath(); ctx.arc(...target, 3, 0, Math.PI * 2); ctx.fill(); + } + if (this.scale >= 0.6) ctx.fillText(marker.destination, x + 9, y - 8); + } else { + ctx.beginPath(); ctx.arc(x, y, 3, 0, Math.PI * 2); ctx.fill(); + if (this.scale >= 1.2) ctx.fillText(marker.name, x + 6, y + 4); } } + } + + // Draw player markers above imagery; offline markers have an empty centre. + ctx.font = "12px sans-serif"; + for (const player of this.players) { + if (!player.connected && player.id !== this.character && !this.element.querySelector("[data-map-offline]")?.checked) continue; const point = this.playerPoint(player); if (!point) continue; const [x, y] = this.toScreen(...point); @@ -470,7 +538,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.tiles.values()].filter(tile => tile.bitmap).length} cached tiles.${detail}${failures ? ` ${failures} tiles failed to load.` : ""}`; + 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.` : ""}`; } } diff --git a/server/backpack_quality_test.go b/server/backpack_quality_test.go @@ -69,14 +69,14 @@ func TestControlBackpackOfSurvivalQualityBounds(t *testing.T) { t.Run(fmt.Sprint(quality), func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/items", url.Values{"template": {"206730"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"206730"}}) before, _ := readTestItemStore(world) data := fmt.Sprintf("type: 51017\ntemplate: 206730\nquality: %d\ncount: 1\n", quality) - response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/items/1", url.Values{"data": {data}}) after, err := readTestItemStore(world) page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/items/1", nil)) if err != nil || page.Code != 200 { t.Fatal(err, page.Code) diff --git a/server/bank_storage_test.go b/server/bank_storage_test.go @@ -14,11 +14,11 @@ import ( func TestBankStoragePreservesFilledBackpack(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n"}}) + response := postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_102: 3}\n"}}) restarted := newServerForTest(t) page, bag := httptest.NewRecorder(), httptest.NewRecorder() - restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) - restarted.httpHandler().ServeHTTP(bag, httptest.NewRequest("GET", "/control/items/3", nil)) + adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(restarted).ServeHTTP(bag, httptest.NewRequest("GET", "/admin/items/3", nil)) if response.Code != http.StatusSeeOther { t.Fatalf("bank placement: %d %s", response.Code, response.Body.String()) @@ -32,7 +32,7 @@ func TestBankStoragePreservesFilledBackpack(t *testing.T) { t.Fatal("bank storage lost ownership or duplicated an item") } if !strings.Contains(page.Body.String(), "<h2>Bank</h2>") || - !strings.Contains(page.Body.String(), "<tr><td>slot_102</td><td><a href='control/items/3'>Small Backpack (ID 3)</a></td></tr>") || + !strings.Contains(page.Body.String(), "<tr><td>slot_102</td><td><a href='admin/items/3'>Small Backpack (ID 3)</a></td></tr>") || !strings.Contains(bag.Body.String(), "Bank, slot_102") { t.Fatal("control panel omitted bank ownership or its final slot") } @@ -55,7 +55,7 @@ func TestBankStorageRejectsInvalidOwnershipGraphs(t *testing.T) { t.Fatal(err) } - response := postControlForm(world, "/control/users/1", url.Values{"data": {document}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Other"}}) - placed := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_1: null}}\nbank: {slot_1: 1}\n"}}) + 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"}}) if placed.Code != http.StatusSeeOther { t.Fatal(placed.Body.String()) } - response := postControlForm(world, "/control/users/2", url.Values{"data": {"bank: {slot_1: 1}\n"}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {"inventory: {slots: {inventory_slot_2: null}}\nbank: {slot_1: 3}\n"}}) + response := postControlForm(world, "/admin/users/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,18 +105,18 @@ func TestBankStorageFailurePreservesPlacement(t *testing.T) { func TestBankStorageSupportsEveryNativeSlot(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) var document strings.Builder document.WriteString("bank:\n") for id := 1; id <= 102; id++ { - response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + response := postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) if response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } document.WriteString(" slot_" + strconv.Itoa(id) + ": " + strconv.Itoa(id) + "\n") } - response := postControlForm(world, "/control/users/1", url.Values{"data": {document.String()}}) + response := postControlForm(world, "/admin/users/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_pending_edit_test.go b/server/browser_pending_edit_test.go @@ -36,6 +36,7 @@ func TestBrowserPendingEquipmentEdit(t *testing.T) { } mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) + mux.HandleFunc("POST /test-edit/{character}", world.editUser) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { world.mutex.Lock() defer world.mutex.Unlock() 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", "/control/users/1", strings.NewReader(url.Values{"data": {string(contents)}}.Encode())) + request := httptest.NewRequest("POST", "/admin/users/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/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, "/control/users", url.Values{"name": {"Explorer"}}) + response := postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) if response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } diff --git a/server/control.go b/server/control.go @@ -16,33 +16,6 @@ import ( "go.yaml.in/yaml/v3" ) -func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { - // Users remain visible while offline or reconnecting between zones. - server.mutex.Lock() - seconds := int(server.gameSeconds_locked()) - players := server.users_locked() - connected := make(map[uint32]bool) - for id, client := range server.clients { - connected[id] = client.ready - } - server.mutex.Unlock() - - w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Server controls</title></head><body><h1>Server controls</h1><p><a href='control'>Refresh</a></p>", html.EscapeString(server.baseURL)) - fmt.Fprintf(w, "<p>Game time: %02d:%02d. A day has 27 hours; time advances at 15x.</p>", seconds/3600, seconds/60%60) - fmt.Fprintf(w, "<form method='post' action='control/time'><label>Hour <input type='number' name='hour' min='0' max='26' value='%d' required></label> <label>Minute <input type='number' name='minute' min='0' max='59' value='%d' required></label> <button>Set time</button></form>", seconds/3600, seconds/60%60) - controlMap(w, 0) - fmt.Fprint(w, "<p><a href='control/items'>Items</a></p><h2>Users</h2><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th><th>Map</th></tr>") - for _, player := range players { - status := "Offline" - if connected[player.ID] { - status = "Connected" - } - fmt.Fprintf(w, "<tr data-map-player='%d'><td>%d</td><td><a href='control/users/%d'>%s</a></td><td>%s</td><td>%s (%d)</td><td data-map-placement></td></tr>", player.ID, player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(gamedata.Playfields[player.Playfield].Name), player.Playfield) - } - fmt.Fprint(w, "</table><h2>Create user</h2><form method='post' action='control/users'><label>Name <input name='name' required maxlength='254'></label> <button>Create user</button></form></body></html>") -} - func (server *server) userPage(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) if err != nil { @@ -70,41 +43,13 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { server.inventoryTables_locked(&itemTables, player.inventory) server.mutex.Unlock() - w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>User</title></head><body><p><a href='control'>All users</a></p>", html.EscapeString(server.baseURL)) + server.adminPageStart(w, "User", "Users") fmt.Fprintf(w, "<h1>%s</h1><p>User %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected) controlMap(w, data.ID) - fmt.Fprint(w, "<h2>Character data</h2><p>This YAML document edits the character in the world database. Slots contain item IDs or null. Saving reconnects an online character. ID is fixed; position is XYZ and rotation is XYZW.</p>") - fmt.Fprintf(w, "<form method='post' action='control/users/%d'><p><label>Character:<br><textarea name='data' rows='40' cols='100' required>%s</textarea></label></p><button>Save character</button></form>", data.ID, html.EscapeString(string(contents))) - fmt.Fprint(w, "<p>Inventory uses inventory_slot_1 through inventory_slot_30; equipment uses named weapons, clothes and implants positions. Slots contain item IDs or null. Clearing a slot unassigns its item. <a href='control/items'>Browse and create item instances</a>. Container slots are edited on the container's item page. experience is progress within the current level, below its next-level requirement; level 200 requires zero. improvement_points is the available IP balance. Native skill spending deducts IP and enforces training caps; editing stats here sets their values directly.</p>") + 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.Fprint(w, itemTables.String()) - fmt.Fprint(w, "<p>insured_experience is the cumulative XP protected by the last insurance save. It cannot exceed current cumulative XP. Death below level 20 preserves XP; later deaths preserve the greater of insured XP and the current level's lower boundary.</p>") - fmt.Fprint(w, "</body></html>") -} - -func (server *server) createUser(w http.ResponseWriter, r *http.Request) { - name := strings.TrimSpace(r.FormValue("name")) - server.mutex.Lock() - player := server.newCharacter_locked() - player.name = name - if err := player.userData().validate(); err != nil { - delete(server.characters, player.id) - server.nextCharacter-- - server.mutex.Unlock() - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - err := server.saveUser_locked(player) - if err != nil { - delete(server.characters, player.id) - server.nextCharacter-- - } - server.mutex.Unlock() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, fmt.Sprintf("%scontrol/users/%d", server.baseURL, player.id), http.StatusSeeOther) + fmt.Fprint(w, "</main></body></html>") } func (server *server) editUser(w http.ResponseWriter, r *http.Request) { @@ -177,7 +122,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("%scontrol/users/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d", server.baseURL, id), http.StatusSeeOther) } func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) { @@ -215,7 +160,7 @@ func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) { client.disconnect(client.conn) } } - http.Redirect(w, r, server.baseURL+"control", http.StatusSeeOther) + http.Redirect(w, r, server.baseURL+"admin", http.StatusSeeOther) } func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) { @@ -273,7 +218,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("%scontrol/users/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/users/%d", 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,28 +15,28 @@ func TestControlPortableContainerCatalog(t *testing.T) { t.Run(container.name, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) for _, template := range []uint32{container.template, 121567, 99241} { - response := postControlForm(world, "/control/items", url.Values{"template": {strconv.FormatUint(uint64(template), 10)}}) + response := postControlForm(world, "/admin/items", url.Values{"template": {strconv.FormatUint(uint64(template), 10)}}) if response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } } - assigned := postControlForm(world, "/control/items/1", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:64"}}) - filled := postControlForm(world, "/control/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"1:20"}}) - nested := postControlForm(world, "/control/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"1:0"}}) + assigned := postControlForm(world, "/admin/items/1", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:64"}}) + 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() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) - world.httpHandler().ServeHTTP(child, httptest.NewRequest("GET", "/control/items/2", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) + adminTestHandler(world).ServeHTTP(child, httptest.NewRequest("GET", "/admin/items/2", nil)) restarted := newTestInventoryServer(t) if assigned.Code != http.StatusSeeOther || filled.Code != http.StatusSeeOther || nested.Code != http.StatusBadRequest { t.Fatal("container placement, final slot or nesting check failed", assigned.Code, filled.Code, nested.Code) } - if !strings.Contains(page.Body.String(), fmt.Sprintf("<h2>Container <a href='control/items/1'>%s (ID 1)</a></h2>", container.name)) || - !strings.Contains(page.Body.String(), "<tr><td>slot_21</td><td><a href='control/items/2'>Solar-Powered Pistol (ID 2)</a></td></tr>") || - !strings.Contains(child.Body.String(), "<a href='control/items/1'>Container 1, slot_21</a>") { + if !strings.Contains(page.Body.String(), fmt.Sprintf("<h2>Container <a href='admin/items/1'>%s (ID 1)</a></h2>", container.name)) || + !strings.Contains(page.Body.String(), "<tr><td>slot_21</td><td><a href='admin/items/2'>Solar-Powered Pistol (ID 2)</a></td></tr>") || + !strings.Contains(child.Body.String(), "<a href='admin/items/1'>Container 1, slot_21</a>") { t.Fatal("container table or contained item parent link missing") } contents := restarted.characters[1].inventory.Containers[1] diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -16,20 +16,20 @@ import ( func TestControlItemCatalogPaginatesAndFilters(t *testing.T) { world := &server{baseURL: "/share/test/"} - handler := world.httpHandler() + handler := adminTestHandler(world) first, second, filtered := httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder() - handler.ServeHTTP(first, httptest.NewRequest("GET", "/share/test/control/items/catalog?catalog=armor", nil)) - handler.ServeHTTP(second, httptest.NewRequest("GET", "/share/test/control/items/catalog?catalog=armor&page=2", nil)) - handler.ServeHTTP(filtered, httptest.NewRequest("GET", "/share/test/control/items/catalog?catalog=121567", nil)) + handler.ServeHTTP(first, httptest.NewRequest("GET", "/share/test/admin/items/catalog?catalog=armor", nil)) + handler.ServeHTTP(second, httptest.NewRequest("GET", "/share/test/admin/items/catalog?catalog=armor&page=2", nil)) + handler.ServeHTTP(filtered, httptest.NewRequest("GET", "/share/test/admin/items/catalog?catalog=121567", nil)) for _, response := range []*httptest.ResponseRecorder{first, second} { if response.Code != http.StatusOK || strings.Count(response.Body.String(), "<button name='template' value='") != 500 { t.Fatalf("catalog page: HTTP %d, expected 500 templates", response.Code) } } - if !strings.Contains(first.Body.String(), "href='control/items/catalog?catalog=armor&amp;page=2'") || - !strings.Contains(second.Body.String(), "href='control/items/catalog?catalog=armor&amp;page=1'") || + if !strings.Contains(first.Body.String(), "href='admin/items/catalog?catalog=armor&amp;page=2'") || + !strings.Contains(second.Body.String(), "href='admin/items/catalog?catalog=armor&amp;page=1'") || !strings.Contains(first.Body.String(), "<base href='/share/test/'>") { t.Fatal("pagination lost the filter or public mounting path") } @@ -50,20 +50,20 @@ func TestControlInstancesPaginateFilteredResults(t *testing.T) { for id := uint32(1); id <= 1001; id++ { world.items[id] = itemRecord{Type: 51018, Template: 121567, Quality: 1, Count: 1} } - handler := world.httpHandler() + handler := adminTestHandler(world) first, second, last, empty := httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder() - handler.ServeHTTP(first, httptest.NewRequest("GET", "/control/items?q=pistol", nil)) - handler.ServeHTTP(second, httptest.NewRequest("GET", "/control/items?q=pistol&page=2", nil)) - handler.ServeHTTP(last, httptest.NewRequest("GET", "/control/items?q=pistol&page=999999999", nil)) - handler.ServeHTTP(empty, httptest.NewRequest("GET", "/control/items?q=missing&page=-1", nil)) + handler.ServeHTTP(first, httptest.NewRequest("GET", "/admin/items?q=pistol", nil)) + handler.ServeHTTP(second, httptest.NewRequest("GET", "/admin/items?q=pistol&page=2", nil)) + handler.ServeHTTP(last, httptest.NewRequest("GET", "/admin/items?q=pistol&page=999999999", nil)) + handler.ServeHTTP(empty, httptest.NewRequest("GET", "/admin/items?q=missing&page=-1", nil)) if strings.Count(first.Body.String(), "<tr>") != 501 || strings.Count(second.Body.String(), "<tr>") != 501 || strings.Count(last.Body.String(), "<tr>") != 2 || strings.Count(empty.Body.String(), "<tr>") != 1 { t.Fatal("instance pages did not contain 500, 500, 1 and 0 rows") } - if !strings.Contains(second.Body.String(), "href='control/items/501'") || strings.Contains(second.Body.String(), "href='control/items/500'") || - !strings.Contains(first.Body.String(), "href='control/items?page=2&amp;q=pistol'") || !strings.Contains(last.Body.String(), "Page 3 of 3") || !strings.Contains(empty.Body.String(), "Page 1 of 1") { + if !strings.Contains(second.Body.String(), "href='admin/items/501'") || strings.Contains(second.Body.String(), "href='admin/items/500'") || + !strings.Contains(first.Body.String(), "href='admin/items?page=2&amp;q=pistol'") || !strings.Contains(last.Body.String(), "Page 3 of 3") || !strings.Contains(empty.Body.String(), "Page 1 of 1") { t.Fatal("instance boundaries or retained filter are incorrect") } } @@ -72,25 +72,25 @@ func postControlForm(world *server, path string, fields url.Values) *httptest.Re request := httptest.NewRequest("POST", path, strings.NewReader(fields.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() - world.httpHandler().ServeHTTP(response, request) + serveAdminTestRequest(world, response, request) return response } func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) - pistol := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - bag := postControlForm(world, "/control/items", url.Values{"template": {"99228"}}) - contained := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - placed := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1, inventory_slot_2: 2}\n"}}) - filled := postControlForm(world, "/control/items/2", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {slot_1: 3}\n"}}) + 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"}}) + 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() - restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items?q=Explorer", nil)) + adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/items?q=Explorer", nil)) details := httptest.NewRecorder() - restarted.httpHandler().ServeHTTP(details, httptest.NewRequest("GET", "/control/items/1", nil)) + adminTestHandler(restarted).ServeHTTP(details, httptest.NewRequest("GET", "/admin/items/1", nil)) for _, response := range []*httptest.ResponseRecorder{pistol, bag, contained, placed, filled} { if response.Code != http.StatusSeeOther { @@ -106,7 +106,7 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing t.Fatalf("slot references lost their items: %+v", inventory) } if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), "Solar-Powered Pistol") || !strings.Contains(page.Body.String(), "Explorer (1)") || - !strings.Contains(page.Body.String(), "Container 2, slot_1") || !strings.Contains(page.Body.String(), "href='control/items/3'") { + !strings.Contains(page.Body.String(), "Container 2, slot_1") || !strings.Contains(page.Body.String(), "href='admin/items/3'") { t.Fatalf("item list: %d %s", page.Code, page.Body.String()) } if details.Code != http.StatusOK || !strings.Contains(details.Body.String(), "Instance properties") || !strings.Contains(details.Body.String(), "Catalog properties") { @@ -121,16 +121,16 @@ func TestControlItemsShareOneRegistryAndShowOwnersAndBackpackContents(t *testing func TestControlItemCanBeUnassignedAndTransferredWithoutChangingID(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"First"}}) - postControlForm(world, "/control/users", url.Values{"name": {"Second"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) + postControlForm(world, "/admin/users", 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"}}) - cleared := postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}}) + cleared := postControlForm(world, "/admin/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: null}\n"}}) unassigned := newServerForTest(t) - transferred := postControlForm(world, "/control/users/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}}) + transferred := postControlForm(world, "/admin/users/2", url.Values{"data": {"inventory:\n slots: {inventory_slot_30: 1}\n"}}) restarted := newServerForTest(t) - postControlForm(restarted, "/control/items", url.Values{"template": {"121567"}}) + postControlForm(restarted, "/admin/items", url.Values{"template": {"121567"}}) if cleared.Code != http.StatusSeeOther || transferred.Code != http.StatusSeeOther || len(unassigned.items) != 1 || len(unassigned.characters[1].inventory.Items) != 0 { t.Fatalf("unassignment or transfer failed: %d %d", cleared.Code, transferred.Code) @@ -153,17 +153,17 @@ func TestControlInventoryRejectsDuplicateUnknownAndInvalidSlotsAtomically(t *tes t.Run(contents, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"First"}}) - postControlForm(world, "/control/users", url.Values{"name": {"Second"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) + postControlForm(world, "/admin/users", 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"}}) before, err := readTestItemStore(world) if err != nil { t.Fatal(err) } - response := postControlForm(world, "/control/users/2", url.Values{"data": {"inventory:\n " + contents}}) + response := postControlForm(world, "/admin/users/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 { @@ -178,7 +178,7 @@ func TestControlItemCreationKeepsStateWhenSavingFails(t *testing.T) { world := newTestServer(t) failDatabaseWrites(t, world) - response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + response := postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) if response.Code != http.StatusInternalServerError || world.nextItem != 0 || len(world.items) != 0 { t.Fatalf("failed save changed registry: %d %s", response.Code, response.Body.String()) @@ -188,14 +188,14 @@ func TestControlItemCreationKeepsStateWhenSavingFails(t *testing.T) { func TestControlEditorShowsAllSkillCategoriesAndDefaultFields(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", 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, "/control/users/1", url.Values{"data": {contents}}); response.Code != http.StatusSeeOther { + if response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}); response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", 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, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/1", url.Values{"data": {contents}}) restarted := newServerForTest(t) packet := fullCharacterPacket(restarted.characters[1]) values := make(map[uint32]uint32) @@ -246,7 +246,7 @@ func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing } } -func TestControlRoutesRequireControlPrefix(t *testing.T) { +func TestControlRoutesRequireAdminPrefix(t *testing.T) { world := &server{baseURL: "/"} handler := world.httpHandler() @@ -263,12 +263,12 @@ func TestControlRoutesRequireControlPrefix(t *testing.T) { func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) for _, template := range []string{"121567", "85686", "101173"} { - postControlForm(world, "/control/items", url.Values{"template": {template}}) + postControlForm(world, "/admin/items", url.Values{"template": {template}}) } page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/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, "/control/users/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/users/1", url.Values{"data": {string(contents)}}) restarted := newServerForTest(t) var name string var x float32 @@ -312,15 +312,15 @@ func TestControlCharacterDocumentSavesNativeFieldsAndNamedSlots(t *testing.T) { func TestControlCharacterDocumentRollsBackAllSections(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/items", url.Values{"template": {"85557"}}) + postControlForm(world, "/admin/users", 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 { t.Fatal(err) } 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, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) - response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Explorer"}}) - created := postControlForm(world, "/control/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) + postControlForm(world, "/admin/users", 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, "/control/users/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/users/1", url.Values{"data": {data}}) restarted := newTestInventoryServer(t) page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/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()) @@ -42,7 +42,7 @@ func TestControlClothingNamesMatchNativeArmorSlots(t *testing.T) { if item.ID != 1 || item.Template != scenario.template || item.Slot != scenario.slot || binary.BigEndian.Uint32(packet[37:41]) != scenario.slot { t.Fatal("named clothing placement changed the native identity or slot", item) } - if !strings.Contains(page.Body.String(), "<tr><td>"+scenario.name+"</td><td><a href='control/items/1'>") || + if !strings.Contains(page.Body.String(), "<tr><td>"+scenario.name+"</td><td><a href='admin/items/1'>") || !strings.Contains(page.Body.String(), scenario.name+": 1") { t.Fatal("equipment table or YAML editor uses a different clothing name") } diff --git a/server/control_inventory.go b/server/control_inventory.go @@ -19,7 +19,7 @@ func (server *server) itemTableRow_locked(w io.Writer, slot string, id *uint32) if definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition(); definition != nil { name = definition.Name } - fmt.Fprintf(w, "<a href='control/items/%d'>%s (ID %d)</a>", *id, html.EscapeString(name), *id) + fmt.Fprintf(w, "<a href='admin/items/%d'>%s (ID %d)</a>", *id, html.EscapeString(name), *id) } fmt.Fprint(w, "</td></tr>") } @@ -62,7 +62,7 @@ func (server *server) inventoryTables_locked(w io.Writer, inventory playerInvent if len(server.items[item.ID].Slots) == 0 { continue } - fmt.Fprintf(w, "<h2>Container <a href='control/items/%d'>%s (ID %d)</a></h2>", item.ID, + fmt.Fprintf(w, "<h2>Container <a href='admin/items/%d'>%s (ID %d)</a></h2>", item.ID, html.EscapeString(gamedata.ItemTemplates[item.Template].Name), item.ID) server.backpackTable_locked(w, server.items[item.ID]) } diff --git a/server/control_inventory_test.go b/server/control_inventory_test.go @@ -16,16 +16,16 @@ func newControlInventoryWorld(t *testing.T) *server { t.Helper() useNPCData(t, testNPCData()) world := newTestServer(t) - if response := postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}); response.Code != http.StatusSeeOther { + if response := postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}); response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } for _, template := range []string{"121567", "85557", "99228", "121567"} { - if response := postControlForm(world, "/control/items", url.Values{"template": {template}}); response.Code != http.StatusSeeOther { + if response := postControlForm(world, "/admin/items", url.Values{"template": {template}}); response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } } for _, placement := range [][2]string{{"1", "0:64"}, {"2", "0:18"}, {"3", "0:65"}, {"4", "3:0"}} { - response := postControlForm(world, "/control/items/"+placement[0], url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {placement[1]}}) + response := postControlForm(world, "/admin/items/"+placement[0], url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {placement[1]}}) if response.Code != http.StatusSeeOther { t.Fatal(response.Body.String()) } @@ -36,13 +36,13 @@ func newControlInventoryWorld(t *testing.T) *server { func TestControlCharacterDocumentSeparatesEquipment(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) - postControlForm(world, "/control/items", url.Values{"template": {"85557"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"85557"}}) - response := postControlForm(world, "/control/users/1", url.Values{"data": {"equipment: {clothes_head: 1}\n"}}) + response := postControlForm(world, "/admin/users/1", url.Values{"data": {"equipment: {clothes_head: 1}\n"}}) restarted := newServerForTest(t) page := httptest.NewRecorder() - restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) + adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/1", nil)) if response.Code != http.StatusSeeOther { t.Fatalf("top-level equipment save: %d %s", response.Code, response.Body.String()) @@ -68,15 +68,15 @@ func TestControlInventoryTablesShowInstancesContainersAndEmptySlots(t *testing.T world.baseURL = "/share/test/" page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/share/test/control/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/share/test/admin/users/1", nil)) body := page.Body.String() for _, expected := range []string{ "<base href='/share/test/'>", "<textarea name='data'", "<h2>Inventory</h2>", "<h2>Equipment</h2>", "<h2>Bank</h2>", - "<tr><td>inventory_slot_1</td><td><a href='control/items/1'>Solar-Powered Pistol (ID 1)</a></td></tr>", - "<tr><td>clothes_head</td><td><a href='control/items/2'>Worn Metaplast Armor Helmet (ID 2)</a></td></tr>", - "<h2>Container <a href='control/items/3'>Small Backpack (ID 3)</a></h2>", - "<tr><td>slot_1</td><td><a href='control/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>", + "<tr><td>inventory_slot_1</td><td><a href='admin/items/1'>Solar-Powered Pistol (ID 1)</a></td></tr>", + "<tr><td>clothes_head</td><td><a href='admin/items/2'>Worn Metaplast Armor Helmet (ID 2)</a></td></tr>", + "<h2>Container <a href='admin/items/3'>Small Backpack (ID 3)</a></h2>", + "<tr><td>slot_1</td><td><a href='admin/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>", "<tr><td>slot_21</td><td>Empty</td></tr>", "<tr><td>slot_102</td><td>Empty</td></tr>", } { @@ -93,16 +93,16 @@ func TestControlBackpackPagesLinkContentsAndParentContainer(t *testing.T) { world := newControlInventoryWorld(t) bag, child := httptest.NewRecorder(), httptest.NewRecorder() - world.httpHandler().ServeHTTP(bag, httptest.NewRequest("GET", "/control/items/3", nil)) - world.httpHandler().ServeHTTP(child, httptest.NewRequest("GET", "/control/items/4", nil)) + adminTestHandler(world).ServeHTTP(bag, httptest.NewRequest("GET", "/admin/items/3", nil)) + adminTestHandler(world).ServeHTTP(child, httptest.NewRequest("GET", "/admin/items/4", nil)) if !strings.Contains(bag.Body.String(), "<h2>Contents</h2>") || - !strings.Contains(bag.Body.String(), "<tr><td>slot_1</td><td><a href='control/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>") || + !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='control/users/1'>Explorer (1)</a>") { + !strings.Contains(bag.Body.String(), "<a href='admin/users/1'>Explorer (1)</a>") { t.Fatal("backpack page lost its owner or readable contents") } - if !strings.Contains(child.Body.String(), "<a href='control/items/3'>Container 3, slot_1</a>") { + if !strings.Contains(child.Body.String(), "<a href='admin/items/3'>Container 3, slot_1</a>") { t.Fatal("contained item has no link to its parent backpack") } } @@ -110,7 +110,7 @@ func TestControlBackpackPagesLinkContentsAndParentContainer(t *testing.T) { func TestControlEquipmentClearUnassignsWithoutLosingItems(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/control/users/1", url.Values{"data": {"equipment: {clothes_head: null}\n"}}) + response := postControlForm(world, "/admin/users/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) @@ -119,7 +119,7 @@ func TestControlEquipmentClearUnassignsWithoutLosingItems(t *testing.T) { t.Fatalf("clear changed unrelated items: %d, placements %d, %v", response.Code, placements, err) } page := httptest.NewRecorder() - restarted.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/2", nil)) + adminTestHandler(restarted).ServeHTTP(page, httptest.NewRequest("GET", "/admin/items/2", nil)) if !strings.Contains(page.Body.String(), "<p>Unassigned.") || len(restarted.characters[1].inventory.Containers[3]) != 1 { t.Fatal("cleared armor remained assigned or backpack contents changed") } @@ -137,7 +137,7 @@ func TestControlEquipmentRejectsInvalidPlacementsAtomically(t *testing.T) { t.Run(name, func(t *testing.T) { world := newControlInventoryWorld(t) - response := postControlForm(world, "/control/users/1", url.Values{"data": {"name: Changed\n" + document}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Other"}}) - postControlForm(world, "/control/items", url.Values{"template": {"85557"}}) - assigned := postControlForm(world, "/control/items/5", url.Values{"action": {"assign"}, "owner": {"2"}, "destination": {"0:18"}}) + postControlForm(world, "/admin/users", 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, "/control/users/1", url.Values{"data": {"equipment: {clothes_head: 5}\n"}}) + response := postControlForm(world, "/admin/users/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,18 +175,18 @@ 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, "/control/users/1", url.Values{"data": {document}}) + prepared := postControlForm(world, "/admin/users/1", url.Values{"data": {document}}) if prepared.Code != http.StatusSeeOther { t.Fatal(prepared.Body.String()) } page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/users/1", nil)) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/users/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='control/items/3'>Small Backpack (ID 3)</a></td></tr>") || - !strings.Contains(page.Body.String(), "<h2>Container <a href='control/items/3'>Small Backpack (ID 3)</a></h2>") || - !strings.Contains(page.Body.String(), "<tr><td>slot_1</td><td><a href='control/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>") { + !strings.Contains(page.Body.String(), "<tr><td>inventory_slot_2</td><td><a href='admin/items/3'>Small Backpack (ID 3)</a></td></tr>") || + !strings.Contains(page.Body.String(), "<h2>Container <a href='admin/items/3'>Small Backpack (ID 3)</a></h2>") || + !strings.Contains(page.Body.String(), "<tr><td>slot_1</td><td><a href='admin/items/4'>Solar-Powered Pistol (ID 4)</a></td></tr>") { t.Fatal("reclaim hides an assigned item or its backpack contents") } } diff --git a/server/control_test.go b/server/control_test.go @@ -19,7 +19,7 @@ func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) { defer connection.Close() client.SetDeadline(time.Now().Add(5 * time.Second)) world.clients[player.id] = &worldClient{conn: connection, ready: true, id: player.id} - request := httptest.NewRequest("POST", "/control/time", strings.NewReader("hour=26&minute=45")) + request := httptest.NewRequest("POST", "/admin/time", strings.NewReader("hour=26&minute=45")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() done := make(chan struct{}) @@ -31,14 +31,14 @@ func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) { } <-done - if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/control" { + if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/admin" { t.Fatalf("time response: %d %v", response.Code, response.Header()) } if hex.EncodeToString(packet[12:]) != "00000001000000005f52412e0000c350000000010000000047bc16000000000000000001" { t.Fatalf("original clock update: %x", packet) } page := httptest.NewRecorder() - world.controlPage(page, httptest.NewRequest("GET", "/control", nil)) + world.controlPage(page, httptest.NewRequest("GET", "/admin", nil)) if !strings.Contains(page.Body.String(), "Game time: 26:45") { t.Fatalf("clock display: %s", page.Body.String()) } @@ -46,7 +46,7 @@ func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) { func TestSetGameTimeRejectsHourOutsideOriginalDay(t *testing.T) { world := newTestServer(t) - request := httptest.NewRequest("POST", "/control/time", strings.NewReader("hour=27&minute=0")) + request := httptest.NewRequest("POST", "/admin/time", strings.NewReader("hour=27&minute=0")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() @@ -66,7 +66,7 @@ func TestUserPageHasMapTeleportAndZoneFinder(t *testing.T) { } response := httptest.NewRecorder() - request := httptest.NewRequest("GET", "/control/users/1", nil) + request := httptest.NewRequest("GET", "/admin/users/1", nil) request.SetPathValue("character", "1") world.userPage(response, request) @@ -74,7 +74,7 @@ func TestUserPageHasMapTeleportAndZoneFinder(t *testing.T) { if !strings.Contains(body, "<select data-map-find>") || !strings.Contains(body, "data-map-teleport>") { t.Fatalf("missing map controls") } - if strings.Count(body, "action='control/teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") { + if strings.Count(body, "action='admin/teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") { t.Fatalf("generic zone teleport is still present") } } @@ -83,8 +83,8 @@ func TestTeleportRejectsZoneWithoutOriginalAssets(t *testing.T) { world := newTestServer(t) player := world.newCharacter() mux := http.NewServeMux() - mux.HandleFunc("POST /control/teleport/{character}", world.teleportPlayer) - request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=690")) + mux.HandleFunc("POST /admin/teleport/{character}", world.teleportPlayer) + request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=690")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() diff --git a/server/database.go b/server/database.go @@ -8,8 +8,6 @@ import ( "os" "strings" "time" - - _ "github.com/mattn/go-sqlite3" ) //go:embed world.sql @@ -31,10 +29,7 @@ func (server *server) database() (*sql.DB, error) { if err := file.Close(); err != nil { return nil, err } - db, err := sql.Open("sqlite3", "data/world.sqlite?_foreign_keys=on&_journal_mode=WAL&_synchronous=FULL&_busy_timeout=5000") - if err != nil { - return nil, err - } + db := sql.OpenDB(databaseConnector{&server.databaseQueries}) // One connection orders chat and world transactions; WAL permits external readers. db.SetMaxOpenConns(1) _, err = db.Exec(worldSchema) diff --git a/server/database_metrics.go b/server/database_metrics.go @@ -0,0 +1,57 @@ +package main + +import ( + "context" + "database/sql/driver" + "sync/atomic" + + "github.com/mattn/go-sqlite3" +) + +// Count executions at the driver boundary, including prepared transaction queries. +// Transaction control and SQLite's internal trigger statements are not queries. +type databaseConnector struct{ queries *atomic.Uint64 } + +func (connector databaseConnector) Driver() driver.Driver { return &sqlite3.SQLiteDriver{} } +func (connector databaseConnector) Connect(ctx context.Context) (driver.Conn, error) { + connection, err := connector.Driver().Open("data/world.sqlite?_foreign_keys=on&_journal_mode=WAL&_synchronous=FULL&_busy_timeout=5000") + if err != nil { + return nil, err + } + return &databaseConnection{connection.(*sqlite3.SQLiteConn), connector.queries}, nil +} + +type databaseConnection struct { + *sqlite3.SQLiteConn + queries *atomic.Uint64 +} + +func (connection *databaseConnection) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + connection.queries.Add(1) + return connection.SQLiteConn.ExecContext(ctx, query, args) +} +func (connection *databaseConnection) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + connection.queries.Add(1) + return connection.SQLiteConn.QueryContext(ctx, query, args) +} +func (connection *databaseConnection) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + statement, err := connection.SQLiteConn.PrepareContext(ctx, query) + if err != nil { + return nil, err + } + return &databaseStatement{statement.(*sqlite3.SQLiteStmt), connection.queries}, nil +} + +type databaseStatement struct { + *sqlite3.SQLiteStmt + queries *atomic.Uint64 +} + +func (statement *databaseStatement) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { + statement.queries.Add(1) + return statement.SQLiteStmt.ExecContext(ctx, args) +} +func (statement *databaseStatement) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { + statement.queries.Add(1) + return statement.SQLiteStmt.QueryContext(ctx, args) +} 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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) player := world.characters[1] player.health, player.nano, player.sitting, player.aggDef = 27, 11, true, 33 player.inventory.Credits = 913 @@ -112,7 +112,7 @@ func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} world.corpseExpiry = []*character{npc} world.npcRespawns = []npcRespawn{{npc, now.Add(100 * time.Second)}} - response := postControlForm(world, "/control/time", url.Values{"hour": {"9"}, "minute": {"17"}}) + response := postControlForm(world, "/admin/time", url.Values{"hour": {"9"}, "minute": {"17"}}) if err := world.flushWorld(); err != nil { t.Fatal(err) @@ -219,10 +219,10 @@ func TestWorldDatabaseRollsBackCorpseCashWithInventory(t *testing.T) { func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) world.characters[1].health, world.characters[1].nano = 30, 12 - response := postControlForm(world, "/control/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/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"}}) 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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) now := time.Now() if err := world.checkpointWorld(now); err != nil { t.Fatal(err) diff --git a/server/embedded_resources_test.go b/server/embedded_resources_test.go @@ -24,9 +24,9 @@ func TestEmbeddedResourcesServeWithoutExternalFiles(t *testing.T) { mux.HandleFunc("GET /browser-resource-index", browserResourceIndex) mux.HandleFunc("GET /wasm/", (&server{baseURL: "/"}).browserClient) mux.HandleFunc("GET /{$}", (&server{baseURL: "/"}).browserClient) - mux.Handle("GET /control/map-assets/", http.StripPrefix("/control/map-assets/", http.FileServerFS(maps))) + mux.Handle("GET /admin/map-assets/", http.StripPrefix("/admin/map-assets/", http.FileServerFS(maps))) - for _, path := range []string{"/", "/wasm/game.js", "/wasm/build.json", "/browser-manifest", "/browser-resource-index", "/control/map-assets/manifest.json", "/browser-assets/version.id", "/browser-assets/cd_image/text/help/What%20%27s-This%20General%20Help.txt"} { + for _, path := range []string{"/", "/wasm/game.js", "/wasm/build.json", "/browser-manifest", "/browser-resource-index", "/admin/map-assets/manifest.json", "/browser-assets/version.id", "/browser-assets/cd_image/text/help/What%20%27s-This%20General%20Help.txt"} { response := httptest.NewRecorder() mux.ServeHTTP(response, httptest.NewRequest("GET", path, nil)) diff --git a/server/fling_crash_test.go b/server/fling_crash_test.go @@ -12,8 +12,6 @@ import ( "strings" "testing" "time" - - "github.com/mattn/go-sqlite3" ) type flingCrashCheckpoint struct { @@ -83,7 +81,7 @@ func runFlingCrashChild(t *testing.T, mode string) { t.Fatal(err) } err = connection.Raw(func(driver any) error { - driver.(*sqlite3.SQLiteConn).RegisterCommitHook(func() int { checkpoint(nil); return 0 }) + driver.(*databaseConnection).RegisterCommitHook(func() int { checkpoint(nil); return 0 }) return nil }) connection.Close() diff --git a/server/flying_vehicle_test.go b/server/flying_vehicle_test.go @@ -163,7 +163,7 @@ func TestFlyingVehiclePredictsPitchedForwardAndReverse(t *testing.T) { world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], scenario.forward, time.Now().Add(-time.Second)) response := httptest.NewRecorder() - world.mapPlayers(response, httptest.NewRequest("GET", "/map/players", nil)) + world.mapPlayers(response, httptest.NewRequest("GET", "/admin/map-players?offline=1", nil)) var result struct{ Players []mapPlayer } if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil { t.Fatal(err) diff --git a/server/http.go b/server/http.go @@ -10,40 +10,14 @@ import ( func (server *server) httpHandler() http.Handler { mux := http.NewServeMux() // Directory redirects must keep the public prefix and query string. - for _, directory := range []string{"wasm", "control/map-assets"} { - mux.HandleFunc("GET /"+directory, func(w http.ResponseWriter, r *http.Request) { - location := server.baseURL + directory + "/" - if r.URL.RawQuery != "" { - location += "?" + r.URL.RawQuery - } - http.Redirect(w, r, location, http.StatusMovedPermanently) - }) - } - - mux.HandleFunc("GET /control", server.controlPage) - mux.HandleFunc("GET /control/users/{character}", server.userPage) - mux.HandleFunc("POST /control/users", server.createUser) - mux.HandleFunc("POST /control/users/{character}", server.editUser) - mux.HandleFunc("GET /control/items", server.itemsPage) - mux.HandleFunc("GET /control/items/catalog", server.itemCatalogPage) - mux.HandleFunc("POST /control/items", server.createItem) - mux.HandleFunc("GET /control/items/{item}", server.itemPage) - mux.HandleFunc("POST /control/items/{item}", server.editItem) - mux.HandleFunc("GET /control/control-map.js", controlMapScript) - mux.HandleFunc("GET /control/map-players", server.mapPlayers) - mapResources, err := fs.Sub(resources, "maps") - if err != nil { - log.Fatal(err) - } - mapFiles := http.StripPrefix("/control/map-assets/", http.FileServerFS(mapResources)) - mux.HandleFunc("GET /control/map-assets/", func(w http.ResponseWriter, r *http.Request) { - if strings.HasSuffix(r.URL.Path, ".png") { - w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") - } else { - w.Header().Set("Cache-Control", "no-cache") + mux.HandleFunc("GET /wasm", func(w http.ResponseWriter, r *http.Request) { + location := server.baseURL + "wasm/" + if r.URL.RawQuery != "" { + location += "?" + r.URL.RawQuery } - mapFiles.ServeHTTP(w, r) + http.Redirect(w, r, location, http.StatusMovedPermanently) }) + mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) mux.Handle("GET /favicon.ico", http.FileServerFS(resources)) mux.HandleFunc("POST /browser-launch", server.browserLaunch) @@ -56,8 +30,9 @@ func (server *server) httpHandler() http.Handler { mux.HandleFunc("POST /browser-profile/{session}", browserProfile) mux.HandleFunc("GET /wasm/", server.browserClient) mux.HandleFunc("GET /{$}", server.browserClient) - mux.HandleFunc("POST /control/time", server.setGameTime) - mux.HandleFunc("POST /control/teleport/{character}", server.teleportPlayer) + protectedAdmin := http.NewCrossOriginProtection().Handler(server.adminAuth(server.adminHandler())) + mux.Handle("/admin", protectedAdmin) + mux.Handle("/admin/", protectedAdmin) // Keep the original launcher's dimension list available. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { traceLog.Printf("HTTP %s %s", r.Method, r.URL.Path) @@ -76,3 +51,49 @@ func (server *server) httpHandler() http.Handler { mounted.Handle(server.baseURL, http.StripPrefix(strings.TrimSuffix(server.baseURL, "/"), mux)) return mounted } + +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/map", server.mapPage) + admin.HandleFunc("GET /admin/stats", server.adminStats) + admin.HandleFunc("GET /admin/sql", server.sqlPage) + admin.HandleFunc("POST /admin/sql", server.sqlPage) + admin.HandleFunc("POST /admin/logout", server.adminLogout) + admin.HandleFunc("GET /admin/users/{character}", server.userPage) + admin.HandleFunc("POST /admin/users/{character}", server.editUser) + admin.HandleFunc("GET /admin/items", server.itemsPage) + admin.HandleFunc("GET /admin/items/catalog", server.itemCatalogPage) + admin.HandleFunc("POST /admin/items", server.createItem) + admin.HandleFunc("GET /admin/items/{item}", server.itemPage) + admin.HandleFunc("POST /admin/items/{item}", server.editItem) + admin.HandleFunc("GET /admin/control-map.js", controlMapScript) + admin.HandleFunc("GET /admin/map-players", server.mapPlayers) + admin.HandleFunc("GET /admin/map-entities", server.mapEntities) + admin.HandleFunc("GET /admin/map-assets", func(w http.ResponseWriter, r *http.Request) { + location := server.baseURL + "admin/map-assets/" + if r.URL.RawQuery != "" { + location += "?" + r.URL.RawQuery + } + http.Redirect(w, r, location, http.StatusMovedPermanently) + }) + mapResources, err := fs.Sub(resources, "maps") + if err != nil { + log.Fatal(err) + } + mapFiles := http.StripPrefix("/admin/map-assets/", http.FileServerFS(mapResources)) + admin.HandleFunc("GET /admin/map-assets/", func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, ".png") { + w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") + } else { + w.Header().Set("Cache-Control", "no-cache") + } + mapFiles.ServeHTTP(w, r) + }) + admin.HandleFunc("POST /admin/time", server.setGameTime) + admin.HandleFunc("POST /admin/weather", server.setWeather) + admin.HandleFunc("POST /admin/teleport/{character}", server.teleportPlayer) + return admin +} diff --git a/server/http_test.go b/server/http_test.go @@ -45,12 +45,12 @@ func TestHTTPHandlerMountsGameAndControls(t *testing.T) { world := newTestServer(t) world.baseURL = baseURL useResources(t, assets.Files) - handler := world.httpHandler() + handler := adminTestHandler(world) game := httptest.NewRecorder() handler.ServeHTTP(game, httptest.NewRequest("GET", baseURL, nil)) controls := httptest.NewRecorder() - handler.ServeHTTP(controls, httptest.NewRequest("GET", baseURL+"control", nil)) + handler.ServeHTTP(controls, httptest.NewRequest("GET", baseURL+"admin", nil)) asset := httptest.NewRecorder() handler.ServeHTTP(asset, httptest.NewRequest("GET", baseURL+"browser-assets/version.id", nil)) @@ -60,7 +60,7 @@ func TestHTTPHandlerMountsGameAndControls(t *testing.T) { if !strings.Contains(game.Body.String(), `<link rel="icon" href="favicon.ico">`) { t.Fatal("game page has no icon relative to its public base URL") } - if controls.Code != http.StatusOK || !strings.Contains(controls.Body.String(), "<base href='"+baseURL+"'>") || !strings.Contains(controls.Body.String(), "action='control/users'") { + if controls.Code != http.StatusOK || !strings.Contains(controls.Body.String(), "<base href='"+baseURL+"'>") || !strings.Contains(controls.Body.String(), "action='admin/time'") { t.Fatalf("control page: HTTP %d, missing scoped forms", controls.Code) } if asset.Code != http.StatusOK || strings.TrimSpace(asset.Body.String()) != "14.9.1" { @@ -98,8 +98,8 @@ func TestHTTPHandlerScopesVisitorCookieAndRedirects(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) world.baseURL = "/share/demo/" - handler := world.httpHandler() - request := httptest.NewRequest("POST", world.baseURL+"control/time", strings.NewReader("hour=13&minute=30")) + handler := adminTestHandler(world) + request := httptest.NewRequest("POST", world.baseURL+"admin/time", strings.NewReader("hour=13&minute=30")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") redirect := httptest.NewRecorder() @@ -107,9 +107,9 @@ func TestHTTPHandlerScopesVisitorCookieAndRedirects(t *testing.T) { launch := httptest.NewRecorder() handler.ServeHTTP(launch, httptest.NewRequest("POST", "https://example.test"+world.baseURL+"browser-launch", nil)) outside := httptest.NewRecorder() - handler.ServeHTTP(outside, httptest.NewRequest("GET", "/control", nil)) + handler.ServeHTTP(outside, httptest.NewRequest("GET", "/admin", nil)) - if redirect.Code != http.StatusSeeOther || redirect.Header().Get("Location") != "/share/demo/control" { + if redirect.Code != http.StatusSeeOther || redirect.Header().Get("Location") != "/share/demo/admin" { t.Fatalf("control redirect: HTTP %d, %v", redirect.Code, redirect.Header()) } cookies := launch.Result().Cookies() @@ -123,10 +123,10 @@ func TestHTTPHandlerScopesVisitorCookieAndRedirects(t *testing.T) { func TestHTTPHandlerPreservesBaseURLInDirectoryRedirects(t *testing.T) { world := &server{baseURL: "/share/demo/"} - handler := world.httpHandler() + handler := adminTestHandler(world) for _, redirect := range []struct{ from, to string }{ {"/share/demo/wasm?profile=1", "/share/demo/wasm/?profile=1"}, - {"/share/demo/control/map-assets", "/share/demo/control/map-assets/"}, + {"/share/demo/admin/map-assets", "/share/demo/admin/map-assets/"}, } { response := httptest.NewRecorder() handler.ServeHTTP(response, httptest.NewRequest("GET", redirect.from, nil)) 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, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Observer"}}) + response := postControlForm(world, "/admin/users", 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, "/control/users/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {string(contents)}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {string(contents)}}) + failed := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {string(contents)}}) + retry := postControlForm(world, "/admin/users/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 @@ -107,7 +107,8 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { return query != "" && !strings.Contains(strings.ToLower(search), query) }) w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Items</title></head><body><p><a href='control'>Server controls</a></p><h1>Item instances</h1><p><a href='control/items/catalog'>Create item: browse catalog</a></p><form method='get' action='control/items'><label>Filter ID, name, template or owner <input name='q' value='%s'></label> <button>Filter</button></form>", html.EscapeString(server.baseURL), html.EscapeString(r.FormValue("q"))) + server.adminPageStart(w, "Items", "Items") + fmt.Fprintf(w, "<h1>Item instances</h1><p><a href='admin/items/catalog'>Create item: browse catalog</a></p><form method='get' action='admin/items'><label>Filter ID, name, template or owner <input name='q' value='%s'></label> <button>Filter</button></form>", html.EscapeString(r.FormValue("q"))) start, end := itemPagination(w, r, len(ids)) fmt.Fprint(w, "<table><tr><th>ID</th><th>Name</th><th>QL</th><th>Count</th><th>Owner</th><th>Location</th></tr>") for _, id := range ids[start:end] { @@ -122,17 +123,17 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { if location.owner != 0 { owner = names[location.owner] } - fmt.Fprintf(w, "<tr><td><a href='control/items/%d'>%d</a></td><td><a href='control/items/%d'>%s</a></td><td>%d</td><td>%d</td><td>", id, id, id, html.EscapeString(name), record.Quality, record.Count) + fmt.Fprintf(w, "<tr><td><a href='admin/items/%d'>%d</a></td><td><a href='admin/items/%d'>%s</a></td><td>%d</td><td>%d</td><td>", id, id, id, html.EscapeString(name), record.Quality, record.Count) if location.owner == 0 { fmt.Fprint(w, owner) } else { - fmt.Fprintf(w, "<a href='control/users/%d'>%s (%d)</a>", location.owner, html.EscapeString(owner), location.owner) + fmt.Fprintf(w, "<a href='admin/users/%d'>%s (%d)</a>", location.owner, html.EscapeString(owner), location.owner) } fmt.Fprintf(w, "</td><td>%s</td></tr>", html.EscapeString(location.label)) } fmt.Fprint(w, "</table>") itemPagination(w, r, len(ids)) - fmt.Fprint(w, "</body></html>") + fmt.Fprint(w, "</main></body></html>") } func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { @@ -152,15 +153,16 @@ func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { // Filter before paging so every page refers to the same ordered result set. w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Create item</title></head><body><p><a href='control/items'>Item instances</a></p><h1>Create item</h1><p>Each row is a catalog template at its listed quality. Create makes an unassigned instance.</p><form method='get' action='control/items/catalog'><label>Filter by name or template ID <input name='catalog' value='%s'></label> <button>Filter</button> <a href='control/items/catalog'>Clear filter</a></form>", html.EscapeString(server.baseURL), html.EscapeString(r.FormValue("catalog"))) + server.adminPageStart(w, "Create item", "Items") + fmt.Fprintf(w, "<h1>Create item</h1><form method='get' action='admin/items/catalog'><label>Filter by name or template ID <input name='catalog' value='%s'></label> <button>Filter</button> <a href='admin/items/catalog'>Clear filter</a></form>", html.EscapeString(r.FormValue("catalog"))) start, end := itemPagination(w, r, len(matches)) - fmt.Fprint(w, "<form method='post' action='control/items'><table><tr><th>Name</th><th>Template</th><th>QL</th><th></th></tr>") + fmt.Fprint(w, "<form method='post' action='admin/items'><table><tr><th>Name</th><th>Template</th><th>QL</th><th></th></tr>") for _, definition := range matches[start:end] { fmt.Fprintf(w, "<tr><td>%s</td><td>%d</td><td>%d</td><td><button name='template' value='%d'>Create</button></td></tr>", html.EscapeString(definition.Name), definition.ID, *definition.Quality, definition.ID) } fmt.Fprint(w, "</table></form>") itemPagination(w, r, len(matches)) - fmt.Fprint(w, "</body></html>") + fmt.Fprint(w, "</main></body></html>") } func (server *server) createItem(w http.ResponseWriter, r *http.Request) { @@ -192,7 +194,7 @@ func (server *server) createItem(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("%scontrol/items/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/items/%d", server.baseURL, id), http.StatusSeeOther) } func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { @@ -233,29 +235,30 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { } definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition() w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprintf(w, "<!doctype html><html><head><base href='%s'><title>Item %d</title></head><body><p><a href='control/items'>All items</a></p><h1>Item %d</h1>", html.EscapeString(server.baseURL), id, id) + server.adminPageStart(w, fmt.Sprintf("Item %d", id), "Items") + fmt.Fprintf(w, "<h1>Item %d</h1>", id) if definition != nil { 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='control/users/%d'>%s (%d)</a>. ", location.owner, html.EscapeString(ownerName), location.owner) + fmt.Fprintf(w, "<p>Owner: <a href='admin/users/%d'>%s (%d)</a>. ", location.owner, html.EscapeString(ownerName), location.owner) } else { fmt.Fprint(w, "<p>Unassigned. ") } if location.container != 0 { - fmt.Fprintf(w, "<a href='control/items/%d'>%s</a>", location.container, html.EscapeString(location.label)) + fmt.Fprintf(w, "<a href='admin/items/%d'>%s</a>", location.container, html.EscapeString(location.label)) } else { fmt.Fprint(w, html.EscapeString(location.label)) } fmt.Fprint(w, "</p>") if location.label == "" { - fmt.Fprintf(w, "<h2>Assign item</h2><form method='get' action='control/items/%d'><label>Player <select name='owner' required>", id) + fmt.Fprintf(w, "<h2>Assign item</h2><form method='get' action='admin/items/%d'><label>Player <select name='owner' required>", id) for _, user := range users { fmt.Fprintf(w, "<option value='%d'>%s (%d)</option>", user.ID, html.EscapeString(user.Name), user.ID) } fmt.Fprint(w, "</select></label> <button>Choose player</button></form>") if selectedName != "" { - fmt.Fprintf(w, "<form method='post' action='control/items/%d'><input type='hidden' name='action' value='assign'><input type='hidden' name='owner' value='%d'><label>Free slot for %s <select name='destination' required>", id, owner, html.EscapeString(selectedName)) + fmt.Fprintf(w, "<form method='post' action='admin/items/%d'><input type='hidden' name='action' value='assign'><input type='hidden' name='owner' value='%d'><label>Free slot for %s <select name='destination' required>", id, owner, html.EscapeString(selectedName)) item := ownedItem{ID: uint32(id), Type: record.Type, Template: record.Template, Quality: record.Quality, Count: record.Count, Ammo: record.Ammo} for _, destination := range controlItemSlots(selectedInventory, item) { label := equipmentSlots[destination.slot] @@ -269,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><p>ID %d is fixed. Slots contain instance IDs or null; containers have 21 slots. Saving reconnects the owner.</p><form method='post' action='control/items/%d'><textarea name='data' rows='25' cols='80' required>%s</textarea><p><button>Save item</button></p></form>", id, 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 and reconnect owner</button></p></form>", id, html.EscapeString(string(contents))) if contentsTable.Len() != 0 { fmt.Fprint(w, "<h2>Contents</h2>", contentsTable.String()) } @@ -281,7 +284,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { } fmt.Fprintf(w, "<h2>Catalog properties</h2><textarea rows='25' cols='80' readonly>%s</textarea>", html.EscapeString(string(catalog))) } - fmt.Fprint(w, "</body></html>") + fmt.Fprint(w, "</main></body></html>") } func (server *server) editItem(w http.ResponseWriter, r *http.Request) { @@ -340,7 +343,7 @@ func (server *server) editItem(w http.ResponseWriter, r *http.Request) { } else { server.mutex.Unlock() } - http.Redirect(w, r, fmt.Sprintf("%scontrol/items/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/items/%d", server.baseURL, id), http.StatusSeeOther) } func (server *server) assignItem(w http.ResponseWriter, r *http.Request) { @@ -407,5 +410,5 @@ func (server *server) assignItem(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("%scontrol/items/%d", server.baseURL, id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%sadmin/items/%d", server.baseURL, id), http.StatusSeeOther) } diff --git a/server/item_store_test.go b/server/item_store_test.go @@ -40,7 +40,7 @@ func TestItemStoreLoadsUnassignedInstancesWithoutCharacters(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - response := postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + response := postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) restarted := newServerForTest(t) if response.Code != http.StatusSeeOther || len(restarted.items) != 1 || restarted.items[1].Template != 121567 || restarted.nextItem != 1 { @@ -51,11 +51,11 @@ func TestItemStoreLoadsUnassignedInstancesWithoutCharacters(t *testing.T) { func TestDatabaseRejectsSharedInstanceReferences(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"First"}}) - postControlForm(world, "/control/users", url.Values{"name": {"Second"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) + postControlForm(world, "/admin/users", 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}"}}) _, 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,19 +73,19 @@ func TestDatabaseRejectsSharedInstanceReferences(t *testing.T) { func TestControlItemAssignmentOffersOnlyFreeCompatibleSlots(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"Explorer"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - postControlForm(world, "/control/users/1", url.Values{"data": {"inventory:\n slots: {inventory_slot_1: 1}\n"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + postControlForm(world, "/admin/users", 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/items", url.Values{"template": {"121567"}}) page := httptest.NewRecorder() - world.httpHandler().ServeHTTP(page, httptest.NewRequest("GET", "/control/items/2?owner=1", nil)) - occupied := postControlForm(world, "/control/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:64"}}) - placed := postControlForm(world, "/control/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}}) - postControlForm(world, "/control/items", url.Values{"template": {"99228"}}) - bag := postControlForm(world, "/control/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:66"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) - contained := postControlForm(world, "/control/items/4", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"3:20"}}) + adminTestHandler(world).ServeHTTP(page, httptest.NewRequest("GET", "/admin/items/2?owner=1", nil)) + occupied := postControlForm(world, "/admin/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:64"}}) + placed := postControlForm(world, "/admin/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"99228"}}) + bag := postControlForm(world, "/admin/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:66"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) + contained := postControlForm(world, "/admin/items/4", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"3:20"}}) restarted := newServerForTest(t) if page.Code != http.StatusOK || strings.Contains(page.Body.String(), "value='0:64'") || strings.Contains(page.Body.String(), "value='0:8'") || @@ -106,11 +106,11 @@ func TestControlBackpackRejectsNestedBackpacksAndSharedContents(t *testing.T) { t.Run(contents, func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/items", url.Values{"template": {"99228"}}) - postControlForm(world, "/control/items", url.Values{"template": {"99228"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"99228"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"99228"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) - response := postControlForm(world, "/control/items/1", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {" + contents + "}\n"}}) + response := postControlForm(world, "/admin/items/1", url.Values{"data": {"type: 51017\ntemplate: 99228\nquality: 1\ncount: 1\nslots: {" + contents + "}\n"}}) if response.Code != http.StatusBadRequest || world.items[1].Slots["slot_1"] != nil || world.nextItem != 3 { t.Fatalf("invalid backpack content accepted: %d %s", response.Code, response.Body.String()) @@ -126,7 +126,7 @@ func TestControlConcurrentCreationAllocatesUniqueGlobalIDs(t *testing.T) { for range 8 { go func() { - responses <- postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + responses <- postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) }() } ids := make(map[string]bool) @@ -147,14 +147,14 @@ func TestControlConcurrentCreationAllocatesUniqueGlobalIDs(t *testing.T) { func TestControlConcurrentAssignmentCannotShareOneInstance(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/users", url.Values{"name": {"First"}}) - postControlForm(world, "/control/users", url.Values{"name": {"Second"}}) - postControlForm(world, "/control/items", url.Values{"template": {"121567"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"First"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Second"}}) + postControlForm(world, "/admin/items", url.Values{"template": {"121567"}}) responses := make(chan *httptest.ResponseRecorder, 2) for _, owner := range []string{"1", "2"} { go func() { - responses <- postControlForm(world, "/control/items/1", url.Values{"action": {"assign"}, "owner": {owner}, "destination": {"0:64"}}) + responses <- postControlForm(world, "/admin/items/1", url.Values{"action": {"assign"}, "owner": {owner}, "destination": {"0:64"}}) }() } statuses := make(map[int]int) diff --git a/server/main.go b/server/main.go @@ -25,7 +25,7 @@ var traceLog = log.New(io.Discard, "", log.LstdFlags) func main() { loginPort := flag.Int("login-port", 7500, "login port") worldPort := flag.Int("world-port", 7501, "world port") - httpPort := flag.Int("http-port", 8080, "HTTP and control panel port") + httpPort := flag.Int("http-port", 8080, "HTTP and admin port") baseURL := flag.String("base-url", "/", "URL path prefix (must start and end with /)") flag.Parse() if !strings.HasPrefix(*baseURL, "/") || !strings.HasSuffix(*baseURL, "/") || @@ -100,7 +100,7 @@ func main() { if err != nil { log.Fatal(err) } - log.Printf("Listening on all interfaces: HTTPS 8443, HTTP %d, login %d, world %d; local controls: http://127.0.0.1:%d%scontrol", server.httpPort, server.loginPort, server.worldPort, server.httpPort, server.baseURL) + log.Printf("Listening on all interfaces: HTTPS 8443, HTTP %d, login %d, world %d; administration: http://127.0.0.1:%d%sadmin", server.httpPort, server.loginPort, server.worldPort, server.httpPort, server.baseURL) for { conn, err := listener.Accept() if err != nil { 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 /control/teleport/{character}", world.teleportPlayer) + mux.HandleFunc("POST /admin/teleport/{character}", world.teleportPlayer) response := httptest.NewRecorder() done := make(chan struct{}) go func() { - request := httptest.NewRequest("POST", "/control/teleport/1", strings.NewReader("playfield=800")) + request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=800")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") mux.ServeHTTP(response, request) close(done) @@ -135,7 +135,7 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) { } <-done page := httptest.NewRecorder() - world.controlPage(page, httptest.NewRequest("GET", "/control", nil)) + world.usersPage(page, httptest.NewRequest("GET", "/admin", nil)) client.Close() reconnected, nextConnection := net.Pipe() defer reconnected.Close() @@ -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='control/users/1'>Local Explorer 1</a>") { + if !strings.Contains(page.Body.String(), "href='admin/users/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 @@ -136,8 +136,8 @@ test('panning past queued tiles loads the current view next', async () => { await new Promise(resolve => setImmediate(resolve)); map.render(); - assert.deepEqual(requests, ['control/map-assets/0.png', 'control/map-assets/1.png', 'control/map-assets/2.png', - 'control/map-assets/3.png', 'control/map-assets/4.png', 'control/map-assets/5.png', 'control/map-assets/19.png']); + assert.deepEqual(requests, ['admin/map-assets/0.png', 'admin/map-assets/1.png', 'admin/map-assets/2.png', + 'admin/map-assets/3.png', 'admin/map-assets/4.png', 'admin/map-assets/5.png', 'admin/map-assets/19.png']); }); test('unused terrain margins do not request tiles behind polygon clipping', () => { @@ -171,3 +171,39 @@ test('panning beyond the polygon bounds requests no terrain tiles', () => { assert.deepEqual(requests, []); }); + +test('pinching anchors the midpoint and does not turn into a teleport tap', () => { + const map = mapWithTiles(128, 1, () => { throw new Error('Unexpected tile request'); }); + map.canvas.getBoundingClientRect = () => ({left: 0, top: 0}); + map.canvas.setPointerCapture = () => {}; + map.canvas.hasPointerCapture = () => false; + map.pick = () => { throw new Error('Pinch must not select a destination'); }; + const pointer = (pointerId, clientX, clientY) => ({pointerId, clientX, clientY, button: 0}); + + map.pointerDown(pointer(1, 32, 64)); + map.pointerDown(pointer(2, 96, 64)); + map.pointerMove(pointer(2, 160, 64)); + map.pointerEnd(pointer(2, 160, 64)); + map.pointerMove(pointer(1, 42, 64)); + map.pointerEnd(pointer(1, 42, 64)); + clearTimeout(map.loadTimer); + + assert.equal(map.scale, 2); + assert.deepEqual(Array.from(map.center), [-21, 0]); + assert.equal(map.pointers.size, 0); +}); + +test('cancelled touch releases the gesture without selecting a destination', () => { + const map = mapWithTiles(128, 1, () => {}); + map.canvas.getBoundingClientRect = () => ({left: 0, top: 0}); + map.canvas.setPointerCapture = () => {}; + map.canvas.hasPointerCapture = () => false; + map.pick = () => { throw new Error('Cancelled touch must not select'); }; + const event = {pointerId: 1, clientX: 30, clientY: 30, button: 0}; + + map.pointerDown(event); + map.pointerEnd(event, true); + + assert.equal(map.drag, null); + assert.equal(map.pointers.size, 0); +}); diff --git a/server/maps.go b/server/maps.go @@ -10,11 +10,11 @@ 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><canvas data-map-canvas width='1000' height='480' style='width:100%%;height:480px;display:block;touch-action:none;border:1px solid #888' aria-label='World and player map'></canvas><p data-map-status>Loading maps...</p><p data-map-location>Drag to pan; use the mouse wheel or buttons to zoom. Moving player positions are estimated between client reports.</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 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) if character != 0 { - fmt.Fprintf(w, "<form method='post' action='control/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/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.Fprint(w, "</div><script src='control/control-map.js' defer></script>") + fmt.Fprint(w, "</div><script src='admin/control-map.js' defer></script>") } func controlMapScript(w http.ResponseWriter, r *http.Request) { @@ -61,6 +61,9 @@ func (server *server) mapPlayers(w http.ResponseWriter, r *http.Request) { } } } + if !player.Connected && r.URL.Query().Get("offline") != "1" && r.URL.Query().Get("character") != fmt.Sprint(player.ID) { + continue + } players = append(players, player) } server.mutex.Unlock() 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", "/control/teleport/1", strings.NewReader("playfield=950&x=52&z=56")) + request := httptest.NewRequest("POST", "/admin/teleport/1", 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", "/control/teleport/1", strings.NewReader("playfield=950&"+coordinates)) + request := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=950&"+coordinates)) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.SetPathValue("character", "1") response := httptest.NewRecorder() @@ -59,7 +59,7 @@ func TestMapPlayersPredictsMovementWithoutChangingSavedPosition(t *testing.T) { world.characters[player.id].movement = heldPlayerMovement(world.characters[player.id], 1, time.Now().Add(-time.Second)) response := httptest.NewRecorder() - world.mapPlayers(response, httptest.NewRequest("GET", "/control/map-players", nil)) + world.mapPlayers(response, httptest.NewRequest("GET", "/admin/map-players?offline=1", nil)) var feed struct { Players []mapPlayer `json:"players"` } @@ -84,7 +84,7 @@ func TestMapPlayersIncludesIndoorEntrance(t *testing.T) { world.zoneLinks["target"][705] = zoneLinks{Doors: []zoneDoor{{ID: 1, Position: [3]float32{100, 20, 200}}}} response := httptest.NewRecorder() - world.mapPlayers(response, httptest.NewRequest("GET", "/control/map-players", nil)) + world.mapPlayers(response, httptest.NewRequest("GET", "/admin/map-players?offline=1", nil)) if !strings.Contains(response.Body.String(), `"entrance":{"playfield":705,"position":[100,20,200]}`) { t.Fatalf("missing indoor entrance: %s", response.Body.String()) diff --git a/server/nano_reservation_test.go b/server/nano_reservation_test.go @@ -219,7 +219,7 @@ func TestNanoReservationItemEditCommitsRefundWithActorReload(t *testing.T) { } conn.packets = nil - response := postControlForm(world, "/control/items/3", url.Values{"data": {"type: 51005\ntemplate: 85366\nquality: 1\ncount: 24\n"}}) + response := postControlForm(world, "/admin/items/3", url.Values{"data": {"type: 51005\ntemplate: 85366\nquality: 1\ncount: 24\n"}}) var nano, reserved, count uint32 if err := world.db.QueryRow("SELECT characters.nano,characters.nano_reserved,items.count FROM characters JOIN items ON items.id=3 WHERE characters.id=1").Scan(&nano, &reserved, &count); err != nil { t.Fatal(err) diff --git a/server/nano_visibility_test.go b/server/nano_visibility_test.go @@ -6,7 +6,7 @@ import ( ) func TestNanoVisibilityRejectsAdmissionAndRefundsObstructedCompletion(t *testing.T) { - for _, kind := range []string{"direct", "periodic", "control", "friendly"} { + for _, kind := range []string{"direct", "periodic", "admin", "friendly"} { t.Run(kind, func(t *testing.T) { var world *server program := uint32(29618) @@ -16,7 +16,7 @@ func TestNanoVisibilityRejectsAdmissionAndRefundsObstructedCompletion(t *testing case "periodic": world, _ = newPeriodicNanoWorld(t) program = 43376 - case "control": + case "admin": fixture := controlNanoFixtures(t)[0] world, _ = newCombatNanoWorld(t, combatNanoFixture{Profession: fixture.Profession, Crystal: fixture.Crystal}) if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil { diff --git a/server/ncu_hacker_interface_test.go b/server/ncu_hacker_interface_test.go @@ -158,11 +158,11 @@ func TestControlNCUHackerInterfaceQualityBounds(t *testing.T) { t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - postControlForm(world, "/control/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) + postControlForm(world, "/admin/items", url.Values{"template": {fmt.Sprint(scenario.template)}}) before, _ := readTestItemStore(world) data := fmt.Sprintf("type: 51022\ntemplate: %d\nquality: %d\ncount: 1\n", scenario.template, scenario.quality) - response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/items/1", url.Values{"data": {data}}) after, err := readTestItemStore(world) if response.Code != scenario.status || err != nil { diff --git a/server/player_follow_test.go b/server/player_follow_test.go @@ -74,7 +74,7 @@ func playerFollowRequest(target uint32) []byte { } func TestPlayerFollowRejectsUntrustedTargetsAndRoutes(t *testing.T) { - for _, scenario := range []string{"short", "long", "foreign owner", "subject type", "target type", "pass-on", "scalar", "control", "correction", "waypoints", "missing target", "dead target", "other zone", "unseen NPC", "offline player", "loading player", "loading owner", "unready owner", "dead owner", "sitting owner", "replaced owner", "unsupported client"} { + for _, scenario := range []string{"short", "long", "foreign owner", "subject type", "target type", "pass-on", "scalar", "admin", "correction", "waypoints", "missing target", "dead target", "other zone", "unseen NPC", "offline player", "loading player", "loading owner", "unready owner", "dead owner", "sitting owner", "replaced owner", "unsupported client"} { t.Run(scenario, func(t *testing.T) { world, output := newCombatWorld(t) player, client := world.characters[1], world.clients[1] @@ -95,7 +95,7 @@ func TestPlayerFollowRejectsUntrustedTargetsAndRoutes(t *testing.T) { binary.BigEndian.PutUint32(request[12:], 0) case "scalar": binary.BigEndian.PutUint32(request[24:], 0x7f800000) - case "control": + case "admin": request[28] = 23 case "correction": request[29] = 1 diff --git a/server/player_movement.go b/server/player_movement.go @@ -601,6 +601,7 @@ func (server *server) advancePlayerMovement(now time.Time) { server.mutex.Lock() updates := make(map[*worldClient][][]byte) server.advancePlayerMovement_locked(now, updates) + server.weatherUpdates_locked(now, updates) server.mutex.Unlock() server.sendCombatUpdates(updates) } 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, "/control/users", url.Values{"name": {"Explorer"}}) - postControlForm(world, "/control/users", url.Values{"name": {"Observer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Observer"}}) - response := postControlForm(world, "/control/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) before, err := readTestPlayerRecord(1, "player") if err != nil { t.Fatal(err) } - response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", url.Values{"name": {"Explorer"}}) contents := fmt.Sprintf("level: %d\nexperience: %d\n", scenario.level, scenario.experience) - response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}}) + response := postControlForm(world, "/admin/users/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, "/control/users", url.Values{"name": {"Explorer"}}) + postControlForm(world, "/admin/users", 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, "/control/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response := postControlForm(world, "/admin/users/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, "/control/users/1", url.Values{"data": {"level: 2\nexperience: 50\n"}}) + response = postControlForm(world, "/admin/users/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/ranged_test.go b/server/ranged_test.go @@ -328,14 +328,14 @@ func TestPistolEquipmentUsesItsRequirementsAndPreservesLoadedRounds(t *testing.T func TestPistolControlAssignmentPreservesLoadedRounds(t *testing.T) { world, _ := newRangedWorld(t) world.baseURL = "/" - created := postControlForm(world, "/control/items", url.Values{"template": {"123742"}}) + created := postControlForm(world, "/admin/items", url.Values{"template": {"123742"}}) if created.Code != http.StatusSeeOther { t.Fatal("could not create pistol", created.Code) } data := "type: 51018\ntemplate: 123742\nquality: 1\ncount: 1\nammo: 9\n" - edited := postControlForm(world, "/control/items/3", url.Values{"data": {data}}) - assigned := postControlForm(world, "/control/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}}) + edited := postControlForm(world, "/admin/items/3", url.Values{"data": {data}}) + assigned := postControlForm(world, "/admin/items/3", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}}) restarted := newTestInventoryServer(t) if edited.Code != http.StatusSeeOther || assigned.Code != http.StatusSeeOther || restarted.items[3].Ammo != 9 || len(restarted.characters[1].inventory.Items) != 3 || restarted.characters[1].inventory.Items[2].Ammo != 9 { @@ -348,7 +348,7 @@ func TestPistolControlRejectsAmmoAboveCapacity(t *testing.T) { world.baseURL = "/" data := "type: 51018\ntemplate: 123742\nquality: 1\ncount: 1\nammo: 21\n" - response := postControlForm(world, "/control/items/1", url.Values{"data": {data}}) + response := postControlForm(world, "/admin/items/1", url.Values{"data": {data}}) restarted := newTestInventoryServer(t) if response.Code != http.StatusBadRequest || world.characters[1].inventory.Items[0].Ammo != 3 || restarted.items[1].Ammo != 3 { diff --git a/server/shop_control_edit_test.go b/server/shop_control_edit_test.go @@ -35,16 +35,16 @@ func TestShopControlEditRetiresDraftBeforeReconnection(t *testing.T) { t.Fatal("mixed basket was not staged") } if scenario.document == "" { - created := postControlForm(world, "/control/items", url.Values{"template": {"95577"}}) - if created.Code != http.StatusSeeOther || created.Header().Get("Location") != "/control/items/2" { + created := postControlForm(world, "/admin/items", url.Values{"template": {"95577"}}) + if created.Code != http.StatusSeeOther || created.Header().Get("Location") != "/admin/items/2" { t.Fatalf("create item: %d %s", created.Code, created.Body.String()) } } conn.packets = nil - path, fields := "/control/users/1", url.Values{"data": {scenario.document}} + path, fields := "/admin/users/1", url.Values{"data": {scenario.document}} if scenario.document == "" { - path, fields = "/control/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}} + path, fields = "/admin/items/2", url.Values{"action": {"assign"}, "owner": {"1"}, "destination": {"0:65"}} } response := postControlForm(world, path, fields) accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{}) @@ -143,7 +143,7 @@ func TestShopRejectedControlSavePreservesAcceptableDraft(t *testing.T) { } conn.packets = nil - response := postControlForm(world, "/control/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/users/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/state.go b/server/state.go @@ -9,6 +9,7 @@ import ( "math" "net" "sync" + "sync/atomic" "time" ) @@ -118,17 +119,18 @@ func (client *worldClient) send(packet []byte) error { } type server struct { - passwordMutex sync.Mutex - databaseMutex sync.Mutex - db *sql.DB - savedNPCs map[uint32]savedNPC - npcZones map[uint32]bool - itemPlacements map[uint32]itemPlacement - loginPort int - worldPort int - httpPort int - baseURL string - mutex sync.Mutex + databaseQueries atomic.Uint64 + passwordMutex sync.Mutex + databaseMutex sync.Mutex + db *sql.DB + savedNPCs map[uint32]savedNPC + npcZones map[uint32]bool + itemPlacements map[uint32]itemPlacement + loginPort int + worldPort int + httpPort int + baseURL string + mutex sync.Mutex // Order entity-state packet batches; acquire before mutex. updateMutex sync.Mutex nextCharacter uint32 @@ -150,6 +152,8 @@ type server struct { chats map[uint32]*chatClient chatLogMutex sync.Mutex browserStreams map[string]*browserStream + weather int + nextWeather time.Time gameSeconds float64 clockStarted time.Time lastNPCUpdate time.Time 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", "/control/teleport/1", strings.NewReader("playfield=800")) + request := httptest.NewRequest("POST", "/admin/teleport/1", 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, "/control/users", url.Values{"name": {name}}) + postControlForm(world, "/admin/users", 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 /control/users", world.createUser) - mux.HandleFunc("POST /control/users/{character}", world.editUser) - mux.HandleFunc("POST /control/teleport/{character}", world.teleportPlayer) - creation := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer")) + 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")) 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", "/control/users/1", strings.NewReader(url.Values{"data": {data}}.Encode())) + edition := httptest.NewRequest("POST", "/admin/users/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", "/control/teleport/1", strings.NewReader("playfield=800")) + teleport := httptest.NewRequest("POST", "/admin/teleport/1", strings.NewReader("playfield=800")) teleport.Header.Set("Content-Type", "application/x-www-form-urlencoded") teleported := httptest.NewRecorder() @@ -78,10 +78,10 @@ running: true } restarted := newServerForTest(t) page := httptest.NewRecorder() - restarted.controlPage(page, httptest.NewRequest("GET", "/control", nil)) + 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") != "/control/users/1" { + if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/admin/users/1" { t.Fatalf("user form response: %d %s", response.Code, response.Body.String()) } } @@ -89,7 +89,7 @@ running: true 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='control/users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") { + if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='admin/users/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 +168,14 @@ func TestMovementModePersistsAndIsSuppliedOnReconnect(t *testing.T) { func TestUserEditorRejectsUnknownFieldsWithoutChangingSavedData(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - creation := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer")) + creation := httptest.NewRequest("POST", "/admin/users", 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", "/control/users/1", strings.NewReader(url.Values{"data": {"id: 1\nname: Changed\nlevle: 7\n"}}.Encode())) + request := httptest.NewRequest("POST", "/admin/users/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 +195,7 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) for _, name := range []string{"First", "Second"} { - request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name="+name)) + request := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name="+name)) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) } @@ -227,15 +227,15 @@ func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) { func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer")) + request := httptest.NewRequest("POST", "/admin/users", 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", "/control/users/1", strings.NewReader(url.Values{"data": {data}}.Encode())) + request = httptest.NewRequest("POST", "/admin/users/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", "/control/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/users/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 +270,7 @@ func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) { func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) { useNPCData(t, testNPCData()) world := newTestServer(t) - request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name=Explorer")) + request := httptest.NewRequest("POST", "/admin/users", 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 +418,7 @@ func TestPositionSavesFollowEachPlayersFixedSchedule(t *testing.T) { world := newTestServer(t) created := time.Now() for _, name := range []string{"First", "Second"} { - request := httptest.NewRequest("POST", "/control/users", strings.NewReader("name="+name)) + request := httptest.NewRequest("POST", "/admin/users", strings.NewReader("name="+name)) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") world.createUser(httptest.NewRecorder(), request) } @@ -507,11 +507,11 @@ func TestOfflinePositionSaveWithSparsePlayerIDs(t *testing.T) { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } - request := httptest.NewRequest("POST", "/control/teleport/7", strings.NewReader("playfield=800")) + request := httptest.NewRequest("POST", "/admin/teleport/7", strings.NewReader("playfield=800")) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") response := httptest.NewRecorder() - world.httpHandler().ServeHTTP(response, request) + adminTestHandler(world).ServeHTTP(response, request) if err := world.flushPositions(time.Now().Add(20 * time.Second)); err != nil { t.Fatal(err) } diff --git a/server/vehicle_test.go b/server/vehicle_test.go @@ -213,7 +213,7 @@ func TestGroundVehicleMovementUsesNativeRunSpeed(t *testing.T) { world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], scenario.forward, time.Now().Add(-time.Second)) response := httptest.NewRecorder() - world.mapPlayers(response, httptest.NewRequest("GET", "/map/players", nil)) + world.mapPlayers(response, httptest.NewRequest("GET", "/admin/map-players?offline=1", nil)) var result struct{ Players []mapPlayer } if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil { t.Fatal(err) diff --git a/server/world.sql b/server/world.sql @@ -300,3 +300,20 @@ CREATE TABLE IF NOT EXISTS team_members ( position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 5), UNIQUE (team_id, position) ); + +CREATE TABLE IF NOT EXISTS admin_users ( + id INTEGER PRIMARY KEY, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_salt BLOB NOT NULL, + password_hash BLOB NOT NULL +); +CREATE TABLE IF NOT EXISTS admin_sessions ( + token_hash BLOB PRIMARY KEY, + admin_id INTEGER NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE, + expires_at INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS admin_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + weather INTEGER NOT NULL DEFAULT 0 CHECK (weather BETWEEN 0 AND 4) +); +INSERT OR IGNORE INTO admin_settings (id) VALUES (1); diff --git a/server/world_store.go b/server/world_store.go @@ -170,6 +170,9 @@ func (server *server) loadNPCs() (bool, error) { if err != nil { return false, err } + if err := db.QueryRow("SELECT weather FROM admin_settings WHERE id=1").Scan(&server.weather); err != nil { + return false, err + } var initialized bool var started string if err := db.QueryRow("SELECT npcs_initialized, last_item_id, last_character_id, last_npc_id, game_seconds, clock_started FROM world WHERE id = 1").Scan( diff --git a/tools/client/server_fixture.py b/tools/client/server_fixture.py @@ -1,6 +1,13 @@ """Create the isolated character used by native and browser smoke checks.""" +import getpass +import hashlib +import http.cookiejar import pathlib +import secrets import sqlite3 +import time +import urllib.parse +import urllib.request def create_player(directory, name, rotation): @@ -17,3 +24,23 @@ def create_player(directory, name, rotation): "rotation_y=excluded.rotation_y, rotation_z=excluded.rotation_z, rotation_w=excluded.rotation_w", (name, *rotation)) database.execute("INSERT OR IGNORE INTO players (id) VALUES (73)") + + +def admin_opener(directory): + """Authorize tools against their own disposable server database.""" + token = secrets.token_urlsafe(32) + with sqlite3.connect(directory / 'data/world.sqlite') as database: + database.execute("INSERT OR IGNORE INTO admin_users (id, username, password_salt, password_hash) VALUES (1, 'fixture', X'00', X'00')") + database.execute("INSERT INTO admin_sessions (token_hash, admin_id, expires_at) VALUES (?, 1, ?)", + (hashlib.sha256(token.encode()).digest(), int(time.time()) + 43200)) + opener = urllib.request.build_opener() + opener.addheaders = [('Cookie', 'ao_admin=' + token)] + return opener + + +def admin_login(url): + """Log in interactively when a verification tool uses an existing server.""" + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + fields = {'username': input('Admin username: '), 'password': getpass.getpass('Admin password: ')} + opener.open(url + '/admin/login', urllib.parse.urlencode(fields).encode()).read() + return opener diff --git a/tools/client/sweep_browser.py b/tools/client/sweep_browser.py @@ -89,20 +89,23 @@ need_launch = True disconnect_started = None +admin = tools.client.server_fixture.admin_opener(fixture) + + def request(path, fields=None): data = urllib.parse.urlencode(fields).encode() if fields is not None else None - return urllib.request.urlopen('http://127.0.0.1:8082' + path, data, timeout=10).read() + return admin.open('http://127.0.0.1:8082' + path, data, timeout=10).read() def character_pose(): # Live pose comes from the player feed. - player = next(player for player in json.loads(request('/control/map-players'))['players'] if player['id'] == 73) + player = next(player for player in json.loads(request('/admin/map-players?offline=1'))['players'] if player['id'] == 73) return {field: player[field] for field in ['position', 'rotation']} def tick(message): global active, instance, need_launch, disconnect_started - player = json.loads(request('/control/map-players'))['players'][0] + player = json.loads(request('/admin/map-players?offline=1'))['players'][0] if active is None: if not queue: return {'action': 'done'} @@ -116,8 +119,8 @@ def tick(message): disconnect_started = None queue.pop(0) log_start = (fixture / 'logs/server.log').stat().st_size - request('/control/teleport/73', {'playfield': zone['id']}) - request('/control/time', {'hour': 13, 'minute': 30}) + request('/admin/teleport/73', {'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']) if need_launch: @@ -126,7 +129,7 @@ def tick(message): active['instance'] = instance return {'action': 'launch', 'instance': instance, 'id': zone['id'], 'phase': phase} active['instance'] = instance - player = json.loads(request('/control/map-players'))['players'][0] + player = json.loads(request('/admin/map-players?offline=1'))['players'][0] # Main-page heartbeats remain responsive even if the game worker faults or blocks. assert message['instance'] == instance diff --git a/tools/client/sweep_playfields.py b/tools/client/sweep_playfields.py @@ -85,14 +85,17 @@ client_log = None process_number = max([int(path.stem[7:]) for path in output.glob('client-*.log')], default=0) +admin = tools.client.server_fixture.admin_opener(fixture) + + def request(path, fields=None): data = urllib.parse.urlencode(fields).encode() if fields is not None else None - return urllib.request.urlopen('http://127.0.0.1:8082' + path, data, timeout=10).read() + return admin.open('http://127.0.0.1:8082' + path, data, timeout=10).read() def character_pose(): # Live pose comes from the player feed. - player = next(player for player in json.loads(request('/control/map-players'))['players'] if player['id'] == 73) + player = next(player for player in json.loads(request('/admin/map-players?offline=1'))['players'] if player['id'] == 73) return {field: player[field] for field in ['position', 'rotation']} @@ -114,12 +117,12 @@ def run_zone(zone, phase): previous_pid = client.pid if client is not None else None if client is None: deadline = time.monotonic() + 10 - while json.loads(request('/control/map-players'))['players'][0]['connected']: + while json.loads(request('/admin/map-players?offline=1'))['players'][0]['connected']: assert time.monotonic() < deadline, 'server did not observe client disconnect' time.sleep(.1) server_log_start = (fixture / 'logs/server.log').stat().st_size - request('/control/teleport/73', {'playfield': zone['id']}) - request('/control/time', {'hour': 13, 'minute': 30}) + request('/admin/teleport/73', {'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']} if client is None: @@ -142,7 +145,7 @@ def run_zone(zone, phase): if client.poll() is not None: result.update(status='client-exit', exit_code=client.returncode) break - player = json.loads(request('/control/map-players'))['players'][0] + player = json.loads(request('/admin/map-players?offline=1'))['players'][0] if ready is not None and player['playfield'] != zone['id']: result.update(status='zoned-during-movement', destination=player['playfield']) break diff --git a/tools/client/test_admin.mjs b/tools/client/test_admin.mjs @@ -0,0 +1,107 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +await fs.mkdir(output, {recursive: true}); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', + args: ['--no-sandbox', '--disable-dev-shm-usage', '--enable-gpu', '--use-gl=angle', '--use-angle=gl', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +let game; +try { + const context = await browser.newContext({viewport: {width: 1280, height: 900}, hasTouch: true}); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + + await page.goto(url + 'admin/'); + await page.getByLabel('Username').fill('Operator'); + await page.getByLabel('Password').fill('long-test-password'); + await page.getByRole('button', {name: 'Create administrator'}).click(); + await page.getByRole('heading', {name: 'General', exact: true}).waitFor(); + await page.waitForFunction(() => /^\d/.test(document.querySelector('#query-rate').textContent)); + await page.screenshot({path: output + '/general.png'}); + await page.getByRole('link', {name: 'Users', 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: '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(); + await page.getByRole('cell', {name: 'a,b', exact: true}).waitFor(); + await page.getByLabel('Output', {exact: true}).selectOption('csv'); + assert.equal(await page.getByLabel('CSV output').inputValue(), 'value\n"a,b"\n'); + await page.getByLabel('Output', {exact: true}).selectOption('table'); + await page.screenshot({path: output + '/sql.png'}); + 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('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.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()); + const before = await page.locator('canvas').boundingBox(); + await page.screenshot({path: output + '/map.png'}); + await page.setViewportSize({width: 390, height: 844}); + const canvas = page.locator('canvas'); + const box = await canvas.boundingBox(); + assert(box.width < before.width && box.width > 300); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + const session = await context.newCDPSession(page); + const x = box.x + box.width / 2, y = box.y + box.height / 2; + const originalView = new URL((await page.waitForRequest(request => request.url().includes('admin/map-entities?'))).url()).searchParams; + await session.send('Input.dispatchTouchEvent', {type: 'touchStart', touchPoints: [{x: x - 30, y}, {x: x + 30, y}]}); + await session.send('Input.dispatchTouchEvent', {type: 'touchMove', touchPoints: [{x: x - 70, y}, {x: x + 70, y}]}); + await session.send('Input.dispatchTouchEvent', {type: 'touchEnd', touchPoints: []}); + await session.send('Input.dispatchTouchEvent', {type: 'touchStart', touchPoints: [{x, y}]}); + await session.send('Input.dispatchTouchEvent', {type: 'touchMove', touchPoints: [{x: x + 35, y: y + 20}]}); + await session.send('Input.dispatchTouchEvent', {type: 'touchEnd', touchPoints: []}); + const touchedView = new URL((await page.waitForRequest(request => request.url().includes('admin/map-entities?'))).url()).searchParams; + assert(Number(touchedView.get('right')) - Number(touchedView.get('left')) < Number(originalView.get('right')) - Number(originalView.get('left'))); + assert.notEqual(touchedView.get('left'), originalView.get('left')); + assert(box.y + box.height <= 844); + await page.screenshot({path: output + '/mobile-map.png'}); + await page.getByRole('link', {name: 'General', exact: true}).click(); + await page.getByRole('button', {name: 'Log out', exact: true}).click(); + await page.getByLabel('Username').fill('Operator'); + await page.getByLabel('Password').fill('long-test-password'); + await page.getByRole('button', {name: 'Log in', exact: true}).click(); + + // Verify weather delivery in the real client, with live simulation refreshes. + await context.addCookies([{name: 'ao_client', value: 'admin-browser', url}]); + const client = await context.newPage(); + await client.setViewportSize({width: 1024, height: 768}); + game = await GameTest.attach(client); + await client.goto(url); + await game.ready(); + 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); + await page.getByRole('button', {name: 'Set weather', exact: true}).click(); + await game.wait('weather packet ' + name, () => game.events.some(event => event.sequence > sequence && event.opcode === '0c5a5d6d' && event.direction === 'framereceived' && Buffer.from(event.hex, 'hex')[41] === type)); + await game.wait('weather refresh ' + name, () => game.events.filter(event => event.sequence > sequence && event.opcode === '0c5a5d6d' && event.direction === 'framereceived' && Buffer.from(event.hex, 'hex')[41] === type).length >= 2); + const frame = game.state.frame; + await game.wait('weather frames ' + name, state => state.frame > frame + 150); + await client.screenshot({path: output + '/weather-' + name + '.png'}); + } + await page.getByLabel('Conditions', {exact: true}).selectOption('0'); + await page.getByRole('button', {name: 'Set weather', exact: true}).click(); + const automaticAt = Date.now(), automaticSequence = game.sequence; + await game.wait('automatic weather resumes', () => Date.now() - automaticAt >= 6500); + assert(!game.events.some(event => event.sequence > automaticSequence && event.opcode === '0c5a5d6d' && event.direction === 'framereceived')); + await client.screenshot({path: output + '/weather-automatic.png'}); + await game.save(output + '/game'); + + assert(mapResponses.every(response => response.npcs.length <= 500 && response.warps.length <= 500)); + assert.deepEqual(errors, []); + assert.equal(game.errors.length, 0); + console.log('PASS: setup/login/logout, navigation, SQL writes/CSV, responsive touch map, native weather packets and rendered frames'); +} finally { + await browser.close(); +} diff --git a/tools/client/test_pending_edit.mjs b/tools/client/test_pending_edit.mjs @@ -38,7 +38,7 @@ try { evidence.pending = await server(); await game.save(output + '/pending'); const stream = game.worldStream, frame = game.state.frame; - const edited = await page.request.post(url + '/control/users/1', { + const edited = await page.request.post(url + '/test-edit/1', { form: {data: 'name: Pending Edit Check\n'}, maxRedirects: 0}); assert.equal(edited.status(), 303); await game.wait('new world stream after live edit', () => game.worldStream !== stream); diff --git a/tools/client/verify_client_1491.py b/tools/client/verify_client_1491.py @@ -8,11 +8,15 @@ import re import socket import struct import subprocess +import sys import time import urllib.parse import urllib.request root = pathlib.Path(__file__).resolve().parents[2] +sys.path.insert(0, str(root)) +import tools.client.server_fixture +admin = tools.client.server_fixture.admin_login("http://127.0.0.1:8081") client = root / 'anarchy-vanilla-14.9.1' output = root / 'local/client/fonts' assert (client / 'version.id').read_text().strip() == '14.9.1' @@ -26,16 +30,16 @@ 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/control/users/{character_id}' -page = urllib.request.urlopen(url).read().decode() +url = f'http://127.0.0.1:8081/admin/users/{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 data = re.sub(r'(?m)^playfield:.*$', 'playfield: 705', data) data = re.sub(r'(?m)^position:.*$', 'position: [960, 16.5, 510]', data) data = re.sub(r'(?m)^rotation:.*$', 'rotation: [0, 0.9238795, 0, -0.3826834]', data) request = urllib.parse.urlencode({'data': data}).encode() -urllib.request.urlopen(url, request).read() -urllib.request.urlopen('http://127.0.0.1:8081/control/time', b'hour=13&minute=30').read() +admin.open(url, request).read() +admin.open('http://127.0.0.1:8081/admin/time', b'hour=13&minute=30').read() # Suppress first-run tutorials so each fresh test character has an unobstructed view. preferences = client / 'Prefs/localtest' diff --git a/tools/client/verify_game.py b/tools/client/verify_game.py @@ -16,6 +16,9 @@ import urllib.request root = pathlib.Path(__file__).resolve().parents[2] +sys.path.insert(0, str(root)) +import tools.client.server_fixture +admin = tools.client.server_fixture.admin_login("http://127.0.0.1:8081") work = root / "local/client/game-14.9.1" client = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else root / "anarchy-vanilla-14.9.1" executable = pathlib.Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else work / "game.exe" @@ -40,15 +43,15 @@ 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/control/users/{character_id}" -page = urllib.request.urlopen(url).read().decode() +url = f"http://127.0.0.1:8081/admin/users/{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 data = re.sub(r"(?m)^playfield:.*$", "playfield: 705", data) data = re.sub(r"(?m)^position:.*$", "position: [960, 16.5, 510]", data) data = re.sub(r"(?m)^rotation:.*$", "rotation: [0, 0.9238795, 0, -0.3826834]", data) -urllib.request.urlopen(url, urllib.parse.urlencode({"data": data}).encode()).read() -urllib.request.urlopen("http://127.0.0.1:8081/control/time", b"hour=13&minute=30").read() +admin.open(url, urllib.parse.urlencode({"data": data}).encode()).read() +admin.open("http://127.0.0.1:8081/admin/time", b"hour=13&minute=30").read() preferences = client / "Prefs/localtest" character_preferences = preferences / f"Char{character_id}" character_preferences.mkdir(exist_ok=True) diff --git a/tools/client/verify_linux_game.py b/tools/client/verify_linux_game.py @@ -51,7 +51,7 @@ def run_linux(): break time.sleep(.1) assert ready, 'Isolated server did not become ready; inspect server.log' - urllib.request.urlopen('http://127.0.0.1:8081/control/time', b'hour=13&minute=30', timeout=5).read() + tools.client.server_fixture.admin_opener(fixture).open('http://127.0.0.1:8081/admin/time', b'hour=13&minute=30', timeout=5).read() # GDB injects SDL events and reads completed game frames before desktop clipping. environment = os.environ.copy()