aorecomp

Anarchy Online classic in the browser

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


commit 3ab51b60d447bcf6ea52ce9661534e6d50041b5e
parent debe1a32ec62c040f6d21ea6a1e20ca1c1ec2e02
Author: anon <anon@example.com>
Date:   Wed, 11 Nov 2026 08:38:53 +0000

Add public player status page and login notice

Diffstat:
MDEVELOPERS.md | 4++++
Mserver/assets/map.js | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mserver/browser_socket.go | 12++++++++++--
Mserver/browser_stream.go | 4++--
Mserver/chat.go | 23+++++++++++++++++++++++
Mserver/chat_integration_test.go | 25++++++++++++++++++-------
Mserver/http.go | 9+++++++++
Aserver/status.go | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/status_test.go | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_status.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 476 insertions(+), 28 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -326,6 +326,10 @@ 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/admin`. +The public `/status` page shows an alphabetical list of connected players with their zones and a map, +refreshing every five seconds. Interior markers show known entrances; private +missions are listed separately by instance. Login chat includes a link to this +page after restored history. Status notices are not saved in chat history. 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 diff --git a/server/assets/map.js b/server/assets/map.js @@ -10,6 +10,8 @@ class AOMap { this.view = "world"; this.form = element.querySelector("[data-map-teleport]"); this.character = Number(element.dataset.character); + this.publicStatus = element.hasAttribute("data-server-status"); + this.path = this.publicStatus ? "status" : "admin"; this.players = []; this.sources = []; this.entities = {npcs: [], warps: []}; @@ -26,9 +28,9 @@ class AOMap { } async start() { - const response = await fetch("admin/map-assets/manifest.json"); + const response = await fetch(`${this.path}/map-assets/manifest.json`); if (!response.ok) { - this.status.textContent = "Map data is missing. Run tools/data/extract_maps.py from the repository root."; + this.status.textContent = this.publicStatus ? "Map imagery is unavailable." : "Map data is missing. Run tools/data/extract_maps.py from the repository root."; return; } this.manifest = await response.json(); @@ -43,7 +45,9 @@ class AOMap { option.textContent = `${zone.name} (${zone.id})`; view.append(option); } - const find = this.element.querySelector("[data-map-find]"); + } + const find = this.element.querySelector("[data-map-find]"); + if (find) { for (const zone of this.manifest.zones.filter(zone => zone.origin).sort((a, b) => a.name.localeCompare(b.name))) { const option = document.createElement("option"); option.value = zone.id; @@ -53,6 +57,8 @@ class AOMap { find.addEventListener("change", () => { if (find.value) this.focusZone(this.zones.get(Number(find.value))); }); + } + if (view) { view.addEventListener("change", () => { this.view = view.value; find.value = ""; @@ -100,7 +106,7 @@ class AOMap { return; } const query = new URLSearchParams(window.location.search); - if (query.has("playfield") && query.has("x") && query.has("z")) { + if (!this.publicStatus && query.has("playfield") && query.has("x") && query.has("z")) { this.sources = [{playfield: Number(query.get("playfield")), position: [Number(query.get("x")), 0, Number(query.get("z"))], name: "Source location"}]; this.focusSource(this.sources[0]); } @@ -186,7 +192,7 @@ class AOMap { this.center = [(left + right) / 2, (bottom + top) / 2]; this.scale = Math.min(this.width / (right - left), this.height / (top - bottom)) * 0.9; this.selection = null; - this.location.textContent = ""; + if (this.location) this.location.textContent = ""; if (this.form) { this.form.querySelector("button").disabled = true; this.form.querySelector("[data-map-zone-choice]").hidden = true; @@ -324,28 +330,61 @@ class AOMap { async poll() { try { if (!document.hidden) { - 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"}); + const offline = this.element.querySelector("[data-map-offline]")?.checked; + const feed = this.publicStatus ? "status/map-players" : `admin/map-players?offline=${offline ? 1 : 0}&character=${this.character}`; + const response = await fetch(feed, {cache: "no-store"}); if (!response.ok) throw new Error(`Player feed returned HTTP ${response.status}`); this.players = (await response.json()).players; + if (this.publicStatus) this.renderRoster(); 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; + if (!this.publicStatus) { + 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) { this.status.textContent = `Cannot refresh player positions: ${error.message}`; } finally { - setTimeout(() => this.poll(), 1000); + setTimeout(() => this.poll(), this.publicStatus ? 5000 : 1000); } } + renderRoster() { + this.element.querySelector("[data-status-total]").textContent = `${this.players.length} ${this.players.length === 1 ? "player" : "players"} online`; + const roster = this.element.querySelector("[data-status-roster]"); + const list = document.createElement("ul"); + for (const player of [...this.players].sort((a, b) => a.name.localeCompare(b.name))) { + const item = document.createElement("li"); + const button = document.createElement("button"); + button.textContent = `${player.name} (${player.zone})`; + button.disabled = !this.playerPoint(player); + button.addEventListener("click", () => this.focusStatusPlayer(player)); + item.append(button); + if (button.disabled) { + const note = document.createElement("small"); + note.textContent = "Map location unavailable"; + item.append(note); + } + list.append(item); + } + roster.replaceChildren(list); + if (!this.players.length) roster.textContent = "No players are connected right now."; + } + + focusStatusPlayer(player) { + this.center = this.playerPoint(player); + this.scale = 0.75; + this.canvas.scrollIntoView({block: "nearest"}); + this.renderSoon(); + } + tile(path) { let tile = this.tiles.get(path); if (!tile) { @@ -366,7 +405,7 @@ class AOMap { if (tile.bitmap || tile.failed || tile.loading) continue; tile.loading = true; this.loadingTiles++; - fetch(`admin/map-assets/${path}`, {cache: "force-cache"}).then(response => { + fetch(`${this.path}/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 => { @@ -434,14 +473,18 @@ class AOMap { return; } } - // Player markers navigate to their existing character editor. + // Public markers focus the map; admin markers open the 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(`admin/players/${player.id}`, document.baseURI); + if (this.publicStatus) { + this.focusStatusPlayer(player); + } else { + window.location.href = new URL(`admin/players/${player.id}`, document.baseURI); + } return; } } @@ -586,6 +629,11 @@ class AOMap { if (!player.connected && player.id !== this.character && !this.element.querySelector("[data-map-offline]")?.checked) continue; const point = this.playerPoint(player); if (!point) continue; + const occupants = this.publicStatus ? this.players.filter(other => { + const otherPoint = this.playerPoint(other); + return otherPoint && otherPoint[0] === point[0] && otherPoint[1] === point[1]; + }) : [player]; + if (occupants[0] !== player) continue; const [x, y] = this.toScreen(...point); if (x < -20 || y < -20 || x > this.width + 20 || y > this.height + 20) continue; ctx.beginPath(); @@ -596,7 +644,9 @@ class AOMap { if (player.connected) ctx.fill(); ctx.stroke(); const atEntrance = player.entrance && this.view === "world" && !this.zones.get(player.playfield)?.origin; - const label = `${player.title ? player.title + " " : ""}${player.name}${player.connected ? "" : " (offline)"}${atEntrance ? ` [${player.zone} entrance]` : ""}`; + const names = occupants.map(other => `${other.title ? other.title + " " : ""}${other.name}`).join(", "); + const separate = occupants.some(other => other.playfield !== player.playfield); + const label = `${names}${player.connected ? "" : " (offline)"}${atEntrance ? (separate ? " [separate interiors]" : ` [${player.zone} entrance]`) : ""}`; ctx.lineWidth = 3; ctx.strokeStyle = "#000"; ctx.strokeText(label, x + 10, y + 4); diff --git a/server/browser_socket.go b/server/browser_socket.go @@ -68,15 +68,23 @@ func (server *server) browserConnection(w http.ResponseWriter, r *http.Request, } defer finish() remoteAddr := browserRemoteAddress(r) + origin := r.Header.Get("Origin") + if origin == "" { + origin = "http://" + r.Host + if r.TLS != nil { + origin = "https://" + r.Host + } + } + statusURL := origin + strings.TrimSuffix(server.baseURL, "/") + "/status" if socket.Subprotocol() == "ao-stream-v1" { - server.resumeBrowserStream(socket, id, credential, chat, remoteAddr) + server.resumeBrowserStream(socket, id, credential, chat, remoteAddr, statusURL) return } // Preserve the TCP byte stream across arbitrary binary WebSocket boundaries. connection := &browserGameConn{Conn: websocket.NetConn(context.Background(), socket, websocket.MessageBinary), peer: browserPeerAddress(remoteAddr)} if chat { - if err := server.serveChatClient(&chatClient{conn: connection, id: id, browserTokenHash: credential}); err != nil { + if err := server.serveChatClient(&chatClient{conn: connection, id: id, browserTokenHash: credential, statusURL: statusURL}); err != nil { log.Printf("Browser chat connection: %v", err) } return diff --git a/server/browser_stream.go b/server/browser_stream.go @@ -226,7 +226,7 @@ func (stream *browserStream) receive(socket *websocket.Conn, message []byte) boo return err == nil } -func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint32, credential string, chat bool, remoteAddr string) { +func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint32, credential string, chat bool, remoteAddr, statusURL string) { socket.SetReadLimit(65536) // The cookie authenticates every attachment; offsets identify replayed bytes. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -289,7 +289,7 @@ func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint defer game.Close() var result error if chat { - result = server.serveChatClient(&chatClient{conn: connection, stream: stream, id: character, browserTokenHash: credential}) + result = server.serveChatClient(&chatClient{conn: connection, stream: stream, id: character, browserTokenHash: credential, statusURL: statusURL}) } else { result = server.serveWorldClient(&worldClient{conn: connection, stream: stream, id: character, loading: true, browserTokenHash: credential}) } diff --git a/server/chat.go b/server/chat.go @@ -8,6 +8,7 @@ import ( "log" "net" "slices" + "strconv" "strings" ) @@ -18,6 +19,7 @@ type chatClient struct { browserTokenHash string id uint32 teamID uint32 // Announced channel membership; owned by the chat goroutine. + statusURL string } func chatPacket(kind uint16, body []byte) []byte { @@ -116,6 +118,20 @@ func (server *chatState) initializeChat(client *chatClient, id uint32) error { for _, entry := range history { initialization = append(initialization, entry.packet()...) } + if client.statusURL != "" { + online := 0 + for _, person := range server.people { + if person.online { + online++ + } + } + players := "players" + if online == 1 { + players = "player" + } + message := fmt.Sprintf("[Server] %d %s online. Find other players at %s", online, players, client.statusURL) + initialization = append(initialization, chatPacket(36, appendChatString(nil, message))...) + } if err := client.send(initialization); err != nil { return err } @@ -130,6 +146,13 @@ func (server *chatState) initializeChat(client *chatClient, id uint32) error { } func (server *server) serveChatClient(client *chatClient) error { + // Browser transports supply their public origin; native clients use HTTP. + if client.statusURL == "" { + client.statusURL = strings.TrimSuffix(server.baseURL, "/") + "/status" + if address, ok := client.conn.LocalAddr().(*net.TCPAddr); ok { + client.statusURL = "http://" + net.JoinHostPort(address.IP.String(), strconv.Itoa(server.httpPort)) + client.statusURL + } + } finish, accepted := server.tasks.enter(func() { client.conn.Close() }) if !accepted { return net.ErrClosed diff --git a/server/chat_integration_test.go b/server/chat_integration_test.go @@ -165,6 +165,11 @@ func TestBrowserWorldVicinityMatchesAcrossWebSocketBoundaries(t *testing.T) { t.Fatalf("chat initialization: %d %v", kind, err) } } + kind, body, err := readChatPacket(chatConnection) + message, ok := readChatString(&body) + if err != nil || kind != 36 || !ok || message != "[Server] 1 player online. Find other players at "+host.URL+"/status" { + t.Fatal("browser login status", kind, message, err) + } metadata := []byte{0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 4, 'i', 'n', 'f', 'o', 1, 1, 3, 0, 6, 's', 'i', 'm', 'p', 'l', 'e', 0, 3, 'y', 'e', 's'} var delivered [][]byte @@ -323,6 +328,19 @@ func TestBrowserChatHistoryFollowsPlayerAcrossSessionsAndTokenChanges(t *testing t.Fatalf("chat initialization: %d %v", kind, err) } } + if index != 0 { + kind, body, err := readChatPacket(connection) + message, valid := readChatString(&body) + if err != nil || kind != 36 || !valid { + t.Fatalf("restored browser history: %d %q %v", kind, message, err) + } + history = append(history, message) + } + kind, body, err := readChatPacket(connection) + message, valid := readChatString(&body) + if err != nil || kind != 36 || !valid || message != "[Server] 2 players online. Find other players at "+host.URL+"/status" { + t.Fatal("status after restored history", kind, message, err) + } if index == 0 { owner.sendVicinity(client, 0, "remember across browsers", nil) for _, expected := range []uint16{20, 34} { @@ -330,13 +348,6 @@ func TestBrowserChatHistoryFollowsPlayerAcrossSessionsAndTokenChanges(t *testing t.Fatalf("live chat: %d %v", kind, err) } } - } else { - kind, body, err := readChatPacket(connection) - message, valid := readChatString(&body) - if err != nil || kind != 36 || !valid { - t.Fatalf("restored browser history: %d %q %v", kind, message, err) - } - history = append(history, message) } socket.CloseNow() } diff --git a/server/http.go b/server/http.go @@ -9,6 +9,15 @@ import ( func (server *server) httpHandler() http.Handler { mux := http.NewServeMux() + mux.HandleFunc("GET /status", server.statusPage) + mux.HandleFunc("GET /status/{$}", server.statusPage) + mux.HandleFunc("GET /status/map-players", server.statusPlayers) + mux.HandleFunc("GET /status/map.js", controlMapScript) + mapResources, err := fs.Sub(resources, "maps") + if err != nil { + log.Fatal(err) + } + mux.Handle("GET /status/map-assets/", http.StripPrefix("/status/map-assets/", http.FileServerFS(mapResources))) // Directory redirects must keep the public prefix and query string. mux.HandleFunc("GET /wasm", func(w http.ResponseWriter, r *http.Request) { location := server.baseURL + "wasm/" diff --git a/server/status.go b/server/status.go @@ -0,0 +1,61 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/json" + "fmt" + "html" + "net/http" + "strings" +) + +func (server *server) statusPage(w http.ResponseWriter, r *http.Request) { + 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>Server status - Rubi-Ka</title><style> +*{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182634;font:15px system-ui,sans-serif}header{background:#142c3e;color:white;padding:16px 24px;display:flex;align-items:center;justify-content:space-between}header a{color:white}main{max-width:1500px;margin:auto;padding:24px}h1{font-size:24px;margin:0}h2{font-size:18px}a{color:#175d8d}button,select{font:inherit;padding:10px;border:1px solid #a7b8c5;border-radius:5px;background:white;color:#182634;max-width:100%%}button{cursor:pointer;min-height:44px}button:focus-visible,select:focus-visible,a:focus-visible{outline:3px solid #e0a22a;outline-offset:2px}.layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:24px}.map,aside{background:white;padding:16px;border:1px solid #d9e1e7;border-radius:8px;min-width:0}.controls{display:flex;gap:8px;flex-wrap:wrap;align-items:center}canvas{width:100%%;height:60vh;min-height:320px;display:block;touch-action:none;border-radius:6px}p{line-height:1.5}.muted{color:#526777}[data-status-roster] ul{padding:0;list-style:none}[data-status-roster] button{border:0;color:#175d8d;text-align:left;width:100%%;overflow-wrap:anywhere;padding:6px 0;min-height:0}[data-status-roster] button:hover{background:#e7edf2}[data-status-roster] button:disabled{color:#526777;cursor:default}small{display:block;color:#526777}@media(max-width:800px){main{padding:12px}.layout{grid-template-columns:1fr}header{padding:16px}canvas{height:50vh}} +</style></head><body><header><h1>Server status</h1><a href="./">Play</a></header><main><p>Find other players on Rubi-Ka. Updates every 5 seconds.</p><div class="layout" data-world-map data-server-status><section class="map" aria-label="Player map"><div class="controls"><label>Find zone <select data-map-find><option value="">Choose a zone</option></select></label><button type="button" data-map-zoom="1" aria-label="Zoom in">+</button><button type="button" data-map-zoom="-1" aria-label="Zoom out">-</button><button type="button" data-map-center>Show world</button></div><p data-map-status role="status">Loading players...</p><canvas width="1000" height="480" aria-label="Online player map"></canvas><p class="muted">Outdoor markers show player positions. Interior markers show the entrance used, not the player's position inside.</p></section><aside><h2 data-status-total>Online players</h2><div data-status-roster>Loading...</div></aside></div></main><script src="status/map.js" defer></script></body></html>`, html.EscapeString(server.baseURL)) +} + +func statusZoneName(playfield uint32) string { + name := gamedata.Playfields[playfield].Name + if name == "" { + return fmt.Sprintf("Playfield %d", playfield) + } + if parts := strings.Split(name, "_"); len(parts) == 4 && parts[0] == "ord" && parts[1] == "smarket" { + faction := map[string]string{"clan": "Clan", "omni": "Omni", "neut": "Neutral"}[parts[2]] + return faction + " " + strings.ToUpper(parts[3][:1]) + parts[3][1:] + " Shop" + } + return strings.ReplaceAll(name, "_", " ") +} + +func (server *server) statusPlayers(w http.ResponseWriter, r *http.Request) { + players, err := server.adminPlayers() + if err != nil { + http.Error(w, "Cannot read online players", http.StatusInternalServerError) + return + } + + // Only detached online player data is public, regardless of query parameters. + online := make([]mapPlayer, 0) + for _, player := range players { + if !player.Connected { + continue + } + player.Zone = statusZoneName(player.Playfield) + if _, public := gamedata.Playfields[player.Playfield]; !public { + if mission := server.missionWorld(player.Playfield); mission != nil { + player.Zone = fmt.Sprintf("Private mission in %s #%d", statusZoneName(mission.offer.definition.Playfield), player.Playfield) + // Missions inside public interiors retain the player's outer entrance. + if _, outdoor := gamedata.MapCoordinates.Playfields[mission.offer.definition.Playfield]; outdoor || player.Entrance == nil { + player.Entrance = &mapEntrance{mission.offer.definition.Playfield, mission.offer.definition.Position} + } + } + } + online = append(online, player) + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + json.NewEncoder(w).Encode(struct { + Players []mapPlayer `json:"players"` + }{online}) +} diff --git a/server/status_test.go b/server/status_test.go @@ -0,0 +1,211 @@ +package main + +import ( + "ao/server/assets" + "ao/server/gamedata" + "context" + "encoding/json" + "net" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +func statusTestWorld(t *testing.T) *server { + t.Helper() + world := newAdminTestServer(t) + world.baseURL = "/share/test/" + world.characters = map[uint32]*character{ + 1: {id: 1, name: "Alice", playfield: 540, position: [3]float32{400, 5, 400}}, + 2: {id: 2, name: "Bob", playfield: 1180, returnDoor: &doorOrigin{540, 10}}, + 3: {id: 3, name: "Carol", playfield: 65536}, + 4: {id: 4, name: "Offline", playfield: 540}, + 5: {id: 5, name: "Loading", playfield: 540}, + 6: {id: 6, name: "NoMap", playfield: 99999}, + 7: {id: 7, name: "Dave", playfield: 65537}, + 1000000: {id: 1000000, name: "NPC", playfield: 540, npc: true}, + } + world.clients = map[uint32]*worldClient{ + 1: {ready: true}, 2: {ready: true}, 3: {ready: true}, 5: {}, 6: {ready: true}, 7: {ready: true}, + } + world.zoneLinks = map[string]map[uint32]zoneLinks{"target": {540: {Doors: []zoneDoor{{ID: 10, Position: [3]float32{450, 5, 450}}}}}} + world.missionExpiry = []acceptedMission{ + {world: 65536, offer: missionOffer{definition: gamedata.MissionTemplate{Playfield: 540, Position: [3]float32{500, 5, 500}}}}, + {world: 65537, offer: missionOffer{definition: gamedata.MissionTemplate{Playfield: 540, Position: [3]float32{500, 5, 500}}}}, + } + return world +} + +func TestStatusPublicPlayersAndInteriorEntrances(t *testing.T) { + world := statusTestWorld(t) + handler := world.httpHandler() + + response := adminRequest(handler, "GET", "/share/test/status/map-players?offline=1&character=4", "", nil) + var result struct { + Players []mapPlayer `json:"players"` + } + err := json.Unmarshal(response.Body.Bytes(), &result) + + if response.Code != 200 || err != nil || len(result.Players) != 5 || response.Header().Get("Cache-Control") != "no-store" { + t.Fatal(response.Code, response.Body, err) + } + if result.Players[0].Name != "Alice" || result.Players[0].Zone != "Old Athen" || result.Players[0].Entrance != nil { + t.Fatal("outdoor player", result.Players[0]) + } + if result.Players[1].Zone != "Clan Basic Shop" || result.Players[1].Entrance == nil || *result.Players[1].Entrance != (mapEntrance{540, [3]float32{450, 5, 450}}) { + t.Fatal("shop entrance", result.Players[1]) + } + if result.Players[2].Zone != "Private mission in Old Athen #65536" || result.Players[2].Entrance == nil || *result.Players[2].Entrance != (mapEntrance{540, [3]float32{500, 5, 500}}) { + t.Fatal("mission entrance", result.Players[2]) + } + if result.Players[3].Name != "NoMap" || result.Players[3].Entrance != nil || result.Players[4].Zone != "Private mission in Old Athen #65537" { + t.Fatal("unmapped player or distinct mission lost", result.Players) + } + for _, forbidden := range []string{"Offline", "Loading", "NPC", "last_ip", "credential", "inventory"} { + if strings.Contains(response.Body.String(), forbidden) { + t.Fatal("public feed includes", forbidden) + } + } +} + +func TestStatusPageAndAssetsArePublicUnderPrefix(t *testing.T) { + world := statusTestWorld(t) + useResources(t, assets.Files) + handler := world.httpHandler() + + page := adminRequest(handler, "GET", "/share/test/status", "", nil) + script := adminRequest(handler, "GET", "/share/test/status/map.js", "", nil) + manifest := adminRequest(handler, "GET", "/share/test/status/map-assets/manifest.json", "", nil) + admin := adminRequest(handler, "GET", "/share/test/admin/map-players", "", nil) + write := adminRequest(handler, "POST", "/share/test/status", "", nil) + + if page.Code != 200 || !strings.Contains(page.Body.String(), `<base href="/share/test/">`) || strings.Contains(page.Body.String(), "admin/") { + t.Fatal("public page", page.Code, page.Body) + } + if script.Code != 200 || manifest.Code != 200 || admin.Code != 303 || write.Code != 404 { + t.Fatal("route access", script.Code, manifest.Code, admin.Code, write.Code) + } +} + +func TestStatusTracksPlayersAcrossZoneOwnersAndDisconnects(t *testing.T) { + world, _ := newTeamWorld(t) + world.baseURL = "/" + world.characters[1].playfield = 540 + world.characters[2].playfield = 800 + for id := uint32(3); id <= 8; id++ { + delete(world.clients, id) + } + world.world = newRoutedTestWorld(t, world) + defer world.world.stop() + handler := world.httpHandler() + + before := adminRequest(handler, "GET", "/status/map-players", "", nil) + callTestZone(t, world, 2, zoneTestCommand(func(state *server) error { + state.leaveWorldClient(state.clients[2]) + return nil + })) + after := adminRequest(handler, "GET", "/status/map-players", "", nil) + var initial, remaining struct { + Players []mapPlayer `json:"players"` + } + initialErr := json.Unmarshal(before.Body.Bytes(), &initial) + remainingErr := json.Unmarshal(after.Body.Bytes(), &remaining) + + if initialErr != nil || remainingErr != nil || len(initial.Players) != 2 || len(remaining.Players) != 1 { + t.Fatal(before.Body, after.Body, initialErr, remainingErr) + } + if initial.Players[0].Playfield != 540 || initial.Players[1].Playfield != 800 || remaining.Players[0].ID != 1 { + t.Fatal("cross-zone snapshot or logout", initial, remaining) + } +} + +func TestStatusMissionInsideInteriorKeepsOuterEntrance(t *testing.T) { + world := statusTestWorld(t) + world.missionExpiry[0].offer.definition.Playfield = 1180 + world.characters[3].returnDoor = &doorOrigin{540, 10} + + response := adminRequest(world.httpHandler(), "GET", "/share/test/status/map-players", "", nil) + var result struct { + Players []mapPlayer `json:"players"` + } + err := json.Unmarshal(response.Body.Bytes(), &result) + + if err != nil || len(result.Players) != 5 || result.Players[2].Entrance == nil || + *result.Players[2].Entrance != (mapEntrance{540, [3]float32{450, 5, 450}}) || result.Players[2].Zone != "Private mission in Clan Basic Shop #65536" { + t.Fatal("outer entrance lost", response.Body, err) + } +} + +func TestStatusLoginNoticeFollowsHistoryWithoutPersisting(t *testing.T) { + world := chatTestServer(t) + world.baseURL, world.httpPort = "/share/test/", 8080 + if _, err := world.chat(); err != nil { + t.Fatal(err) + } + if err := world.appendChatHistory([]uint32{1}, chatHistoryEntry{Time: time.Now(), Channel: "say", Sender: "Bob", Message: "hello"}); err != nil { + t.Fatal(err) + } + host, peer := net.Pipe() + peer.SetDeadline(time.Now().Add(3 * time.Second)) + done := make(chan error, 1) + go func() { done <- world.serveChatClient(&chatClient{conn: chatIPv6TestConn{host}}) }() + t.Cleanup(func() { + peer.Close() + if err := <-done; err != nil { + t.Error(err) + } + }) + + if _, _, err := readChatPacket(peer); err != nil { + t.Fatal(err) + } + if _, err := peer.Write(chatTestAuth(1)); err != nil { + t.Fatal(err) + } + for range 3 { + if _, _, err := readChatPacket(peer); err != nil { + t.Fatal(err) + } + } + historyKind, historyBody, historyErr := readChatPacket(peer) + kind, body, err := readChatPacket(peer) + message, ok := readChatString(&body) + history, readErr := world.chatHistory(1) + + if historyErr != nil || historyKind != 36 || !strings.Contains(string(historyBody), "Bob: hello") { + t.Fatal("history must precede status", historyKind, historyErr) + } + if err != nil || kind != 36 || !ok || message != "[Server] 2 players online. Find other players at http://[::1]:8080/share/test/status" { + t.Fatal(kind, message, err) + } + if readErr != nil || len(history) != 1 { + t.Fatal("status persisted to history", history, readErr) + } +} + +func TestStatusBrowser(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for status UI verification") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + world := statusTestWorld(t) + useResources(t, assets.Files) + host := httptest.NewServer(world.httpHandler()) + defer host.Close() + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_status.mjs"), host.URL+world.baseURL, filepath.Join(root, "local/status-browser")) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + + err := command.Run() + + if err != nil { + t.Fatal(err) + } +} diff --git a/tools/client/test_status.mjs b/tools/client/test_status.mjs @@ -0,0 +1,71 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; + +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']}); +try { + const page = await browser.newPage({viewport: {width: 1280, height: 900}}); + const errors = []; + const requests = []; + page.on('pageerror', error => errors.push(error.message)); + page.on('request', request => requests.push(request.url())); + const tile = page.waitForResponse(response => response.url().includes('/status/map-assets/') && response.url().endsWith('.png') && response.ok()); + + await page.goto(url + 'status'); + await page.getByRole('heading', {name: '5 players online', exact: true}).waitFor(); + await tile; + await page.getByRole('button', {name: 'Alice (Old Athen)', exact: true}).click(); + await page.waitForFunction(() => { + const canvas = document.querySelector('canvas'); + const pixel = canvas.getContext('2d').getImageData(canvas.width / 2, canvas.height / 2, 1, 1).data; + return pixel[0] === 0 && pixel[1] === 207 && pixel[2] === 255; + }); + const map = page.locator('canvas'); + const box = await map.boundingBox(); + await map.click({position: {x: box.width / 2, y: box.height / 2}}); + await page.getByRole('button', {name: 'Bob (Clan Basic Shop)', exact: true}).click(); + await page.getByRole('button', {name: 'Carol (Private mission in Old Athen #65536)', exact: true}).click(); + await map.click({position: {x: box.width / 2, y: box.height / 2}}); + await page.screenshot({path: output + '/desktop.png', fullPage: true}); + await page.setViewportSize({width: 390, height: 844}); + await page.getByRole('button', {name: 'Alice (Old Athen)', exact: true}).click(); + await page.screenshot({path: output + '/mobile.png', fullPage: true}); + + assert.equal(await page.getByRole('button', {name: 'NoMap (Playfield 99999)', exact: true}).isDisabled(), true); + assert.deepEqual(await page.locator('[data-status-roster] button').allTextContents(), [ + 'Alice (Old Athen)', 'Bob (Clan Basic Shop)', 'Carol (Private mission in Old Athen #65536)', + 'Dave (Private mission in Old Athen #65537)', 'NoMap (Playfield 99999)', + ]); + assert.equal(await page.locator('[data-map-location], [data-status-roster] h2').count(), 0); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + assert.equal(await page.locator('a[href*="admin"], form').count(), 0); + assert.equal(requests.some(request => request.includes('/admin/')), false); + assert.equal(page.url(), url + 'status'); + assert.deepEqual(errors, []); + + // A changed feed must refresh both the roster and total without a navigation. + await page.route('**/status/map-players', route => route.fulfill({json: {players: []}})); + await page.getByRole('heading', {name: '0 players online', exact: true}).waitFor(); + await page.getByText('No players are connected right now.', {exact: true}).waitFor(); + assert.equal(await page.getByRole('button', {name: 'Alice (Old Athen)', exact: true}).count(), 0); + assert.deepEqual(errors, []); + + // The shared renderer must keep the authenticated admin map working too. + const login = await page.request.post(url + 'admin/login', { + form: {username: 'Operator', password: 'status-test-password', password_confirm: 'status-test-password'}, + }); + assert(login.ok()); + await page.goto(url + 'admin/map'); + await page.waitForFunction(() => document.querySelector('[data-map-status]').textContent.includes('5 connected players')); + await page.getByLabel('Find zone').selectOption('540'); + await page.getByLabel('Offline players').check(); + const offline = await page.waitForResponse(response => response.url().includes('admin/map-players?offline=1')); + assert((await offline.json()).players.some(player => player.name === 'Offline')); + assert.deepEqual(errors, []); +} finally { + await browser.close(); +}