aorecomp

Anarchy Online classic in the browser

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


commit 9957da6f651052e3500e219157c97bbefec2a812
parent 750c1e70162e19a0cc54d479042a971f079d0a02
Author: anon <anon@example.com>
Date:   Sat,  7 Nov 2026 05:23:45 +0000

Route player administration and setup through zone owners

Diffstat:
MDEVELOPERS.md | 8++++++++
Mserver/browser_launch.go | 14--------------
Mserver/browser_ownership_test.go | 14++++++++++++++
Mserver/e2e_api.go | 44+++++++++++++++++++++++++++++++++++++-------
Aserver/e2e_owner_test.go | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/http.go | 66+++++++++++++++++++++++++++++++++---------------------------------
Aserver/zone_http.go | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/zone_http_test.go | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 438 insertions(+), 54 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -185,6 +185,14 @@ player's streams and preserves a new connection already awaiting publication. Production state partitioning and administrative/test entry points still need migration before the global simulation loops can be removed. +Per-player admin inspection, editing and teleport requests run as commands on +the current zone owner. Request bodies are read before admission, and responses +are buffered until the command returns, so network I/O cannot hold an owner. +Only a pre-execution ownership change retries a request. The test setup API uses +the same boundary, rechecks its cookie against the selected player and transfers +the actor and inventory after a committed position change. Global admin views, +environment controls and item administration still need routed ownership. + World and chat transport entry points use the routing directory and chat owner when a world runtime is installed. An integration regression empties the root character map and holds both root simulation locks while exercising native login, diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -36,20 +36,6 @@ func (server *server) browserPlayerID(credential string) (uint32, error) { return id, err } -func (server *server) browserCharacter_locked(r *http.Request) *character { - cookie, err := r.Cookie("ao_client") - if err != nil { - return nil - } - hash := fmt.Sprintf("%x", sha256.Sum256([]byte(cookie.Value))) - for _, character := range server.characters { - if !character.npc && character.browserTokenHash == hash { - return character - } - } - return nil -} - func (state *server) browserLaunch(w http.ResponseWriter, r *http.Request) { var id uint32 var token string diff --git a/server/browser_ownership_test.go b/server/browser_ownership_test.go @@ -16,6 +16,20 @@ import ( "github.com/coder/websocket" ) +// Single-state fixtures inspect actors directly; authenticated handlers resolve SQL identities. +func (state *server) browserCharacter_locked(r *http.Request) *character { + credential := browserCredential(r) + if credential == "" { + return nil + } + for _, player := range state.characters { + if !player.npc && player.browserTokenHash == credential { + return player + } + } + return nil +} + func browserOwnershipFixture(t *testing.T) (*server, *http.Cookie) { t.Helper() fixture := newCheckpointWorld(t) diff --git a/server/e2e_api.go b/server/e2e_api.go @@ -17,16 +17,35 @@ func (server *server) e2eHandler() http.Handler { return mux } -func (server *server) e2ePlayer(w http.ResponseWriter, r *http.Request) { +func (state *server) e2ePlayer(w http.ResponseWriter, r *http.Request) { + id, err := state.browserPlayerID(browserCredential(r)) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if id == 0 { + http.Error(w, "a browser player is required", http.StatusUnauthorized) + return + } + handle := func(owner *server, w http.ResponseWriter, r *http.Request) { owner.e2eOwnedPlayer(w, r, id) } + if state.world != nil { + state.servePlayerHTTP(w, r, id, handle) + return + } + handle(state, w, r) +} + +func (server *server) e2eOwnedPlayer(w http.ResponseWriter, r *http.Request, id uint32) { server.updateMutex.Lock() defer server.updateMutex.Unlock() server.mutex.Lock() defer server.mutex.Unlock() - player := server.browserCharacter_locked(r) - if player == nil { + player := server.characters[id] + if player == nil || player.browserTokenHash != browserCredential(r) { http.Error(w, "a browser player is required", http.StatusUnauthorized) return } + if r.Method == "POST" && server.clients[player.id] != nil { http.Error(w, "prepare conditions before connecting the game", http.StatusConflict) return @@ -70,12 +89,17 @@ func (server *server) e2ePlayer(w http.ResponseWriter, r *http.Request) { } lower, _ := player.experienceBounds() w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]any{"id": player.id, "name": player.name, + result := map[string]any{"id": player.id, "name": player.name, "playfield": player.playfield, "position": player.position, "sitting": player.sitting, "level": player.level, "experience": lower + player.experience, "ip": player.stats.ImprovementPoints, "credits": player.inventory.Credits, "health": player.health, "maximumHealth": player.maximumHealth(), - "items": items, "lastItem": server.nextItem}) + "items": items, "lastItem": server.nextItem} + if err := server.transferPlayer_locked(player); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + json.NewEncoder(w).Encode(result) } func (server *server) e2eSetup_locked(player *character, r *http.Request) error { @@ -91,8 +115,14 @@ func (server *server) e2eSetup_locked(player *character, r *http.Request) error if err := decoder.Decode(&request); err != nil { return err } - player.playfield, player.position, player.rotation = request.Playfield, request.Position, request.Rotation - return server.savePosition_locked(player) + updated := *player + updated.playfield, updated.position, updated.rotation = request.Playfield, request.Position, request.Rotation + if err := server.savePosition_locked(&updated); err != nil { + return err + } + player.playfield, player.position, player.rotation = updated.playfield, updated.position, updated.rotation + player.savedPosition = updated.savedPosition + return nil case "progress": var request struct { Level uint16 diff --git a/server/e2e_owner_test.go b/server/e2e_owner_test.go @@ -0,0 +1,90 @@ +//go:build e2e + +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestRoutedSetupAPITransfersOnlyAfterCommit(t *testing.T) { + fixture, cookie := browserOwnershipFixture(t) + fixture.world = newRoutedTestWorld(t, fixture) + defer fixture.world.stop() + fixture.updateMutex.Lock() + defer fixture.updateMutex.Unlock() + fixture.mutex.Lock() + defer fixture.mutex.Unlock() + handler := fixture.e2eHandler() + request := func(method, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.AddCookie(cookie) + response := httptest.NewRecorder() + handler.ServeHTTP(response, r) + return response + } + if _, err := fixture.db.Exec("CREATE TRIGGER reject_setup BEFORE UPDATE OF playfield ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT,'position'); END"); err != nil { + t.Fatal(err) + } + + rejected := request("POST", "/_test/player/position", `{"playfield":705,"position":[100,16,200],"rotation":[0,0,0,1]}`) + + if rejected.Code != http.StatusBadRequest { + t.Fatal(rejected.Code, rejected.Body.String()) + } + owner, err := fixture.world.owner(1) + if err != nil { + t.Fatal(err) + } + before := &zoneTransferQuery{player: 1} + if err := owner.call(before); err != nil || before.playfield != 950 || !before.present { + t.Fatal("failed setup changed ownership", before, err) + } + if _, err := fixture.db.Exec("DROP TRIGGER reject_setup"); err != nil { + t.Fatal(err) + } + + moved := request("POST", "/_test/player/position", `{"playfield":705,"position":[100,16,200],"rotation":[0,0,0,1]}`) + observed := request("GET", "/_test/player", "") + + var snapshot struct { + ID, Playfield uint32 + Position [3]float32 + } + if moved.Code != http.StatusOK || observed.Code != http.StatusOK { + t.Fatal(moved.Code, moved.Body.String(), observed.Code, observed.Body.String()) + } + if err := json.Unmarshal(observed.Body.Bytes(), &snapshot); err != nil || snapshot.ID != 1 || snapshot.Playfield != 705 || snapshot.Position != [3]float32{100, 16, 200} { + t.Fatal(snapshot, err) + } + destination, err := fixture.world.owner(1) + if err != nil || destination == owner { + t.Fatal("setup retained the source owner", err) + } + after := &zoneTransferQuery{player: 1} + if err := destination.call(after); err != nil || !after.present || after.playfield != 705 || len(after.items) != 1 { + t.Fatal("setup lost inventory at the destination", after, err) + } + if err := owner.call(before); err != nil || before.present || len(before.items) != 0 { + t.Fatal("source retained transferred state", before, err) + } + + spawned := request("POST", "/_test/player/leet", `{"position":[102,16,200]}`) + var npc struct{ ID uint32 } + if spawned.Code != http.StatusOK { + t.Fatal(spawned.Code, spawned.Body.String()) + } + if err := json.Unmarshal(spawned.Body.Bytes(), &npc); err != nil || npc.ID < 1000000 { + t.Fatal(npc, err) + } + npcOwner, err := fixture.world.owner(npc.ID) + if err != nil || npcOwner != destination { + t.Fatal("fixture NPC was not owned by its zone", err) + } + if len(fixture.characters) != 0 { + t.Fatal("setup API repopulated global actors") + } +} diff --git a/server/http.go b/server/http.go @@ -53,39 +53,39 @@ func (server *server) httpHandler() http.Handler { return mounted } -func (server *server) adminHandler() http.Handler { +func (state *server) adminHandler() http.Handler { admin := http.NewServeMux() admin.HandleFunc("POST /admin/browser-profile/{session}", browserProfile) - admin.HandleFunc("GET /admin", server.controlPage) - admin.HandleFunc("GET /admin/{$}", server.controlPage) - admin.HandleFunc("GET /admin/players", server.usersPage) - admin.HandleFunc("GET /admin/map", server.mapPage) - admin.HandleFunc("GET /admin/stats", server.adminStats) - admin.HandleFunc("GET /admin/sql", server.sqlPage) - admin.HandleFunc("POST /admin/sql", server.sqlPage) - admin.HandleFunc("POST /admin/logout", server.adminLogout) - admin.HandleFunc("GET /admin/admins", server.adminAccountsPage) - admin.HandleFunc("GET /admin/admins/new", server.createAdmin) - admin.HandleFunc("POST /admin/admins/new", server.createAdmin) - admin.HandleFunc("GET /admin/admins/{admin}", server.changeAdminPassword) - admin.HandleFunc("POST /admin/admins/{admin}", server.changeAdminPassword) - admin.HandleFunc("GET /admin/players/{character}", server.userPage) - admin.HandleFunc("POST /admin/players/{character}", server.editUser) - admin.HandleFunc("GET /admin/players/{character}/password", server.changePlayerPassword) - admin.HandleFunc("POST /admin/players/{character}/password", server.changePlayerPassword) - admin.HandleFunc("GET /admin/items", server.itemsPage) - admin.HandleFunc("GET /admin/items/catalog", server.itemCatalogPage) - admin.HandleFunc("GET /admin/items/catalog/{template}", server.itemTemplatePage) - admin.HandleFunc("GET /admin/item-icons/{icon}", server.itemIconPage) - admin.HandleFunc("GET /admin/shops/{template}", server.shopCatalogPage) - 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", state.controlPage) + admin.HandleFunc("GET /admin/{$}", state.controlPage) + admin.HandleFunc("GET /admin/players", state.usersPage) + admin.HandleFunc("GET /admin/map", state.mapPage) + admin.HandleFunc("GET /admin/stats", state.adminStats) + admin.HandleFunc("GET /admin/sql", state.sqlPage) + admin.HandleFunc("POST /admin/sql", state.sqlPage) + admin.HandleFunc("POST /admin/logout", state.adminLogout) + admin.HandleFunc("GET /admin/admins", state.adminAccountsPage) + admin.HandleFunc("GET /admin/admins/new", state.createAdmin) + admin.HandleFunc("POST /admin/admins/new", state.createAdmin) + admin.HandleFunc("GET /admin/admins/{admin}", state.changeAdminPassword) + admin.HandleFunc("POST /admin/admins/{admin}", state.changeAdminPassword) + admin.HandleFunc("GET /admin/players/{character}", state.playerHTTP((*server).userPage)) + admin.HandleFunc("POST /admin/players/{character}", state.playerHTTP((*server).editUser)) + admin.HandleFunc("GET /admin/players/{character}/password", state.changePlayerPassword) + admin.HandleFunc("POST /admin/players/{character}/password", state.changePlayerPassword) + admin.HandleFunc("GET /admin/items", state.itemsPage) + admin.HandleFunc("GET /admin/items/catalog", state.itemCatalogPage) + admin.HandleFunc("GET /admin/items/catalog/{template}", state.itemTemplatePage) + admin.HandleFunc("GET /admin/item-icons/{icon}", state.itemIconPage) + admin.HandleFunc("GET /admin/shops/{template}", state.shopCatalogPage) + admin.HandleFunc("POST /admin/items", state.createItem) + admin.HandleFunc("GET /admin/items/{item}", state.itemPage) + admin.HandleFunc("POST /admin/items/{item}", state.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-players", state.mapPlayers) + admin.HandleFunc("GET /admin/map-entities", state.mapEntities) admin.HandleFunc("GET /admin/map-assets", func(w http.ResponseWriter, r *http.Request) { - location := server.baseURL + "admin/map-assets/" + location := state.baseURL + "admin/map-assets/" if r.URL.RawQuery != "" { location += "?" + r.URL.RawQuery } @@ -104,9 +104,9 @@ func (server *server) adminHandler() http.Handler { } mapFiles.ServeHTTP(w, r) }) - admin.HandleFunc("POST /admin/time", server.setGameTime) - admin.HandleFunc("POST /admin/weather", server.setWeather) - admin.HandleFunc("GET /admin/players/{character}/teleport", server.teleportPage) - admin.HandleFunc("POST /admin/players/{character}/teleport", server.teleportPlayer) + admin.HandleFunc("POST /admin/time", state.setGameTime) + admin.HandleFunc("POST /admin/weather", state.setWeather) + admin.HandleFunc("GET /admin/players/{character}/teleport", state.playerHTTP((*server).teleportPage)) + admin.HandleFunc("POST /admin/players/{character}/teleport", state.playerHTTP((*server).teleportPlayer)) return admin } diff --git a/server/zone_http.go b/server/zone_http.go @@ -0,0 +1,98 @@ +package main + +import ( + "bytes" + "io" + "net/http" + "strconv" +) + +// The zone owns the buffered response until its command completes. Network +// reads and writes remain with the HTTP goroutine, outside simulation ownership. +type zoneHTTPResponse struct { + header http.Header + status int + body bytes.Buffer +} + +func (response *zoneHTTPResponse) Header() http.Header { return response.header } +func (response *zoneHTTPResponse) WriteHeader(status int) { + if response.status == 0 { + response.status = status + } +} +func (response *zoneHTTPResponse) Write(body []byte) (int, error) { + response.WriteHeader(http.StatusOK) + return response.body.Write(body) +} + +type zonePlayerHTTP struct { + player uint32 + request *http.Request + response *zoneHTTPResponse + handle func(*server, http.ResponseWriter, *http.Request) +} + +func (command zonePlayerHTTP) execute(state *server) error { + if state.characters[command.player] == nil { + return errZoneOwnerChanged + } + command.handle(state, command.response, command.request) + return nil +} + +func (state *server) playerHTTP(handle func(*server, http.ResponseWriter, *http.Request)) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if state.world == nil { + handle(state, w, r) + return + } + id, err := strconv.ParseUint(r.PathValue("character"), 10, 32) + if err != nil { + http.Error(w, "Invalid player", http.StatusBadRequest) + return + } + state.servePlayerHTTP(w, r, uint32(id), handle) + } +} + +func (state *server) servePlayerHTTP(w http.ResponseWriter, r *http.Request, player uint32, handle func(*server, http.ResponseWriter, *http.Request)) { + // Match net/http's form limit while detaching request I/O from the owner. + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 10<<20)) + r.Body.Close() + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + response := &zoneHTTPResponse{header: make(http.Header)} + for { + route, err := state.world.lookupOn(state.world.admissions, player) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if route == nil { + http.NotFound(w, r) + return + } + err = route.zone.call(zonePlayerHTTP{player, r, response, handle}) + // Retry only a pre-execution ownership change. A handler that ran must + // never repeat its mutation, even if it transferred the player onward. + if err == errZoneOwnerChanged { + continue + } + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + break + } + for key, values := range response.header { + w.Header()[key] = values + } + if response.status != 0 { + w.WriteHeader(response.status) + } + w.Write(response.body.Bytes()) +} diff --git a/server/zone_http_test.go b/server/zone_http_test.go @@ -0,0 +1,158 @@ +package main + +import ( + "html" + "io" + "net/http" + "net/http/httptest" + "net/url" + "regexp" + "strings" + "testing" + "time" + + "go.yaml.in/yaml/v3" +) + +func TestRoutedPlayerAdministrationEditsAndTransfersThroughOwners(t *testing.T) { + fixture := newCheckpointWorld(t) + fixture.world = newRoutedTestWorld(t, fixture) + defer fixture.world.stop() + fixture.updateMutex.Lock() + defer fixture.updateMutex.Unlock() + fixture.mutex.Lock() + defer fixture.mutex.Unlock() + handler := adminTestHandler(fixture) + page := adminRequest(handler, "GET", "/admin/players/1", "", nil) + if page.Code != http.StatusOK { + t.Fatal(page.Code, page.Body.String()) + } + match := regexp.MustCompile(`(?s)<textarea[^>]*>(.*?)</textarea>`).FindStringSubmatch(page.Body.String()) + if len(match) != 2 { + t.Fatal("player editor was not rendered") + } + var editor characterEditor + if err := decodeUsers(strings.NewReader(html.UnescapeString(match[1])), &editor); err != nil { + t.Fatal(err) + } + editor.Name, editor.Inventory.Credits = "Edited", 913 + document, err := yaml.Marshal(editor) + if err != nil { + t.Fatal(err) + } + + edited := adminRequest(handler, "POST", "/admin/players/1", url.Values{"data": {string(document)}}.Encode(), nil) + moved := adminRequest(handler, "POST", "/admin/players/1/teleport", "playfield=705", nil) + + if edited.Code != http.StatusSeeOther || moved.Code != http.StatusSeeOther { + t.Fatal(edited.Code, edited.Body.String(), moved.Code, moved.Body.String()) + } + owner, err := fixture.world.owner(1) + if err != nil { + t.Fatal(err) + } + query := &zoneTransferQuery{player: 1} + if err := owner.call(query); err != nil || !query.present || query.playfield != 705 || len(query.items) != 1 { + t.Fatal(query, err) + } + var name string + var credits, playfield uint32 + if err := fixture.db.QueryRow("SELECT name,credits,playfield FROM characters JOIN players USING(id) WHERE id=1").Scan(&name, &credits, &playfield); err != nil || name != "Edited" || credits != 913 || playfield != 705 { + t.Fatal(name, credits, playfield, err) + } + next := adminRequest(handler, "GET", "/admin/players/1/teleport", "", nil) + if next.Code != http.StatusOK || !strings.Contains(next.Body.String(), "Teleport Edited") || len(fixture.characters) != 0 { + t.Fatal("player page did not follow ownership", next.Code) + } +} + +type pausedHTTPWriter struct { + *httptest.ResponseRecorder + entered, release chan struct{} +} + +func (writer *pausedHTTPWriter) Write(body []byte) (int, error) { + close(writer.entered) + <-writer.release + return writer.ResponseRecorder.Write(body) +} + +type signaledHTTPBody struct { + io.ReadCloser + entered chan struct{} +} + +func (body *signaledHTTPBody) Read(data []byte) (int, error) { + if body.entered != nil { + close(body.entered) + body.entered = nil + } + return body.ReadCloser.Read(data) +} + +func TestRoutedPlayerHTTPSlowNetworkDoesNotHoldItsOwner(t *testing.T) { + fixture := newCheckpointWorld(t) + fixture.world = newRoutedTestWorld(t, fixture) + defer fixture.world.stop() + owner, err := fixture.world.owner(1) + if err != nil { + t.Fatal(err) + } + reader, input := io.Pipe() + defer reader.Close() + defer input.Close() + upload := make(chan struct{}) + request := httptest.NewRequest("POST", "/admin/players/1/teleport", &signaledHTTPBody{reader, upload}) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + response := httptest.NewRecorder() + done := make(chan struct{}) + go func() { defer close(done); adminTestHandler(fixture).ServeHTTP(response, request) }() + t.Cleanup(func() { <-done }) + select { + case <-upload: + case <-time.After(3 * time.Second): + t.Fatal("request did not reach the body reader") + } + // A request body has not arrived, but an owner command must still complete. + responsive := make(chan error, 1) + go func() { responsive <- owner.call(&zoneAccountObservation{player: 1}) }() + select { + case err := <-responsive: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("request upload held the zone owner") + } + if _, err := io.WriteString(input, "playfield=950"); err != nil { + t.Fatal(err) + } + input.Close() + <-done + if response.Code != http.StatusSeeOther { + t.Fatal(response.Code, response.Body.String()) + } + + writer := &pausedHTTPWriter{ResponseRecorder: httptest.NewRecorder(), entered: make(chan struct{}), release: make(chan struct{})} + defer close(writer.release) + downloaded := make(chan struct{}) + t.Cleanup(func() { <-downloaded }) + go func() { + defer close(downloaded) + adminTestHandler(fixture).ServeHTTP(writer, httptest.NewRequest("GET", "/admin/players/1", nil)) + }() + select { + case <-writer.entered: + case <-time.After(3 * time.Second): + t.Fatal("response did not reach the network writer") + } + go func() { responsive <- owner.call(&zoneAccountObservation{player: 1}) }() + select { + case err := <-responsive: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("response download held the zone owner") + } +}