aorecomp

Anarchy Online classic in the browser

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


commit a7d0db93843b25b804c5c85cea7fad2d0f4c63bd
parent 3cfc15c0c77cb8fba7fb8962b9428a63301c79f2
Author: anon <anon@example.com>
Date:   Tue, 20 Oct 2026 23:25:58 +0000

Support shared demos under a URL prefix and include browser bundle

Diffstat:
M.gitignore | 8+++++++-
MDEVELOPERS.md | 34+++++++++++++++++++---------------
MREADME.md | 39+++++++++++++++++++++++++++++++++++++--
Mdocs/repository-packaging.md | 9++++-----
Mserver/assets/map.js | 8++++----
Mserver/browser_client.go | 15++++++++++++++-
Mserver/browser_client_test.go | 12++++++------
Mserver/browser_launch.go | 2+-
Mserver/browser_launch_test.go | 2+-
Mserver/browser_socket_test.go | 5+++--
Mserver/control.go | 20++++++++++----------
Mserver/control_test.go | 2+-
Mserver/embedded_resources_test.go | 4++--
Aserver/http.go | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/http_test.go | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/main.go | 53+++++++++++------------------------------------------
Mserver/main_test.go | 2+-
Mserver/maps.go | 4++--
Mserver/state.go | 2++
Mserver/users_test.go | 2+-
Msrc/browser/index.html | 9+++++----
Msrc/browser/profile-worker.js | 4++--
Msrc/runtime/browser_audio.js | 2+-
Msrc/runtime/browser_fetch.js | 10+++++++---
Msrc/runtime/browser_host.js | 4++--
Msrc/runtime/browser_network.js | 2+-
Msrc/runtime/browser_profile.js | 2+-
Msrc/tests/browser_loading.mjs | 6+++---
28 files changed, 274 insertions(+), 114 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -4,7 +4,13 @@ /anarchy-assets-14.9.1/ /.runtime-bundle /client/ -/server/assets/client/ +/server/assets/client/* +!/server/assets/client/index.html +!/server/assets/client/game.js +!/server/assets/client/game.wasm.br +!/server/assets/client/profile-worker.js +!/server/assets/client/audio-worklet.js +!/server/assets/client/build.json /client-*/ /local/ /logs/ diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -35,15 +35,9 @@ temporary file, synced and closed, then renamed over the destination. On Unix, each file replacement is atomic. Chat history uses serialized, synced record appends and size-based rotation. -The browser build is kept outside Git. Before building the server, copy the -six matching files into `server/assets/client/`: `index.html`, `game.js`, -`game.wasm.br`, `profile-worker.js`, `audio-worklet.js`, and `build.json`. -For example, copy them from a client build machine: - -```sh -rsync -a workstation:/path/to/ao/server/assets/client/ ./server/assets/client/ -go run ./server -``` +The matching browser build is checked in under `server/assets/client/`: +`index.html`, `game.js`, `game.wasm.br`, `profile-worker.js`, `audio-worklet.js`, +and `build.json`. A fresh clone can run `go run ./server` immediately. No Emscripten, Python, Make, C compiler, or original Windows client is needed on the server build machine. Rebuild the Go binary after updating resources. @@ -67,6 +61,16 @@ can be moved to `logs/profiles/`. Server messages are appended to go run ./server ``` +### Reverse proxy deployment + +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. + +Keep saved player data and logs outside the public static directory. + ## Browser client Open [the game](http://127.0.0.1:8080/) in a browser supporting shared WebAssembly @@ -153,14 +157,14 @@ make wasm -j8 ``` This downloads/builds the audio dependencies, compiles the game, and writes the -six files above to ignored `server/assets/client/`, which Go embeds when building. The first build is +six files above to tracked `server/assets/client/`, which Go embeds when building. The first build is heavy; allow several gigabytes of build space and substantial compilation time. ThinLTO optimizes calls across source files with eight linker workers. Keep `src/build/wasm/lto-cache/` to reuse that work on subsequent builds. Publishing also caches Brotli compression in `src/build/wasm/web/`, so page-only updates reuse the compressed executable. The browser decodes it over HTTP. -Copy the complete matching bundle to other machines after validating it. Do not -mix JavaScript and WASM from different builds or commit generated client files. +Commit the complete matching bundle after validating it. Do not mix JavaScript +and WASM from different builds. Intermediate build output stays ignored. ## Game data @@ -311,7 +315,7 @@ The server may need network access on its first build to download Go modules. | `server/`, `data/` | Go server, extracted world data, and local saved characters. | | `server/gamedata/` | Embedded YAML definitions, provenance and Go schemas. | | `server/assets/` | Embedded static resources and their Go loader. | -| `server/assets/client/` | Ignored browser build, embedded when building the server. | +| `server/assets/client/` | Checked-in browser build, embedded when building the server. | | `anarchy-vanilla-14.9.1/` | Local original game for Windows reference comparisons. | | `anarchy-runtime-14.9.1/` | Windows runtime assets and native vendor DLLs. | | `anarchy-assets-14.9.1/` | Portable game assets and configuration; no Windows executables or plug-ins. | @@ -370,8 +374,8 @@ Linux only needs windowed mode. Read [src/README.md](src/README.md) before chang validation remain in progress. - Keep original binaries, downloaded tools, generated reports and saved users local. Maintained reconstructed sources, game definitions and required static - resource files belong in Git. Generated browser builds remain ignored. This - local handoff does not publish game data to a public host. Preserve + resource files and the matching published browser bundle belong in Git. + Intermediate client builds stay ignored. Preserve unrelated user edits between turns. ### Validation diff --git a/README.md b/README.md @@ -6,8 +6,8 @@ binary. ## Build and run -Requires Go 1.24+ and a matching browser build in `server/assets/client/`. -[Copy or build the browser bundle](DEVELOPERS.md#server-build-and-operation) first. +Requires Go 1.24+. A matching browser client is checked in under +`server/assets/client/`; no WASM build or C toolchain is needed. ```sh go build -o ao-server ./server @@ -20,6 +20,41 @@ Open [localhost:8080](http://localhost:8080/). For phones and other devices, use Distribute the binary by itself. Runtime state lives in `data/`; logs and profiles live in `logs/`. +## Shared demo and downloads + +[Play the demo](/share/demo/) or open its +[server controls](/share/demo/control). +Both are available without authentication. +[Browse the source and history](/share/demo/repo/), +or clone and run your own server: + +```sh +git clone https://<demo-host>/share/demo/repo.git ao +cd ao +go run ./server +``` + +Prebuilt servers include the browser client and all static resources. Download +one, make it executable on Linux/macOS, and run it from a writable directory: + +- [Windows x64](/share/demo/repo/releases/aoserver-latest-windows-amd64.exe) +- [Linux x64](/share/demo/repo/releases/aoserver-latest-linux-amd64) +- [Linux ARM64](/share/demo/repo/releases/aoserver-latest-linux-arm64) +- [macOS Intel](/share/demo/repo/releases/aoserver-latest-macos-amd64) +- [macOS Apple Silicon](/share/demo/repo/releases/aoserver-latest-macos-arm64) + +[Published commit](/share/demo/repo/releases/commit.txt). + +Behind a reverse proxy, pass the public URL path, including its trailing slash: + +```sh +./ao-server -base-url /share/demo/ +``` + +Have the proxy preserve that prefix and the Host header, forward WebSocket +upgrades, and serve trusted HTTPS. The server supplies the browser isolation +headers needed for shared WASM memory. + ## Repository overview ```text diff --git a/docs/repository-packaging.md b/docs/repository-packaging.md @@ -46,9 +46,8 @@ their local work, rather than merging the old history back into this repository. ## Clone and run -Clone the repository normally and copy the complete `server/assets/client/` -bundle from a client build machine using the [developer instructions](../DEVELOPERS.md#server-build-and-operation). -Generated browser output is ignored and must not be committed. Build with +Clone the repository normally; the complete matching `server/assets/client/` +bundle is checked in. No WASM toolchain is needed for server work. Build with `go build -o ao-server ./server` using Go 1.24 or newer. Distribute the resulting binary by itself; it can run from an empty directory. Open `http://127.0.0.1:8080/`. The server listens on all interfaces; use its HTTPS @@ -102,8 +101,8 @@ stopped afterward. ## Updating published files `make wasm -j8` builds dependencies and the client, then publishes the six -matching files to ignored `server/assets/client/`. Copy them together and -rebuild the server. `build.json` records the source revision, source digest, +matching files to tracked `server/assets/client/`. Commit them together after +validation and rebuild the server. `build.json` records the source revision, source digest, compiler identity and output hashes. Edit `src/runtime/` or `src/browser/` and republish instead of editing generated JavaScript. diff --git a/server/assets/map.js b/server/assets/map.js @@ -23,7 +23,7 @@ class AOMap { } async start() { - const response = await fetch("/map-assets/manifest.json"); + const response = await fetch("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; @@ -227,7 +227,7 @@ class AOMap { async poll() { try { if (!document.hidden) { - const response = await fetch("/map-players", {cache: "no-store"}); + const response = await fetch("map-players", {cache: "no-store"}); if (!response.ok) throw new Error(`Player feed returned HTTP ${response.status}`); this.players = (await response.json()).players; if (!this.initialized) { @@ -263,7 +263,7 @@ class AOMap { if (tile.bitmap || tile.failed || tile.loading) continue; tile.loading = true; this.loadingTiles++; - fetch(`/map-assets/${path}`, {cache: "force-cache"}).then(response => { + fetch(`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 => { @@ -320,7 +320,7 @@ class AOMap { if (!point) continue; const screen = this.toScreen(...point); if (Math.hypot(x - screen[0], y - screen[1]) < 9 && player.id !== this.character) { - window.location.href = `/users/${player.id}`; + window.location.href = new URL(`users/${player.id}`, document.baseURI); return; } } diff --git a/server/browser_client.go b/server/browser_client.go @@ -4,6 +4,7 @@ import ( "ao/server/assets" "crypto/sha256" "fmt" + "html" "io" "io/fs" "net/http" @@ -35,7 +36,7 @@ var browserClientVersion = func() string { return fmt.Sprintf("%x", digest.Sum(nil)) }() -func browserClient(w http.ResponseWriter, r *http.Request) { +func (server *server) browserClient(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cross-Origin-Opener-Policy", "same-origin") w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp") w.Header().Set("Cache-Control", "no-cache") @@ -67,6 +68,18 @@ func browserClient(w http.ResponseWriter, r *http.Request) { w.Header().Set("ETag", browserAssetVersion("client/"+name, info)) } + if name == "index.html" { + contents, err := io.ReadAll(file) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("ETag", strings.TrimSuffix(w.Header().Get("ETag"), "\"")+fmt.Sprintf("-%x\"", server.baseURL)) + page := strings.ReplaceAll(string(contents), "__AO_BASE_URL__", html.EscapeString(server.baseURL)) + http.ServeContent(w, r, info.Name(), info.ModTime(), strings.NewReader(page)) + return + } + // Browsers decode the published Brotli representation before compiling WASM. if name == "game.wasm.br" { w.Header().Set("Content-Type", "application/wasm") diff --git a/server/browser_client_test.go b/server/browser_client_test.go @@ -24,7 +24,7 @@ func TestBrowserClientServesPublishedWasm(t *testing.T) { request.Header.Set("Accept-Encoding", "br") response := httptest.NewRecorder() - browserClient(response, request) + (&server{baseURL: "/"}).browserClient(response, request) if response.Code != http.StatusOK || response.Header().Get("Content-Type") != "application/wasm" || response.Header().Get("Content-Encoding") != "br" { t.Fatalf("WASM response: %d %v", response.Code, response.Header()) @@ -55,12 +55,12 @@ func TestBrowserClientRevalidatesUnchangedFiles(t *testing.T) { path = "/wasm/game.wasm" } first := httptest.NewRecorder() - browserClient(first, httptest.NewRequest("GET", path, nil)) + (&server{baseURL: "/"}).browserClient(first, httptest.NewRequest("GET", path, nil)) request := httptest.NewRequest("GET", path, nil) request.Header.Set("If-None-Match", first.Header().Get("ETag")) response := httptest.NewRecorder() - browserClient(response, request) + (&server{baseURL: "/"}).browserClient(response, request) if first.Header().Get("ETag") == "" || response.Code != http.StatusNotModified || response.Body.Len() != 0 { t.Fatalf("cache revalidation: %d %v %q", response.Code, response.Header(), response.Body.String()) @@ -83,7 +83,7 @@ func TestBrowserClientDetectsSameSecondReplacement(t *testing.T) { t.Fatal(err) } first := httptest.NewRecorder() - browserClient(first, httptest.NewRequest("GET", "/wasm/game.js", nil)) + (&server{baseURL: "/"}).browserClient(first, httptest.NewRequest("GET", "/wasm/game.js", nil)) if err := os.WriteFile("client/game.js", []byte("new"), 0644); err != nil { t.Fatal(err) } @@ -95,7 +95,7 @@ func TestBrowserClientDetectsSameSecondReplacement(t *testing.T) { request.Header.Set("If-None-Match", first.Header().Get("ETag")) response := httptest.NewRecorder() - browserClient(response, request) + (&server{baseURL: "/"}).browserClient(response, request) if response.Code != http.StatusOK || response.Body.String() != "new" || response.Header().Get("ETag") == first.Header().Get("ETag") { t.Fatalf("replacement response: %d %v %q", response.Code, response.Header(), response.Body.String()) @@ -114,7 +114,7 @@ func TestBrowserClientServesPublishedPageWithoutBuildDirectory(t *testing.T) { for _, path := range []string{"/", "/wasm/"} { response := httptest.NewRecorder() - browserClient(response, httptest.NewRequest("GET", path, nil)) + (&server{baseURL: "/"}).browserClient(response, httptest.NewRequest("GET", path, nil)) if response.Code != http.StatusOK || response.Body.String() != "Loading client" || response.Header().Get("Cross-Origin-Opener-Policy") != "same-origin" || response.Header().Get("Cross-Origin-Embedder-Policy") != "require-corp" { t.Fatalf("client page %s: %d %q", path, response.Code, response.Body.String()) diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -45,7 +45,7 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.SetCookie(w, &http.Cookie{Name: "ao_client", Value: token, Path: "/", + http.SetCookie(w, &http.Cookie{Name: "ao_client", Value: token, Path: server.baseURL, HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode, MaxAge: 31536000}) } w.Header().Set("Content-Type", "text/plain") diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go @@ -14,7 +14,7 @@ func TestBrowserLaunchCreatesPersistentVisitor(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{worldPort: 7501, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient)} + world := &server{baseURL: "/", worldPort: 7501, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient)} response := httptest.NewRecorder() world.browserLaunch(response, httptest.NewRequest("POST", "/browser-launch", nil)) diff --git a/server/browser_socket_test.go b/server/browser_socket_test.go @@ -18,11 +18,12 @@ import ( func TestBrowserWorldPreservesPacketStream(t *testing.T) { world := newTestServer(t) world.newCharacter().browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("visitor-token"))) - host := httptest.NewServer(http.HandlerFunc(world.browserWorld)) + world.baseURL = "/share/demo/" + host := httptest.NewServer(world.httpHandler()) defer host.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - socket, _, err := websocket.Dial(ctx, host.URL, &websocket.DialOptions{ + socket, _, err := websocket.Dial(ctx, host.URL+world.baseURL+"browser-world", &websocket.DialOptions{ HTTPHeader: http.Header{"Cookie": {"ao_client=visitor-token"}}, }) if err != nil { diff --git a/server/control.go b/server/control.go @@ -27,9 +27,9 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { server.mutex.Unlock() w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprint(w, "<!doctype html><html><head><title>Server controls</title></head><body><h1>Server controls</h1><p><a href='/control'>Refresh</a></p>") + 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='/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) + fmt.Fprintf(w, "<form method='post' action='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) fmt.Fprint(w, "<p>NPC definitions are compiled from server/gamedata; rebuild and restart to apply changes.</p>") controlMap(w, 0) fmt.Fprint(w, "<h2>Users</h2><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th><th>Map</th></tr>") @@ -38,9 +38,9 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { if connected[player.ID] { status = "Connected" } - fmt.Fprintf(w, "<tr data-map-player='%d'><td>%d</td><td><a href='/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.Fprintf(w, "<tr data-map-player='%d'><td>%d</td><td><a href='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='/users'><label>Name <input name='name' required maxlength='254'></label> <button>Create user</button></form></body></html>") + fmt.Fprint(w, "</table><h2>Create user</h2><form method='post' action='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) { @@ -66,10 +66,10 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprint(w, "<!doctype html><html><head><title>User</title></head><body><p><a href='/control'>All users</a></p>") + 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)) fmt.Fprintf(w, "<h1>%s</h1><p>User %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected) controlMap(w, data.ID) - fmt.Fprintf(w, "<h2>Character data</h2><p>ID is fixed. Position is XYZ; rotation is XYZW. Saving reconnects an online character to apply the data.</p><form method='post' action='/users/%d'><textarea name='data' rows='20' cols='80' required>%s</textarea><p><button>Save character</button></p></form>", data.ID, html.EscapeString(string(contents))) + fmt.Fprintf(w, "<h2>Character data</h2><p>ID is fixed. Position is XYZ; rotation is XYZW. Saving reconnects an online character to apply the data.</p><form method='post' action='users/%d'><textarea name='data' rows='20' cols='80' required>%s</textarea><p><button>Save character</button></p></form>", data.ID, html.EscapeString(string(contents))) fmt.Fprint(w, "</body></html>") } @@ -95,7 +95,7 @@ func (server *server) createUser(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - http.Redirect(w, r, fmt.Sprintf("/users/%d", player.id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%susers/%d", server.baseURL, player.id), http.StatusSeeOther) } func (server *server) editUser(w http.ResponseWriter, r *http.Request) { @@ -129,7 +129,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("/users/%d", data.ID), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%susers/%d", server.baseURL, data.ID), http.StatusSeeOther) } func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) { @@ -157,7 +157,7 @@ func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) { client.conn.Close() } } - http.Redirect(w, r, "/control", http.StatusSeeOther) + http.Redirect(w, r, server.baseURL+"control", http.StatusSeeOther) } func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) { @@ -213,7 +213,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("/users/%d", id), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("%susers/%d", server.baseURL, id), http.StatusSeeOther) } func (server *server) updateUser(destination userData) error { diff --git a/server/control_test.go b/server/control_test.go @@ -71,7 +71,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='/teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") { + if strings.Count(body, "action='teleport/1'") != 1 || strings.Contains(body, "<button>Teleport</button>") { t.Fatalf("generic zone teleport is still present") } } diff --git a/server/embedded_resources_test.go b/server/embedded_resources_test.go @@ -22,8 +22,8 @@ func TestEmbeddedResourcesServeWithoutExternalFiles(t *testing.T) { mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) mux.HandleFunc("GET /browser-manifest", browserManifest) mux.HandleFunc("GET /browser-resource-index", browserResourceIndex) - mux.HandleFunc("GET /wasm/", browserClient) - mux.HandleFunc("GET /{$}", browserClient) + mux.HandleFunc("GET /wasm/", (&server{baseURL: "/"}).browserClient) + mux.HandleFunc("GET /{$}", (&server{baseURL: "/"}).browserClient) mux.Handle("GET /map-assets/", http.StripPrefix("/map-assets/", http.FileServerFS(maps))) for _, path := range []string{"/", "/wasm/game.js", "/wasm/build.json", "/browser-manifest", "/browser-resource-index", "/map-assets/manifest.json", "/browser-assets/version.id", "/browser-assets/cd_image/text/help/What%20%27s-This%20General%20Help.txt"} { diff --git a/server/http.go b/server/http.go @@ -0,0 +1,61 @@ +package main + +import ( + "fmt" + "html" + "io/fs" + "log" + "net/http" + "strings" +) + +func (server *server) httpHandler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /control", server.controlPage) + mux.HandleFunc("GET /users/{character}", server.userPage) + mux.HandleFunc("POST /users", server.createUser) + mux.HandleFunc("POST /users/{character}", server.editUser) + mux.HandleFunc("GET /control-map.js", controlMapScript) + mux.HandleFunc("GET /map-players", server.mapPlayers) + mapResources, err := fs.Sub(resources, "maps") + if err != nil { + log.Fatal(err) + } + mapFiles := http.StripPrefix("/map-assets/", http.FileServerFS(mapResources)) + mux.HandleFunc("GET /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") + } + mapFiles.ServeHTTP(w, r) + }) + mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) + mux.HandleFunc("POST /browser-launch", server.browserLaunch) + mux.HandleFunc("GET /browser-world", server.browserWorld) + mux.HandleFunc("GET /browser-chat", server.browserChat) + mux.HandleFunc("GET /browser-manifest", browserManifest) + mux.HandleFunc("GET /browser-resource-index", browserResourceIndex) + mux.HandleFunc("POST /browser-profile/{session}", browserProfile) + mux.HandleFunc("GET /wasm/", server.browserClient) + mux.HandleFunc("GET /{$}", server.browserClient) + mux.HandleFunc("POST /time", server.setGameTime) + mux.HandleFunc("POST /teleport/{character}", server.teleportPlayer) + // Serve the original launcher's dimension list and informational pages. + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + log.Printf("HTTP %s %s", r.Method, r.URL.Path) + if strings.HasSuffix(r.URL.Path, "dimensions.txt") { + server.dimensionList(w, r) + return + } + fmt.Fprintf(w, `<html><body><a href="%swasm/">Play Anarchy Online 14.9.1</a> | <a href="%scontrol">Server controls</a></body></html>`, html.EscapeString(server.baseURL), html.EscapeString(server.baseURL)) + }) + + // Keep internal routes independent of the public mounting path. + if server.baseURL == "/" { + return mux + } + mounted := http.NewServeMux() + mounted.Handle(server.baseURL, http.StripPrefix(strings.TrimSuffix(server.baseURL, "/"), mux)) + return mounted +} diff --git a/server/http_test.go b/server/http_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "ao/server/assets" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestHTTPHandlerMountsGameAndControls(t *testing.T) { + for _, baseURL := range []string{"/", "/share/demo/"} { + t.Run(baseURL, func(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + world.baseURL = baseURL + useResources(t, assets.Files) + handler := world.httpHandler() + + game := httptest.NewRecorder() + handler.ServeHTTP(game, httptest.NewRequest("GET", baseURL, nil)) + controls := httptest.NewRecorder() + handler.ServeHTTP(controls, httptest.NewRequest("GET", baseURL+"control", nil)) + asset := httptest.NewRecorder() + handler.ServeHTTP(asset, httptest.NewRequest("GET", baseURL+"browser-assets/version.id", nil)) + + if game.Code != http.StatusOK || !strings.Contains(game.Body.String(), `<base href="`+baseURL+`">`) || strings.Contains(game.Body.String(), "__AO_BASE_URL__") { + t.Fatalf("game page: HTTP %d, missing public base URL", game.Code) + } + if controls.Code != http.StatusOK || !strings.Contains(controls.Body.String(), "<base href='"+baseURL+"'>") || !strings.Contains(controls.Body.String(), "action='users'") { + t.Fatalf("control page: HTTP %d, missing scoped forms", controls.Code) + } + if asset.Code != http.StatusOK || strings.TrimSpace(asset.Body.String()) != "14.9.1" { + t.Fatalf("asset: HTTP %d, %q", asset.Code, asset.Body.String()) + } + }) + } +} + +func TestHTTPHandlerScopesVisitorCookieAndRedirects(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + world.baseURL = "/share/demo/" + handler := world.httpHandler() + request := httptest.NewRequest("POST", world.baseURL+"time", strings.NewReader("hour=13&minute=30")) + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + redirect := httptest.NewRecorder() + handler.ServeHTTP(redirect, request) + 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)) + + if redirect.Code != http.StatusSeeOther || redirect.Header().Get("Location") != "/share/demo/control" { + t.Fatalf("control redirect: HTTP %d, %v", redirect.Code, redirect.Header()) + } + cookies := launch.Result().Cookies() + if launch.Code != http.StatusOK || len(cookies) != 1 || cookies[0].Path != "/share/demo/" || !cookies[0].Secure { + t.Fatalf("visitor cookie: HTTP %d, %v", launch.Code, cookies) + } + if outside.Code != http.StatusNotFound { + t.Fatalf("unmounted control page: HTTP %d", outside.Code) + } +} diff --git a/server/main.go b/server/main.go @@ -13,6 +13,7 @@ import ( "net" "net/http" "os" + "path" "strings" "time" ) @@ -21,7 +22,12 @@ 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") + baseURL := flag.String("base-url", "/", "URL path prefix (must start and end with /)") flag.Parse() + if !strings.HasPrefix(*baseURL, "/") || !strings.HasSuffix(*baseURL, "/") || + (*baseURL != "/" && path.Clean(*baseURL)+"/" != *baseURL) || strings.ContainsAny(*baseURL, "?#\\%") { + log.Fatal("base-url must be an absolute URL path ending in / without query, fragment, or escapes") + } for _, port := range []int{*loginPort, *worldPort, *httpPort} { if port < 1 || port > 65535 { log.Fatal("ports must be between 1 and 65535") @@ -46,51 +52,14 @@ func main() { } server := newServer() server.loginPort, server.worldPort, server.httpPort = *loginPort, *worldPort, *httpPort + server.baseURL = *baseURL httpAddress := fmt.Sprintf(":%d", server.httpPort) - http.HandleFunc("GET /control", server.controlPage) - http.HandleFunc("GET /users/{character}", server.userPage) - http.HandleFunc("POST /users", server.createUser) - http.HandleFunc("POST /users/{character}", server.editUser) - http.HandleFunc("GET /control-map.js", controlMapScript) - http.HandleFunc("GET /map-players", server.mapPlayers) - mapResources, err := fs.Sub(resources, "maps") - if err != nil { - log.Fatal(err) - } - mapFiles := http.StripPrefix("/map-assets/", http.FileServerFS(mapResources)) - http.HandleFunc("GET /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") - } - mapFiles.ServeHTTP(w, r) - }) - http.HandleFunc("GET /browser-assets/{path...}", browserAsset) - http.HandleFunc("POST /browser-launch", server.browserLaunch) - http.HandleFunc("GET /browser-world", server.browserWorld) - http.HandleFunc("GET /browser-chat", server.browserChat) - http.HandleFunc("GET /browser-manifest", browserManifest) - http.HandleFunc("GET /browser-resource-index", browserResourceIndex) - http.HandleFunc("POST /browser-profile/{session}", browserProfile) - http.HandleFunc("GET /wasm/", browserClient) - http.HandleFunc("GET /{$}", browserClient) - http.HandleFunc("POST /time", server.setGameTime) - http.HandleFunc("POST /teleport/{character}", server.teleportPlayer) - // Serve the original launcher's dimension list and informational pages. - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - log.Printf("HTTP %s %s", r.Method, r.URL.Path) - if strings.HasSuffix(r.URL.Path, "dimensions.txt") { - server.dimensionList(w, r) - return - } - fmt.Fprint(w, `<html><body><a href="/wasm/">Play Anarchy Online 14.9.1</a> | <a href="/control">Server controls</a></body></html>`) - }) + handler := server.httpHandler() go func() { - log.Fatal(http.ListenAndServe(httpAddress, nil)) + log.Fatal(http.ListenAndServe(httpAddress, handler)) }() go func() { - log.Fatal(http.ListenAndServeTLS(":8443", "data/https/cert.pem", "data/https/key.pem", nil)) + log.Fatal(http.ListenAndServeTLS(":8443", "data/https/cert.pem", "data/https/key.pem", handler)) }() go server.serveWorld() go server.serveChat() @@ -103,7 +72,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/control", server.httpPort, server.loginPort, server.worldPort, server.httpPort) + 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) for { conn, err := listener.Accept() if err != nil { diff --git a/server/main_test.go b/server/main_test.go @@ -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='/users/1'>Local Explorer 1</a>") { + if !strings.Contains(page.Body.String(), "href='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/maps.go b/server/maps.go @@ -12,9 +12,9 @@ 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) if character != 0 { - fmt.Fprintf(w, "<form method='post' action='/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='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-map.js' defer></script>") + fmt.Fprint(w, "</div><script src='control-map.js' defer></script>") } func controlMapScript(w http.ResponseWriter, r *http.Request) { diff --git a/server/state.go b/server/state.go @@ -62,6 +62,7 @@ type server struct { loginPort int worldPort int httpPort int + baseURL string mutex sync.Mutex npcUpdateMutex sync.RWMutex nextCharacter uint32 @@ -81,6 +82,7 @@ type server struct { func newServer() *server { server := &server{ loginPort: 7500, worldPort: 7501, httpPort: 8080, + baseURL: "/", gameSeconds: 48600, clockStarted: time.Now(), characters: make(map[uint32]*character), roamingNPCs: make(map[uint32][]*character), diff --git a/server/users_test.go b/server/users_test.go @@ -115,7 +115,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='/users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") { + if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") { t.Fatalf("offline user disappeared: %s", page.Body.String()) } contents, err := os.ReadFile("data/players/1/player.yaml") diff --git a/src/browser/index.html b/src/browser/index.html @@ -1,11 +1,12 @@ <!doctype html> <html lang="en"> <meta charset="utf-8"> +<base href="__AO_BASE_URL__"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-visual"> <title>Anarchy Online 14.9.1</title> <style> html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #111; color: #ddd; font: 14px sans-serif; } - @font-face { font-family: GameVerdana; src: url('/browser-assets/fonts/verdana.ttf'); } + @font-face { font-family: GameVerdana; src: url('browser-assets/fonts/verdana.ttf'); } #game-surface { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } canvas { display: block; width: 100%; height: 100%; touch-action: none; } button, select, input { font: inherit; } @@ -221,7 +222,7 @@ // The published sizes distinguish the compressed transfer from decoded progress. async function instantiateClient(imports, receive) { - const response = await fetch('/wasm/game.wasm'); + const response = await fetch('wasm/game.wasm'); if (!response.ok) throw new Error(`Client download: HTTP ${response.status}`); const totalMB = Number('__WASM_DOWNLOAD_MB__'); status.textContent = `Downloading Anarchy Online client...\n0.00 / ${totalMB.toFixed(2)} MB`; @@ -345,13 +346,13 @@ show(); document.addEventListener(type, resumeAudio, true); } status.textContent = 'Downloading Anarchy Online client...'; - const response = await fetch('/browser-launch', {method: 'POST'}); + const response = await fetch('browser-launch', {method: 'POST'}); if (!response.ok) { status.textContent = await response.text(); return; } Module.arguments = (await response.text()).trim().split(' ').slice(1); // The render worker owns the backing canvas after startup. [canvas.width, canvas.height] = renderSize(); const script = document.createElement('script'); - script.src = '/wasm/game.js'; + script.src = 'wasm/game.js'; script.onerror = () => { status.textContent = 'Could not load the client'; }; document.body.append(script); } diff --git a/src/browser/profile-worker.js b/src/browser/profile-worker.js @@ -15,7 +15,7 @@ onmessage = event => { visibility = configuration.visibility; memory = new Uint32Array(configuration.memory); started = configuration.started; - fetch('/wasm/build.json').then(response => { + fetch(new URL('build.json', location.href)).then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); }).then(value => { build = value.source_commit; }).catch(error => { @@ -62,7 +62,7 @@ async function upload() { events = []; frames = []; metrics = {}; dropped = 0; started = ended; uploading = true; try { - const response = await fetch(`/browser-profile/${configuration.session}`, { + const response = await fetch(new URL(`../browser-profile/${configuration.session}`, location.href), { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(batch), signal: AbortSignal.timeout(10000) }); diff --git a/src/runtime/browser_audio.js b/src/runtime/browser_audio.js @@ -7,7 +7,7 @@ addToLibrary({ const state = new Int32Array(HEAPU8.buffer, ring, 6); const device = {state, node: null, failed: false}; AOAudio.devices.set(ring, device); - AOAudio.module ||= context.audioWorklet.addModule('/wasm/audio-worklet.js'); + AOAudio.module ||= context.audioWorklet.addModule(new URL('wasm/audio-worklet.js', document.baseURI)); device.ready = AOAudio.module.then(() => { device.node = new AudioWorkletNode(context, 'ao-audio', { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [channels], diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js @@ -176,9 +176,12 @@ addToLibrary({ } // Validate all file versions together; size queries need no asset bytes. + function serverURL(name, assetURL) { + return assetURL.slice(0, assetURL.lastIndexOf('/browser-assets/') + 1) + name; + } async function fileMetadata(url) { if (!metadata) { - metadata = AOAssetRequest(new URL('/browser-manifest', url).href, { + metadata = AOAssetRequest(serverURL('browser-manifest', url), { cache: 'no-store', headers: {Accept: 'application/json'} }).then(({response, bytes}) => { if (!response.ok) throw response; @@ -189,7 +192,8 @@ addToLibrary({ }); } const listing = await metadata; - const name = decodeURIComponent(new URL(url).pathname).slice('/browser-assets/'.length); + const pathname = new URL(url).pathname; + const name = decodeURIComponent(pathname.slice(pathname.lastIndexOf('/browser-assets/') + '/browser-assets/'.length)); return listing[name]; } @@ -249,7 +253,7 @@ addToLibrary({ if (url.endsWith('/ResourceDatabase.dat')) databaseHandle = file; } const info = await fileMetadata(indexURL); - const {response, bytes} = await AOAssetRequest(new URL('/browser-resource-index', indexURL).href, + const {response, bytes} = await AOAssetRequest(serverURL('browser-resource-index', indexURL), {headers: {'If-Match': info.version}}); if (!response.ok) throw new Error(`Resource prefetch index: HTTP ${response.status}`); const records = new DataView(bytes); diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js @@ -101,7 +101,7 @@ addToLibrary({ ao_asset_manifest_js__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOAssetRequest', 'emscripten_proxy_finish'], ao_asset_manifest_js: (context, request) => { const base = HEAPU32[request >> 2]; - AOAssetRequest(new URL('/browser-manifest', UTF8ToString(base)).href, + AOAssetRequest(new URL('browser-manifest', UTF8ToString(base)).href, {cache: 'no-store', headers: {Accept: 'application/json'}}).then(({response, bytes}) => { if (response.ok) HEAPU32[(request + 4) >> 2] = stringToNewUTF8(new TextDecoder().decode(bytes)); @@ -140,7 +140,7 @@ addToLibrary({ }; canvas.addEventListener('pointerup', released); canvas.addEventListener('pointercancel', released); - return stringToNewUTF8(new URL('/browser-assets', location.href).href); + return stringToNewUTF8(new URL('browser-assets', document.baseURI).href); }, ao_mouse_capture__proxy: 'sync', ao_mouse_capture: (enabled) => { diff --git a/src/runtime/browser_network.js b/src/runtime/browser_network.js @@ -139,7 +139,7 @@ addToLibrary({ entry.error = true; return; } - const url = new URL(port === worldPort ? '/browser-world' : '/browser-chat', location.href); + const url = new URL(port === worldPort ? 'browser-world' : 'browser-chat', document.baseURI); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; entry.url = url; AOSockets.connect(entry); diff --git a/src/runtime/browser_profile.js b/src/runtime/browser_profile.js @@ -86,7 +86,7 @@ addToLibrary({ const session = crypto.randomUUID(); let worker; try { - worker = new Worker('/wasm/profile-worker.js'); + worker = new Worker(new URL('wasm/profile-worker.js', document.baseURI)); } catch (error) { console.warn('Profiling unavailable; gameplay continues', error); return 0; diff --git a/src/tests/browser_loading.mjs b/src/tests/browser_loading.mjs @@ -23,7 +23,7 @@ function fixture(response) { '#loading': loading, '#download-progress': downloadProgress, '#download-fill': downloadFill })[selector] ?? canvas}, fetch: async url => { - assert.equal(url, '/wasm/game.wasm'); + assert.equal(url, 'wasm/game.wasm'); return response; } }); @@ -135,14 +135,14 @@ async function startsWithMainThreadGraphicsWithoutOffscreenCanvas() { test.context.document.createElement = () => ({}); test.context.document.body = {append: script => scripts.push(script.src)}; test.context.fetch = async (url, options) => { - assert.equal(url, '/browser-launch'); + assert.equal(url, 'browser-launch'); assert.equal(options.method, 'POST'); return new Response('Clientr.exe localtest localtest 73'); }; await test.context.startGame(); - assert.deepEqual(scripts, ['/wasm/game.js']); + assert.deepEqual(scripts, ['wasm/game.js']); assert.equal(canvas.transferControlToOffscreen, undefined); assert.equal(canvas.width, 1024); assert.equal(canvas.height, 768);