commit 23c1777ff2cdf35fd05639486a8fe0cda47c90c1 parent e8fab899f2cc4de50ca3468f7311ff2c4d83f7b2 Author: anon <anon@example.com> Date: Fri, 6 Nov 2026 08:19:26 +0000 Give visitors starter items and persisted display titles Diffstat:
28 files changed, 343 insertions(+), 53 deletions(-)
diff --git a/TODO.md b/TODO.md @@ -35,6 +35,13 @@ research separately. More screenshots and test cases do not count as new gamepla ## P0: first experience +- [x] **Give new visitors starter items and a separate Visitor title.** New + visitors receive the character-creation starter kit atomically. A free-text + `title` column beside `name` stores `Visitor` and clears on adoption; generated + names stay unchanged. Verified native labels, inspection, adoption, restart, + profile editing, item ownership, rollback and no duplicate grants. Existing + inventory, cursor, touch and private-storage browser regressions also pass. + - [x] **Load the game when private browsing denies local storage.** Firefox private windows stop at "Starting Anarchy Online..." because OPFS `getDirectory()` rejects with `SecurityError`. Use temporary local preferences diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md @@ -95,6 +95,39 @@ stored password credential, not the name's spelling, so a visitor can adopt its generated name without losing its character or mistaking itself for a duplicate account. +New visitors receive the same profession/faction starter kit as character +creation. The default Omni Soldier gets seven inventory entries, including +25 treatment-laboratory and 3 first-aid charges. Player creation, items, +ownership and identity counters commit together. Name collision retries reuse +the pending kit, and reconnects do not issue it again. Adoption keeps the kit. + +Visitors display `Visitor` as a separate native title; generated names retain +their existing 6-8 letters and remain usable in chat and login. The title is +stored in `characters.title` beside `name`, exposed in the profile editor, and +cleared atomically on adoption. Titles accept up to 31 bytes without a NUL, +matching the native SetName decoder's limit; empty text clears the title. +No client executable or browser-page change is required. +Existing development databases must be recreated for the added title column. + +The native `SetNameIIR_t` packet has key `0x734e5a7b`, with a u32 field selector +4, zero byte, u32 text length and the ASCII title. The key follows +`client/game/llr.dll/lifted-0014.c::sub_38023F20`; serialization and execution are +`client/game/kkr.dll/lifted-0038.c::sub_360812A0` and `sub_360812F0`. +The original setter `sub_36070F40` stores title text separately from the name. +The decoder `sub_36081140` rejects text lengths of 32 bytes or more. +DDR's `TargetingModule_t::HandleNametags` calls `sub_2B0624E0`, which reads +`N3Msg_GetTitleName`; the target HUD also reads it in `sub_2B0654A0`. +Character inspection carries the same text in its counted title string. +These are text fields, distinct from fixed earned PvP ranks and profession +title levels. + +The visitor browser regression covers owner/observer delivery, inspection, +adoption with the original generated name, and cold restart. Native screenshots +show `Visitor Gliribin` above the actor and in the target HUD, then `Gliribin` +after adoption. Starter regressions cover exact contents, ownership, concurrent +launches, rollback, retry and restart; inventory/cursor/touch/private-storage +browser checks run with the complete visitor kit. + Focused account and creation checks pass with generated names, including cold loading, keeping a generated name during adoption, 32 concurrent launches, case-insensitive collisions and failed-save cleanup. The launch collision and diff --git a/docs/character-info.md b/docs/character-info.md @@ -29,8 +29,10 @@ Serializer 0x1005b9a0 and decoder 0x1005bbd0 establish this mandatory payload: Multi-byte fields are big-endian. Flags 0 and four empty strings produce a 52-byte payload, with no version byte or optional tail. Level 54 and Side 33 are absent from this packet; the actor spawn already carries them. The title -string is separate from the nickname. The current player model has no authored -first/last/title names, description, pet ownership, organization or side XP. +string is separate from the nickname. Unadopted browser players receive the +stored free-text title `Visitor`; inspection retains the database title. The +current player model has no authored first/last names, description, pet ownership, +organization or side XP. Those fields remain empty or zero. It has no false-profession effect, so real and visual profession agree. ProfessionLevel retains its independent native default 1: KKR constructor 0x10072760 initializes stat 10 separately from Level diff --git a/server/browser_account.go b/server/browser_account.go @@ -179,7 +179,7 @@ func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) { player.browserTokenHash = credential err = server.insertBrowserPlayer_locked(tx, player, salt, hash) } else if action == "claim" { - err = updateRecord(tx, "characters", id, "name, password_salt, password_hash, browser_token_hash", []any{name, salt, hash, credential}) + err = updateRecord(tx, "characters", id, "name, title, password_salt, password_hash, browser_token_hash", []any{name, "", salt, hash, credential}) } else { err = updateRecord(tx, "characters", id, "browser_token_hash", []any{credential}) } @@ -195,6 +195,7 @@ func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) { } if action == "claim" { player.name, player.savedProfile.Name = name, name + player.title, player.savedProfile.Title = "", "" } else if action == "create" { server.publishBrowserPlayer_locked(player) } diff --git a/server/browser_account_test.go b/server/browser_account_test.go @@ -39,7 +39,8 @@ func TestBrowserAccountClaimPreservesCharacterAndSurvivesRestart(t *testing.T) { world := newTestServer(t) cookie := accountVisitor(t, world) player := world.characters[1] - inventory := playerInventory{LastID: 1, Credits: 123, Items: []ownedItem{{ID: 1, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}}} + inventory := player.inventory + inventory.Credits = 123 if err := world.saveInventory_locked(player, inventory); err != nil { t.Fatal(err) } @@ -54,6 +55,7 @@ func TestBrowserAccountClaimPreservesCharacterAndSurvivesRestart(t *testing.T) { } if response.Code != 204 || response.Header().Get("Cache-Control") != "no-store" || player.name != "Alice" || restored.characters[1].name != "Alice" || + player.title != "" || restored.characters[1].title != "" || player.health != before.health || player.nano != before.nano || player.position != before.position || player.stats != before.stats || !reflect.DeepEqual(player.inventory, before.inventory) || !reflect.DeepEqual(restored.characters[1].inventory, before.inventory) || world.clients[1].ready { t.Fatalf("claim lost the existing player or session: %d %s", response.Code, response.Body.String()) diff --git a/server/browser_creation_test.go b/server/browser_creation_test.go @@ -180,8 +180,8 @@ func TestBrowserCreationChargedKitsSplitRejoinAndSurviveRestart(t *testing.T) { } restored := newTestInventoryServer(t) - if len(player.inventory.Items) != 8 || world.nextItem != 8 || player.inventory.Items[scenario.slot-64].Count != uint16(scenario.retained) || - player.inventory.Items[7].ID != 8 || player.inventory.Items[7].Slot != 71 || player.inventory.Items[7].Count != uint16(scenario.remainder) || + if len(player.inventory.Items) != 8 || world.nextItem != 15 || player.inventory.Items[scenario.slot-64].Count != uint16(scenario.retained) || + player.inventory.Items[7].ID != 15 || player.inventory.Items[7].Slot != 71 || player.inventory.Items[7].Count != uint16(scenario.remainder) || !reflect.DeepEqual(restored.characters[2].inventory.Items, player.inventory.Items) { t.Fatal("starter kit split lost charges, duplicated an identity or failed cold loading") } @@ -191,7 +191,7 @@ func TestBrowserCreationChargedKitsSplitRejoinAndSurviveRestart(t *testing.T) { } restored = newTestInventoryServer(t) - if !reflect.DeepEqual(player.inventory.Items, before) || !reflect.DeepEqual(restored.characters[2].inventory.Items, before) || restored.nextItem != 8 { + if !reflect.DeepEqual(player.inventory.Items, before) || !reflect.DeepEqual(restored.characters[2].inventory.Items, before) || restored.nextItem != 15 { t.Fatal("starter kit rejoin changed the issued items or reused the retired identity") } }) @@ -213,7 +213,7 @@ func TestBrowserCreationRejectsInvalidChoicesWithoutChangingCurrentPlayer(t *tes response := creationRequest(world, cookie, fields) - if response.Code != 400 || len(response.Result().Cookies()) != 0 || !reflect.DeepEqual(*world.characters[1], before) || world.nextCharacter != 1 || world.nextItem != 0 { + if response.Code != 400 || len(response.Result().Cookies()) != 0 || !reflect.DeepEqual(*world.characters[1], before) || world.nextCharacter != 1 || world.nextItem != 7 { t.Fatalf("invalid creation changed state: %d %s", response.Code, response.Body.String()) } }) @@ -277,10 +277,10 @@ func checkBrowserCreationFailure(t *testing.T, statement string) { response := creationRequest(world, cookie, creationForm()) restored := newTestInventoryServer(t) - if response.Code != 500 || len(response.Result().Cookies()) != 0 || world.nextCharacter != 1 || world.nextItem != 0 || + if response.Code != 500 || len(response.Result().Cookies()) != 0 || world.nextCharacter != 1 || world.nextItem != 7 || !reflect.DeepEqual(*world.characters[1], before) || !reflect.DeepEqual(items, world.items) || !reflect.DeepEqual(placements, world.itemPlacements) || - len(restored.users_locked()) != 1 || restored.nextCharacter != 1 || restored.nextItem != 0 || - restored.characters[1].browserTokenHash != before.browserTokenHash || len(restored.items) != 0 { + len(restored.users_locked()) != 1 || restored.nextCharacter != 1 || restored.nextItem != 7 || + restored.characters[1].browserTokenHash != before.browserTokenHash || !reflect.DeepEqual(restored.items, items) { t.Fatalf("failed creation published partial state: %d %s", response.Code, response.Body.String()) } if _, err := world.db.Exec("DROP TRIGGER reject_creation"); err != nil { @@ -297,7 +297,7 @@ func checkBrowserCreationFailure(t *testing.T, statement string) { func TestBrowserCreationConcurrentReplayCommitsOnceAndOldPlayerCanLogIn(t *testing.T) { world := newTestServer(t) visitor := accountVisitor(t, world) - inventory := playerInventory{LastID: 1, Credits: 123, Items: []ownedItem{{ID: 1, Type: 51022, Template: 85686, Quality: 1, Slot: 21, Count: 1}}} + inventory := playerInventory{LastID: 8, Credits: 123, Items: []ownedItem{{ID: 8, Type: 51022, Template: 85686, Quality: 1, Slot: 21, Count: 1}}} if err := world.saveInventory_locked(world.characters[1], inventory); err != nil { t.Fatal(err) } @@ -343,7 +343,7 @@ func TestBrowserCreationConcurrentReplayCommitsOnceAndOldPlayerCanLogIn(t *testi t.Fatalf("old character login or stale creation failed: %d %d", stale.Code, login.Code) } restored := newTestInventoryServer(t) - if !reflect.DeepEqual(restored.characters[1].inventory.Items, before.inventory.Items) || restored.characters[1].inventory.Credits != 123 || restored.itemPlacements[1] != (itemPlacement{Player: 1, Slot: 21}) { + if !reflect.DeepEqual(restored.characters[1].inventory.Items, before.inventory.Items) || restored.characters[1].inventory.Credits != 123 || restored.itemPlacements[8] != (itemPlacement{Player: 1, Slot: 21}) { t.Fatal("creation or login lost the original equipped item") } } @@ -367,7 +367,7 @@ func TestBrowserCreationRequiresCurrentCookieAndUniqueName(t *testing.T) { missingHead := creationRequest(world, other, fields) if missing.Code != 401 || stale.Code != 401 || duplicate.Code != 409 || missingHead.Code != 400 || - !reflect.DeepEqual(*world.characters[2], before) || world.nextCharacter != 2 || world.nextItem != 0 { + !reflect.DeepEqual(*world.characters[2], before) || world.nextCharacter != 2 || world.nextItem != 14 { t.Fatalf("creation authorization/uniqueness failed: %d %d %d %d", missing.Code, stale.Code, duplicate.Code, missingHead.Code) } } diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -32,6 +32,7 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) { if character == nil { token := rand.Text() character = server.newCharacter_locked() + character.title = "Visitor" character.running = true character.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(token))) character.playfield = 705 diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "os" + "reflect" "regexp" "testing" ) @@ -16,7 +17,7 @@ func TestBrowserLaunchCreatesPersistentVisitor(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{baseURL: "/", worldPort: 7501, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient)} + world := &server{baseURL: "/", worldPort: 7501, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} t.Cleanup(func() { if world.db != nil { world.db.Close() @@ -43,11 +44,21 @@ func TestBrowserLaunchCreatesPersistentVisitor(t *testing.T) { t.Fatalf("saved first character: %+v", loaded.characters[1]) } visitor := loaded.characters[1] + if len(visitor.inventory.Items) != 7 || loaded.nextItem != 7 || !reflect.DeepEqual(visitor.inventory.Items, world.characters[1].inventory.Items) { + t.Fatal("visitor starter kit did not survive restart") + } + for index, template := range []uint32{116628, 116629, 116693, 121569, 29092, 99719, 29426} { + item := visitor.inventory.Items[index] + if item.ID != uint32(index+1) || item.Template != template || item.Quality != 1 || item.Slot != uint32(64+index) || + item.Count != []uint16{25, 3, 1, 1, 1, 1, 1}[index] || loaded.itemPlacements[item.ID] != (itemPlacement{Player: 1, Slot: item.Slot}) { + t.Fatal("visitor received an incorrect starter item", item) + } + } if !regexp.MustCompile(`^[A-Z][a-z]{5,7}$`).MatchString(visitor.name) || visitor.name != world.characters[1].name { t.Fatalf("visitor name is not usable in tell commands: %q", visitor.name) } - if !visitor.running { - t.Fatal("new visitor did not start in run mode") + if !visitor.running || visitor.title != "Visitor" || world.characters[1].title != "Visitor" { + t.Fatal("new visitor did not retain its title and run mode") } if visitor.position[0] < 957 || visitor.position[0] > 963 || visitor.position[1] != 16.5 || visitor.position[2] < 507 || visitor.position[2] > 513 { t.Fatalf("visitor is not near Bronto Burger: %v", visitor.position) @@ -78,7 +89,7 @@ func TestBrowserLaunchResumesOwnedCharacterAfterRestart(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{worldPort: 7501, characters: make(map[uint32]*character)} + world := &server{worldPort: 7501, characters: make(map[uint32]*character), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} t.Cleanup(func() { if world.db != nil { world.db.Close() @@ -104,6 +115,9 @@ func TestBrowserLaunchResumesOwnedCharacterAfterRestart(t *testing.T) { if response.Code != http.StatusOK || response.Body.String() != first.Body.String() || len(loaded.characters) != 1 || loaded.characters[1].name != world.characters[1].name { t.Fatalf("launch response: %d %q", response.Code, response.Body.String()) } + if loaded.nextItem != 7 || !reflect.DeepEqual(loaded.characters[1].inventory.Items, world.characters[1].inventory.Items) { + t.Fatal("resuming the visitor changed or duplicated the starter kit") + } } func TestBrowserLaunchSeparatesVisitorsAndReplacesUnknownCookie(t *testing.T) { @@ -111,7 +125,7 @@ func TestBrowserLaunchSeparatesVisitorsAndReplacesUnknownCookie(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{worldPort: 7501, characters: make(map[uint32]*character)} + world := &server{worldPort: 7501, characters: make(map[uint32]*character), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} t.Cleanup(func() { if world.db != nil { world.db.Close() @@ -149,7 +163,34 @@ func TestVisitorCredentialSurvivesCharacterEditing(t *testing.T) { } world.browserLaunch(response, request) - if response.Code != http.StatusOK || response.Body.String() != first.Body.String() || world.nextCharacter != 1 || world.characters[1].name != "Edited visitor" { + if response.Code != http.StatusOK || response.Body.String() != first.Body.String() || world.nextCharacter != 1 || world.characters[1].name != "Edited visitor" || world.characters[1].title != "Visitor" { t.Fatal("editing lost the visitor credential") } } + +func TestBrowserLaunchStarterKitFailureRollsBackAndCanRetry(t *testing.T) { + world := newTestServer(t) + if _, err := world.db.Exec("CREATE TRIGGER reject_starter BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(ABORT,'refuse starter item'); END"); err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + + world.browserLaunch(response, httptest.NewRequest("POST", "/browser-launch", nil)) + restored := newTestInventoryServer(t) + + if response.Code != http.StatusInternalServerError || len(response.Result().Cookies()) != 0 || world.nextCharacter != 0 || world.nextItem != 0 || + world.characters[1] != nil || len(world.items) != 0 || len(world.itemPlacements) != 0 || + len(restored.users_locked()) != 0 || restored.nextCharacter != 0 || restored.nextItem != 0 || len(restored.items) != 0 { + t.Fatal("failed starter grant left a partial visitor or inventory", response.Code, response.Body) + } + + // A retry receives one complete kit, reusing only the rolled-back identities. + if _, err := world.db.Exec("DROP TRIGGER reject_starter"); err != nil { + t.Fatal(err) + } + retry := httptest.NewRecorder() + world.browserLaunch(retry, httptest.NewRequest("POST", "/browser-launch", nil)) + if retry.Code != http.StatusOK || world.nextCharacter != 1 || world.nextItem != 7 || len(world.characters[1].inventory.Items) != 7 { + t.Fatal("visitor starter grant could not retry", retry.Code, retry.Body) + } +} diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -535,6 +535,10 @@ func TestExpiredBrowserWorldSessionRemovesLivingTargetAndRetargetsNPC(t *testing if binary.BigEndian.Uint32(spawn[20:24]) != 0x271b3a6b || binary.BigEndian.Uint32(spawn[28:32]) != 2 { t.Fatalf("observer did not receive browser player: %x", spawn) } + title, err := readPacket(observer) + if err != nil || binary.BigEndian.Uint32(title[20:24]) != 0x734e5a7b { + t.Fatalf("observer did not receive browser player title: %x %v", title, err) + } if err := socket.Write(ctx, websocket.MessageBinary, append(binary.BigEndian.AppendUint64(nil, uint64(len(cookie))), n3Packet(0x570c2039, 50000, 2, nil)...)); err != nil { t.Fatal(err) } diff --git a/server/character_info.go b/server/character_info.go @@ -5,6 +5,15 @@ import ( "fmt" ) +func characterTitlePacket(player *character) []byte { + // SetNameIIR_t selects the title with field 4, followed by a byte and counted text. + body := binary.BigEndian.AppendUint32(nil, 4) + body = append(body, 0) + body = binary.BigEndian.AppendUint32(body, uint32(len(player.title))) + body = append(body, player.title...) + return n3Packet(0x734e5a7b, 50000, player.id, body) +} + func characterInfoPacket(player *character) []byte { // The five byte stats are Profession, ProfessionLevel, TitleLevel, VisualSex and VisualProfession. // NPCs retain native defaults, including the byte representation of profession -1. @@ -24,8 +33,11 @@ func characterInfoPacket(player *character) []byte { for _, value := range []uint32{player.health, player.maximumHealth(), regeneration[0], regeneration[1], regeneration[2], regeneration[3], 0, 0} { body = binary.BigEndian.AppendUint32(body, value) } - // BreedHostility, clan and the four counted name/description strings are empty. - body = append(body, make([]byte, 8)...) + // First/last names and description are empty; inspection retains the stored title. + body = append(body, 0, 0, 0, 0) + body = binary.BigEndian.AppendUint16(body, uint16(len(player.title))) + body = append(body, player.title...) + body = append(body, 0, 0) return n3Packet(0x4d38242e, 50000, player.id, body) } diff --git a/server/character_info_test.go b/server/character_info_test.go @@ -59,6 +59,22 @@ func TestCharacterInfoSelfUsesProfileStatsWithoutAbsorbingModifiers(t *testing.T } } +func TestCharacterInfoRetainsVisitorTitleSeparatelyFromName(t *testing.T) { + world, connections := newTeamWorld(t) + world.characters[2].title = "Visitor" + world.characters[2].name = "Samplevisitor" + + if err := world.handleCharacterInfo(world.clients[1], teamRequest(1, 105, 2, 0)); err != nil { + t.Fatal(err) + } + + packet := connections[0].packets[0] + if !bytes.Equal(packet[73:88], []byte{0, 0, 0, 0, 0, 7, 'V', 'i', 's', 'i', 't', 'o', 'r', 0, 0}) || + world.characters[2].name != "Samplevisitor" { + t.Fatal("inspection lost the visitor title or changed the player name") + } +} + func TestCharacterInfoRejectsUnrepresentedOrUnauthenticatedRequests(t *testing.T) { for _, scenario := range []string{"missing", "unseen npc", "other zone", "offline", "foreign owner", "sender type", "target type", "argument", "action", "key", "legacy", "not ready", "loading", "target not ready", "target loading", "replaced"} { t.Run(scenario, func(t *testing.T) { diff --git a/server/database.go b/server/database.go @@ -73,7 +73,7 @@ type playerVitals struct { } func (character *character) profile() playerProfile { - return playerProfile{ID: character.id, Name: character.name, Appearance: unpackAppearance(character.appearance), + return playerProfile{ID: character.id, Name: character.name, Title: character.title, Appearance: unpackAppearance(character.appearance), HeadMesh: character.headMesh, Height: character.height, MonsterData: character.monsterData, Level: character.level, Experience: character.experience, InsuredExperience: character.insuredExperience, Profession: max(1, character.profession), Stats: character.baseStats(), Running: character.running, @@ -146,7 +146,7 @@ func (record *characterRecord) fields() []any { func (record characterRecord) character() *character { profile, position := record.Profile, record.Position.editor() - data := userData{ID: profile.ID, Name: profile.Name, Playfield: position.Playfield, Position: position.Position, Rotation: position.Rotation, + data := userData{ID: profile.ID, Name: profile.Name, Title: profile.Title, Playfield: position.Playfield, Position: position.Position, Rotation: position.Rotation, Appearance: profile.Appearance.packed(), HeadMesh: profile.HeadMesh, Height: profile.Height, MonsterData: profile.MonsterData, Level: profile.Level, Experience: profile.Experience, InsuredExperience: profile.InsuredExperience, Profession: profile.Profession, Stats: profile.Stats, Running: profile.Running, ReturnDoor: position.ReturnDoor, BrowserTokenHash: profile.BrowserTokenHash} diff --git a/server/dialogue_test.go b/server/dialogue_test.go @@ -172,6 +172,10 @@ func TestNPCConversationBelongsToItsWorldConnection(t *testing.T) { } } readPacket(first) // The second player's spawn is broadcast to the first. + title, err := readPacket(first) + if err != nil || binary.BigEndian.Uint32(title[16:20]) != 0x734e5a7b { + t.Fatalf("observer did not receive the second player's title: %x %v", title, err) + } second.Write(targetPacket(n3Packet(0x570c2039, 50000, 2, nil))) readPacket(first) for _, stat := range []uint32{16, 17, 18, 19, 20, 21, 138, 118, 119, 120, 149, 51, 425, 430, 78, 156} { diff --git a/server/main.go b/server/main.go @@ -385,11 +385,12 @@ func (server *server) serveWorldClient(client *worldClient) error { server.updateMutex.Unlock() return err } - updates := [][]byte{playfieldUpdate, characterPacket(character)} + updates := [][]byte{playfieldUpdate, characterPacket(character), characterTitlePacket(character)} for id, other := range server.characters { if id != character.id && other.playfield == character.playfield && server.clients[id] != nil { snapshot := other.predictedMovement(time.Now()) updates = append(updates, characterPacket(&snapshot)) + updates = append(updates, characterTitlePacket(other)) if !server.clients[id].loading { updates = append(updates, playerCombatStatPackets(other)...) updates = append(updates, equippedItemPackets(other)...) @@ -445,6 +446,7 @@ func (server *server) serveWorldClient(client *worldClient) error { } updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked())) spawn := characterPacket(character) + title := characterTitlePacket(character) playfield := character.playfield server.mutex.Unlock() server.sendCombatUpdates(combatUpdates) @@ -463,6 +465,7 @@ func (server *server) serveWorldClient(client *worldClient) error { client.ready = true server.mutex.Unlock() server.broadcast(playfield, character.id, spawn) + server.broadcast(playfield, character.id, title) for _, update := range petUpdates { server.broadcast(playfield, character.id, update) } diff --git a/server/profile_database.go b/server/profile_database.go @@ -1,7 +1,7 @@ package main // These columns are shared by players and NPCs; the pointers serve SQL scans and writes. -const profileColumns = "name, appearance_race, appearance_fatness, appearance_breed, appearance_sex, appearance_side, appearance_head, head_mesh, height, " + +const profileColumns = "name, title, appearance_race, appearance_fatness, appearance_breed, appearance_sex, appearance_side, appearance_head, head_mesh, height, " + "monster_data, level, experience, insured_experience, profession, improvement_points, abilities_strength, abilities_agility, abilities_stamina, " + "abilities_intelligence, abilities_sense, abilities_psychic, body_martial_arts, body_brawling, body_riposte, body_dimach, " + "body_adventuring, body_swimming, body_body_development, body_nano_pool, melee_one_hand_blunt, melee_one_hand_edged, " + @@ -22,7 +22,7 @@ const profileColumns = "name, appearance_race, appearance_fatness, appearance_br func (profile *playerProfile) fields() []any { return []any{ - &profile.Name, &profile.Appearance.Race, &profile.Appearance.Fatness, &profile.Appearance.Breed, + &profile.Name, &profile.Title, &profile.Appearance.Race, &profile.Appearance.Fatness, &profile.Appearance.Breed, &profile.Appearance.Sex, &profile.Appearance.Side, &profile.Appearance.Head, &profile.HeadMesh, &profile.Height, &profile.MonsterData, &profile.Level, &profile.Experience, &profile.InsuredExperience, &profile.Profession, &profile.Stats.ImprovementPoints, &profile.Stats.Abilities.Strength, &profile.Stats.Abilities.Agility, &profile.Stats.Abilities.Stamina, &profile.Stats.Abilities.Intelligence, &profile.Stats.Abilities.Sense, diff --git a/server/roaming_test.go b/server/roaming_test.go @@ -38,6 +38,10 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) { readWorldUpdates(t, client) if player.id == 2 { readPacket(clients[0]) + title, err := readPacket(clients[0]) + if err != nil || binary.BigEndian.Uint32(title[20:24]) != 0x734e5a7b { + t.Fatalf("observer did not receive the second player's title: %x %v", title, err) + } } // Drain readiness and its combat foundations to the first observer as well. var peer sync.WaitGroup diff --git a/server/state.go b/server/state.go @@ -16,6 +16,7 @@ import ( type character struct { id uint32 name string + title string playfield uint32 position [3]float32 rotation [4]float32 diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go @@ -190,6 +190,10 @@ func TestTargetMovementIsPersistedAndRelayedToReleaseClient(t *testing.T) { } if id == 2 { readPacket(clients[0]) + title, err := readPacket(clients[0]) + if err != nil || binary.BigEndian.Uint32(title[20:24]) != 0x734e5a7b { + t.Fatalf("observer did not receive the second player's title: %x %v", title, err) + } } if id == 2 { client.Write(targetPacket(n3Packet(0x570c2039, 50000, id, nil))) diff --git a/server/users.go b/server/users.go @@ -19,6 +19,7 @@ import ( type userData struct { ID uint32 Name string + Title string Playfield uint32 Position [3]float32 Rotation [4]float32 @@ -40,6 +41,7 @@ type userData struct { type playerProfile struct { ID uint32 `yaml:"id"` Name string `yaml:"name"` + Title string `yaml:"title"` Appearance appearanceFields `yaml:"appearance"` HeadMesh uint32 `yaml:"head_mesh"` Height uint16 `yaml:"height"` @@ -63,14 +65,14 @@ type playerPosition struct { } func (character *character) userData() userData { - return userData{ID: character.id, Name: character.name, Playfield: character.playfield, Position: character.position, + return userData{ID: character.id, Name: character.name, Title: character.title, Playfield: character.playfield, Position: character.position, Rotation: character.rotation, Appearance: character.appearance, HeadMesh: character.headMesh, Height: character.height, MonsterData: character.monsterData, Level: character.level, Experience: character.experience, InsuredExperience: character.insuredExperience, Profession: max(1, character.profession), Stats: character.baseStats(), Running: character.running, ReturnDoor: character.returnDoor, BrowserTokenHash: character.browserTokenHash} } func (data userData) character() *character { - character := &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position, + character := &character{id: data.ID, name: data.Name, title: data.Title, playfield: data.Playfield, position: data.Position, rotation: data.Rotation, appearance: data.Appearance, headMesh: data.HeadMesh, height: data.Height, monsterData: data.MonsterData, level: data.Level, experience: data.Experience, insuredExperience: data.InsuredExperience, @@ -101,6 +103,9 @@ func (data userData) validateFields() error { if len(strings.TrimSpace(data.Name)) == 0 || len(data.Name) > 254 || strings.ContainsRune(data.Name, 0) { return fmt.Errorf("name must contain 1-254 bytes without a NUL") } + if len(data.Title) > 31 || strings.ContainsRune(data.Title, 0) { + return fmt.Errorf("title must contain at most 31 bytes without a NUL") + } if data.Level == 0 || data.Level > 200 { return fmt.Errorf("level must be between 1 and 200") } diff --git a/server/users_test.go b/server/users_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "encoding/hex" + "fmt" "net" "net/http" "net/http/httptest" @@ -58,6 +59,7 @@ func TestUserCreationEditingAndOfflineTeleportSurviveRestart(t *testing.T) { created := httptest.NewRecorder() data := `id: 1 name: Edited Explorer +title: Freelance Explorer appearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0} monster_data: 0 level: 7 @@ -89,7 +91,7 @@ running: true t.Fatal("teleport must return to its map", teleported.Code, teleported.Header()) } player := restarted.characters[1] - if player.name != "Edited Explorer" || player.playfield != 800 || player.level != 7 || player.appearance != 789 || player.position != [3]float32{679.625, 74.75, 537.875} || !player.running { + if player.name != "Edited Explorer" || player.title != "Freelance Explorer" || player.playfield != 800 || player.level != 7 || player.appearance != 789 || player.position != [3]float32{679.625, 74.75, 537.875} || !player.running { t.Fatalf("saved character: %+v", player) } if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='admin/players/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") { @@ -104,6 +106,48 @@ running: true } } +func TestUserTitleEditingRespectsClientTextLimit(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) + for _, scenario := range []struct { + title string + valid bool + }{ + {"Freelance Explorer", true}, + {strings.Repeat("x", 31), true}, + {strings.Repeat("x", 32), false}, + {"Hidden\x00title", false}, + {"", true}, + } { + t.Run(fmt.Sprintf("%q", scenario.title), func(t *testing.T) { + before := world.characters[1].title + edited := world.characters[1].editor() + edited.Title = scenario.title + data, err := yaml.Marshal(edited) + if err != nil { + t.Fatal(err) + } + + response := postControlForm(world, "/admin/players/1", url.Values{"data": {string(data)}}) + restarted := newServerForTest(t) + + expected, status := before, http.StatusBadRequest + if scenario.valid { + expected, status = scenario.title, http.StatusSeeOther + } + if response.Code != status || world.characters[1].title != expected || restarted.characters[1].title != expected { + t.Fatal("title validation or persistence failed", response.Code, response.Body.String()) + } + packet := targetPacket(characterTitlePacket(restarted.characters[1])) + if binary.BigEndian.Uint32(packet[29:33]) != 4 || packet[33] != 0 || + binary.BigEndian.Uint32(packet[34:38]) != uint32(len(expected)) || string(packet[38:38+len(expected)]) != expected { + t.Fatal("stored title was not published as native title text", packet) + } + }) + } +} + func TestMovementModePersistsAndIsSuppliedOnReconnect(t *testing.T) { for _, target := range []bool{false, true} { for _, mode := range []struct { diff --git a/server/visitor_names.go b/server/visitor_names.go @@ -77,6 +77,9 @@ func (server *server) saveVisitor_locked(player *character) error { if err != nil { return err } + if err := server.browserStartingItems_locked(player); err != nil { + return err + } for { player.name = randomVisitorName() var exists bool @@ -87,11 +90,22 @@ func (server *server) saveVisitor_locked(player *character) error { continue } // The index also protects against a competing database writer after the check. - err := server.saveUser_locked(player) + tx, err := db.Begin() + if err != nil { + return err + } + err = server.insertBrowserPlayer_locked(tx, player, []byte{}, []byte{}) + if err == nil { + err = tx.Commit() + } + tx.Rollback() var constraint sqlite3.Error if errors.As(err, &constraint) && constraint.ExtendedCode == sqlite3.ErrConstraintUnique { continue } + if err == nil { + server.publishBrowserPlayer_locked(player) + } return err } } diff --git a/server/visitor_names_test.go b/server/visitor_names_test.go @@ -167,6 +167,19 @@ func TestBrowserLaunchConcurrentNamesStayUnique(t *testing.T) { if players != 32 || names != 32 || world.nextCharacter != 32 { t.Fatal("concurrent launches reused a name or identity", players, names, world.nextCharacter) } + if world.nextItem != 224 || len(world.items) != 224 || len(world.itemPlacements) != 224 { + t.Fatal("concurrent launches reused starter item identities") + } + for id := uint32(1); id <= 32; id++ { + if len(world.characters[id].inventory.Items) != 7 { + t.Fatal("visitor is missing starter items", id) + } + for _, item := range world.characters[id].inventory.Items { + if world.itemPlacements[item.ID] != (itemPlacement{Player: id, Slot: item.Slot}) { + t.Fatal("visitor received another player's starter item", id, item.ID) + } + } + } } func TestBrowserVisitorCanAdoptItsGeneratedName(t *testing.T) { diff --git a/server/world.sql b/server/world.sql @@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS world ( CREATE TABLE IF NOT EXISTS characters ( id INTEGER PRIMARY KEY CHECK (id BETWEEN 1 AND 4294967295), name TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', appearance_race INTEGER NOT NULL DEFAULT 0 CHECK (appearance_race BETWEEN 0 AND 3), appearance_fatness INTEGER NOT NULL DEFAULT 0 CHECK (appearance_fatness BETWEEN 0 AND 3), appearance_breed INTEGER NOT NULL DEFAULT 0 CHECK (appearance_breed BETWEEN 0 AND 7), diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -84,7 +84,7 @@ func TestWorldReplacementRemovesRemoteActorBeforeReplayingEquipment(t *testing.T keys = append(keys, binary.BigEndian.Uint32(packet[16:20])) } - expected := []uint32{0x271b3a6b, 0x570c2039} + expected := []uint32{0x271b3a6b, 0x734e5a7b, 0x570c2039} for range 16 { expected = append(expected, 0x2b333d6e) } diff --git a/tests/e2e/browser.test.mjs b/tests/e2e/browser.test.mjs @@ -11,12 +11,12 @@ test('movement, targeting, posture and page recovery', {timeout: 180_000}, async await withFixture('interaction', async fixture => { const context = await fixture.visitor(); await fixture.setup(context, 'position', {playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]}); - await fixture.setup(context, 'grant-item', {template: 121567}); const target = await fixture.setup(context, 'leet', {position: [960, 16.5, 498]}); const game = await fixture.game(context); const page = game.page; assert.equal(game.state.localId, 1); - assert.equal(game.local().inventory[0].templates[0], 121567); + assert.deepEqual(game.local().inventory.map(item => item.templates[0]).sort((a, b) => a - b), + [29092, 29426, 99719, 116628, 116629, 116693, 121569]); const inventory = game.local().inventory; const z = game.local().position[2]; @@ -53,7 +53,7 @@ test('movement, targeting, posture and page recovery', {timeout: 180_000}, async const state = await fixture.state(context); assert.equal(state.sitting, false); assert(state.position[2] > 510.5); - assert.equal(state.items.length, 1); + assert.equal(state.items.length, 7); assert.deepEqual(game.errors, []); }); }); @@ -63,8 +63,8 @@ test('overflow refusal preserves both stacks through restart', {timeout: 180_000 const context = await fixture.visitor(); await fixture.setup(context, 'position', {playfield: 950, position: [52.625, 14.75, 56.875], rotation: [0, 0, 0, 1]}); for (let index = 0; index < 2; ++index) await fixture.setup(context, 'grant-item', {template: 152030}); - await fixture.setup(context, 'item', {id: 1, slot: 64, count: 1}); - const before = await fixture.setup(context, 'item', {id: 2, slot: 65, count: 65535}); + await fixture.setup(context, 'item', {id: 8, slot: 71, count: 1}); + const before = await fixture.setup(context, 'item', {id: 9, slot: 72, count: 65535}); const cookies = await context.cookies(); const game = await fixture.game(context); await game.key('i'); @@ -77,23 +77,23 @@ test('overflow refusal preserves both stacks through restart', {timeout: 180_000 }; for (const attempt of [0, 1]) { const sequence = game.sequence; - await click(48); - await click(49); + await click(55); + await click(56); await game.wait('actual overflow join request', () => game.events.some(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 53)); await game.save(fixture.output + '/refused-' + attempt); - await game.wait('both overflow sources remain usable', () => cell(48) && cell(49)); + await game.wait('both overflow sources remain usable', () => cell(55) && cell(56)); assert.deepEqual(game.state.dragged, [0, 0]); - assert.deepEqual(game.local().inventory.map(item => [item.slot, item.count]).sort((a, b) => a[0] - b[0]), - [[48, 1], [49, 65535]]); + assert.deepEqual(game.local().inventory.filter(item => item.id >= 8).map(item => [item.slot, item.count]).sort((a, b) => a[0] - b[0]), + [[55, 1], [56, 65535]]); const state = await fixture.state(context); assert.deepEqual(state.items, before.items); - assert.equal(state.lastItem, 2); + assert.equal(state.lastItem, 9); } await game.page.reload(); await game.ready(); - assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.count]).sort((a, b) => a[0] - b[0]), - [[1, 48, 1], [2, 49, 65535]]); + assert.deepEqual(game.local().inventory.filter(item => item.id >= 8).map(item => [item.id, item.slot, item.count]).sort((a, b) => a[0] - b[0]), + [[8, 55, 1], [9, 56, 65535]]); assert.deepEqual(game.errors, []); await game.save(fixture.output + '/before-restart'); await fixture.restart(); @@ -101,7 +101,7 @@ test('overflow refusal preserves both stacks through restart', {timeout: 180_000 await restored.addCookies(cookies); const state = await fixture.state(restored); assert.deepEqual(state.items, before.items); - assert.equal(state.lastItem, 2); + assert.equal(state.lastItem, 9); }); }); diff --git a/tests/e2e/cursor.test.mjs b/tests/e2e/cursor.test.mjs @@ -11,7 +11,6 @@ test('browser cursor preserves native shapes, camera controls and item dragging' const response = await context.request.post(fixture.url + '/browser-launch'); assert.equal(response.status(), 200); await fixture.setup(context, 'position', {playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]}); - await fixture.setup(context, 'grant-item', {template: 121567}); const items = (await fixture.state(context)).items; const target = await fixture.setup(context, 'leet', {position: [960, 16.5, 498]}); const game = await fixture.game(context); @@ -94,11 +93,11 @@ test('browser cursor preserves native shapes, camera controls and item dragging' await worker.evaluate(() => { self.requestAnimationFrame = self.cursorTestRAF; }); } - const destination = game.state.grids[0].cells.find(cell => cell.index === 1); + const destination = game.state.grids[0].cells.find(cell => cell.index === 8); assert(destination); await game.click((destination.bounds[0] + destination.bounds[2]) / 2, (destination.bounds[1] + destination.bounds[3]) / 2); await game.wait('native item drop', state => state.dragged[0] === 0 && state.grids[0].cells.some(cell => - cell.index === 1 && cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy)); + cell.index === 8 && cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy)); assert.deepEqual((await fixture.state(context)).items, items); await game.key('i'); @@ -151,7 +150,6 @@ test('mobile cursor stays suppressed while touch transfers an inventory item', { hasTouch: true, isMobile: true}); const response = await context.request.post(fixture.url + '/browser-launch'); assert.equal(response.status(), 200); - await fixture.setup(context, 'grant-item', {template: 121567}); const items = (await fixture.state(context)).items; const game = await fixture.game(context); await game.key('i'); @@ -165,9 +163,9 @@ test('mobile cursor stays suppressed while touch transfers an inventory item', { await tap(0); await game.wait('touch pickup', state => state.dragged[0] !== 0); - await tap(1); + await tap(8); await game.wait('touch drop', state => state.dragged[0] === 0 && state.grids[0].cells.some(cell => - cell.index === 1 && cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy)); + cell.index === 8 && cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy)); assert.equal(await game.page.locator('canvas').evaluate(canvas => getComputedStyle(canvas).cursor), 'none'); assert.deepEqual((await fixture.state(context)).items, items); diff --git a/tests/e2e/storage.test.mjs b/tests/e2e/storage.test.mjs @@ -10,7 +10,6 @@ for (const denied of [true, false]) { {timeout: 120_000}, async () => { await withFixture(denied ? 'storage-denied' : 'storage-persistent', async fixture => { const context = await fixture.visitor(); - await fixture.setup(context, 'grant-item', {template: 121567}); const items = (await fixture.state(context)).items; if (denied) { // Firefox private browsing rejects this call on both pages and workers. diff --git a/tests/e2e/visitor.test.mjs b/tests/e2e/visitor.test.mjs @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import {before, test} from 'node:test'; +import {buildServer, withFixture} from './fixture.mjs'; + +before(buildServer); + +function receivedTitle(game, id) { + const event = game.events.findLast(event => event.direction === 'framereceived' && event.opcode === '734e5a7b' && + Buffer.from(event.hex, 'hex').readUInt32BE(24) === id); + assert(event, 'the server must publish the title for this actor'); + const packet = Buffer.from(event.hex, 'hex'); + assert.equal(packet.readUInt32BE(29), 4); + assert.equal(packet[33], 0); + assert.equal(packet.readUInt32BE(34), packet.length - 38); + return packet.subarray(38).toString(); +} + +test('visitor title is separate from the name and disappears on adoption', {timeout: 180_000}, async () => { + await withFixture('visitor-title', async fixture => { + const context = await fixture.visitor(); + await fixture.setup(context, 'position', {playfield: 705, position: [960, 16.5, 510], rotation: [0, 0, 0, 1]}); + const before = await fixture.state(context); + const game = await fixture.game(context); + await game.key('F1'); + await game.save(fixture.output + '/visitor-self'); + assert.match(before.name, /^[A-Z][a-z]{5,7}$/); + assert.equal(before.items.length, 7); + assert.equal(receivedTitle(game, 1), 'Visitor'); + + const observer = await fixture.visitor(); + await fixture.setup(observer, 'position', {playfield: 705, position: [960, 16.5, 505], rotation: [0, 0, 0, 1]}); + const watching = await fixture.game(observer); + const select = async () => { + const [x, y] = await watching.pick(50000, 1); + await watching.click(x, y); + await watching.wait('visitor selected', state => state.selected[0] === 50000 && state.selected[1] === 1); + }; + await select(); + assert.equal(receivedTitle(watching, 1), 'Visitor'); + await watching.save(fixture.output + '/visitor-observed'); + const sequence = watching.sequence; + await watching.key('t'); + await watching.wait('visitor inspection', () => watching.events.some(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '4d38242e' && event.hex.includes(Buffer.from('Visitor').toString('hex')))); + await watching.save(fixture.output + '/visitor-inspected'); + + await game.page.keyboard.press('Control+Alt+M'); + await game.page.locator('#claim-button').click(); + await game.page.locator('#account-name').fill(before.name); + await game.page.locator('#account-password').fill('visitor title test'); + await Promise.all([game.page.waitForEvent('load'), game.page.locator('#account-submit').click()]); + await game.ready(); + assert.equal(receivedTitle(game, 1), ''); + await game.key('F1'); + await game.save(fixture.output + '/adopted-self'); + await watching.key('Escape'); + await select(); + assert.equal(receivedTitle(watching, 1), ''); + await watching.save(fixture.output + '/adopted-observed'); + assert.deepEqual((await fixture.state(context)).items, before.items); + assert.equal((await fixture.state(context)).name, before.name); + + const cookies = await context.cookies(); + const observerCookies = await observer.cookies(); + await fixture.restart(); + const restored = await fixture.context(); + await restored.addCookies(cookies); + const adopted = await fixture.game(restored); + assert.equal(receivedTitle(adopted, 1), ''); + await adopted.key('F1'); + await adopted.save(fixture.output + '/adopted-cold'); + assert.deepEqual((await fixture.state(restored)).items, before.items); + const returned = await fixture.context(); + await returned.addCookies(observerCookies); + const visitor = await fixture.game(returned); + assert.equal(receivedTitle(visitor, 2), 'Visitor'); + await visitor.key('F1'); + await visitor.save(fixture.output + '/visitor-cold'); + for (const client of [game, watching, adopted, visitor]) assert.deepEqual(client.errors, []); + }); +});