aorecomp

Anarchy Online classic in the browser

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


commit ae585b666bfacbf43f27b544eb0697ad13710985
parent aeb23a46e06a05554570e3b9e3d3c65ba953bb7f
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 22:48:56 +0000

fix: cancel and refresh stale bank withdrawals

Diffstat:
MTODO.md | 8++++++++
Mdocs/bank-storage.md | 32++++++++++++++++++++++++++++++++
Mserver/backpacks.go | 7+++++++
Aserver/browser_stale_bank_test.go | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/stale_bank_test.go | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_stale_bank.mjs | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 284 insertions(+), 0 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -4013,6 +4013,14 @@ 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] Cancel and refresh stale bank withdrawals. Reproduction: a controlled + earlier transfer empties bank slot0 while its native window still shows the + source; clicking it sends a real request that receives no reply and hides the + icon. Completion: cancel the pending source before replaying current contents, + remove the ghost, retain the other usable bank item, and permit its same-window + withdrawal. These checks now pass, preserving the bank anchor and all three + physical identities across page/cold recovery, with no ownership writes for + repeated stale requests. See [stale withdrawals](docs/bank-storage.md#stale-withdrawal-sources). - [x] [P0] Preserve selected-quality stack contracts after a refused split. Reproduction: a real QL2 Ctrl-split during a controlled pending equip rebuilt its native endpoints as 25811/25811 instead of 25812/25811. Resolve the shared diff --git a/docs/bank-storage.md b/docs/bank-storage.md @@ -356,3 +356,35 @@ needed for this working branch. ```sh AO_GAME_TEST=1 go test ./server -run '^TestBrowserBankedWeaponRecovery$' -count=1 -timeout=10m -v ``` + +## Stale withdrawal sources + +A live bank window can still expose a slot that no longer owns an item. The +previous transfer guard returned without replying, leaving the picked native +source hidden. An authenticated request for an empty slot within the original +102-slot bank now receives CharacterAction146 for its page105 source, followed +by current BankIIR contents. Cancellation precedes replacement so the old source +does not retain its dummy state. The remaining item stays usable in the same +window. The server bank anchor, ownership, quantities and global item counter +remain unchanged; this refusal performs no database writes. + +`TestBankStaleWithdrawalCancelsAndRefreshesWithoutWrites` uses the public +inventory handler for an ordinary withdrawal followed by two repeated requests. +It covers an empty bank and a retained second item, exact ordered replies, +unchanged persisted ownership, a SQL write audit and cold reconstruction. + +`TestBrowserStaleBankWithdrawal` isolates the stale-view condition by committing +a banked part into the owner's carried backpack without refreshing the native +window. This is a controlled checkpoint, not earned progression or a claim that +ordinary reliable delivery drops that reply. Real native input then sends the +stale withdrawal. The baseline times out waiting for cancellation; the fixed +run removes the ghost and collects the remaining part through the same window. +Page replay retains the bag and collected part, and reopening the bag exposes +the earlier transferred part. Fresh Go loading retains all three physical IDs. +The passing native run takes 15.60 seconds, including page replay, under +`local/stale-bank/20261103-144547/`. No client or published-bundle change is needed. +Related Go checks pass67roots/258results; focused race checks pass3/23, and vet +and driver syntax checks pass. `local/stale-bank/verification.json` independently +checks the actual request, cancellation-before-refresh, both contents snapshots, +four clean native traces and exact item ledgers. The broader disappearance audit +remains open. diff --git a/server/backpacks.go b/server/backpacks.go @@ -207,6 +207,13 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte) } index := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == sourceSlot }) if index < 0 { + // A stale bank window still hides its picked source until cancellation. + if sourcePage == 105 && sourceSlot < bankCapacity { + if err := client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, sourceSlot})); err != nil { + return err + } + return client.send(bankInventoryPacket(player)) + } return nil } item := items[index] diff --git a/server/browser_stale_bank_test.go b/server/browser_stale_bank_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleBankWithdrawal(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for stale bank withdrawal") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/stale-bank", 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, 0.70710677, 0, 0.70710677} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-bank"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + inventory := playerInventory{LastID: 3, Items: []ownedItem{ + {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, Bank: []ownedItem{ + {ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 0, Count: 1}, + {ID: 3, Type: 51005, Template: 42640, Quality: 1, Slot: 1, 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) + }) + // Isolate an earlier committed transfer without refreshing the bank window. + mux.HandleFunc("POST /test-stale-view", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + defer world.mutex.Unlock() + inventory := player.inventory + item := inventory.Bank[0] + item.Slot = 0 + inventory.Bank = slices.Clone(inventory.Bank[1:]) + inventory.Containers = maps.Clone(inventory.Containers) + if inventory.Containers == nil { + inventory.Containers = make(map[uint32][]ownedItem) + } + inventory.Containers[1] = []ownedItem{item} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_stale_bank.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) + } + expected := []ownedItem{{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}} + contents := []ownedItem{{ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 0, Count: 1}} + cold := newTestInventoryServer(t) + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + !slices.Equal(player.inventory.Containers[1], contents) || !slices.Equal(cold.characters[1].inventory.Containers[1], contents) || + len(player.inventory.Bank) != 0 || len(cold.characters[1].inventory.Bank) != 0 || world.nextItem != 3 || cold.nextItem != 3 { + t.Fatal("stale bank request changed identity or lost the remaining transfer") + } +} diff --git a/server/stale_bank_test.go b/server/stale_bank_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "bytes" + "cmp" + "encoding/binary" + "reflect" + "slices" + "testing" +) + +func TestBankStaleWithdrawalCancelsAndRefreshesWithoutWrites(t *testing.T) { + for _, remaining := range []bool{false, true} { + t.Run(map[bool]string{false: "empty", true: "remaining item"}[remaining], func(t *testing.T) { + world, conn := newBankWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := player.inventory + count := 1 + if remaining { + count = 2 + } + inventory.Bank = slices.Clone(inventory.Items[:count]) + for index := range inventory.Bank { + inventory.Bank[index].Slot = uint32(index) + } + inventory.Items = slices.Clone(inventory.Items[count:]) + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + request := backpackMoveRequest(105, 0, 50000, 1, 111)[20:] + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + anchor := *client.bank + auditCheckpointWrites(t, world) + conn.packets = nil + + for range 2 { + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + cold := newTestInventoryServer(t) + expected := player.inventory + expected.Items = slices.Clone(expected.Items) + slices.SortFunc(expected.Items, func(a, b ownedItem) int { return cmp.Compare(a.Slot, b.Slot) }) + if len(expected.Bank) == 0 { + expected.Bank = nil + } + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || *client.bank != anchor || + !reflect.DeepEqual(expected, cold.characters[1].inventory) { + t.Fatal("stale withdrawal wrote ownership or changed the bank session", err) + } + if len(conn.packets) != 4 { + t.Fatalf("two stale withdrawals need cancellation and current contents each: got %d packets", len(conn.packets)) + } + for index := 0; index < len(conn.packets); index += 2 { + cancel, contents := conn.packets[index], conn.packets[index+1] + if binary.BigEndian.Uint32(cancel[16:20]) != 0x5e477770 || + !bytes.Equal(cancel[29:49], []byte{0, 0, 0, 146, 0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) || + !bytes.Equal(contents, targetPacket(bankInventoryPacket(player))) { + t.Fatalf("incorrect cancellation or stale contents: %x %x", cancel, contents) + } + } + }) + } +} diff --git a/tools/client/test_stale_bank.mjs b/tools/client/test_stale_bank.mjs @@ -0,0 +1,72 @@ +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', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +let game; +const evidence = {}; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'stale-bank', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const source = (state, slot) => state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 105 && cell.identity[1] === slot && !cell.dummy); + const clickCell = async cell => game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + await game.key('KeyI'); + if (!game.state.camera.firstPerson) await game.key('F8'); + await game.click(...await game.pick(51005, 3221357727), 'right'); + await game.wait('both bank sources open', state => source(state, 0) && source(state, 1)); + assert((await page.request.post(url + '/test-stale-view')).ok()); + evidence.transferred = await server(); + assert.deepEqual(evidence.transferred.Bank.map(item => [item.ID, item.Slot]), [[3, 1]]); + assert.equal(evidence.transferred.Containers[1][0].ID, 2); + await game.save(output + '/stale'); + const sequence = game.sequence; + await clickCell(source(game.state, 0)); + await game.wait('actual stale bank withdrawal', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 105 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === 0)); + await game.wait('stale bank request cancelled', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '5e477770' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 146)); + await game.wait('bank refresh removes stale source and retains remaining item', state => !source(state, 0) && source(state, 1)); + assert.deepEqual(game.state.dragged, [0, 0]); + assert.deepEqual(await server(), evidence.transferred); + await game.save(output + '/refused'); + await clickCell(source(game.state, 1)); + await game.wait('remaining source transfers in same window', state => game.local(state).inventory.some(item => item.id === 3 && item.slot === 49)); + evidence.after = await server(); + assert.deepEqual(evidence.after.Items.map(item => [item.ID, item.Slot]), [[1, 64], [3, 65]]); + assert.equal(evidence.after.Bank.length, 0); + await game.save(output + '/collected'); + 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.slot, item.templates]), + [[1, 48, [99228, 99228]], [3, 49, [42640, 42640]]]); + assert.deepEqual(await server(), evidence.after); + await game.key('KeyI'); + await game.click(684, 45, 'right'); + await game.wait('earlier transferred item retained in backpack after page replay', state => state.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 107 && cell.identity[1] === 65536 && !cell.dummy))); + assert.deepEqual(game.errors, []); + console.log('PASS: stale bank withdrawal cancelled, current contents usable and all three instances retained after page/cold recovery'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + if (game) await game.save(output + '/final'); + } finally { await browser.close(); } +}