aorecomp

Anarchy Online classic in the browser

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


commit a40d4c097c8d178e823e919719a5430d4de14dea
parent e13b7b128a55bc998bb1cc9075bd127d8f49b954
Author: anon <anon@example.com>
Date:   Fri, 16 Oct 2026 21:29:04 +0000

Ship browser client and runtime data for Go-only checkouts

Diffstat:
M.gitattributes | 4++++
M.gitignore | 2++
MMakefile | 8+++++++-
MREADME.md | 44+++++++++++++++++++++++++++++++++++---------
Mdocs/portable-assets.md | 8+++++---
Adocs/repository-packaging.md | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aruntime/manifest.json | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_client.go | 20++++++++++++++++++++
Aserver/browser_client_test.go | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/browser_launch.go | 16++++++++++++++--
Mserver/browser_launch_test.go | 24++++++++++++++++++++++++
Mserver/main.go | 13+++++--------
Aserver/runtime_bundle.go | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/runtime_bundle_test.go | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/package_runtime.py | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/publish_wasm.py | 50++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 667 insertions(+), 23 deletions(-)

diff --git a/.gitattributes b/.gitattributes @@ -2,3 +2,7 @@ # Unified patches contain intentional whitespace in their context lines. *.patch -whitespace + +# Published client and runtime bundles are already compressed. +*.gz binary +/runtime/runtime.tar.gz.* binary diff --git a/.gitignore b/.gitignore @@ -2,6 +2,8 @@ /anarchy-vanilla-14.9.1/ /anarchy-runtime-14.9.1/ /anarchy-assets-14.9.1/ +/.runtime-bundle +/client/*-test.* /client-*/ /local/ /toolchains/ diff --git a/Makefile b/Makefile @@ -1,3 +1,9 @@ -.PHONY: all clean test +.PHONY: all clean test wasm all clean test: +$(MAKE) -C src $@ + +# Only client maintainers need Emscripten; the server uses the published files. +wasm: + python3 tools/client/build_wasm_dependencies.py + +$(MAKE) -C src -f Makefile.wasm + python3 tools/client/publish_wasm.py diff --git a/README.md b/README.md @@ -2,10 +2,26 @@ ## Build and run -Run commands from the repository root. The local game assets and extracted -`data/` directory must be present; they are not in Git. Keep the server running -in a separate terminal, then choose a client. Character `1` must exist in -[server controls](http://127.0.0.1:8080/control). +Run commands from the repository root. The browser client and compressed runtime +data are checked in. Ordinary server development needs Go 1.24 or newer; it does +not need Emscripten, Python, Make, a C compiler, or the original Windows client. + +```sh +go run ./server +``` + +Open [the game](http://127.0.0.1:8080/wasm/) in a browser supporting WebAssembly +JSPI, shared memory, OffscreenCanvas and WebGL 2, then click **Enter Rubi-Ka**. +The first server run verifies and unpacks the bundled data. The first browser +launch creates a character at Bronto Burger if no characters exist. Existing +characters and local data are preserved. [Server controls](http://127.0.0.1:8080/control) +provide character editing, teleporting and time controls. + +The browser build is an initial port: Bronto Burger has passed rendering, +movement, inventory/map, audio and connection checks. Lush Fields currently has +a known loading fault. +For native clients, keep the server running in a separate terminal and use the +commands below. Creating a character in server controls also works. ### Server (Windows or Linux) @@ -120,6 +136,8 @@ The server may need network access on its first build to download Go modules. | `src/data/`, `src/vendor/` | Non-code game initializers and translated support libraries. | | `src/tests/` | Native contract and regression tests. | | `server/`, `data/` | Go server, extracted world data, and local saved characters. | +| `client/` | Published browser page, JavaScript and compressed WASM; served by Go. | +| `runtime/` | Compressed runtime data, unpacked automatically on first server run. | | `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. | @@ -130,14 +148,20 @@ The server may need network access on its first build to download Go modules. | `old_wip/` | Archived experiments and old baselines; not part of the current build. | | `docs/` | Architecture, reverse-engineering evidence, and validation history. | +The early standalone 14.9.1 sources are preserved by the annotated Git tag +`ao-14.9.1-source-baseline` (commit `c5cc2f3`, source directory `decompiled/`). +All 34 module extraction hashes match the current baseline. See the +[repository size and packaging notes](docs/repository-packaging.md). + The obsolete 13.2 `client-target` installation was removed. Its preferences are retained under `local/client-target-prefs/`. The old 13.2 sources and release clients are archived locally under `old_wip/`; they are not build dependencies. ## Maintainer handoff -**The baseline is 14.9.1.** Preserve classic Rubi-Ka scenery and GUI. Native Linux -comes before WASM; Linux only needs windowed mode. Read [src/README.md](src/README.md) before changing the runtime. +**The baseline is 14.9.1.** Preserve classic Rubi-Ka scenery and GUI. +Performance work is currently paused for the portable browser handoff. +Linux only needs windowed mode. Read [src/README.md](src/README.md) before changing the runtime. - Compile the checked-in sources directly. Do not regenerate `src/game/` over manual edits. Generation and decompilation tools are optional archaeology. @@ -168,9 +192,11 @@ comes before WASM; Linux only needs windowed mode. Read [src/README.md](src/READ Bronto Burger renders with movement, inventory/map, audio and a live server connection in the optimized browser build. Performance and broader gameplay validation remain in progress. -- Keep original binaries, assets, downloaded tools, generated reports and saved - users local. Maintained reconstructed sources belong in Git. Do not publish - proprietary game data. Preserve unrelated user edits between turns. +- Keep original binaries, downloaded tools, generated reports and saved users + local. Maintained reconstructed sources, the published browser client and the + required compressed runtime data belong in Git. The runtime bundle contains + game data; this local handoff does not publish it to a public host. Preserve + unrelated user edits between turns. ### Validation diff --git a/docs/portable-assets.md b/docs/portable-assets.md @@ -1,8 +1,10 @@ # Portable runtime assets `anarchy-assets-14.9.1/` is the portable client's working directory. It contains -data and configuration, not the Windows installation. Keep it local and copy it -with the repository when moving to Linux; it is deliberately ignored by Git. +data and configuration, not the Windows installation. Its unpacked form is +ignored by Git. The required files are now included in the compressed `runtime/` +bundle and unpacked automatically by `go run ./server` on a fresh checkout. +See [repository packaging](repository-packaging.md) for the current handoff. `tools/client/prepare_portable_assets.py` creates it from an explicit allowlist in `anarchy-runtime-14.9.1/` and refuses to overwrite an existing directory. @@ -27,7 +29,7 @@ host dependencies. Startup messages such as `attach bbr.dll` name modules compiled into the Linux executable; they do not mean DLL files are being loaded. -## Validation method +## Original validation method `tools/client/verify_linux_game.py` runs the maintained executable from this asset directory. The GDB harness records successful `open`/`openat` calls using diff --git a/docs/repository-packaging.md b/docs/repository-packaging.md @@ -0,0 +1,74 @@ +# Repository size and browser handoff + +The October 16 audit found 118 MiB of Git metadata/history before adding the +published client and runtime bundle. The working checkout had 33 GiB of ignored +local experiments/references, 4.8 GiB of client build products and 2.6 GiB of +toolchains. Those files are not copied by Git clone. Current tracked source and +documentation occupied about 565 MiB uncompressed. + +No history rewrite was needed. Packed historical obsolete browser/code paths +accounted for about 181 KB, and the largest packed source blob was 2.3 MB. +The old 13.2 decompilation/build and original client installations are ignored +local archives, not gigabytes hidden in Git history. + +## Preserved source reference + +The annotated tag `ao-14.9.1-source-baseline` points to `c5cc2f3`, the first +standalone 14.9.1 C source commit. Its `decompiled/data/extraction.json` matches +all 34 module names and source SHA-256 identities in the maintained +`src/data/extraction.json`. The original source is under `decompiled/src/` in +that commit; the maintained source is under `src/game/` now. + +For example, inspect an original function without changing the working tree: + +```sh +git show ao-14.9.1-source-baseline:decompiled/src/bbr.dll/lifted-0057.c +``` + +Keep this tag and the development commits when moving or hosting the repository. +There is no configured Git remote at this checkpoint, so nothing has been pushed +or made public. + +## Clone and run + +Clone the repository normally, change into its root and run `go run ./server`. +Go 1.24 or newer and a compatible browser are sufficient. The first Go build may +download the small Go module dependencies. Open `http://127.0.0.1:8080/wasm/`. +The server stays on loopback; run it on the laptop where the browser is running. + +The checked-in browser build is about 46 MiB compressed. Runtime data occupies +about 906 MiB compressed, split into 48 MiB parts so no individual blob is huge. +This includes all portable 14.9.1 playfields, audio, textures, fonts/configuration, +and the terrain, zone links, NPC data and map images used by the Go server. +It excludes original executables, support DLLs, older clients, saved users, +logs, screenshots, item-extraction intermediates and build tools. + +On first run, Go checks every part's SHA-256 before extracting missing files into +`anarchy-assets-14.9.1/` and `data/`. Existing files are preserved. A completed +installation is recorded in ignored `.runtime-bundle`; subsequent runs skip +extraction. An interrupted first run can be retried. If files are deliberately +removed, remove `.runtime-bundle` to restore missing bundled files on next run. +To replace a locally edited file with its bundled original, remove that file +and the marker first. Saved characters are never bundled or overwritten. + +Allow roughly 4 GiB for a normal checkout, Git history and unpacked runtime +data, before browser caches. Compiler tools and intermediate build objects add +several more GiB only on client build machines. + +## Updating published files + +`make wasm -j8` builds dependencies and the client, then publishes the matching +page, JavaScript and compressed WASM to `client/`. Commit the four published +files together. `client/build.json` records the source revision, current source +digest, compiler identity and output hashes. Do not edit generated JavaScript +directly; edit `src/runtime/` or `src/browser/` and republish. + +`python3 tools/client/package_runtime.py` repackages runtime data from the local +portable assets and extracted server data. This is independent of WASM builds; +it is not needed for normal server work. The fixed allowlist excludes users and +diagnostics, removes the machine-specific GPU preference and normalizes archive +metadata. Commit `runtime/manifest.json` and all its parts together. + +Compressed bundles should change infrequently. Repeatedly committing new asset +bundles would grow history; keep ordinary Go development away from these files. +The bundle is part of this local handoff, not a public asset publication. diff --git a/runtime/manifest.json b/runtime/manifest.json @@ -0,0 +1,80 @@ +{ + "parts": [ + { + "name": "runtime.tar.gz.000", + "sha256": "6a6d3fe9972e708d5a8f48092209ddf2cdea02653d7d65918da0ec6ff10d1398" + }, + { + "name": "runtime.tar.gz.001", + "sha256": "cf96736fbd4824e77cdfc81238f8033fdda8260cb972ac1a39b5973911a4e2c1" + }, + { + "name": "runtime.tar.gz.002", + "sha256": "cbc77c6391b8d6967e512a15c7af684c26d462d5bb97a3cf2a9e3513ef19cab3" + }, + { + "name": "runtime.tar.gz.003", + "sha256": "0cb3dc569abc4fa1c4e40bdc1e890d252ac1cd256412672ba8bbc8308071b189" + }, + { + "name": "runtime.tar.gz.004", + "sha256": "96035ef00f031fa96d88aa4c3984358db6761c7135edf2bf6166f5c583b4cd93" + }, + { + "name": "runtime.tar.gz.005", + "sha256": "f7cc6ea50a2904c058797480f5bae13c7e702fa7223b58bd8a49a01580a7f3f6" + }, + { + "name": "runtime.tar.gz.006", + "sha256": "c4cf161c9a443a0bda3fdd2885e461152ce893b128509cdfc5af94f67da02e42" + }, + { + "name": "runtime.tar.gz.007", + "sha256": "baede34a9a3d4fedb98734232a53d149efd6f5819305dd3fd3c0e81a62fae631" + }, + { + "name": "runtime.tar.gz.008", + "sha256": "93abbcd19ce8b9f38e429a474134e748a78139a83a3d4fedf6932a0f72f01f62" + }, + { + "name": "runtime.tar.gz.009", + "sha256": "69b9eddd2ed435cf201656b38ea704ec7fe8466dc42cc3f903480f7a8c8eac21" + }, + { + "name": "runtime.tar.gz.010", + "sha256": "5817afd3b77afaa8a70658999f56d3f207fa7f19b3acfbf700a83b036fd3c65a" + }, + { + "name": "runtime.tar.gz.011", + "sha256": "5de6bdf17d251c51fc2de99985f8416b17885055499254673e3a2af41f9bc6a2" + }, + { + "name": "runtime.tar.gz.012", + "sha256": "a62216c2877ac97b86ff4b7772dcc3a47382d3730fb521742ed515287c110bd7" + }, + { + "name": "runtime.tar.gz.013", + "sha256": "b85054c5660ce52c29ea989c2cac6b8ae76f9f06cbfa837bd496a6774e485a1e" + }, + { + "name": "runtime.tar.gz.014", + "sha256": "f86904dd39e56734bfd1425cff55d3cb0488b2f25fdf6da76a5d090916e404cc" + }, + { + "name": "runtime.tar.gz.015", + "sha256": "5d8486c4976cf54a23168ff62daa0fa6953b13d65a1487361dc46525d16bb5ee" + }, + { + "name": "runtime.tar.gz.016", + "sha256": "ce27b5adaf4b0073b7efb0009ef85db07b66fed46487749ef7d6cd2baa34d386" + }, + { + "name": "runtime.tar.gz.017", + "sha256": "476c1d23bd566867f43c33be49e05de9e93258d5966b656f99ab0a9c52aaae26" + }, + { + "name": "runtime.tar.gz.018", + "sha256": "c3014b8a2d00af74e77c7193fead387d2005b14220d5a6900abb19f19f387297" + } + ] +} diff --git a/server/browser_client.go b/server/browser_client.go @@ -0,0 +1,20 @@ +package main + +import ( + "net/http" +) + +func 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") + + // Browsers decode the committed gzip representation before compiling WASM. + if r.URL.Path == "/wasm/game.wasm" { + w.Header().Set("Content-Type", "application/wasm") + w.Header().Set("Content-Encoding", "gzip") + http.ServeFile(w, r, "client/game.wasm.gz") + return + } + http.StripPrefix("/wasm/", http.FileServer(http.Dir("client"))).ServeHTTP(w, r) +} diff --git a/server/browser_client_test.go b/server/browser_client_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "bytes" + "compress/gzip" + "io" + "net/http" + "net/http/httptest" + "os" + "testing" +) + +func TestBrowserClientServesCommittedWasm(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.Mkdir("client", 0755); err != nil { + t.Fatal(err) + } + var compressed bytes.Buffer + writer := gzip.NewWriter(&compressed) + if _, err := writer.Write([]byte("\x00asm\x01\x00\x00\x00")); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client/game.wasm.gz", compressed.Bytes(), 0644); err != nil { + t.Fatal(err) + } + request := httptest.NewRequest("GET", "/wasm/game.wasm", nil) + request.Header.Set("Accept-Encoding", "gzip") + response := httptest.NewRecorder() + + browserClient(response, request) + + if response.Code != http.StatusOK || response.Header().Get("Content-Type") != "application/wasm" || response.Header().Get("Content-Encoding") != "gzip" { + t.Fatalf("WASM response: %d %v", response.Code, response.Header()) + } + if response.Header().Get("Cross-Origin-Opener-Policy") != "same-origin" || response.Header().Get("Cross-Origin-Embedder-Policy") != "require-corp" || response.Header().Get("Cache-Control") != "no-cache" { + t.Fatalf("isolation/cache headers: %v", response.Header()) + } + reader, err := gzip.NewReader(response.Body) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + contents, err := io.ReadAll(reader) + if err != nil || string(contents) != "\x00asm\x01\x00\x00\x00" { + t.Fatalf("decoded WASM: %x, %v", contents, err) + } +} + +func TestBrowserClientServesPublishedPageWithoutBuildDirectory(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.Mkdir("client", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client/index.html", []byte("Enter Rubi-Ka"), 0644); err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + + browserClient(response, httptest.NewRequest("GET", "/wasm/", nil)) + + if response.Code != http.StatusOK || response.Body.String() != "Enter Rubi-Ka" { + t.Fatalf("client page: %d %q", response.Code, response.Body.String()) + } +} diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -9,8 +9,20 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) { server.mutex.Lock() defer server.mutex.Unlock() - // Supply an existing offline character to the original launcher contract. - for _, user := range server.users_locked() { + // A fresh checkout starts in the verified Bronto Burger scene. + users := server.users_locked() + if len(users) == 0 { + character := server.newCharacter_locked() + character.playfield = 705 + character.position = [3]float32{960, 16.5, 510} + character.rotation = [4]float32{0, 0.9238795, 0, -0.3826834} + if err := server.saveUsers_locked(); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + users = server.users_locked() + } + for _, user := range users { if server.clients[user.ID] == nil { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "Clientr.exe localtest localtest %d 2130706433 %d 0 0", user.ID, server.worldPort) diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go @@ -3,9 +3,33 @@ package main import ( "net/http" "net/http/httptest" + "os" "testing" ) +func TestBrowserLaunchCreatesFirstCharacter(t *testing.T) { + t.Chdir(t.TempDir()) + 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)} + response := httptest.NewRecorder() + + world.browserLaunch(response, httptest.NewRequest("POST", "/browser-launch", nil)) + loaded := &server{characters: make(map[uint32]*character)} + err := loaded.loadUsers() + + if response.Code != http.StatusOK || response.Body.String() != "Clientr.exe localtest localtest 1 2130706433 7501 0 0" { + t.Fatalf("launch response: %d %q", response.Code, response.Body.String()) + } + if err != nil { + t.Fatal(err) + } + if len(loaded.characters) != 1 || loaded.characters[1].playfield != 705 || loaded.characters[1].position != [3]float32{960, 16.5, 510} { + t.Fatalf("saved first character: %+v", loaded.characters[1]) + } +} + func TestBrowserLaunchSelectsAnOfflinePlayer(t *testing.T) { world := &server{ worldPort: 7620, diff --git a/server/main.go b/server/main.go @@ -26,6 +26,9 @@ func main() { log.Fatal("ports must be between 1 and 65535") } } + if err := prepareRuntime(); err != nil { + log.Fatal(err) + } server := newServer() server.loginPort, server.worldPort, server.httpPort = *loginPort, *worldPort, *httpPort httpAddress := fmt.Sprintf("127.0.0.1:%d", server.httpPort) @@ -48,13 +51,7 @@ func main() { http.HandleFunc("POST /browser-launch", server.browserLaunch) http.HandleFunc("GET /browser-world", server.browserWorld) http.HandleFunc("GET /browser-manifest", browserManifest) - wasmFiles := http.StripPrefix("/wasm/", http.FileServer(http.Dir("src/build/wasm/web"))) - http.HandleFunc("GET /wasm/", func(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") - wasmFiles.ServeHTTP(w, r) - }) + http.HandleFunc("GET /wasm/", browserClient) browserFiles := http.StripPrefix("/browser/", http.FileServer(http.Dir("old_wip/browser"))) http.HandleFunc("GET /browser/", func(w http.ResponseWriter, r *http.Request) { // Shared WASM memory lets the client worker wait for browser host calls. @@ -72,7 +69,7 @@ func main() { server.dimensionList(w, r) return } - fmt.Fprint(w, "<html><body>Local Anarchy Online development server.</body></html>") + fmt.Fprint(w, `<html><body><a href="/wasm/">Play Anarchy Online 14.9.1</a> | <a href="/control">Server controls</a></body></html>`) }) go func() { log.Fatal(http.ListenAndServe(httpAddress, nil)) diff --git a/server/runtime_bundle.go b/server/runtime_bundle.go @@ -0,0 +1,115 @@ +package main + +import ( + "archive/tar" + "compress/gzip" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strings" +) + +func prepareRuntime() error { + manifest, err := os.ReadFile("runtime/manifest.json") + if err != nil { + return err + } + version := fmt.Sprintf("%x\n", sha256.Sum256(manifest)) + installed, err := os.ReadFile(".runtime-bundle") + if err != nil && !os.IsNotExist(err) { + return err + } + if string(installed) == version { + return nil + } + var bundle struct { + Parts []struct { + Name string `json:"name"` + SHA256 string `json:"sha256"` + } `json:"parts"` + } + if err := json.Unmarshal(manifest, &bundle); err != nil { + return err + } + + // Verify every part before unpacking. A partial clone must fail explicitly. + log.Print("Preparing bundled game data (first run)...") + var readers []io.Reader + for _, part := range bundle.Parts { + if filepath.Base(part.Name) != part.Name { + return fmt.Errorf("invalid runtime part %q", part.Name) + } + file, err := os.Open(filepath.Join("runtime", part.Name)) + if err != nil { + return err + } + defer file.Close() + digest := sha256.New() + if _, err := io.Copy(digest, file); err != nil { + return err + } + if fmt.Sprintf("%x", digest.Sum(nil)) != part.SHA256 { + return fmt.Errorf("runtime part %s failed SHA-256 verification", part.Name) + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + return err + } + readers = append(readers, file) + } + compressed, err := gzip.NewReader(io.MultiReader(readers...)) + if err != nil { + return err + } + defer compressed.Close() + archive := tar.NewReader(compressed) + for { + header, err := archive.Next() + if err == io.EOF { + break + } + if err != nil { + return err + } + if header.Typeflag != tar.TypeReg || !filepath.IsLocal(header.Name) || filepath.ToSlash(filepath.Clean(header.Name)) != header.Name || + !(strings.HasPrefix(header.Name, "anarchy-assets-14.9.1/") || strings.HasPrefix(header.Name, "data/")) { + return fmt.Errorf("invalid runtime entry %q", header.Name) + } + + // Preserve local data and preferences; interrupted first runs can be retried. + if _, err := os.Stat(header.Name); err == nil { + continue + } else if !os.IsNotExist(err) { + return err + } + if err := os.MkdirAll(filepath.Dir(header.Name), 0755); err != nil { + return err + } + file, err := os.Create(header.Name + ".tmp") + if err != nil { + return err + } + _, copyErr := io.Copy(file, archive) + closeErr := file.Close() + if copyErr != nil { + return copyErr + } + if closeErr != nil { + return closeErr + } + if err := os.Rename(header.Name+".tmp", header.Name); err != nil { + return err + } + } + // Read the gzip trailer as well, so a damaged archive cannot be marked complete. + if _, err := io.Copy(io.Discard, compressed); err != nil { + return err + } + if err := os.MkdirAll("anarchy-assets-14.9.1/Screenshots", 0755); err != nil { + return err + } + return os.WriteFile(".runtime-bundle", []byte(version), 0644) +} diff --git a/server/runtime_bundle_test.go b/server/runtime_bundle_test.go @@ -0,0 +1,112 @@ +package main + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "crypto/sha256" + "fmt" + "os" + "strings" + "testing" +) + +func writeRuntimeBundle(t *testing.T, name, contents string) { + t.Helper() + var buffer bytes.Buffer + compressed := gzip.NewWriter(&buffer) + archive := tar.NewWriter(compressed) + if err := archive.WriteHeader(&tar.Header{Name: name, Mode: 0644, Size: int64(len(contents))}); err != nil { + t.Fatal(err) + } + if _, err := archive.Write([]byte(contents)); err != nil { + t.Fatal(err) + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + if err := compressed.Close(); err != nil { + t.Fatal(err) + } + if err := os.Mkdir("runtime", 0755); err != nil { + t.Fatal(err) + } + var parts []string + for index, data := range [][]byte{buffer.Bytes()[:20], buffer.Bytes()[20:]} { + name := fmt.Sprintf("runtime.tar.gz.%03d", index) + if err := os.WriteFile("runtime/"+name, data, 0644); err != nil { + t.Fatal(err) + } + parts = append(parts, fmt.Sprintf(`{"name":%q,"sha256":"%x"}`, name, sha256.Sum256(data))) + } + if err := os.WriteFile("runtime/manifest.json", []byte(`{"parts":[`+strings.Join(parts, ",")+`]}`), 0644); err != nil { + t.Fatal(err) + } +} + +func TestRuntimeBundlePreparesFreshCheckout(t *testing.T) { + t.Chdir(t.TempDir()) + writeRuntimeBundle(t, "anarchy-assets-14.9.1/version.id", "14.9.1") + + err := prepareRuntime() + + if err != nil { + t.Fatal(err) + } + contents, err := os.ReadFile("anarchy-assets-14.9.1/version.id") + if err != nil || string(contents) != "14.9.1" { + t.Fatalf("installed asset: %q, %v", contents, err) + } + if _, err := os.Stat(".runtime-bundle"); err != nil { + t.Fatal(err) + } +} + +func TestRuntimeBundlePreservesLocalEditsOnRetry(t *testing.T) { + t.Chdir(t.TempDir()) + writeRuntimeBundle(t, "data/npc_spawns.yaml", "bundled") + if err := os.Mkdir("data", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("data/npc_spawns.yaml", []byte("customized"), 0644); err != nil { + t.Fatal(err) + } + + err := prepareRuntime() + + if err != nil { + t.Fatal(err) + } + contents, err := os.ReadFile("data/npc_spawns.yaml") + if err != nil || string(contents) != "customized" { + t.Fatalf("local data changed: %q, %v", contents, err) + } +} + +func TestRuntimeBundleRejectsDamagedPart(t *testing.T) { + t.Chdir(t.TempDir()) + writeRuntimeBundle(t, "data/npc_spawns.yaml", "bundled") + if err := os.WriteFile("runtime/runtime.tar.gz.001", []byte("damaged"), 0644); err != nil { + t.Fatal(err) + } + + err := prepareRuntime() + + if err == nil || !strings.Contains(err.Error(), "SHA-256") { + t.Fatalf("damaged part accepted: %v", err) + } + if _, err := os.Stat(".runtime-bundle"); !os.IsNotExist(err) { + t.Fatalf("damaged bundle marked installed: %v", err) + } +} + +func TestRuntimeBundleRejectsOutsidePath(t *testing.T) { + t.Chdir(t.TempDir()) + writeRuntimeBundle(t, "../outside", "invalid") + + err := prepareRuntime() + + if err == nil || !strings.Contains(err.Error(), "invalid runtime entry") { + t.Fatalf("outside path accepted: %v", err) + } +} diff --git a/tools/client/package_runtime.py b/tools/client/package_runtime.py @@ -0,0 +1,53 @@ +"""Package only the installed game data and extracted data needed by the server.""" +import gzip +import hashlib +import io +import json +import pathlib +import tarfile + + +root = pathlib.Path(__file__).resolve().parents[2] +assets = root / 'anarchy-assets-14.9.1' +destination = root / 'runtime' +destination.mkdir(exist_ok=True) +work = root / 'local/runtime-package' +work.mkdir(parents=True, exist_ok=True) + +# Exclude saved characters, screenshots, logs, executables and extraction inputs. +files = [] +for name in ['cd_image', 'Setupf', 'fonts']: + files.extend(path for path in (assets / name).rglob('*') if path.is_file()) +files.extend(assets / name for name in ['Prefs/Main.cfg', 'Prefs/localtest/Login.cfg', 'version.id']) +files.extend(root / 'data' / name for name in ['terrain.bin', 'zone_links.yaml', 'npc_spawns.yaml']) +files.extend(path for path in (root / 'data/maps').rglob('*') if path.is_file()) + +# Normalize metadata so unchanged inputs produce identical compressed bundles. +with (work / 'runtime.tar.gz').open('wb') as output_file: + with gzip.GzipFile(filename='', mode='wb', fileobj=output_file, mtime=0) as compressed: + with tarfile.open(fileobj=compressed, mode='w|') as archive: + for path in sorted(files): + contents = path.read_bytes() + if path.is_relative_to(assets): + assert path.suffix.lower() not in ['.exe', '.dll', '.com', '.asi', '.flt', '.m3d'], path + assert contents[:2] != b'MZ' and contents[:4] != b'\x7fELF', path + if path == assets / 'Prefs/Main.cfg': + contents = b'\n'.join(line for line in contents.splitlines() if not line.startswith(b'GfxDeviceName ')) + b'\n' + header = tarfile.TarInfo(path.relative_to(root).as_posix()) + header.size = len(contents) + header.mode = 0o644 + archive.addfile(header, io.BytesIO(contents)) + +# Keep every Git blob below common host limits; Go joins the parts on first run. +parts = [] +with (work / 'runtime.tar.gz').open('rb') as archive: + while contents := archive.read(48 * 1024 * 1024): + name = 'runtime.tar.gz.%03d' % len(parts) + (destination / name).write_bytes(contents) + parts.append({'name': name, 'sha256': hashlib.sha256(contents).hexdigest()}) +for path in destination.glob('runtime.tar.gz.*'): + if path.name not in [part['name'] for part in parts]: + path.unlink() +(destination / 'manifest.json').write_text(json.dumps({'parts': parts}, indent=2) + '\n') +print('Packaged %d files in %d parts, %d compressed bytes' % ( + len(files), len(parts), (work / 'runtime.tar.gz').stat().st_size)) diff --git a/tools/client/publish_wasm.py b/tools/client/publish_wasm.py @@ -0,0 +1,50 @@ +"""Publish the browser client for Go-only checkouts, without intermediate files.""" +import gzip +import hashlib +import json +import pathlib +import shutil +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +source = root / 'src/build/wasm/web' +destination = root / 'client' +destination.mkdir(exist_ok=True) +staging = root / 'src/build/wasm/publish' +staging.mkdir(exist_ok=True) + +# Publish one matching JS/WASM pair; gzip keeps the binary small enough for Git. +for name in ['game.js', 'index.html']: + shutil.copyfile(source / name, staging / name) +with (source / 'game.wasm').open('rb') as input_file: + with (staging / 'game.wasm.gz').open('wb') as output_file: + with gzip.GzipFile(filename='', mode='wb', fileobj=output_file, mtime=0) as compressed: + shutil.copyfileobj(input_file, compressed) + +# Record the exact inputs and published bytes, including uncommitted source edits. +inputs = subprocess.check_output( + ['git', 'ls-files', 'src', 'tools/client/build_wasm_dependencies.py'], cwd=root +).decode().splitlines() +digest = hashlib.sha256() +for name in inputs: + digest.update(name.encode() + b'\0') + digest.update((root / name).read_bytes()) +metadata = { + 'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root).decode().strip(), + 'source_sha256': digest.hexdigest(), + 'compiler': subprocess.check_output([ + str(root / 'toolchains/emsdk/upstream/emscripten/emcc'), '--version' + ]).decode().splitlines()[0], + 'files': {}, +} +for name in ['game.js', 'game.wasm.gz', 'index.html']: + path = staging / name + metadata['files'][name] = { + 'bytes': path.stat().st_size, + 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(), + } +(staging / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n') +for path in staging.iterdir(): + path.replace(destination / path.name) +print('Published browser client to', destination)