aorecomp

Anarchy Online classic in the browser

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


commit a9b337fb402eb9b89cd3c15594b0d7bbdd39eb16
parent 54adf801e78d0fe72a7068532f5f90e94556844f
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 03:55:21 +0000

Clear stale carried rows after empty-source move refusals

Diffstat:
MTODO.md | 9+++++++++
Mdocs/inventory.md | 26++++++++++++++++++++++++++
Aserver/browser_stale_inventory_move_test.go | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/inventory.go | 11++++++++++-
Mserver/inventory_test.go | 6+++++-
Aserver/stale_inventory_move_test.go | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_stale_inventory_move.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 339 insertions(+), 2 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] Clear an empty carried source after stale weapon wear. Reproduction: + a controlled earlier bank transfer leaves the old ordinary icon visible; + native right-click wear sends a real request but receives no response. Source + cancellation followed by clearing only that empty row now removes the ghost, + without false wear success or ownership writes. The same WASM page withdraws + and equips the exact banked weapon, then page/cold recovery retains both + instances. First/last carried rows and invalid/pending requests have handler + checks. The broader disappearance audit remains open. See + [stale carried sources](docs/inventory.md#stale-carried-move-sources). - [x] [P0] Refresh stale reclaim withdrawals. Reproduction: a controlled earlier collection/bank transfer leaves an old native source visible; clicking its already-collected snapshot slot receives no reply and hides the icon. Source diff --git a/docs/inventory.md b/docs/inventory.md @@ -191,6 +191,32 @@ and confirmation emit this packet. The server checks the session, owner, page, occupied slot and both templates, saves the deletion, then echoes the action. Repeated requests for the now-empty slot do nothing. +### Stale carried move sources + +A controlled earlier bank transfer can leave an old carried weapon icon in the +native view. Right-click wear still sends a real ContainerAddItem request, but +the server previously ignored the empty source, leaving that unusable ghost. +For a current living session with no pending equipment, an ordinary source and +an owner-directed valid equipment/carried destination, the server now cancels +the source with action146 before clearing just its empty row with action112. +This is a private GUI correction: no ownership is deleted, no successful move is +reported and no live weapon destruction is sent. The banked physical instance +remains intact. Invalid, foreign and pending-equipment requests keep their guards. + +`TestStaleOrdinaryMoveClearsOnlyEmptySourceWithoutWrites` checks first/last carried +rows, repeated cancellation/clear ordering, exact cold ownership, allocation and +zero writes. Its companion checks invalid/foreign requests and a real pending +equipment move without changing its original state. +`TestBrowserStaleOrdinaryMove` reproduces the native right-click request from +the missed-transfer checkpoint, clears the ghost and retains an unrelated part. +The same page opens the real bank, withdraws that exact weapon and equips it. +Native page replay and cold loading retain weapon1 worn in slot6 and part2 in +saved slot65, with zero cash and no extra identity. Location, loadout, skills and +the earlier transfer are controlled; this is not earned progression evidence. +The baseline and17-second corrected captures are in `local/stale-inventory-move/`. +The initial ordinary-grid rearrangement did not publish a move and is not used +as evidence of this server failure. + ## Native visual order The shipped `cd_image/text/help/The Inventory Window.txt` documents left-click diff --git a/server/browser_stale_inventory_move_test.go b/server/browser_stale_inventory_move_test.go @@ -0,0 +1,107 @@ +package main + +import ( + "cmp" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserStaleOrdinaryMove(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for stale ordinary moves") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/stale-inventory-move", 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.stats = testCharacterStats() + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-inventory-move"))) + 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: 64, Count: 1}, + {ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 65, 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 bank transfer without refreshing its old carried source. + 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.Items[0] + item.Slot = 0 + inventory.Bank = []ownedItem{item} + inventory.Items = slices.Clone(inventory.Items[1:]) + 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() + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + 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_stale_inventory_move.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) + expected := []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}, + {ID: 2, Type: 51005, Template: 42640, Quality: 1, Slot: 65, Count: 1}} + for _, actual := range []playerInventory{player.inventory, cold.characters[1].inventory} { + items := slices.Clone(actual.Items) + slices.SortFunc(items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) }) + if !slices.Equal(items, expected) || len(actual.Bank) != 0 || actual.Credits != 0 { + t.Fatal("stale ordinary move lost the banked item or changed another instance", actual) + } + } + if world.nextItem != 2 || cold.nextItem != 2 { + t.Fatal("stale ordinary move allocated another instance") + } +} diff --git a/server/inventory.go b/server/inventory.go @@ -349,6 +349,16 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return server.syncStacks_locked(client) } } + destination := binary.BigEndian.Uint32(body[32:36]) + if index < 0 && client.equipment == nil && key == 0x47537a24 && sourceType == 104 && sourceSlot >= 64 && sourceSlot < 94 && + binary.BigEndian.Uint32(body[24:28]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == client.id && + (destination > 0 && destination < 46 && destination != 32 || destination >= 64 && destination < 94) { + // Cancel the stale drag before clearing only its now-empty carried row. + if err := client.send(characterActionPacket(client.id, [5]uint32{146, 104, sourceSlot})); err != nil { + return err + } + return client.send(characterActionPacket(client.id, [5]uint32{112, 104, sourceSlot})) + } if index < 0 || (sourceSlot >= 64 && sourceType != 104) || (sourceSlot > 0 && sourceSlot < 16 && sourceType != 101) || (sourceSlot >= 33 && sourceSlot <= 45 && sourceType != 103) || @@ -366,7 +376,6 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { } return nil } - destination := binary.BigEndian.Uint32(body[32:36]) if key == 0x47537a24 && (sourceSlot < 64 || destination < 64) { if binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id { return nil diff --git a/server/inventory_test.go b/server/inventory_test.go @@ -225,7 +225,11 @@ func TestInventoryRejectsForeignOccupiedAndStaleRequests(t *testing.T) { err := world.handleInventory(client, packet[20:]) - if err != nil || !reflect.DeepEqual(before, world.characters[1].inventory.Items) || len(conn.packets) != 0 { + expectedPackets := 0 + if scenario == "repeat move" { + expectedPackets = 2 + } + if err != nil || !reflect.DeepEqual(before, world.characters[1].inventory.Items) || len(conn.packets) != expectedPackets { t.Fatalf("invalid request changed inventory: %+v %v", world.characters[1].inventory, err) } }) diff --git a/server/stale_inventory_move_test.go b/server/stale_inventory_move_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "testing" +) + +func TestStaleOrdinaryMoveClearsOnlyEmptySourceWithoutWrites(t *testing.T) { + for _, source := range []uint32{64, 93} { + t.Run(fmt.Sprint(source), func(t *testing.T) { + world, output := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + if granted, err := world.grantItem_locked(player, 42640); err != nil || !granted { + t.Fatal(granted, err) + } + inventory := player.inventory + item := inventory.Items[0] + item.Slot = 0 + inventory.Bank = []ownedItem{item} + inventory.Items = slices.Clone(inventory.Items[1:]) + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + auditCheckpointWrites(t, world) + + for range 2 { + if err := world.handleInventory(client, inventoryMovePacket(1, source, 6)[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 || len(output.packets) != 4 { + t.Fatal("stale ordinary move changed ownership, allocation or omitted correction", err) + } + for index, action := range []uint32{146, 112, 146, 112} { + packet := output.packets[index] + if binary.BigEndian.Uint32(packet[16:20]) != 0x5e477770 || + binary.BigEndian.Uint32(packet[29:33]) != action || binary.BigEndian.Uint32(packet[33:37]) != 104 || + binary.BigEndian.Uint32(packet[37:41]) != source-16 || binary.BigEndian.Uint64(packet[41:49]) != 0 { + t.Fatalf("stale move did not cancel/clear only its native source: %x", packet) + } + } + }) + } +} + +func TestStaleOrdinaryMoveIgnoresInvalidOrPendingRequests(t *testing.T) { + for _, scenario := range []string{"foreign actor", "foreign target", "invalid source", "invalid destination", "wrong page", "pending equipment"} { + t.Run(scenario, func(t *testing.T) { + world, output := newEquipmentWorld(t) + client := world.clients[1] + if err := world.handleInventory(client, characterActionPacket(1, [5]uint32{112, 104, 64, 0, 0})[20:]); err != nil { + t.Fatal(err) + } + request := inventoryMovePacket(1, 64, 6)[20:] + switch scenario { + case "foreign actor": + binary.BigEndian.PutUint32(request[8:12], 2) + case "foreign target": + binary.BigEndian.PutUint32(request[28:32], 2) + case "invalid source": + binary.BigEndian.PutUint32(request[20:24], 94) + case "invalid destination": + binary.BigEndian.PutUint32(request[32:36], 94) + case "wrong page": + binary.BigEndian.PutUint32(request[16:20], 103) + case "pending equipment": + if granted, err := world.grantItem_locked(world.characters[1], 209283); err != nil || !granted { + t.Fatal(granted, err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil { + t.Fatal("equipment fixture did not begin", err) + } + request = inventoryMovePacket(1, 65, 66)[20:] + } + pending := client.equipment + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + output.packets = nil + + err = world.handleInventory(client, request) + after, readErr := readTestItemStore(world) + + if err != nil || readErr != nil || !bytes.Equal(before, after) || len(output.packets) != 0 || client.equipment != pending { + t.Fatal("invalid stale move changed ownership, pending equipment or produced correction traffic", err, readErr) + } + }) + } +} diff --git a/tools/client/test_stale_inventory_move.mjs b/tools/client/test_stale_inventory_move.mjs @@ -0,0 +1,78 @@ +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-inventory-move', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = (pageId, slot) => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === pageId && cell.identity[1] === slot && !cell.dummy); + const click = async (source, button = 'left') => { + assert(source, 'the exact native source must be usable'); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, button); + }; + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + await game.key('KeyI'); + assert(cell(104, 48) && cell(104, 49)); + assert((await page.request.post(url + '/test-stale-view')).ok()); + evidence.transferred = await server(); + assert.deepEqual(evidence.transferred.Items.map(item => [item.ID, item.Slot]), [[2, 65]]); + assert.deepEqual(evidence.transferred.Bank.map(item => [item.ID, item.Slot]), [[1, 0]]); + await game.save(output + '/stale'); + const sequence = game.sequence; + await click(cell(104, 48), 'right'); + await game.wait('actual stale ordinary move', () => game.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '47537a24' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 104 && Buffer.from(event.hex, 'hex').readUInt32BE(33) === 48 && + Buffer.from(event.hex, 'hex').readUInt32BE(45) === 6)); + await game.wait('stale ordinary move 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('empty authoritative source cleared', () => !cell(104, 48) && cell(104, 49) && game.state.dragged[0] === 0); + assert.deepEqual(await server(), evidence.transferred); + await game.save(output + '/refused'); + + // The correction must leave the actual banked instance available on this page. + if (!game.state.camera.firstPerson) await game.key('F8'); + await game.click(...await game.pick(51005, 3221357727), 'right'); + await game.wait('banked source retained', () => cell(105, 0)); + await click(cell(105, 0)); + await game.wait('same physical weapon withdrawn', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 48)); + await game.click(170, 8); + if (!cell(104, 48)) await game.key('KeyI'); + const retry = game.sequence; + await click(cell(104, 48), 'right'); + await game.wait('valid same-page wear completes', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 6) && + game.events.some(event => event.sequence > retry && event.direction === 'framereceived' && event.opcode === '47537a24')); + evidence.after = await server(); + assert.deepEqual(evidence.after.Items.map(item => [item.ID, item.Slot]).sort((a, b) => a[0] - b[0]), [[1, 6], [2, 65]]); + assert.equal(evidence.after.Bank.length, 0); + await game.save(output + '/moved'); + 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]).sort((a, b) => a[0] - b[0]), [[1, 6], [2, 49]]); + assert.deepEqual(await server(), evidence.after); + assert.deepEqual(game.errors, []); + console.log('PASS: stale ordinary source cleared, exact banked item withdrawn/moved and both instances retained through 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(); } +}