aorecomp

Anarchy Online classic in the browser

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


commit 9820071cabdbaafe99307b9f1e68d8d6a6e15395
parent a8b44db989338a93829b41878396430af0e9c1ed
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 21:08:26 +0000

Cover immediate use and wear of anonymous item proxies

Diffstat:
MTODO.md | 14+++++++++++---
Mdocs/inventory.md | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_item_proxy_test.go | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_item_proxies.mjs | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 287 insertions(+), 3 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3422,7 +3422,7 @@ with payloads and known client/server provenance. wear, removal, reconnect and cold startup. The earned QL8 body/pants run currently verifies effective values by inspecting that form's screenshots; raw zero AC entries are not evidence of lost armor. -- [ ] [P1] Audit native inventory-proxy identities immediately after rewards. +- [x] [P1] Audit native inventory-proxy identities immediately after rewards. Mission 81's new boots have the correct slot, QL, templates and count while their raw proxy still reports type/id 0; page replay populates exact ID 87. The prior helmet has the same initial proxy shape and later qualifies/wears @@ -3435,8 +3435,12 @@ with payloads and known client/server provenance. See [earned recovery restock](docs/mission-levels.md#earned-recovery-restock). Another earned laboratory, instance 263, has the same initial proxy shape. Ordinary shop-to-city zoning populates identity 51005/263 while retaining - its slot, templates and 50 charges. Immediate use before zoning remains - unverified. + its slot, templates and 50 charges. A short controlled native regression now + verifies immediate laboratory use and glove wear while both ordinary proxies + still have raw type/id 0/0, before any replay. Owner/slot requests preserve the + real durable IDs and quantities; page/cold replay supplies those same IDs. + Mission rewards and purchases share this AddTemplate path. See + [anonymous ordinary additions](docs/inventory.md#anonymous-ordinary-additions). Evidence: `local/earned-seven/tmp_proxy_history.py` and its native captures. - [ ] [P1] Audit inventory layout persistence through city/shop zoning and earned sales. The connected run starts with its saved 516-byte map, then an OPFS @@ -3562,6 +3566,10 @@ and server restarts. Turn every reproduced bug into a focused regression test. inventory retain all31 identities through two-client page and cold recovery; the broader disappearance report remains open. See [equipment replacement](docs/inventory.md#occupied-equipment-replacement). + A focused new-item check now verifies immediate use and wear/remove/rewear + while ordinary AddTemplate proxies still report raw type/id 0/0. Page/cold + replay retains the same physical IDs; see + [anonymous additions](docs/inventory.md#anonymous-ordinary-additions). The ordinary creature-upgrade run now conserves all 26 final identities through level-cap refusal, skill purchases, two selected glove qualities, repeated wear/removal, a cancelled/accepted pistol sale and both-client page/cold diff --git a/docs/inventory.md b/docs/inventory.md @@ -83,6 +83,57 @@ require a separate live object. The equipped Kinetic Axe and portable Chests use flag 2; their native object updates are sent separately. The [backpack protocol](backpacks.md) explains this distinction. +## Anonymous ordinary additions + +An ordinary `AddTemplate` (`0x052e2f0c`) contains only low/high templates, +quality and count. New template proxies can therefore report raw identity +`0/0` while already representing a durable owned item. The shared +`inventoryAdditionPacket` builder supplies this message for both ordinary shop +purchases and completed mission rewards. Live weapons and backpacks use their +separate typed updates described in [shop delivery](shop-live-items.md). + +The maintained native proxy constructor +`client/game/kkr.dll/lifted-0017.c::sub_3602D010` initializes identity fields +`+8/+0xc` to zero. The full inventory reader `sub_3602DC40` reads the explicit +identity into those fields, along with flags/count and template information. +These source paths explain the different representations; they do not establish +which message sequence the historical server used for every reward. + +`TestBrowserAnonymousPurchasesAreUsable` isolates the reported proxy shape in +two WASM clients. A controlled mixed catalog supplies a QL1 laboratory and QL1 +Metaplast gloves through the normal purchase transaction. Both native rows +initially have `0/0` identities. Before any page/world replay, right-clicking +the laboratory sends owner 1's page104/slot48 Use request, restores 30 HP, +consumes one of 50 charges and installs the Treatment lock. An immediate repeat +does not consume another charge. Native glove wear sends page104/slot49 to +slot24 and reaches the observer. The Clothes form shows its worn icon; removal +and re-wear retain the same instance before replay. Both proxies still report +`0/0` after these successful operations; their durable IDs 1/2, types, quantities and locations are +already correct. The test rejects an intervening FullCharacter/world replay. + +Page replay supplies physical identities `51005:1` and `51022:2` for the same +49-charge laboratory and worn gloves. Fresh clients after database close retain +those exact identities, templates, slots, health 80 and the 4,600-credit balance. +The observer receives neither item. This closes the immediate-use uncertainty +for ordinary template additions; the broader disappearance audit remains open. +The wallet, skills, location and mixed stock are controlled fixtures, not earned +progression or historical stock evidence. No protocol or client change is needed +for this case. Native requests, state transitions and durable comparisons are +retained under `local/anonymous-item-proxies/`. + +The complete controlled check passes normally in 37.77 seconds and under the +race detector in 75.48 seconds, including fresh-server clients. Captures are in +`local/anonymous-item-proxies/20261102-130116/` and `20261102-130355/`. +Vet passes; the published WASM bundle is unchanged. + +Run the focused regression with: + +```sh +AO_GAME_TEST=1 go test ./server -run '^TestBrowserAnonymousPurchasesAreUsable$' -count=1 -timeout=8m -v +``` + +## Inventory transfers + `ContainerAddItem` (`0x47537a24`) carries source page/slot, target owner identity and destination slot. The server accepts only an authenticated current session's own ordinary inventory and an empty destination. It saves before acknowledging diff --git a/server/browser_item_proxy_test.go b/server/browser_item_proxy_test.go @@ -0,0 +1,112 @@ +package main + +import ( + "ao/server/gamedata" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" +) + +func TestBrowserAnonymousPurchasesAreUsable(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused new-item proxy check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/anonymous-item-proxies", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + for _, phase := range []string{"purchase", "cold"} { + t.Run(phase, func(t *testing.T) { + world := newServer() + t.Cleanup(func() { world.db.Close() }) + if phase == "purchase" { + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.level, player.appearance = fmt.Sprint("Proxy", index), 10, 0x515 + player.playfield, player.position = 1183, [3]float32{188 - float32(index*2), 5.11, 139.5} + player.rotation = [4]float32{0, 0.70710677, 0, 0.70710677} + player.stats = testCharacterStats() + player.stats.Abilities.Strength, player.stats.Abilities.Agility = 20, 20 + player.stats.Body.BodyDevelopment = 20 + player.stats.NanoAiding.Treatment = 6 + player.health, player.inventory.Credits = 50, 5000 + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("proxy-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + } + // Mixed fixture stock isolates delivery, not historical booth membership. + stock := gamedata.ShopStock[99383] + t.Cleanup(func() { gamedata.ShopStock[99383] = stock }) + gamedata.ShopStock[99383] = []gamedata.ShopItem{{Template: 25812, Quality: 1}, {Template: 85596, Quality: 1}} + } + owner, watcher := world.characters[1], world.characters[2] + if phase == "purchase" && len(owner.inventory.Items) != 0 || phase == "cold" && len(owner.inventory.Items) != 2 { + t.Fatal("unexpected native proxy fixture phase") + } + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + json.NewEncoder(w).Encode(map[string]any{"inventory": owner.inventory, "health": owner.health, + "sitting": owner.sitting, "lock": owner.skillLocks[124], "observer": watcher.inventory}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advanceEquipment(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_item_proxies.mjs"), host.URL, filepath.Join(output, phase)) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + world.mutex.Lock() + defer world.mutex.Unlock() + expected := []ownedItem{ + {ID: 1, Type: 51005, Template: 25812, Quality: 1, Slot: 64, Count: 49}, + {ID: 2, Type: 51022, Template: 85596, Quality: 1, Slot: 24, Count: 1}, + } + if !reflect.DeepEqual(owner.inventory.Items, expected) || owner.health != 80 || owner.inventory.Credits != 4600 || + len(watcher.inventory.Items) != 0 || watcher.inventory.Credits != 5000 || world.nextItem != 2 || owner.equipmentBonus(90) != 1 { + t.Fatal("immediate native use/wear or cold recovery lost an instance, charge, health or cash") + } + }) + if t.Failed() { + return + } + } +} diff --git a/tools/client/test_item_proxies.mjs b/tools/client/test_item_proxies.mjs @@ -0,0 +1,113 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', headless: false, + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {}; +try { + // Keep the owner's unrelated native regeneration phase outside the short check. + for (const index of [1, 0]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'proxy-' + index, url}]); + const page = await context.newPage(); + const game = await GameTest.attach(page); + games[index] = game; + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + const initial = await server(); + if (owner.local().inventory.length === 0) { + assert.equal(initial.inventory.Credits, 5000); + assert.equal(owner.local().stats[27], 50); + await owner.key('KeyI'); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + const [x, y] = await owner.pick(51035, 3221226655); + await owner.click(x, y, 'right'); + await owner.wait('fixture catalog opens', state => state.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 494)); + await owner.click(864, 85); + await owner.click(924, 85); + const purchase = owner.sequence; + await owner.click(874, 475); + await owner.wait('new anonymous ordinary proxies', state => owner.local(state).inventory.length === 2 && + owner.local(state).stats[61] === 4600); + assert.deepEqual(owner.local().inventory, [ + {slot: 48, type: 0, id: 0, quality: 1, templates: [25812, 25812], count: 50}, + {slot: 49, type: 0, id: 0, quality: 1, templates: [85596, 85596], count: 1}, + ]); + evidence.purchased = {native: owner.local().inventory, server: await server()}; + await owner.save(output + '/purchased'); + + // Both operations must succeed before any replay can supply physical IDs. + await owner.key('F1'); + await owner.key('KeyX'); + await owner.wait('native self sitting', state => owner.local(state).stats[430] === 2); + const used = owner.sequence; + await owner.click(681, 45, 'right'); + await owner.wait('anonymous laboratory restores HP and consumes one charge', state => + owner.local(state).stats[27] === 80 && owner.local(state).inventory.some(item => item.slot === 48 && item.count === 49)); + evidence.used = {native: owner.local().inventory, server: await server()}; + assert.equal(evidence.used.server.health, 80); + assert.equal(evidence.used.server.inventory.Items[0].Count, 49); + assert(Date.parse(evidence.used.server.lock) > Date.now()); + assert(owner.events.some(event => event.sequence > used && event.direction === 'framesent' && event.opcode === '52526858')); + await owner.click(681, 45, 'right'); + assert.equal((await server()).inventory.Items[0].Count, 49); + await owner.key('KeyX'); + await owner.wait('standing for wear', state => owner.local(state).stats[430] !== 2); + const worn = observer.sequence; + await owner.click(735, 45, 'right'); + await owner.wait('anonymous gloves worn', state => owner.local(state).inventory.some(item => + item.slot === 24 && item.templates[0] === 85596)); + await observer.wait('observer receives immediate wear', () => observer.events.some(event => { + if (event.sequence <= worn || event.direction !== 'framereceived' || event.opcode !== '35505644') return false; + const packet = Buffer.from(event.hex, 'hex'); + return packet.readUInt32BE(45) === 6 && packet.readUInt32BE(53) === 24; + })); + evidence.worn = {native: owner.local().inventory, server: await server()}; + assert.equal(evidence.worn.server.inventory.Items[1].ID, 2); + assert.equal(evidence.worn.server.inventory.Items[1].Slot, 24); + await owner.page.keyboard.press('Control+1'); + await owner.click(953, 53); + await owner.save(output + '/anonymous-worn-cell'); + await owner.click(927, 206, 'right'); + await owner.wait('anonymous gloves removed to their ordinary cell', state => owner.local(state).inventory.some(item => + item.slot === 49 && item.templates[0] === 85596)); + await owner.wait('removal action finishes', state => !owner.local(state).actions.includes(3)); + await owner.click(735, 45, 'right'); + await owner.wait('same anonymous gloves re-worn', state => owner.local(state).inventory.some(item => + item.slot === 24 && item.templates[0] === 85596)); + evidence.reworn = {native: owner.local().inventory, server: await server()}; + assert.deepEqual(evidence.reworn.server.inventory, evidence.worn.server.inventory); + assert.equal(owner.navigation, 1); + assert(!owner.events.some(event => event.sequence > purchase && event.direction === 'framereceived' && + ['29304349', '5f4b1a39', '445f2a0b'].includes(event.opcode)), 'Replay hid an immediate-use failure'); + await owner.save(output + '/used-and-worn'); + await owner.page.reload(); + await owner.ready(); + } + + // FullCharacter supplies the physical identities for the same used instances. + assert.deepEqual(owner.local().inventory, [ + {slot: 24, type: 51022, id: 2, quality: 1, templates: [85596, 85596], count: 1}, + {slot: 48, type: 51005, id: 1, quality: 1, templates: [25812, 25812], count: 49}, + ]); + assert.equal(owner.local().stats[27], 80); + assert.equal(owner.local().stats[61], 4600); + assert.deepEqual(observer.local().inventory, []); + evidence.replayed = {native: owner.local().inventory, server: await server()}; + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: anonymous laboratory use and glove wear before replay; physical IDs/counts retained after page/cold recovery'); +} finally { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2)); + try { await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); } + finally { await browser.close(); } +}