aorecomp

Anarchy Online classic in the browser

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


commit 3f1df5db439012cb52c9d96020f57dfabee99298
parent 40303ca3372fea1db66199f49abbbc19d428a61b
Author: anon <anon@example.com>
Date:   Tue,  3 Nov 2026 16:41:08 +0000

Admit reviewed Kerans weapon qualities

Diffstat:
MTODO.md | 8++++++++
Adocs/kerans.md | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_kerans_test.go | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/gamedata/item_families.yaml | 3+++
Mserver/gamedata/item_quality_test.go | 2++
Aserver/kerans_quality_test.go | 368+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/client/test_kerans.mjs | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 803 insertions(+), 0 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -373,6 +373,14 @@ unverified mass/deletion/reclaim policies are in [backpacks](docs/backpacks.md). page/fresh-server ownership with 24 loaded and 75 carried rounds. Historical acquisition and offhand scheduling remain open; see [Home Defender contracts](docs/home-defender.md). + Two audited Kerans SMG pairs now admit QL1..98 and QL99..199, fixing + qualified QL2 wear refusal. Public-handler checks cover both strict SMG/Burst + gates, selected damage/timing/value, Dodge defense, Sense bonuses, bullet + reloads, pickup, sale and cold identity. Two controlled native clients verify + QL2/50/98/100 wear, QL101 refusal, cached rating/resources, Sense302/304, + a 120-bullet reload, one shot, exact sale and page/fresh-server retention. + Fixed QL200 stays separate; acquisition and the Burst special remain open. + See [Kerans contracts](docs/kerans.md). Two further audited M-10 pistol pairs now admit QL12..21 and QL22..37, fixing qualified QL13 rejection through the shared path. Public-handler and short two-client native checks cover strict Pistol/Fling gates, selected diff --git a/docs/kerans.md b/docs/kerans.md @@ -0,0 +1,91 @@ +# OT Kerans selected qualities + +Cheap OT Kerans Automatic Grinner 160476/160477 now admits QL1..98, and +OT Kerans Automatic Grinner 160478/160479 admits QL99..199 through the shared +quality, wear, weapon, price and native delivery paths. Previously a qualified +QL2 instance stayed carried after a native wear request. The production change +is two explicit family rows; Quality OT Kerans 160480 remains fixed at QL200. +Burst requirements are checked, but the separate Burst attack remains open. + +## Original contracts + +All five complete original 14.9.1 resources independently reparse to the +maintained catalog, including headers, text, functions, resources, weights, +predicates, hashes and offsets. Within each pair only quality, price, maximum +damage, critical bonus and the strict SMG/Burst thresholds vary. Attack uses +100% SMG (114), defense 100% Dodge Ranged (154). OnWear function53045 adds +Sense (20): two for Cheap, four for regular and six for fixed QL200. + +All retain minimum damage1, attack150cs, recharge145cs, equip350cs, range27m, +Ranged Initiative (119), Poison damage (96), mesh21147, resource21128 and +icon9013. The 120-round clip uses ammunition type2, supplied by Bullets21605. +The authored Burst cycle1500 is retained without claiming a working special. + +| QL | Maximum | Critical bonus | Value | Minimum SMG | Minimum Burst | Sense | +| --- | --- | --- | --- | --- | --- | --- | +| 1 | 26 | 24 | 2874 | 6 | 6 | 2 | +| 2 | 27 | 25 | 2888 | 11 | 10 | 2 | +| 49 | 91 | 89 | 36324 | 233 | 176 | 2 | +| 50 | 92 | 91 | 37732 | 237 | 179 | 2 | +| 97 | 156 | 155 | 136674 | 459 | 345 | 2 | +| 98 | 157 | 156 | 139476 | 464 | 349 | 2 | +| 99 | 158 | 157 | 142292 | 469 | 353 | 4 | +| 100 | 159 | 158 | 142334 | 474 | 357 | 4 | +| 149 | 226 | 226 | 248990 | 705 | 530 | 4 | +| 150 | 227 | 227 | 253300 | 710 | 533 | 4 | +| 198 | 293 | 293 | 560590 | 936 | 702 | 4 | +| 199 | 294 | 294 | 569084 | 941 | 706 | 4 | +| 200 | 295 | 295 | 574803 | 946 | 710 | 6 | + +Original payload SHA256 values: + +- 160476: `b83293c5412c98454fa9b002e959f168ab28a04b68be6148ea5b9ec7f8cdb75b`. +- 160477: `498be86ef93b2382e2c03597384ffcfd07c3473ecd9356e560423d472e371914`. +- 160478: `c8741dc575f92ffc30ea08298292d2046fb9ac51b0633592c7ee483e5a8c3748`. +- 160479: `47de3dcae79cc1a4b0852e98ac74f00421299b50a3add578cd7a0fff4c622cfd`. +- 160480: `1b182443a49b5642e1af97860a30d814f244c7518a5487129052f0aa6f1d9632`. + +Raw bytes and the full independent audit are under `local/kerans/original/`. +Bounded web searches supplied no period acquisition evidence. The local Fandom +`Fixer:Weapons` guide, touched June2015, mentions OT vendors and mission rolling; +this later guide does not establish 14.9.1 membership or distributions. Original +acquisition remains open and production stock, missions and drops are unchanged. + +## Focused verification + +Public handlers cover both stored anchors at twelve representative qualities, +the fixed QL200 record, both strict skill gates, the 3.5-second equip boundary, +selected properties and native low/high identities after cold loading. Combat +checks normal/critical damage, attack/recharge, one-round consumption and +opposed Dodge/Duck fixtures. Wrong shells leave storage unchanged; repeated +correct reload requests fill120 once and preserve the remaining83 bullets. +Controlled generated drops follow the same instances through duplicate pickup, +refused wear, repeated wear/remove, cancellation, sale and cold recovery. These +isolated contracts do not establish trainability or historical loot membership. + +The short two-client WASM fixture uses controlled level-200 Solitus characters, +abilities300 and raw SMG400/Burst283, both within cap540. Effective skills474/357 +qualify through QL100. Real input wears/removes QL2/50/98, wears QL100 and +refuses QL101. Cheap/regular bonuses raise Sense to302/304 without changing raw +abilities; cached native rating475 and maximum nano1050 must agree before +opening the skill form. The observer retains its own maximum nano1047. +Reloading from a controlled200-bullet stack leaves80 carried; one ordinary +2-point shot leaves119 loaded. Cancelling then accepting the QL2 sale pays145 +credits. Page replay and a fresh server retain the same five instances, rounds, +wallet and exactly-once Sense bonus. This is controlled evidence, not earned +levels, supplies or progression. + +The native baseline reproduces qualified refusal in37.78s. The accepted run +`local/kerans/20261103-083653` passes in95.19s (warm74.64, cold20.55), or +102.818s including Go. Reviewed captures show the original model, Sense302/304 +and usable retained inventory. Independent original-byte, packet and SQLite +checks verify five surviving physical items, 199 remaining rounds, unchanged +raw skills/abilities and the exact145-credit wallet in both snapshots. All16 +native traces are error-free with no dropped events; the independent report is +`local/kerans/verification.json`. + +The five new Go groups pass120 results in23.153s. Shared family admission and +exact-quality boundaries pass154 results in7.651s. The shared weapon-quality, +wear, ammunition, rating and ability-bonus selection passes15 groups and339 +results in92.017s. Vet, JavaScript syntax and whitespace checks pass. +All five new groups also pass under the race detector:120 results in113.041s. diff --git a/server/browser_kerans_test.go b/server/browser_kerans_test.go @@ -0,0 +1,150 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserKeransQualities(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the focused native Kerans check") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/kerans", time.Now().Format("20060102-150405")) + t.Chdir(t.TempDir()) + for _, phase := range []string{"warm", "cold"} { + t.Run(phase, func(t *testing.T) { + world := newServerForTest(t) + var target *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (target == nil || actor.id < target.id) { + target = actor + } + } + if phase == "warm" { + for index := 0; index < 2; index++ { + player := world.newCharacter() + player.name, player.appearance = fmt.Sprint("Kerans", index), 0x515 + player.position = [3]float32{60 - float32(index)*3, 14.75, 53} + player.rotation = [4]float32{0, 1, 0, 0} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("kerans-", index)))) + player.level = 200 + player.stats.Abilities = characterAbilitiesStats{300, 300, 300, 300, 300, 300} + player.stats.Ranged.SubmachineGun, player.stats.Ranged.Burst = 400, 283 + for stat, raw := range map[uint32]uint16{114: 400, 148: 283} { + if uint32(raw) > player.trainingMaximum(stat) { + t.Fatal("controlled raw skill exceeds its native cap", stat) + } + } + for stat, expected := range map[uint32]int32{114: 474, 148: 357} { + if actual, _ := player.effectiveStat(stat); actual != expected { + t.Fatal("controlled effective skill differs", stat, actual) + } + } + player.health, player.nano = player.maximumHealth(), player.maximumNano() + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + } + // Controlled contracts and a nearby original Leet isolate the weapon check. + for _, item := range []struct{ template, quality uint32 }{ + {160476, 2}, {160477, 50}, {160477, 98}, {160479, 100}, {160478, 101}, {21605, 1}, + } { + if granted, err := world.grantItem_locked(world.characters[1], item.template); err != nil || !granted { + t.Fatal(granted, err) + } + world.characters[1].inventory.Items[len(world.characters[1].inventory.Items)-1].Quality = item.quality + } + world.characters[1].inventory.Items[5].Count = 200 + if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil { + t.Fatal(err) + } + target.position, target.motion.home = [3]float32{61, 14.75, 51.5}, [3]float32{61, 14.75, 51.5} + world.combatRoll = func(limit uint32) uint32 { + if limit == 100 { + return 99 + } + return 0 + } + } + owner, watcher := world.characters[1], world.characters[2] + 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, "observer": watcher.inventory, + "target": target.id, "health": target.health, "fighting": owner.fighting, "ownerHealth": owner.health, "sense": owner.effectiveAbility(20), "rating": owner.attackRating(), "maxHealth": owner.maximumHealth(), "maxNano": owner.maximumNano()}) + }) + 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) + world.advanceCombat(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + if err := os.MkdirAll(filepath.Join(output, phase), 0755); err != nil { + t.Fatal(err) + } + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_kerans.mjs"), host.URL, filepath.Join(output, phase)) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + cancel() + <-stopped + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("VACUUM INTO ?", filepath.Join(output, phase, "world.sqlite")); err != nil { + t.Fatal(err) + } + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + expected := []ownedItem{ + {ID: 2, Type: 51018, Template: 160477, Quality: 50, Slot: 65, Count: 1}, + {ID: 3, Type: 51018, Template: 160477, Quality: 98, Slot: 66, Count: 1}, + {ID: 4, Type: 51018, Template: 160479, Quality: 100, Slot: 6, Count: 1, Ammo: 119}, + {ID: 5, Type: 51018, Template: 160478, Quality: 101, Slot: 68, Count: 1}, + {ID: 6, Type: 51005, Template: 21605, Quality: 1, Slot: 69, Count: 80}, + } + + if !slices.Equal(owner.inventory.Items, expected) || owner.inventory.Credits != 145 || owner.health == 0 || + len(watcher.inventory.Items) != 0 || + watcher.inventory.Credits != 0 || world.nextItem != 6 || owner.effectiveAbility(20) != 304 || owner.stats.Abilities.Sense != 300 || owner.attackRating() != 475 || owner.maximumNano() != 1050 { + t.Fatal("native wear, sale or cold recovery lost an instance or cash", owner.inventory) + } + }) + if t.Failed() { + return + } + } +} diff --git a/server/gamedata/item_families.yaml b/server/gamedata/item_families.yaml @@ -24,6 +24,9 @@ - [124260, 124261] # Old Springfield Arms Home Defender: docs/home-defender.md. - [124230, 124231] +# OT Kerans Automatic Grinner: original descriptor audits; docs/kerans.md. +- [160476, 160477] +- [160478, 160479] # Unbalanced Advanced Baseballbat: original payload audit; docs/early-melee.md. - [122691, 122692] # Kinetic Axe: original descriptor audit; docs/kinetic-axe.md. diff --git a/server/gamedata/item_quality_test.go b/server/gamedata/item_quality_test.go @@ -21,6 +21,7 @@ func TestReviewedItemFamilyQualityRanges(t *testing.T) { {160288, 160289, 1, 98}, {125456, 125457, 10, 159}, {124256, 124257, 1, 4}, {124258, 124259, 5, 69}, {124260, 124261, 70, 179}, {124230, 124231, 1, 15}, + {160476, 160477, 1, 98}, {160478, 160479, 99, 199}, {70558, 85640, 1, 200}, {70559, 85689, 1, 200}, {70560, 85688, 1, 200}, {70561, 85744, 1, 200}, {70562, 85597, 1, 200}, {70563, 85558, 1, 200}, {70564, 85515, 1, 200}, {70565, 85514, 1, 200}, {85481, 85690, 1, 200}, {85521, 85520, 1, 200}, {85562, 85561, 1, 200}, {85602, 85601, 1, 200}, @@ -59,6 +60,7 @@ func TestUnreviewedItemQualityRemainsExact(t *testing.T) { supported bool }{{209285, 25, true}, {209285, 26, false}, {85557, 0, false}, {161966, 200, true}, {161966, 199, false}, {160417, 1, true}, {160417, 2, false}, + {160480, 200, true}, {160480, 199, false}, {160480, 201, false}, {124262, 180, true}, {124262, 179, false}, {124262, 181, false}, {124232, 16, true}, {124232, 17, false}, {125458, 160, true}, {125458, 161, false}, {129028, 21, true}, {129028, 22, false}, {160290, 99, true}, {160290, 100, false}, {4294967295, 1, false}} { t.Run(fmt.Sprintf("%d/%d", entry.template, entry.quality), func(t *testing.T) { diff --git a/server/kerans_quality_test.go b/server/kerans_quality_test.go @@ -0,0 +1,368 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "slices" + "testing" + "time" +) + +func TestKeransQualitiesEnforceWearBoundariesAndRecover(t *testing.T) { + for _, row := range []struct { + low, high, quality, maximum, critical, value uint32 + smg, burst uint16 + sense int32 + }{ + {160476, 160477, 1, 26, 24, 2874, 6, 6, 2}, {160476, 160477, 2, 27, 25, 2888, 11, 10, 2}, + {160476, 160477, 49, 91, 89, 36324, 233, 176, 2}, {160476, 160477, 50, 92, 91, 37732, 237, 179, 2}, + {160476, 160477, 97, 156, 155, 136674, 459, 345, 2}, {160476, 160477, 98, 157, 156, 139476, 464, 349, 2}, + {160478, 160479, 99, 158, 157, 142292, 469, 353, 4}, {160478, 160479, 100, 159, 158, 142334, 474, 357, 4}, + {160478, 160479, 149, 226, 226, 248990, 705, 530, 4}, {160478, 160479, 150, 227, 227, 253300, 710, 533, 4}, + {160478, 160479, 198, 293, 293, 560590, 936, 702, 4}, {160478, 160479, 199, 294, 294, 569084, 941, 706, 4}, + {160480, 160480, 200, 295, 295, 574803, 946, 710, 6}, + } { + for _, template := range slices.Compact([]uint32{row.low, row.high}) { + for _, failed := range []uint32{0, 114, 148} { + t.Run(fmt.Sprintf("%d/QL%d/below%d", template, row.quality, failed), func(t *testing.T) { + world, output := newEquipmentWorld(t) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Ranged.SubmachineGun, player.stats.Ranged.Burst = row.smg, row.burst + if failed == 114 { + player.stats.Ranged.SubmachineGun-- + } + if failed == 148 { + player.stats.Ranged.Burst-- + } + player.inventory.Items[0].Template, player.inventory.Items[0].Quality = template, row.quality + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + started := time.Now() + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment != nil { + finish := client.equipment.readyAt + if finish.Before(started.Add(3500*time.Millisecond)) || finish.After(time.Now().Add(3500*time.Millisecond)) { + t.Fatal("Kerans equip delay differs") + } + world.advanceEquipment(finish.Add(-time.Nanosecond)) + if player.inventory.Items[0].Slot != 64 { + t.Fatal("weapon moved before its deadline") + } + world.advanceEquipment(finish) + } + cold := newTestInventoryServer(t).characters[1] + + expected := ownedItem{ID: 1, Type: 51018, Template: template, Quality: row.quality, Slot: 64, Count: 1} + if failed == 0 { + expected.Slot = 6 + } + if !slices.Equal(player.inventory.Items, []ownedItem{expected}) || !slices.Equal(cold.inventory.Items, []ownedItem{expected}) { + t.Fatal("wear boundary lost the selected instance", player.inventory, cold.inventory) + } + bonus := int32(0) + if failed == 0 { + bonus = row.sense + } + if player.equipmentBonus(20) != bonus || cold.equipmentBonus(20) != bonus || cold.stats.Abilities.Sense != 1 || cold.effectiveAbility(20) != 1+bonus { + t.Fatal("Sense bonus was lost, applied on refusal or persisted into raw abilities") + } + if failed != 0 { + return + } + weapon := cold.attackWeapon() + if weapon == nil { + t.Fatal("qualified weapon did not survive cold loading") + } + for stat, value := range map[uint32]uint32{286: 1, 285: row.maximum, 284: row.critical, 74: row.value, 294: 150, 210: 145, 211: 350, 287: 27, 440: 119, 436: 96, 420: 2, 212: 120, 374: 1500} { + if itemStat(weapon, stat) != value { + t.Fatal("selected property differs", stat, itemStat(weapon, stat), value) + } + } + low, high := row.low, row.high + if row.quality == *gamedata.ItemTemplates[low].Quality { + high = low + } else if row.quality == *gamedata.ItemTemplates[high].Quality { + low = high + } + var delivered []byte + for _, packet := range output.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x3b1d2268 { + delivered = packet + } + } + if len(delivered) < 91 || binary.BigEndian.Uint32(delivered[71:75]) != row.quality || binary.BigEndian.Uint32(delivered[79:83]) != low || binary.BigEndian.Uint32(delivered[87:91]) != high { + t.Fatal("native delivery lost quality or endpoints") + } + }) + } + } + } +} + +func TestKeransSelectedDamageTimingAndAmmunition(t *testing.T) { + for _, row := range []struct{ template, quality, normal, critical uint32 }{ + {160476, 1, 104, 200}, {160476, 2, 108, 208}, {160476, 49, 364, 720}, {160476, 50, 368, 732}, + {160476, 97, 624, 1244}, {160476, 98, 628, 1252}, {160478, 99, 632, 1260}, {160478, 100, 636, 1268}, + {160478, 149, 904, 1808}, {160478, 150, 908, 1816}, {160478, 198, 1172, 2344}, {160478, 199, 1176, 2352}, {160480, 200, 1180, 2360}, + } { + for _, critical := range []bool{false, true} { + t.Run(fmt.Sprintf("QL%d/critical%v", row.quality, critical), func(t *testing.T) { + world, output := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + target.position, target.health = [3]float32{1, 0, 0}, 10000 + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Ranged.SubmachineGun, player.stats.Ranged.Burst = 1200, 1000 + player.stats.Speed.RangedInitiative, player.aggDef = 0, 75 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality, player.inventory.Items[0].Ammo = row.template, row.quality, 20 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.combatRoll = func(limit uint32) uint32 { + if limit == 10000 || limit == 100 && critical { + return 0 + } + return limit - 1 + } + + if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + hit := player.nextAttack + world.advanceCombat(hit) + cold := newTestInventoryServer(t) + + damage := row.normal + if critical { + damage = row.critical + } + attack, recharge := 1500*time.Millisecond, 1450*time.Millisecond + if row.quality == 200 { + attack, recharge = 1490*time.Millisecond, 1440*time.Millisecond + } + if target.health != 10000-damage || player.rechargeUntil.Sub(hit) != recharge || player.nextAttack.Sub(hit) != attack+recharge || player.inventory.Items[0].Ammo != 19 || cold.characters[1].inventory.Items[0].Ammo != 19 || player.inventory.Items[1].Count != 100 { + t.Fatal("selected damage, cadence or rounds differ", target.health, player.inventory, player.nextAttack.Sub(hit), player.rechargeUntil.Sub(hit)) + } + if !slices.ContainsFunc(output.packets, func(packet []byte) bool { + return binary.BigEndian.Uint32(packet[16:20]) == 0x46002f16 && binary.BigEndian.Uint32(packet[24:28]) == 1 && binary.BigEndian.Uint32(packet[33:37]) == 19 + }) { + t.Fatal("shot did not publish its retained rounds") + } + }) + } + } +} + +func TestKeransReloadRequiresBullets(t *testing.T) { + for _, row := range []struct{ template, quality uint32 }{{160476, 2}, {160477, 50}, {160478, 100}, {160479, 149}} { + t.Run(fmt.Sprintf("%d/QL%d", row.template, row.quality), func(t *testing.T) { + world, _ := newRangedWorld(t) + player := world.characters[1] + player.inventory.Items[0].Template, player.inventory.Items[0].Quality = row.template, row.quality + player.inventory.Items[1].Template, player.inventory.Items[1].Count = 21613, 200 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + request := explicitReloadRequest(1, 48, 1) + decodeInventory1491(request) + + if err := world.handleReload(world.clients[1], request); err != nil { + t.Fatal(err) + } + if after, err := readTestItemStore(world); err != nil || !bytes.Equal(before, after) { + t.Fatal("wrong shells changed the store", err) + } + player.inventory.Items[1].Template = 21605 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + request = explicitReloadRequest(2, 48, 1) + decodeInventory1491(request) + for range 2 { + if err := world.handleReload(world.clients[1], request); err != nil { + t.Fatal(err) + } + } + cold := newTestInventoryServer(t).characters[1] + + if player.inventory.Items[0].Ammo != 120 || player.inventory.Items[1].Count != 83 || !slices.Equal(player.inventory.Items, cold.inventory.Items) { + t.Fatal("bullet reload lost or duplicated rounds", player.inventory, cold.inventory) + } + }) + } +} + +func TestKeransUsesDodgeRangedInsteadOfDuck(t *testing.T) { + for _, dodge := range []uint16{0, 10000} { + t.Run(fmt.Sprint(dodge), func(t *testing.T) { + world, output := newRangedWorld(t) + player, target := world.characters[1], world.characters[1000000] + player.appearance = 0x515 + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Ranged.SubmachineGun, player.stats.Ranged.Burst = 1200, 1000 + player.inventory.Items[0].Template, player.inventory.Items[0].Quality, player.inventory.Items[0].Ammo = 160476, 2, 20 + target.position, target.stats.Speed.DodgeRanged, target.stats.Speed.DuckExplosions = [3]float32{1, 0, 0}, dodge, 10000-dodge + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.combatRoll = func(limit uint32) uint32 { + if limit == 10000 { + return 5000 + } + return limit - 1 + } + + if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack) + + health, opcode := uint32(892), uint32(0x46002f16) + if dodge != 0 { + health, opcode = 1000, 0x5c654b28 + } + if target.health != health || !slices.ContainsFunc(output.packets, func(packet []byte) bool { + return binary.BigEndian.Uint32(packet[16:20]) == opcode && binary.BigEndian.Uint32(packet[24:28]) == player.id + }) { + t.Fatal("Kerans used the wrong defense skill", target.health) + } + }) + } +} + +func TestKeransGeneratedPickupEquipRemoveAndSale(t *testing.T) { + for _, scenario := range []struct { + template, quality uint32 + smg, burst uint16 + sense int32 + credits uint32 + }{ + {160476, 2, 11, 10, 2, 145}, {160477, 2, 11, 10, 2, 145}, + {160476, 50, 237, 179, 2, 1887}, {160477, 50, 237, 179, 2, 1887}, + {160478, 100, 474, 357, 4, 7117}, {160479, 100, 474, 357, 4, 7117}, + {160478, 149, 705, 530, 4, 12450}, {160479, 149, 705, 530, 4, 12450}, + } { + t.Run(fmt.Sprintf("%d/QL%d", scenario.template, scenario.quality), func(t *testing.T) { + world, _ := newKillExperienceWorld(t, "unarmed") + // Controlled membership tests delivery, not historical Leet equipment drops. + profile := *world.characters[1000000].combatProfile + profile.Loot = []gamedata.NPCLoot{{Template: scenario.template, Quality: [2]uint32{scenario.quality, scenario.quality}, Chance: 100}} + world.characters[1000000].combatProfile = &profile + world.combatRoll = func(uint32) uint32 { return 0 } + identity := world.nextItem + 1 + + attackForExperience(t, world, "unarmed") + if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil { + t.Fatal(err) + } + } + world = newTestInventoryServer(t) + player := world.characters[1] + player.appearance = 0x515 + client := &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true} + world.clients[1] = client + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.Ranged.SubmachineGun, player.stats.Ranged.Burst = scenario.smg-1, scenario.burst + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment != nil || + len(player.inventory.Items) != 1 || player.inventory.Items[0].ID != identity || player.inventory.Items[0].Slot != 64 { + t.Fatal("rejected wear lost the picked-up instance", err) + } + player.stats.Ranged.SubmachineGun++ + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + for _, move := range [][2]uint32{{64, 6}, {6, 64}, {64, 6}, {6, 64}} { + request := inventoryMovePacket(1, move[0], move[1]) + if move[0] < 64 { + request = itemMovePacket(1, move[0], move[1]) + } + if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil { + t.Fatal("generated selected-quality weapon did not move", err) + } + world.advanceEquipment(client.equipment.readyAt) + cold := newTestInventoryServer(t) + sense := int32(0) + if move[1] == 6 { + sense = scenario.sense + } + if player.equipmentBonus(20) != sense || cold.characters[1].equipmentBonus(20) != sense { + t.Fatal("repeated wear lost or duplicated Sense") + } + expected := []ownedItem{{ID: identity, Type: 51018, Template: scenario.template, Quality: scenario.quality, Slot: move[1], Count: 1}} + if !slices.Equal(player.inventory.Items, expected) || !slices.Equal(cold.characters[1].inventory.Items, expected) || + len(cold.characters[1000000].corpse.items) != 0 || cold.characters[1].inventory.Credits != 1 || cold.nextItem != identity { + t.Fatal("pickup, repeated wear or cold recovery lost or duplicated the weapon") + } + } + + // Sell that same instance after cancellation and a cold reconnect. + player.appearance = 0x515 + player.position = [3]float32{60, 14.75, 53} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if err := world.handleShopUse(client, shopUseRequest(1)); err != nil { + t.Fatal(err) + } + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + if len(cold.characters[1].inventory.Items) != 1 || cold.characters[1].inventory.Credits != 1 { + t.Fatal("cancelled sale lost the selected-quality weapon") + } + world, player = cold, cold.characters[1] + client = &worldClient{id: 1, conn: &combatTestConn{}, target: true, ready: true} + world.clients[1] = client + if err := world.handleShopUse(client, shopUseRequest(1)); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, add); err != nil { + t.Fatal(err) + } + for range 2 { + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + } + cold = newTestInventoryServer(t) + + for _, current := range []*server{world, cold} { + if len(current.characters[1].inventory.Items) != 0 || current.characters[1].inventory.Credits != scenario.credits || + current.characters[1].experience != 100 || current.nextItem != identity { + t.Fatal("selected-quality sale lost or repeated value, rewards or an instance", current.characters[1].inventory) + } + if _, exists := current.items[identity]; exists { + t.Fatal("sold weapon returned in the shared cache") + } + } + }) + } +} diff --git a/tools/client/test_kerans.mjs b/tools/client/test_kerans.mjs @@ -0,0 +1,181 @@ +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 = {}; +async function bagClick(game, id, button = 'right') { + await game.wait('native equipment action finishes', state => + !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6)); + const cell = game.local().inventory.find(item => item.id === id).slot - 48; + assert(cell >= 0 && cell < 9); + await game.click(681 + cell % 3 * 54, 45 + Math.floor(cell / 3) * 54, button); +} +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'kerans-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + evidence.initial = await state(); + if (evidence.initial.inventory.Items.length === 6) { + assert.equal(owner.local().stats[4], 1); + assert.equal(owner.local().stats[114], 400); + assert.equal(owner.local().stats[148], 283); + await owner.key('KeyI'); + await owner.page.keyboard.press('Control+1'); + for (const id of [1, 2, 3, 4]) { + const sequence = observer.sequence; + await bagClick(owner, id); + await owner.wait('selected Kerans worn', snapshot => owner.local(snapshot).inventory.some(item => item.id === id && item.slot === 6)); + await observer.wait('observer receives selected Kerans', () => observer.events.some(event => + event.sequence > sequence && event.direction === 'framereceived' && event.opcode === '3b1d2268' && + event.actor[0] === 51018 && event.actor[1] === id)); + const event = observer.events.find(event => event.sequence > sequence && event.direction === 'framereceived' && + event.opcode === '3b1d2268' && event.actor[0] === 51018 && event.actor[1] === id); + const packet = Buffer.from(event.hex, 'hex'), stats = new Map(); + for (let offset = 59; offset < packet.readUInt16BE(6) - 4; offset += 8) + stats.set(packet.readUInt32BE(offset), packet.readUInt32BE(offset + 4)); + const [quality, definition, maximum, critical, value, low, high, sense] = { + 1: [2, 160476, 27, 25, 2888, 160476, 160477, 2], + 2: [50, 160477, 92, 91, 37732, 160476, 160477, 2], + 3: [98, 160477, 157, 156, 139476, 160477, 160477, 2], + 4: [100, 160478, 159, 158, 142334, 160478, 160479, 4], + }[id]; + assert.equal(stats.get(23), definition); + const base = { + 160476: {74: 2874, 284: 24, 285: 26, 286: 1, 294: 150}, + 160477: {74: 139476, 284: 156, 285: 157, 286: 1, 294: 150}, + 160478: {74: 142292, 284: 157, 285: 158, 286: 1, 294: 150}, + }[definition]; + for (const [stat, expected] of Object.entries({74: value, 284: critical, 285: maximum, + 286: 1, 294: 150, 701: quality, 702: low, 703: high})) + assert.equal(stats.get(Number(stat)) ?? base[stat], expected, 'selected Kerans stat ' + stat); + const worn = await state(); + assert.equal(worn.sense, 300 + sense); + assert.equal(worn.rating, 475); + assert.equal(worn.maxNano, 1050); + await owner.wait('native ability-derived foundations', snapshot => + owner.local(snapshot).stats[22] === 475 && owner.local(snapshot).stats[221] === 1050); + if (id >= 3) { + await owner.key('KeyU'); + await owner.save(output + '/sense-' + sense); + await owner.key('KeyU'); + } + evidence['worn' + id] = {native: owner.local().inventory, server: await state()}; + await owner.save(output + '/worn-' + id); + if (id !== 4) { + await owner.click(867, 206, 'right'); + await owner.wait('same Kerans removed', snapshot => owner.local(snapshot).inventory.some(item => item.id === id && item.slot >= 48)); + assert.equal((await state()).sense, 300); + assert.equal((await state()).maxNano, 1047); + } + } + const rejected = await state(), rejectionSequence = owner.sequence; + await bagClick(owner, 5); + await owner.save(output + '/rejected-101'); + assert(!owner.events.some(event => event.sequence > rejectionSequence && event.direction === 'framesent' && event.opcode === '47537a24')); + assert.deepEqual((await state()).inventory, rejected.inventory); + + // Native ammunition-on-weapon input loads exactly one hundred twenty bullets. + await bagClick(owner, 6, 'left'); + await owner.click(867, 206, 'right'); + await owner.wait('bullet stack debited', snapshot => owner.local(snapshot).inventory.some(item => item.id === 6 && item.count === 80)); + assert.equal((await state()).inventory.Items[3].Ammo, 120); + await owner.wait('native reload completes', snapshot => !owner.local(snapshot).actions.includes(5)); + + // An ordinary Q attack consumes one round from the selected QL100 instance. + const deadline = Date.now() + 10000; + while (owner.state.selected[0] !== 50000 || owner.state.selected[1] !== rejected.target) { + assert(Date.now() < deadline, 'Native Tab did not select the controlled Leet'); + const selected = owner.state.selected; + await owner.key('Tab'); + await owner.wait('native target cycle advances', snapshot => snapshot.selected[0] !== selected[0] || snapshot.selected[1] !== selected[1]); + } + const attack = owner.sequence; + await owner.key('KeyQ'); + await owner.wait('ordinary selected-quality hit', () => owner.events.some(event => event.sequence > attack && + event.direction === 'framereceived' && event.opcode === '46002f16' && event.actor[1] === owner.local().id)); + const result = owner.events.find(event => event.sequence > attack && event.direction === 'framereceived' && + event.opcode === '46002f16' && event.actor[1] === owner.local().id); + assert.equal(Buffer.from(result.hex, 'hex').readUInt32BE(33), 119); + await owner.key('KeyQ'); + await Promise.all(games.map(game => game.wait('native selected-quality impact', snapshot => + snapshot.actors.some(actor => actor.id === rejected.target && actor.stats[27] === 98)))); + evidence.hit = await state(); + assert.equal(evidence.hit.health, 98); + assert.equal(evidence.hit.fighting, 0); + assert.equal(evidence.hit.inventory.Items[3].Ammo, 119); + await owner.save(output + '/hit'); + + // Cancel, then accept the QL2 instance's sale at the original training machine. + await owner.page.keyboard.press('Control+1'); + await owner.wait('weapon panel closed', snapshot => !snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 360)); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + const offered = await state(); + for (let attempt = 0; attempt < 2; ++attempt) { + await owner.click(...await owner.pick(51035, 3221226422), 'right'); + await owner.wait('training machine open', snapshot => snapshot.regions.some(([left, top, right, bottom]) => + left === 832 && top === 0 && right === 1024 && bottom === 494)); + const cell = owner.local().inventory.find(item => item.id === 1).slot - 48; + await owner.click(681 + cell % 3 * 54, 45 + Math.floor(cell / 3) * 54); + const sequence = owner.sequence; + await owner.click(864, 416); + await owner.wait('sale offered', () => owner.events.some(event => event.sequence > sequence && + event.direction === 'framesent' && event.opcode === '36284f6e')); + assert.deepEqual((await state()).inventory, offered.inventory); + await owner.save(output + '/sale-offer-' + attempt); + if (attempt === 0) { + await owner.click(945, 475); + await owner.wait('cancelled Kerans restored', snapshot => owner.local(snapshot).inventory.some(item => item.id === 1 && item.slot === 48)); + assert.deepEqual((await state()).inventory, offered.inventory); + } + } + await owner.click(874, 475); + await owner.wait('exact selected-quality sale', snapshot => owner.local(snapshot).stats[61] === 145); + evidence.sale = await state(); + await owner.page.reload(); + await owner.ready(); + } + assert.deepEqual(owner.local().inventory.map(item => [item.id, item.slot, item.quality, ...item.templates, item.count]).sort((a, b) => a[0] - b[0]), [ + [2, 49, 50, 160476, 160477, 1], [3, 50, 98, 160477, 160477, 1], + [4, 6, 100, 160478, 160479, 1], [5, 52, 101, 160478, 160479, 1], [6, 53, 1, 21605, 21605, 80], + ]); + assert.equal(owner.local().stats[61], 145); + assert.deepEqual(observer.local().inventory.map(item => [item.id, item.slot, item.quality, ...item.templates, item.count]), + []); + evidence.final = {native: owner.local().inventory, server: await state()}; + assert.equal(evidence.final.server.inventory.Items[2].Ammo, 119); + assert(evidence.final.server.ownerHealth > 0); + assert.equal(evidence.final.server.sense, 304); + assert.equal(owner.local().stats[22], 475); + assert.equal(owner.local().stats[221], 1050); + assert.equal(observer.local().stats[221], 1047); + await owner.key('KeyU'); + await owner.save(output + '/retained-sense'); + await owner.key('KeyU'); + if (!owner.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104 && !cell.dummy))) { + await owner.key('KeyI'); + await owner.wait('retained inventory opens', snapshot => snapshot.grids.some(grid => + grid.cells.some(cell => cell.identity[0] === 104 && !cell.dummy))); + } + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: native Kerans qualities, wear/removal, strict refusal, bullet reload/shot, exact sale and page/cold ownership'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2)); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +}