aorecomp

Anarchy Online classic in the browser

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


commit 844245d1a9d227e126b07b247355d2fd99cd9e73
parent 8629e7b1d17c7c6aec1cfa5ef98396afd2749849
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 03:11:03 +0000

Prevent bank backpacks from overwriting native character slots

Diffstat:
MTODO.md | 9+++++++++
Mdocs/bank-storage.md | 38+++++++++++++++++++++++++++++++++++++-
Mserver/bank.go | 7-------
Aserver/bank_attachment_test.go | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_bank_attachment_test.go | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_bank_attachment.mjs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 265 insertions(+), 8 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4057,6 +4057,15 @@ and server restarts. Turn every reproduced bug into a focused regression test. both directions during wear/removal without writes or deadline changes. No product defect reproduced on this path; see [backpack joins](docs/backpacks.md#stack-join-during-pending-equipment). +- [x] [P0] Prevent banked backpack updates from replacing native character rows. + Reproduction: opening a bank with bag2 in bank slot6 replaces worn weapon1's + native slot6 identity, while its old templates and durable ownership remain. + Bank opening now sends only the bank snapshot. A short WASM check verifies + retained worn identity, normal bag withdrawal/open/close/redeposit, weapon + removal/rewear and page/cold conservation of both instances. Public-handler + checks cover worn and first/last carried row collisions without writes or + allocation. This isolates the broader disappearance audit above. See + [bank attachment](docs/bank-storage.md#character-slot-attachment). - [x] [P0] Refresh ordinary stacks after a stale player-trade offer. Reproduction: a controlled earlier merge consumes the offered source; both trade windows cancel but the owner retains a ghost and stale counts. Cancellation now diff --git a/docs/bank-storage.md b/docs/bank-storage.md @@ -84,7 +84,10 @@ BankIIR has the owner SimpleChar envelope and these big-endian fields: | Inventory count | `(entryCount + 1) * 1009`, u32 | | Each entry | u32 slot, u16 flags, u16 count, u32 type, u32 instance, u32 low template, u32 high template, u32 quality, u32 auxiliary | -Template entries use flags 3; owned live Chests use flags 2 and a ChestFullUpdate. +Template entries use flags3; portable Chests and Mission Keys28577 use flags2. +These rows retain actual identities and can use template data until a live +object exists. Bank opening sends the bank snapshot without creating owned +Chest objects; normal Use after withdrawal creates the carried Chest. There is no trailing proxy identity. Bank slots never pass through the ordinary inventory conversion from internal 64..93 to native 48..77. @@ -103,6 +106,39 @@ source slots only, preserving bank and packed bag source positions. Unique withdrawal rejection also sends native TextMessage `0x5f4b442a` with the same wording as the client's local validator: `You already have this unique item...`. +## Character slot attachment + +An owned SimpleItem FullUpdate's explicit slot addresses the parent character's +ordinary/equipment inventory during native attachment. Setting page105 does +not redirect that attachment into the bank. Original `kkr.dll` routines +`0x100b25c0` and `0x10063340` show this path; retained pseudocode is under +`local/ncu-upgrade-research/native/`. The maintained call at +`client/game/kkr.dll/lifted-0053.c::sub_360B25C0` passes character+0x150 to +`sub_36063340` for this attachment. + +Creating banked backpacks on opening the bank therefore overwrote unrelated +native character rows. A controlled worn weapon1 in slot6 became type51017/id2 +when banked backpack2 also occupied bank slot6. The row retained the weapon's +template endpoints, while durable ownership still correctly held weapon1 and +banked bag2. This was a native identity collision, not loss from storage. + +Bank opening now publishes only BankIIR. It leaves existing character rows +alone and allows an uninstantiated bag to withdraw normally. Its subsequent +ordinary Use creates a Chest at its actual carried slot. No replacement slot, +extra identity or client workaround is introduced. + +`TestBankOpeningDoesNotAttachStoredBackpackToCharacterSlots` covers worn slot6 +and both carried boundaries (shared64/93, native48/77) against overlapping bank +slots, with no writes and unchanged cold ownership. The short native +`TestBrowserBankBackpackPreservesWornIdentity` reproduces the corruption, then +verifies the fixed opening, actual bag withdrawal/open/close/redeposit, weapon +removal/rewear, page replay and exact cold ownership. The returned bag uses +normal first-free bank slot0. This is a controlled fixture, not earned play. + +Captures are `local/bank-attachment/20261103-185531/` before and +`20261103-185932/` after. The corrected native check takes20 seconds. The broader +disappearance audit remains open. + ## Server policy and persistence `item_locations.bank_player_id` is a distinct root placement. Its constraints diff --git a/server/bank.go b/server/bank.go @@ -132,13 +132,6 @@ func (server *server) openBank_locked(client *worldClient) error { } } client.bank = &bankSession{player.playfield, predictedPosition_locked(player, time.Now())} - for _, item := range player.inventory.Bank { - if item.isPortableContainer() { - if err := client.send(backpackPacket(client.id, player.playfield, item, 105)); err != nil { - return err - } - } - } return client.send(bankInventoryPacket(player)) } diff --git a/server/bank_attachment_test.go b/server/bank_attachment_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "bytes" + "encoding/binary" + "reflect" + "testing" +) + +func TestBankOpeningDoesNotAttachStoredBackpackToCharacterSlots(t *testing.T) { + for _, row := range []struct { + name string + itemSlot, bankSlot uint32 + }{ + {"worn weapon", 6, 6}, + {"first carried row", 64, 48}, + {"last carried row", 93, 77}, + } { + t.Run(row.name, func(t *testing.T) { + world, output := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.playfield, player.position = 705, [3]float32{985, 20.2001, 580} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := player.inventory + inventory.LastID = 2 + inventory.Items = []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: row.itemSlot, Count: 1}} + inventory.Bank = []ownedItem{{ID: 2, Type: 51017, Template: 99228, Quality: 1, Slot: row.bankSlot, Count: 1}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + output.packets = nil + + if err := world.handleTerminalUse(client, bankUseRequest(1)[20:]); err != nil { + t.Fatal(err) + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory, inventory) || !reflect.DeepEqual(cold.characters[1].inventory, inventory) || + world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("bank opening wrote state or changed either physical instance", err) + } + if len(output.packets) != 2 || binary.BigEndian.Uint32(output.packets[0][16:20]) != 0x52526858 || + binary.BigEndian.Uint32(output.packets[1][16:20]) != 0x343c287f || + binary.BigEndian.Uint32(output.packets[1][45:49]) != row.bankSlot || binary.BigEndian.Uint32(output.packets[1][57:61]) != 2 { + t.Fatal("bank opening added a live item to the ordinary character inventory") + } + }) + } +} diff --git a/server/browser_bank_attachment_test.go b/server/browser_bank_attachment_test.go @@ -0,0 +1,84 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserBankBackpackPreservesWornIdentity(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for bank backpack attachment") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/bank-attachment", time.Now().Format("20060102-150405")) + world := newTestServer(t) + player := world.newCharacter() + player.playfield, player.position = 1183, [3]float32{193.79826, 5.01, 136.83983} + player.rotation = [4]float32{0, .70710677, 0, .70710677} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("bank-attachment"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 2, Items: []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}, Bank: []ownedItem{ + {ID: 2, Type: 51017, Template: 99228, Quality: 1, Slot: 6, Count: 1}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + 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(player.inventory) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*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_bank_attachment.mjs"), host.URL, output) + 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) + } + cold := newTestInventoryServer(t) + bank := slices.Clone(inventory.Bank) + bank[0].Slot = 0 + if !slices.Equal(player.inventory.Items, inventory.Items) || !slices.Equal(cold.characters[1].inventory.Items, inventory.Items) || + !slices.Equal(player.inventory.Bank, bank) || !slices.Equal(cold.characters[1].inventory.Bank, bank) || + world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("bank attachment changed worn or banked ownership") + } +} diff --git a/tools/client/test_bank_attachment.mjs b/tools/client/test_bank_attachment.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +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', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +let game; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'bank-attachment', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.type, item.slot]), [[1, 51018, 6]]); + const before = await server(); + if (!game.state.camera.firstPerson) await game.key('F8'); + await game.click(...await game.pick(51005, 3221357727), 'right'); + await game.wait('bank opens', state => state.regions.some(region => + region[0] === 0 && region[1] === 0 && region[2] === 178 && region[3] === 128)); + await game.save(output + '/opened'); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.type, item.slot]), [[1, 51018, 6]], + 'banked slot6 must not replace worn slot6'); + assert.deepEqual(await server(), before); + + // The uninstantiated banked bag must still withdraw and open through normal Use. + await game.key('KeyI'); + await game.click(30, 45); + await game.wait('exact backpack withdrawn', state => game.local(state).inventory.some(item => item.id === 2 && item.slot === 48)); + await game.click(170, 8); + await game.wait('bank closes', state => !state.regions.some(region => + region[0] === 0 && region[1] === 0 && region[2] === 178 && region[3] === 128)); + const grids = game.state.grids.length, opened = game.sequence; + await game.click(681, 45, 'right'); + await game.wait('withdrawn backpack opens its contents', state => state.grids.length > grids && + game.events.some(event => event.sequence > opened && event.direction === 'framereceived' && event.opcode === '4e536976')); + await game.save(output + '/bag-open'); + const closing = game.sequence; + await game.click(681, 45, 'right'); + await game.wait('backpack closes normally', () => game.events.some(event => event.sequence > closing && + event.direction === 'framereceived' && event.opcode === '2049527c' && event.actor[1] === 2)); + await game.click(...await game.pick(51005, 3221357727), 'right'); + await game.wait('bank reopens', state => state.regions.some(region => + region[0] === 0 && region[1] === 0 && region[2] === 178 && region[3] === 128)); + await game.click(681, 45); + await game.click(30, 45); + await game.wait('same backpack returned to bank', state => !game.local(state).inventory.some(item => item.id === 2)); + await game.click(170, 8); + await page.keyboard.press('Control+1'); + await game.click(867, 206, 'right'); + await game.wait('same worn weapon removed', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 48)); + await game.wait('ordinary source usable', state => state.grids.some(grid => grid.cells.some(cell => + cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy))); + await game.wait('equipment action ends', state => !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + await game.click(681, 45, 'right'); + await game.wait('same physical weapon worn again', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 6)); + await game.save(output + '/reworn'); + const expected = {...before, Bank: before.Bank.map(item => ({...item, Slot: 0}))}; + assert.deepEqual(await server(), expected); + await page.reload(); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + assert.deepEqual(game.local().inventory.map(item => [item.id, item.type, item.slot]), [[1, 51018, 6]]); + assert.deepEqual(await server(), expected); + assert.deepEqual(game.errors, []); + console.log('PASS: bank backpack preserves worn identity, normal withdrawal/Use, weapon removal/rewear and page/cold ownership'); +} finally { + try { if (game) await game.save(output + '/final'); } + finally { await browser.close(); } +}