aorecomp

Anarchy Online classic in the browser

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


commit 1bcbadb5a1b7511227b622b06eaa8b0959e7b5e7
parent 1073efbe4f815105367411936e78507c716cca41
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 01:26:39 +0000

Copy bound mission keys through native item combination

Diffstat:
MTODO.md | 9+++++++--
Mdocs/mission-acceptance.md | 4+++-
Adocs/mission-keys.md | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_mission_key_copy_test.go | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/item_database.go | 17+++++++++++++++++
Mserver/item_store.go | 1+
Aserver/mission_key_copy.go | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_key_copy_test.go | 286+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/tradeskills.go | 3+++
Atools/client/test_mission_key_copy.mjs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 619 insertions(+), 3 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -2463,8 +2463,13 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). keys identify their assigned destination in the native UI, copies retain the same assignment, and door admission follows actual key-instance bindings. Current keys show the base "Mission Key to" name; the server persists their - contract association and support bound-key entry; native destination metadata - remains unimplemented. Cover held, banked, traded, deleted and reclaimed keys; possession + contract association and supports bound-key entry. Native action81 copying + now preserves both inputs and atomically binds a distinct key to the same + assignment. Focused handler checks cover traded-key copying and copied-key-only + cold entry; a short WASM check verifies usable inputs/result and page replay. + Native destination metadata and ordinary duplicator shop acquisition remain + unimplemented. See [mission keys](docs/mission-keys.md). + Cover held, banked, traded, deleted and reclaimed keys; possession of an unrelated template28577 must never admit a player to another mission. - [x] [P1] Trace zero native identities on simple mission inventory proxies. Original `kkr.dll` constructors `0x1002d010`/`0x1002d580` leave the simple diff --git a/docs/mission-acceptance.md b/docs/mission-acceptance.md @@ -27,7 +27,9 @@ the newly allocated first key's numeric instance ID in the distinct56003 quest identity namespace. `mission_keys` binds actual item instances to missions; template28577 alone is not an admission credential. Its first key is original type51053/QL1. Deleting a key removes its binding, without deleting the contract. -Copying keys and their usable native destination metadata remain open. +Native copying now creates a separately bound instance while retaining the +original and duplicator; see [mission keys](mission-keys.md). Usable native +destination metadata remains open. The shared inventory transaction persists item allocation, placement, contract and key binding before publishing live state. Ignored inserts are detected with diff --git a/docs/mission-keys.md b/docs/mission-keys.md @@ -0,0 +1,62 @@ +# Mission key copying + +The original Mission Key Duplicator28564 creates another key to the source +key's accepted assignment. Both inputs remain owned. Each result is a distinct +type51053/template28577/QL1 instance with its own durable `mission_keys` row; +the template, slot, journal owner and numeric mission ID are not credentials. + +## Source and native request + +Shipped template28564 is type51054/QL1, with Carry/Use capabilities and no +authored sections or charges. Its description specifies picking up the tool +and using it on a Mission Key, then giving copies to friends; possession admits +entry without team membership. Template28577 is type51053/QL1 with base name +`Mission Key to`. Original payload hashes are respectively +`acca734f1dbcfa07e880e8d2e8baa83244da1b0f4824eee026008b8f2d4e81d6` and +`d97843d6c7ac43741bcc808046d2cbb1ba7991d279aa222bb15624c7d640f72c`. +The shipped `text/help/The Mission Window.txt` independently describes tools +from shops for duplicating mission keys. + +The native WASM check picks up the ordinary duplicator and Shift-right-clicks +the ordinary key. The actual request is CharacterAction81: +`{81,104,sourceNativeSlot,104,targetNativeSlot}`. The captured source50/target49 +translate to saved slots66/65. An unmodified right-click emitted no request; +the generic Use5 contract alone was insufficient evidence of key-copy routing. +The server previously replied with ordinary combination failure `{84,2,0,0,0}`. +Captures are retained in `local/mission-key-copy/`. + +## Atomic behavior and boundaries + +The existing combination handler authenticates the current living, ready +session, distinct carried slots and busy inventory state. Copying requires the +exact QL1/count1 duplicator and key types, an actual source-key binding, a live +uncompleted assignment and a free ordinary slot. A banked or reclaimed key is +not a carried combination target. Keys received from another player use their +binding independently of journal ownership or team membership. + +The new key, first-free placement, global allocation and assignment binding +commit in one inventory transaction. Required insertion and final binding/item/ +placement verification precede COMMIT and native AddTemplate delivery. Failed +or ignored writes and failed COMMIT publish no result. Lost output preserves +the committed copy for reconnect. No XP, credit reward or extra journal is +granted. Copies use the existing key revocation and physical ownership rules. + +Action81 has no operation nonce. Each admitted request intentionally creates +another distinct copy, including when the source is itself a copy. Concurrent +requests serialize allocation; this does not promise exactly-once retries after +the referenced inputs remain reusable. + +`TestMissionKeyCopy*` verifies native socket dispatch, copied-key-only cold +entry, invalid inputs and unavailable assignments, full inventory, eight +transaction failures and retry, concurrent copies, lost output, and an actual +player trade followed by guest copying and entry. `TestBrowserMissionKeyCopy` +verifies the real native gesture, exact packet, newly usable key, restored +reusable inputs, unchanged cash, page replay and cold database loading. Its +accepted contract and provisioned tool isolate copying; this is not earned +progression or evidence of ordinary tool acquisition. + +Destination-specific native naming and ordinary duplicator shop acquisition +remain open. Copies still display the original base name. The bounded naming +investigation is retained in `local/mission-key-metadata/`; do not invent an +instance identity or name message to conceal that evidence gap. Historical key +retention after completion/abandonment remains separately unresolved. diff --git a/server/browser_mission_key_copy_test.go b/server/browser_mission_key_copy_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" +) + +func TestBrowserMissionKeyCopy(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for mission key copying") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/mission-key-copy", time.Now().Format("20060102-150405")) + world, _ := newAcceptedMissionWorld(t) + player := world.characters[1] + if granted, err := world.grantItem_locked(player, 28564); err != nil || !granted { + t.Fatal(granted, err) + } + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("mission-key-copy"))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + before := player.inventory + if err := world.db.Close(); err != nil { + t.Fatal(err) + } + world = newServerForTest(t) + 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() + bindings := make(map[uint32]uint32) + rows, err := world.db.Query("SELECT item_id, mission_id FROM mission_keys ORDER BY item_id") + if err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer rows.Close() + for rows.Next() { + var item, mission uint32 + if err := rows.Scan(&item, &mission); err != nil { + t.Error(err) + return + } + bindings[item] = mission + } + if err := rows.Err(); err != nil { + t.Error(err) + return + } + json.NewEncoder(w).Encode(map[string]any{"inventory": world.characters[1].inventory, "bindings": bindings}) + }) + 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_mission_key_copy.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) + items := cold.characters[1].inventory.Items + if len(items) != 4 || !reflect.DeepEqual(items[:3], before.Items) || + items[3] != (ownedItem{ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 67, Count: 1}) || + cold.nextItem != 4 || cold.characters[1].inventory.Credits != before.Credits { + t.Fatal("copy lost the tool, original key, selected assignment or cold ownership") + } + var mission uint32 + if err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=4").Scan(&mission); err != nil || mission != 2 { + t.Fatal("copied key lost its cold assignment", mission, err) + } +} diff --git a/server/item_database.go b/server/item_database.go @@ -253,6 +253,13 @@ func (server *server) persistItems_locked(store itemStore) error { savedNPCs[npc.id] = savedNPC{State: state, NextSave: time.Now().Add(20 * time.Second)} } } + if store.copiedMissionKey != nil { + var savedID uint32 + if err := tx.QueryRow("INSERT INTO mission_keys (item_id, mission_id) VALUES (?, ?) RETURNING item_id", + store.copiedMissionKey.itemID, store.copiedMissionKey.missionID).Scan(&savedID); err != nil { + return fmt.Errorf("save copied mission key: %w", err) + } + } if store.updatedMission != nil { mission := store.updatedMission var savedID uint32 @@ -413,6 +420,16 @@ func (server *server) persistItems_locked(store itemStore) error { } } } + if store.copiedMissionKey != nil { + key := store.copiedMissionKey + placement := placements[key.itemID] + if err := tx.QueryRow(`SELECT k.item_id FROM mission_keys k JOIN items i ON i.id=k.item_id + JOIN item_locations l ON l.item_id=k.item_id + WHERE k.item_id=? AND k.mission_id=? AND (i.type,i.template,i.quality,i.count,i.ammo) IS (51053,28577,1,1,0) + AND l.player_id=? AND l.slot=? AND l.reclaim_at IS NULL`, key.itemID, key.missionID, placement.Player, placement.Slot).Scan(&savedID); err != nil { + return fmt.Errorf("copied mission key was not saved: %w", err) + } + } if err := tx.Commit(); err != nil { return err } diff --git a/server/item_store.go b/server/item_store.go @@ -58,6 +58,7 @@ type itemStore struct { vitalUpdate *playerVitalUpdate skillLock *skillLockUpdate mission *acceptedMission + copiedMissionKey *missionKeyBinding updatedMission *acceptedMission removedMission *acceptedMission spawnedNPCs []*character diff --git a/server/mission_key_copy.go b/server/mission_key_copy.go @@ -0,0 +1,68 @@ +package main + +import ( + "database/sql" + "encoding/binary" + "fmt" + "slices" + "time" +) + +type missionKeyBinding struct { + itemID, missionID uint32 +} + +func (server *server) copyMissionKey_locked(client *worldClient, tool, original ownedItem) error { + refuse := func() error { + return client.send(characterActionPacket(client.id, [5]uint32{84, 2})) + } + if tool.Type != 51054 || tool.Quality != 1 || tool.Count != 1 || + original.Type != 51053 || original.Template != 28577 || original.Quality != 1 || original.Count != 1 { + return refuse() + } + + // Copy the actual held key's binding, including keys received from another owner. + var missionID uint32 + if err := server.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=?", original.ID).Scan(&missionID); err != nil { + if err == sql.ErrNoRows { + return refuse() + } + return err + } + if !slices.ContainsFunc(server.missionExpiry, func(mission acceptedMission) bool { + return mission.id == missionID && !mission.completed && time.Now().Before(mission.expiresAt) + }) { + return refuse() + } + player := server.characters[client.id] + slot := uint32(64) + for slot < 94 && slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == slot }) { + slot++ + } + if slot == 94 { + return refuse() + } + if server.nextItem == ^uint32(0) { + return fmt.Errorf("item identities exhausted") + } + + // Persist the new instance, placement and assignment together; retain both inputs. + copy := ownedItem{ID: server.nextItem + 1, Type: 51053, Template: 28577, Quality: 1, Slot: slot, Count: 1} + inventory := player.inventory + inventory.LastID = copy.ID + inventory.Items = append(slices.Clone(inventory.Items), copy) + store, err := server.itemStore_locked(player, inventory) + if err != nil { + return err + } + store.copiedMissionKey = &missionKeyBinding{copy.ID, missionID} + if err := server.writeItemStore_locked(store); err != nil { + return err + } + player.inventory = inventory + var addition []byte + for _, value := range []uint32{28577, 28577, 1, 1} { + addition = binary.BigEndian.AppendUint32(addition, value) + } + return client.send(n3Packet(0x052e2f0c, 50000, client.id, addition)) +} diff --git a/server/mission_key_copy_test.go b/server/mission_key_copy_test.go @@ -0,0 +1,286 @@ +package main + +import ( + "bytes" + "encoding/binary" + "net" + "reflect" + "slices" + "sync" + "testing" + "time" +) + +func newMissionKeyCopyWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, output := newAcceptedMissionWorld(t) + if granted, err := world.grantItem_locked(world.characters[1], 28564); err != nil || !granted { + t.Fatal(granted, err) + } + output.packets = nil + return world, output +} + +func TestMissionKeyCopyNativeDispatchAndColdEntryWithoutOriginal(t *testing.T) { + newMissionKeyCopyWorld(t) + world := reloadMissionEntranceWorld(t) + connection := connectZoningClient(t, world, true) + defer connection.Close() + + if _, err := connection.Write(targetPacket(characterActionPacket(1, [5]uint32{81, 104, 66, 104, 65}))); err != nil { + t.Fatal(err) + } + addition, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + player := cold.characters[1] + client := &worldClient{id: 1, target: true, ready: true, conn: &combatTestConn{}} + cold.clients[1] = client + if err := cold.handleInventory(client, characterActionPacket(1, [5]uint32{112, 104, 65, 28577, 28577})[20:]); err != nil { + t.Fatal(err) + } + player.geometry = cold.geometry + player.position, player.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0} + if err := cold.handleMovement(client, playerMovementRequest(player, 1)); err != nil { + t.Fatal(err) + } + restored := reloadMissionEntranceWorld(t) + var key, binding uint32 + err = restored.db.QueryRow("SELECT item_id,mission_id FROM mission_keys").Scan(&key, &binding) + + if err != nil || key != 4 || binding != 2 || restored.characters[1].playfield != 65536 || + world.characters[1].playfield != 3000 || restored.nextItem != 5 || restored.characters[1].inventory.Credits != 4 || + !slices.Equal(restored.characters[1].inventory.Items, []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51054, Template: 28564, Quality: 1, Slot: 66, Count: 1}, + {ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 67, Count: 1}}) { + t.Fatalf("copy admission: key=%d binding=%d world=%d originalWorld=%d next=%d cash=%d items=%+v error=%v", key, binding, + restored.characters[1].playfield, world.characters[1].playfield, restored.nextItem, restored.characters[1].inventory.Credits, + restored.characters[1].inventory.Items, err) + } + if len(addition) != 45 || binary.BigEndian.Uint32(addition[16:20]) != 0x052e2f0c || + !bytes.Equal(addition[29:45], []byte{0, 0, 111, 161, 0, 0, 111, 161, 0, 0, 0, 1, 0, 0, 0, 1}) { + t.Fatal("native dispatch did not publish one QL1 key after its binding committed") + } +} + +func TestMissionKeyCopyRejectsUnsupportedInputsAndUnavailableAssignments(t *testing.T) { + for _, scenario := range []string{"tool type", "tool quality", "tool count", "key type", "key template", "key quality", "key count", "unbound", "expired", "completed", "full inventory", "banked key", "reclaimed key"} { + t.Run(scenario, func(t *testing.T) { + world, output := newMissionKeyCopyWorld(t) + player := world.characters[1] + request := combinationRequest(1, 66, 65) + switch scenario { + case "tool type": + player.inventory.Items[2].Type = 51005 + case "tool quality": + player.inventory.Items[2].Quality = 2 + case "tool count": + player.inventory.Items[2].Count = 2 + case "key type": + player.inventory.Items[1].Type = 51005 + case "key template": + player.inventory.Items[1].Template = 95577 + case "key quality": + player.inventory.Items[1].Quality = 2 + case "key count": + player.inventory.Items[1].Count = 2 + case "unbound": + if _, err := world.db.Exec("DELETE FROM mission_keys"); err != nil { + t.Fatal(err) + } + case "expired": + world.missionExpiry[0].expiresAt = time.Now().Add(-time.Second) + case "completed": + world.missionExpiry[0].completed = true + case "full inventory": + for range 27 { + if granted, err := world.grantItem_locked(player, 42640); err != nil || !granted { + t.Fatal(granted, err) + } + } + case "banked key", "reclaimed key": + inventory := player.inventory + key := inventory.Items[1] + inventory.Items = slices.Delete(slices.Clone(inventory.Items), 1, 2) + if scenario == "banked key" { + key.Slot = 0 + inventory.Bank = []ownedItem{key} + } else { + inventory.Reclaim = []reclaimItem{{Item: key, AvailableAt: time.Now().Add(time.Minute)}} + } + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + inventory, lastID := player.inventory, world.nextItem + auditCheckpointWrites(t, world) + + err = world.handleItemCombination(world.clients[1], request) + after, readErr := readTestItemStore(world) + + if err != nil || readErr != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + !reflect.DeepEqual(player.inventory, inventory) || world.nextItem != lastID { + t.Fatal("refused copy changed ownership or allocation", err, readErr) + } + if scenario == "banked key" || scenario == "reclaimed key" { + if len(output.packets) != 0 { + t.Fatal("a non-carried key was treated as a current combination target") + } + } else if !reflect.DeepEqual(output.packets, [][]byte{targetPacket(characterActionPacket(1, [5]uint32{84, 2}))}) { + t.Fatal("unsupported key copying omitted ordinary combination failure") + } + }) + } +} + +func TestMissionKeyCopyRollsBackRequiredWritesAndRetries(t *testing.T) { + for _, scenario := range []struct{ name, sql string }{ + {"item abort", "CREATE TRIGGER fail_copy BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(ABORT,'copy'); END"}, + {"item ignored", "CREATE TRIGGER fail_copy BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(IGNORE); END"}, + {"placement ignored", "CREATE TRIGGER fail_copy BEFORE INSERT ON item_locations WHEN NEW.item_id=4 BEGIN SELECT RAISE(IGNORE); END"}, + {"binding abort", "CREATE TRIGGER fail_copy BEFORE INSERT ON mission_keys BEGIN SELECT RAISE(ABORT,'binding'); END"}, + {"binding ignored", "CREATE TRIGGER fail_copy BEFORE INSERT ON mission_keys BEGIN SELECT RAISE(IGNORE); END"}, + {"late binding deletion", "CREATE TRIGGER fail_copy AFTER UPDATE OF last_item_id ON world BEGIN DELETE FROM mission_keys WHERE item_id=4; END"}, + {"late placement deletion", "CREATE TRIGGER fail_copy AFTER UPDATE OF last_item_id ON world BEGIN DELETE FROM item_locations WHERE item_id=4; END"}, + {"commit", "CREATE TABLE pending_copy (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_copy AFTER INSERT ON mission_keys BEGIN INSERT INTO pending_copy VALUES(999999); END"}, + } { + t.Run(scenario.name, func(t *testing.T) { + world, output := newMissionKeyCopyWorld(t) + before := world.characters[1].inventory + if _, err := world.db.Exec(scenario.sql); err != nil { + t.Fatal(err) + } + + failure := world.handleItemCombination(world.clients[1], combinationRequest(1, 66, 65)) + cold := newTestInventoryServer(t) + + var bindings int + if err := cold.db.QueryRow("SELECT count(*) FROM mission_keys").Scan(&bindings); err != nil { + t.Fatal(err) + } + if failure == nil || bindings != 1 || world.nextItem != 3 || cold.nextItem != 3 || len(output.packets) != 0 || + !reflect.DeepEqual(world.characters[1].inventory, before) || !reflect.DeepEqual(cold.characters[1].inventory, before) { + t.Fatal("failed copy published or retained an unbound key, spent inputs or lost allocation", failure) + } + + if _, err := world.db.Exec("DROP TRIGGER fail_copy"); err != nil { + t.Fatal(err) + } + if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 66, 65)); err != nil { + t.Fatal(err) + } + cold = newTestInventoryServer(t) + var mission uint32 + err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=4").Scan(&mission) + + if err != nil || mission != 2 || cold.nextItem != 4 || len(output.packets) != 1 || len(cold.characters[1].inventory.Items) != 4 || + !slices.Equal(cold.characters[1].inventory.Items[:3], before.Items) || cold.characters[1].inventory.Credits != 4 { + t.Fatal("copy retry lost an input or its exact bound result", err) + } + }) + } +} + +func TestMissionKeyCopyCanCopyACopyAndSerializeConcurrentCopies(t *testing.T) { + world, output := newMissionKeyCopyWorld(t) + client := world.clients[1] + if err := world.handleItemCombination(client, combinationRequest(1, 66, 65)); err != nil { + t.Fatal(err) + } + var pending sync.WaitGroup + failures := make(chan error, 2) + + for range 2 { + pending.Add(1) + go func() { + defer pending.Done() + failures <- world.handleItemCombination(client, combinationRequest(1, 66, 67)) + }() + } + pending.Wait() + close(failures) + cold := newTestInventoryServer(t) + var bindings int + err := cold.db.QueryRow("SELECT count(*) FROM mission_keys WHERE mission_id=2 AND item_id IN (2,4,5,6)").Scan(&bindings) + + for failure := range failures { + if failure != nil { + t.Fatal(failure) + } + } + if err != nil || bindings != 4 || cold.nextItem != 6 || len(cold.characters[1].inventory.Items) != 6 || len(output.packets) != 3 || + cold.characters[1].inventory.Items[2] != (ownedItem{ID: 3, Type: 51054, Template: 28564, Quality: 1, Slot: 66, Count: 1}) { + t.Fatal("copies of a copy lost reusable inputs, assignment or distinct atomic identities", err) + } +} + +func TestMissionKeyCopyOutputFailureRetainsCommittedBinding(t *testing.T) { + world, output := newMissionKeyCopyWorld(t) + client := world.clients[1] + client.writeWake, client.writeClosed = make(chan struct{}, 1), true + + failure := world.handleItemCombination(client, combinationRequest(1, 66, 65)) + cold := newTestInventoryServer(t) + var mission uint32 + err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=4").Scan(&mission) + + if failure != net.ErrClosed || err != nil || mission != 2 || cold.nextItem != 4 || len(output.packets) != 0 || len(cold.characters[1].inventory.Items) != 4 { + t.Fatal("lost output rolled back a committed copy or lost its binding", failure, err) + } +} + +func TestMissionKeyCopyTradedKeyCanBeCopiedAndAdmitItsNewHolder(t *testing.T) { + world, _ := newMissionKeyCopyWorld(t) + owner := world.characters[1] + data := owner.userData() + data.ID, data.Name = 2, "Key holder" + guest := data.character() + guest.geometry = world.geometry + world.characters[2] = guest + world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}} + if err := world.saveUser_locked(guest); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(guest, playerInventory{}); err != nil { + t.Fatal(err) + } + if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 66, 65)); err != nil { + t.Fatal(err) + } + + playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{}) + playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 67}) + playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{}) + playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{}) + if granted, err := world.grantItem_locked(guest, 28564); err != nil || !granted { + t.Fatal(granted, err) + } + if err := world.handleItemCombination(world.clients[2], combinationRequest(2, 65, 64)); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(world.clients[2], characterActionPacket(2, [5]uint32{112, 104, 64, 28577, 28577})[20:]); err != nil { + t.Fatal(err) + } + guest.position, guest.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0} + if err := world.handleMovement(world.clients[2], playerMovementRequest(guest, 1)); err != nil { + t.Fatal(err) + } + cold := reloadMissionEntranceWorld(t) + var mission uint32 + err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=6").Scan(&mission) + + if err != nil || mission != 2 || cold.characters[2].playfield != 65536 || len(cold.characters[2].missions) != 0 || + !slices.Equal(cold.characters[2].inventory.Items, []ownedItem{ + {ID: 5, Type: 51054, Template: 28564, Quality: 1, Slot: 65, Count: 1}, + {ID: 6, Type: 51053, Template: 28577, Quality: 1, Slot: 66, Count: 1}}) || + len(cold.characters[1].inventory.Items) != 3 || cold.characters[1].inventory.Credits != 4 { + t.Fatal("trade or guest copying lost the source assignment or required journal ownership", err) + } +} diff --git a/server/tradeskills.go b/server/tradeskills.go @@ -38,6 +38,9 @@ func (server *server) handleItemCombination(client *worldClient, body []byte) er return nil } first, second := player.inventory.Items[source], player.inventory.Items[target] + if first.Template == 28564 { + return server.copyMissionKey_locked(client, first, second) + } recipe, exists := gamedata.ItemCombinations[first.Template][second.Template] if !exists { return client.send(characterActionPacket(client.id, [5]uint32{84, 2, 0, 0, 0})) diff --git a/tools/client/test_mission_key_copy.mjs b/tools/client/test_mission_key_copy.mjs @@ -0,0 +1,80 @@ +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: 'mission-key-copy', url}]); + const page = await context.newPage(); + game = await GameTest.attach(page); + const server = async () => (await page.request.get(url + '/test-state')).json(); + const cell = slot => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy); + const click = async (slot, button = 'left') => { + const source = cell(slot); + assert(source, `ordinary slot ${slot} 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('i'); + await game.wait('original key and duplicator visible', () => cell(49) && cell(50)); + evidence.initial = await server(); + await game.save(output + '/initial'); + + // Native item combination uses the picked tool and Shift-right-click of the key. + const start = game.sequence; + await click(50); + await game.wait('duplicator held', state => state.dragged[0] === 104 && state.dragged[1] === 50); + await page.keyboard.down('Shift'); + try { await click(49, 'right'); } + finally { await page.keyboard.up('Shift'); } + await game.wait('actual native key-copy request', () => game.events.some(event => event.sequence > start && + event.direction === 'framesent' && event.opcode === '5e477770' && + Buffer.from(event.hex, 'hex').readUInt32BE(29) === 81)); + const request = game.events.find(event => event.sequence > start && event.direction === 'framesent' && + event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 81); + assert.deepEqual(Array.from({length: 5}, (_, index) => Buffer.from(request.hex, 'hex').readUInt32BE(29 + index * 4)), + [81, 104, 50, 104, 49]); + await game.save(output + '/requested'); + await game.wait('new key delivered to the ordinary inventory', state => + game.local(state).inventory.filter(item => item.templates[0] === 28577).length === 2 && cell(51)); + evidence.copied = await server(); + assert.deepEqual(evidence.copied.bindings, {'2': 2, '4': 2}); + assert.deepEqual(evidence.copied.inventory.Items.slice(0, 3), evidence.initial.inventory.Items); + assert.deepEqual(evidence.copied.inventory.Items[3], + {ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 67, Count: 1, Ammo: 0}); + assert.equal(evidence.copied.inventory.Credits, evidence.initial.inventory.Credits); + await game.key('Escape'); + await game.wait('both reusable inputs remain usable', state => state.dragged[0] === 0 && cell(49) && cell(50)); + await game.save(output + '/copied'); + + // A page replay must preserve both distinct key instances and the reusable tool. + 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.templates[0], item.slot]), + [[1, 209283, 48], [2, 28577, 49], [3, 28564, 50], [4, 28577, 51]]); + evidence.replayed = await server(); + assert.deepEqual(evidence.replayed, evidence.copied); + assert.deepEqual(game.errors, []); + console.log('PASS: native tool-on-key copy, reusable inputs, exact assignment and page/cold persistence'); +} 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(); } +}