aorecomp

Anarchy Online classic in the browser

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


commit c3462043d5f83cbf3d6c657bd3c275c9c3519f25
parent b4ea37951d827aa35cc20211cd55a4418535e7d2
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 18:28:29 +0000

Accept exact mission objectives from carried backpacks

Diffstat:
MTODO.md | 11++++++++---
Mdocs/mission-objectives.md | 43++++++++++++++++++++++++++++++++++++++++++-
Aserver/browser_mission_backpack_test.go | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_backpack_return_test.go | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/mission_completion.go | 19+++++++++++++++----
Atools/client/test_mission_backpack.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 351 insertions(+), 8 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -2278,9 +2278,14 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). assuming every recorded enemy qualifies. Cover full inventory and failed-commit/retry; see [token evidence](docs/mission-encounters.md#completion-token-evidence). -- [ ] [P1] Extend return-item submission to native carried-backpack sources after - verifying their original producer/callback. Main-inventory hand-in is verified; - banked, unknown and other players' items must stay ineligible. +- [x] [P1] Extend return-item submission to native carried-backpack sources. + Original producer/resolver/success-callback evidence confirms page107's packed + session handle and inner slot. The exact carried objective now settles through + the existing atomic reward transaction; banked, foreign and unknown sources + remain ineligible. Go checks cover closed known bags, replay and failed/ignored + writes/commit retry. A focused WASM check opens the real bag and hands its book + to the issuing booth, retaining the selected reward after reconnect/cold load. + See [backpack hand-in](docs/mission-objectives.md#carried-backpack-return-sources). - [ ] [P2] Recover original completed-instance lifetime and re-entry policy. The fixed contract keeps existing occupants until its original deadline while revoking all bound keys; no separate invented timer is introduced. diff --git a/docs/mission-objectives.md b/docs/mission-objectives.md @@ -149,7 +149,8 @@ find-item, inspect and return-item server policies remain distinct. With the book held on the cursor, right-clicking the actual booth emits GenericCmd0x52526858 action5 (UseItemOnItem), data version0, local character -identity, source104/main-inventory slot and target56001/booth ID. Right-clicking +identity, source104/main-inventory slot or source107/packed backpack slot, +and target56001/booth ID. Right-clicking the journal instead emits action84 (UseItemOnMission), target56003/quest ID. That remote action is denied for this return-item contract. Native requests from both interactions were captured without WebSocket changes. Raw14.9.1 kkr.dll @@ -203,6 +204,46 @@ It also describes killing a mission target after completing find-person, supporting continued occupancy after success. This is near-period player evidence, not an original14.9.1 server capture. +## Carried-backpack return sources + +Return-item hand-in also accepts a known carried backpack's contents. Source +page107 packs the session's container handle in the upper16 bits and its inner +slot in the lower16. The handle must still resolve to an owned portable bag in +the character's carried/equipped inventory. A known bag may be closed; banked, +foreign, unknown and invalid-slot sources remain ineligible. The same bound +objective, booth, range, session and reward-capacity checks apply. + +Original KKR producer1002a8b0 forwards the supplied source into action5. +Resolver10061800 maps page107's handle to a Chest inventory, and1005f970 masks +its inner slot. Validator1005e4e0 admits this page while excluding bank/reclaim +pages105/106. Action completion1004d880 dispatches5 to1004ca70, which preserves +the inventory source identity for1005f000. These are shipped-client facts; +they do not recover historical reward or token formulas. Complete original +evidence is retained in `local/mission-backpack-return/native-*.json`. + +Only source admission changes. The existing settlement transaction consumes the +contained objective, revokes keys, pays cash and creates the selected reward +before sending success. Existing CharacterAction112 then removes the exact +page107/packed-slot row, retaining the bag and unrelated contents. + +Focused Go regressions reproduce rejection before the change and verify open +and closed known bags, stale/new replays, banked/foreign/unknown sources, and +failed/ignored objective-placement deletion or deferred COMMIT with safe retry. +A controlled native fixture starts with an accepted objective already inside +its bag beside the issuing booth. Actual input opens that bag, picks up the +book and right-clicks the world booth. Its captured source is107:65536, with +no synthetic request. The exact book3 and key2 retire; axe1 and bag4 remain, +and new QL2 glove5 plus20 credits arrive once. Page reconnect supplies the same +three physical IDs, and a separate cold read retains the completed mission, +empty bag and24-credit wallet. Screenshots show the empty bag, reward and +native completion text; there are no client errors. + +`TestBrowserMissionBackpackReturn` takes12.24 seconds. Artifacts are retained +under `local/mission-backpack-return/20261102-102610/`; the fixture establishes +this behavior without earning levels, traveling or clearing a mission. +Earlier driver failures clicked a compacted empty inventory cell and expected +the wrong bag-window dimensions; their traces are retained separately. + ## Verification Focused Go tests cover single allocation, exact native identity/world replay, diff --git a/server/browser_mission_backpack_test.go b/server/browser_mission_backpack_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserMissionBackpackReturn(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused backpack hand-in check") + } + + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/mission-backpack-return", time.Now().Format("20060102-150405")) + world, _, _ := newMissionBackpackReturnWorld(t) + player := world.characters[1] + player.position, player.rotation = [3]float32{99.8, 115.75, 151.4}, [4]float32{0, 1, 0, 0} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("bag-return"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.db.Close(); err != nil { + t.Fatal(err) + } + world = newServer() + t.Cleanup(func() { world.db.Close() }) + 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": world.characters[1].inventory, + "completed": world.missionExpiry[0].completed}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_mission_backpack.mjs"), host.URL, output) + command.Dir = root + command.Stdout, command.Stderr = os.Stdout, os.Stderr + err := command.Run() + cold := newTestInventoryServer(t) + + if err != nil { + t.Fatal(err) + } + if !cold.missionExpiry[0].completed || len(cold.items) != 3 || cold.characters[1].inventory.Credits != 24 || + len(cold.characters[1].inventory.Containers[4]) != 0 { + t.Fatal("native bag hand-in did not preserve its durable outcome") + } + t.Logf("Browser artifacts: %s", output) +} diff --git a/server/mission_backpack_return_test.go b/server/mission_backpack_return_test.go @@ -0,0 +1,160 @@ +package main + +import ( + "encoding/binary" + "reflect" + "testing" +) + +func newMissionBackpackReturnWorld(t *testing.T) (*server, *worldClient, *combatTestConn) { + t.Helper() + world, client, output := newMissionItemRewardWorld(t, 85596, 2) + if granted, err := world.grantItem_locked(world.characters[1], 99228); !granted || err != nil { + t.Fatal(granted, err) + } + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 67, 1)[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, backpackMoveRequest(104, 66, 51017, 4, 111)[20:]); err != nil { + t.Fatal(err) + } + output.packets = nil + return world, client, output +} + +func missionBackpackReturnRequest(sequence uint32) []byte { + request := missionReturnRequest(sequence) + binary.BigEndian.PutUint32(request[40:], 107) + binary.BigEndian.PutUint32(request[44:], 1<<16) + return request +} + +func TestMissionBackpackReturnConsumesExactCarriedObjective(t *testing.T) { + for _, state := range []string{"open", "closed"} { + t.Run(state, func(t *testing.T) { + world, client, output := newMissionBackpackReturnWorld(t) + if state == "closed" { + client.backpacks[1] = backpackHandle{4, false} + } + + if err := world.handleMissionReturn(client, missionBackpackReturnRequest(2)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + + if len(world.characters[1].missions) != 0 || !cold.missionExpiry[0].completed || + cold.characters[1].inventory.Credits != 24 || len(cold.items) != 3 || + len(cold.characters[1].inventory.Containers[4]) != 0 || + len(world.characters[1].inventory.Containers[4]) != 0 || + !reflect.DeepEqual(cold.characters[1].inventory.Items, world.characters[1].inventory.Items) { + t.Fatal("carried bag objective did not settle atomically", cold.characters[1].inventory) + } + if len(output.packets) != 6 || binary.BigEndian.Uint32(output.packets[0][29:]) != 1 { + t.Fatal("bag return did not complete native Use before settlement", output.packets) + } + deleted := false + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:]) == 112 && + binary.BigEndian.Uint32(packet[33:]) == 107 && binary.BigEndian.Uint32(packet[37:]) == 1<<16 { + deleted = true + } + } + if !deleted { + t.Fatal("objective removal did not address the native bag handle") + } + + output.packets = nil + for _, sequence := range []uint32{2, 3} { + if err := world.handleMissionReturn(client, missionBackpackReturnRequest(sequence)); err != nil { + t.Fatal(err) + } + } + + if world.characters[1].inventory.Credits != 24 || len(world.items) != 3 || len(output.packets) != 1 || + binary.BigEndian.Uint32(output.packets[0][29:]) != 2 { + t.Fatal("repeated bag hand-in paid again") + } + }) + } +} + +func TestMissionBackpackReturnRejectsUnavailableSources(t *testing.T) { + for _, scenario := range []string{"unknown handle", "instance as handle", "empty slot", "bank page", "banked bag", "foreign bag", "non-container"} { + t.Run(scenario, func(t *testing.T) { + world, client, output := newMissionBackpackReturnWorld(t) + player := world.characters[1] + request := missionBackpackReturnRequest(2) + switch scenario { + case "unknown handle": + binary.BigEndian.PutUint32(request[44:], 2<<16) + case "instance as handle": + binary.BigEndian.PutUint32(request[44:], 4<<16) + case "empty slot": + binary.BigEndian.PutUint32(request[44:], 1<<16|20) + case "bank page": + binary.BigEndian.PutUint32(request[40:], 105) + case "banked bag": + bag := player.inventory.Items[2] + bag.Slot = 0 + player.inventory.Bank = []ownedItem{bag} + player.inventory.Items = player.inventory.Items[:2] + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + case "foreign bag": + world.characters[2] = &character{id: 2, inventory: playerInventory{ + Items: []ownedItem{player.inventory.Items[2]}, Containers: player.inventory.Containers}} + player.inventory.Items = player.inventory.Items[:2] + case "non-container": + player.inventory.Items[2].Type = 51005 + } + before := player.inventory + + if err := world.handleMissionReturn(client, request); err != nil { + t.Fatal(err) + } + + if !reflect.DeepEqual(player.inventory, before) || len(player.missions) != 1 || len(output.packets) != 1 || + binary.BigEndian.Uint32(output.packets[0][29:]) != 2 { + t.Fatal("unavailable bag source changed ownership or completed the mission") + } + }) + } +} + +func TestMissionBackpackReturnRollsBackAndRetries(t *testing.T) { + for _, statement := range []string{ + "CREATE TRIGGER fail_bag_return BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(FAIL,'bag objective'); END", + "CREATE TRIGGER fail_bag_return BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(IGNORE); END", + "CREATE TABLE pending_bag_return (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_bag_return AFTER UPDATE OF completed ON missions BEGIN INSERT INTO pending_bag_return VALUES(999999); END", + } { + t.Run(statement, func(t *testing.T) { + world, client, output := newMissionBackpackReturnWorld(t) + before := world.characters[1].inventory + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + failure := world.handleMissionReturn(client, missionBackpackReturnRequest(2)) + cold := reloadMissionEntranceWorld(t) + + if failure == nil || len(output.packets) != 0 || cold.missionExpiry[0].completed || + !reflect.DeepEqual(before, cold.characters[1].inventory) || !reflect.DeepEqual(before, world.characters[1].inventory) { + t.Fatal("failed bag settlement lost contents, cash or pending mission", failure) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_bag_return"); err != nil { + t.Fatal(err) + } + if err := world.handleMissionReturn(client, missionBackpackReturnRequest(3)); err != nil { + t.Fatal(err) + } + cold = reloadMissionEntranceWorld(t) + + if !cold.missionExpiry[0].completed || len(cold.characters[1].inventory.Containers[4]) != 0 || + cold.characters[1].inventory.Credits != 24 || len(cold.items) != 3 { + t.Fatal("bag hand-in did not recover after failed transaction") + } + }) + } +} diff --git a/server/mission_completion.go b/server/mission_completion.go @@ -43,15 +43,26 @@ func (server *server) handleMissionReturn(client *worldClient, body []byte) erro index := slices.IndexFunc(player.missions, func(mission acceptedMission) bool { return !mission.completed && mission.offer.booth == binary.BigEndian.Uint32(body[52:56]) && time.Now().Before(mission.expiresAt) }) - item := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { - return item.Slot >= 64 && item.Slot < 94 && binary.BigEndian.Uint32(body[40:44]) == 104 && item.Slot == binary.BigEndian.Uint32(body[44:48]) - }) + // Page 107 addresses a known carried bag through this session's native handle. + page, slot := binary.BigEndian.Uint32(body[40:44]), binary.BigEndian.Uint32(body[44:48]) + items := player.inventory.Items + if page == 107 { + bag := client.backpacks[slot>>16].id + items = nil + if bag != 0 && slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.ID == bag && item.isPortableContainer() }) { + items = player.inventory.Containers[bag] + } + slot &= 65535 + } else if page != 104 || slot < 64 || slot >= 94 { + items = nil + } + item := slices.IndexFunc(items, func(item ownedItem) bool { return item.Slot == slot }) booth, exists := gamedata.MissionBooths[binary.BigEndian.Uint32(body[52:56])] accepted := binary.BigEndian.Uint32(body[24:28]) == 5 && binary.BigEndian.Uint32(body[48:52]) == 56001 && index >= 0 && item >= 0 && exists && booth.Playfield == player.playfield && client.trade == nil && client.shop == nil && client.bank == nil && client.equipment == nil && client.nanoCast == nil if accepted { - mission, objective := player.missions[index], player.inventory.Items[item] + mission, objective := player.missions[index], items[item] position := predictedPosition_locked(player, time.Now()) x, y, z := position[0]-booth.Position[0], position[1]-booth.Position[1], position[2]-booth.Position[2] accepted = mission.objective != 0 && objective.ID == mission.objective && objective.Template == mission.offer.definition.ObjectiveItem && diff --git a/tools/client/test_mission_backpack.mjs b/tools/client/test_mission_backpack.mjs @@ -0,0 +1,60 @@ +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', headless: false, + args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage']}); +let game; +try { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'bag-return', 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(); + const before = await server(); + assert.equal(before.completed, false); + assert.equal(before.inventory.Containers[4][0].ID, 3); + await game.key('KeyI'); + await game.click(789, 45, 'right'); + await game.wait('native backpack window', state => state.regions.some(region => + region[0] === 0 && region[1] === 0 && region[2] === 178 && region[3] === 128)); + await game.save(output + '/book-in-bag'); + await game.click(30, 45); + const [x, y] = await game.pick(56001, 3221228472); + const handIn = game.sequence; + await game.click(x, y, 'right'); + await game.wait('native bag-source mission completion', state => game.local(state).stats[61] === 24 && + !game.local(state).inventory.some(item => item.templates[0] === 28577)); + const request = game.events.find(event => event.sequence > handIn && event.direction === 'framesent' && + event.opcode === '52526858' && Buffer.from(event.hex, 'hex').readUInt32BE(37) === 5); + assert(request, 'Native item-on-item Use did not reach the server'); + const packet = Buffer.from(request.hex, 'hex'); + assert.equal(packet.readUInt32BE(packet.length - 16), 107); + assert.equal(packet.readUInt32BE(packet.length - 12), 1 << 16); + assert.equal(packet.readUInt32BE(packet.length - 8), 56001); + assert.equal(packet.readUInt32BE(packet.length - 4), 3221228472); + assert(game.events.some(event => event.sequence > handIn && event.direction === 'framereceived' && + event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 112 && + Buffer.from(event.hex, 'hex').readUInt32BE(33) === 107 && Buffer.from(event.hex, 'hex').readUInt32BE(37) === 1 << 16)); + const after = await server(); + assert.equal(after.completed, true); + assert.equal(after.inventory.Credits, 24); + assert.equal(after.inventory.Containers[4]?.length ?? 0, 0); + assert.deepEqual(after.inventory.Items.map(item => [item.ID, item.Template, item.Quality, item.Slot]), + [[1, 209283, 1, 64], [4, 99228, 1, 67], [5, 85596, 2, 65]]); + await game.save(output + '/completed'); + await page.reload(); + await game.ready(); + assert.equal(game.local().stats[61], 24); + assert.deepEqual(game.local().inventory.map(item => item.id).sort((a, b) => a - b), [1, 4, 5]); + assert.equal((await server()).completed, true); + assert.deepEqual(game.errors, []); + console.log('PASS: actual page107 bag-source hand-in consumes exact book/key and pays one selected reward, retained after reconnect'); +} finally { + try { if (game) await game.save(output + '/final'); } + finally { await browser.close(); } +}