aorecomp

Anarchy Online classic in the browser

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


commit debe1a32ec62c040f6d21ea6a1e20ca1c1ec2e02
parent 4046c3dafcd394ac327a9dc63ac553cb3d5a459f
Author: anon <anon@example.com>
Date:   Wed, 11 Nov 2026 06:47:40 +0000

Use prefixed visitor names and strip the prefix on adoption

Diffstat:
MDEVELOPERS.md | 7+++++--
Mclient/browser/index.html | 2+-
Mclient/tests/browser_accounts.mjs | 9+++++----
Mdocs/character-info.md | 4++--
Mserver/browser_account_change.go | 25++++++++++++++++---------
Mserver/browser_launch.go | 2+-
Mserver/browser_launch_test.go | 8++++----
Mserver/visitor_names.go | 16+++++-----------
Mserver/visitor_names_test.go | 85+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Mtests/e2e/visitor.test.mjs | 40++++++++++++++++++++++++++++++----------
10 files changed, 122 insertions(+), 76 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -386,7 +386,10 @@ Open [the game](http://127.0.0.1:8080/) in a browser supporting shared WebAssemb memory, OffscreenCanvas and WebGL 2. It loads automatically with a randomized Solitus visitor near Bronto Burger in Omni-Entertainment. A persistent cookie identifies your character on later visits; no account or training is -required. New visitors start in run mode with character tips disabled. +required. New visitors start in run mode with character tips disabled. Their +names combine `Visitor` with a capitalized four- or five-letter suffix, staying +within the 12-character limit without a separate title. Saving a visitor defaults +to the generated suffix without `Visitor`; the name remains editable. Opt's Create character from scratch opens the original native creator. After naming, speak to an Arrival Hall representative to choose a faction and enter its training ground. Use Save this character in Opt to enable name/password @@ -417,7 +420,7 @@ chat input. The composer accepts the game's Windows-1252 character set and reports unsupported characters before sending. Android Firefox has been tested on an Android phone. iOS Safari still crashes during startup and is not yet supported. -Press Enter to chat nearby. `/tell Visitor81 hello` sends a private message; +Press Enter to chat nearby. `/tell VisitorBaba hello` sends a private message; `/g Global hello` sends to everyone connected. `/whisper` and `/shout` change the vicinity range. Visitor names contain no spaces so they work in commands. Normal speech reaches 10 metres, whisper 1.5 metres and shout 60 metres, within diff --git a/client/browser/index.html b/client/browser/index.html @@ -1208,7 +1208,7 @@ show(); ]) { document.querySelector('#' + action + '-button').onclick = () => { accountAction = action; - if (action === 'claim') document.querySelector('#account-name').value = currentName; + if (action === 'claim') document.querySelector('#account-name').value = currentName.replace(/^Visitor/, ''); accountError.textContent = ''; accountError.classList.remove('success'); const changingPassword = action === 'password'; diff --git a/client/tests/browser_accounts.mjs b/client/tests/browser_accounts.mjs @@ -54,7 +54,7 @@ function response(status, body) { test('Options offers visitor account flows with credentials hidden until a choice', async () => { const page = accountPage(); - page.replies.push(response(200, {name: 'Lupeza', visitor: true})); + page.replies.push(response(200, {name: 'VisitorLupez', visitor: true})); await page.load(); page.open(); @@ -63,11 +63,12 @@ test('Options offers visitor account flows with credentials hidden until a choic assert.equal(page.element('#password-button').hidden, true); assert.equal(page.element('#account-choices').disabled, false); assert.equal(page.element('#account-form').hidden, true); - assert.match(page.element('#account-current').textContent, /Playing as Lupeza/); + assert.match(page.element('#account-current').textContent, /Playing as VisitorLupez/); assert.equal(page.element('#account-password').value, ''); assert.equal(page.requests[0].url, 'browser-account'); page.choose('claim'); - assert.equal(page.element('#account-name').value, 'Lupeza'); + assert.equal(page.element('#account-name').value, 'Lupez'); + assert.equal(page.element('#account-name').disabled, false); }); test('an adopted player can change password with adoption hidden', async () => { @@ -210,7 +211,7 @@ test('Options opens immediately during loading and reuses identity on every open test('Create launches the native creator without submitting account fields', async () => { const page = accountPage(); - page.replies.push(response(200, {name: 'Lupeza', visitor: true})); + page.replies.push(response(200, {name: 'VisitorLupez', visitor: true})); await page.load(); page.open(); diff --git a/docs/character-info.md b/docs/character-info.md @@ -29,8 +29,8 @@ 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. Unadopted browser players receive the -stored free-text title `Visitor`; inspection retains the database title. The +string is separate from the nickname. Browser visitors have `Visitor` prefixed +to their generated nickname and no free-text title; 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 diff --git a/server/browser_account_change.go b/server/browser_account_change.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "slices" + "strings" ) var ( @@ -51,6 +52,20 @@ func (write *browserAccountWrite) persist(tx *sql.Tx) error { return errBrowserLogin } } else { + if write.action == "claim" { + var adopted bool + var name string + if err := tx.QueryRow("SELECT name, length(password_hash)>0 FROM characters WHERE id=?", write.target).Scan(&name, &adopted); err != nil { + return err + } + if adopted { + return errBrowserAdopted + } + // Adopting the generated name removes its visitor prefix. + if strings.EqualFold(name, write.name) { + write.name = strings.TrimPrefix(name, "Visitor") + } + } var taken bool except := write.target if write.created != nil { @@ -62,15 +77,6 @@ func (write *browserAccountWrite) persist(tx *sql.Tx) error { if taken { return errBrowserNameTaken } - if write.action == "claim" { - var adopted bool - if err := tx.QueryRow("SELECT length(password_hash)>0 FROM characters WHERE id=?", write.target).Scan(&adopted); err != nil { - return err - } - if adopted { - return errBrowserAdopted - } - } } if write.created != nil { @@ -162,6 +168,7 @@ func (change *browserAccountChange) persist(coordinator *worldCoordinator) error return err } change.target = write.target + change.name = write.name if change.created != nil { change.created.id = write.target } diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -59,7 +59,7 @@ func (state *server) browserLaunch(w http.ResponseWriter, r *http.Request) { } token = rand.Text() - player := &character{title: "Visitor", running: true, level: 1, profession: 1, + player := &character{running: true, level: 1, profession: 1, browserTokenHash: fmt.Sprintf("%x", sha256.Sum256([]byte(token))), playfield: 705, position: [3]float32{960 + float32(mathrand.IntN(49)-24)/8, 16.5, 510 + float32(mathrand.IntN(49)-24)/8}, rotation: [4]float32{0, 0.9238795, 0, -0.3826834}} diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go @@ -67,11 +67,11 @@ func TestBrowserLaunchCreatesPersistentVisitor(t *testing.T) { 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 { + if !regexp.MustCompile(`^Visitor[A-Z][a-z]{3,4}$`).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 || visitor.title != "Visitor" || world.characters[1].title != "Visitor" { - t.Fatal("new visitor did not retain its title and run mode") + if !visitor.running || visitor.title != "" || world.characters[1].title != "" { + t.Fatal("new visitor has a title or lost 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) @@ -167,7 +167,7 @@ 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" || world.characters[1].title != "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 != "" { t.Fatal("editing lost the visitor credential") } } diff --git a/server/visitor_names.go b/server/visitor_names.go @@ -9,8 +9,8 @@ import ( "modernc.org/sqlite/lib" ) -// CV/CCV beginnings, CV middles and CV/CVC endings keep names at 6-8 letters. -var visitorNameParts = [3][]string{ +// CV/CCV beginnings and CV/CVC endings form four- or five-letter suffixes. +var visitorNameParts = [2][]string{ strings.Fields(` ba be bi bo bu ca ce ci co cu da de di do du fa fe fi fo fu ga ge gi go gu ha he hi ho hu ja je ji jo ju ka ke ki ko ku @@ -23,11 +23,6 @@ var visitorNameParts = [3][]string{ pla ple pli plo plu pra pre pri pro pru sla sle sli slo slu sna sne sni sno snu sta ste sti sto stu tra tre tri tro tru`), strings.Fields(` - ba be bi bo bu da de di do du fa fe fi fo fu ga ge gi go gu - ja je ji jo ju ka ke ki ko ku la le li lo lu ma me mi mo mu - na ne ni no nu pa pe pi po pu ra re ri ro ru sa se si so su - ta te ti to tu va ve vi vo vu za ze zi zo zu`), - strings.Fields(` ba be bi bo bu ban ben bin bon bun bal bel bil bol bul bam bem bim bom bum da de di do du dan den din don dun dal del dil dol dul dam dem dim dom dum fa fe fi fo fu fan fen fin fon fun fal fel fil fol ful fam fem fim fom fum @@ -65,10 +60,9 @@ func usableVisitorName(name string) bool { func randomVisitorName() string { for { name := visitorNameParts[0][visitorNameRoll(len(visitorNameParts[0]))] + - visitorNameParts[1][visitorNameRoll(len(visitorNameParts[1]))] + - visitorNameParts[2][visitorNameRoll(len(visitorNameParts[2]))] - if usableVisitorName(name) { - return strings.ToUpper(name[:1]) + name[1:] + visitorNameParts[1][visitorNameRoll(len(visitorNameParts[1]))] + if len(name) <= 5 && usableVisitorName(name) { + return "Visitor" + strings.ToUpper(name[:1]) + name[1:] } } } diff --git a/server/visitor_names_test.go b/server/visitor_names_test.go @@ -10,11 +10,11 @@ import ( ) func TestVisitorNamePoolDistinctCapacity(t *testing.T) { - // Unique parts, prefix-free beginnings and fixed middles prove unique names. + // Unique parts and prefix-free beginnings prove unique suffixes. for position, parts := range visitorNameParts { seen := make(map[string]bool) for _, part := range parts { - if seen[part] || len(part) < 2 || len(part) > 3 || position == 1 && len(part) != 2 { + if seen[part] || len(part) < 2 || len(part) > 3 { t.Fatal("ambiguous syllable", position, part) } for _, letter := range part { @@ -33,30 +33,30 @@ func TestVisitorNamePoolDistinctCapacity(t *testing.T) { } } - // Count the actual usable pool after filtering, without storing millions of names. - var counts [3]int + // Count the usable suffixes that fit after the seven-letter prefix. + var counts [2]int for _, beginning := range visitorNameParts[0] { - for _, middle := range visitorNameParts[1] { - for _, ending := range visitorNameParts[2] { - name := beginning + middle + ending - if len(name) < 6 || len(name) > 8 { - t.Fatal("name outside the intended length", name) - } - if usableVisitorName(name) { - counts[len(name)-6]++ - } + for _, ending := range visitorNameParts[1] { + name := beginning + ending + if len(name) <= 5 && usableVisitorName(name) { + counts[len(name)-4]++ } } } - if counts != [3]int{494983, 1882830, 1224905} { + if counts != [2]int{6677, 25399} { t.Fatal("usable distinct capacity changed", counts) } } -func TestRandomVisitorNameRejectsCrossSyllableWords(t *testing.T) { +func TestBrowserLaunchRejectsLongAndBlockedVisitorNames(t *testing.T) { + world := newTestServer(t) original := visitorNameRoll t.Cleanup(func() { visitorNameRoll = original }) - rolls := []int{slices.Index(visitorNameParts[0], "tri"), slices.Index(visitorNameParts[1], "ji"), slices.Index(visitorNameParts[2], "ze"), 0, 0, 0} + rolls := []int{ + slices.Index(visitorNameParts[0], "bla"), slices.Index(visitorNameParts[1], "ban"), + slices.Index(visitorNameParts[0], "ji"), slices.Index(visitorNameParts[1], "za"), + slices.Index(visitorNameParts[0], "bla"), slices.Index(visitorNameParts[1], "ba"), + } calls := 0 visitorNameRoll = func(bound int) int { value := rolls[calls] @@ -67,10 +67,10 @@ func TestRandomVisitorNameRejectsCrossSyllableWords(t *testing.T) { return value } - name := randomVisitorName() + accountVisitor(t, world) - if name != "Bababa" || calls != 6 { - t.Fatal("blocked combination was not retried", name, calls) + if world.characters[1].name != "VisitorBlaba" || calls != 6 { + t.Fatal("long or blocked combination was not retried", world.characters[1].name, calls) } } @@ -78,7 +78,7 @@ func TestBrowserLaunchRetriesCaseInsensitiveNameCollision(t *testing.T) { world := newTestServer(t) existing := world.newCharacter() profile := existing.userData() - profile.Name = "bAbAbA" + profile.Name = "vIsItOrBaBa" if err := world.updateUser(profile); err != nil { t.Fatal(err) } @@ -87,7 +87,7 @@ func TestBrowserLaunchRetriesCaseInsensitiveNameCollision(t *testing.T) { calls := 0 visitorNameRoll = func(int) int { calls++ - if calls == 6 { + if calls == 4 { return 1 } return 0 @@ -96,14 +96,14 @@ func TestBrowserLaunchRetriesCaseInsensitiveNameCollision(t *testing.T) { world.browserLaunch(response, httptest.NewRequest("POST", "/browser-launch", nil)) - if response.Code != http.StatusOK || world.characters[2].name != "Bababe" || calls != 6 || existing.name != "bAbAbA" { + if response.Code != http.StatusOK || world.characters[2].name != "VisitorBabe" || calls != 4 || existing.name != "vIsItOrBaBa" { t.Fatal("visitor collision changed an existing character or skipped retry", response.Code, calls) } // The database protects unclaimed names too; repeated NPC names remain valid. - if _, err := world.db.Exec("UPDATE characters SET name='BABABE' WHERE id=1"); err == nil { + if _, err := world.db.Exec("UPDATE characters SET name='VISITORBABE' WHERE id=1"); err == nil { t.Fatal("database accepted a case-insensitive duplicate visitor name") } - if _, err := world.db.Exec("INSERT INTO characters(id,name) VALUES (4294967294,'Bababe'),(4294967295,'Bababe')"); err != nil { + if _, err := world.db.Exec("INSERT INTO characters(id,name) VALUES (4294967294,'VisitorBabe'),(4294967295,'VisitorBabe')"); err != nil { t.Fatal("player name constraint affected NPCs", err) } } @@ -117,7 +117,7 @@ func TestBrowserLaunchRetriesNameClaimedDuringSave(t *testing.T) { t.Fatal(err) } // Claim the candidate after the availability check, at the INSERT boundary. - if _, err := world.db.Exec("CREATE TRIGGER claim_candidate BEFORE INSERT ON characters WHEN NEW.id=2 AND NEW.name='Bababa' BEGIN UPDATE characters SET name=NEW.name WHERE id=1; END"); err != nil { + if _, err := world.db.Exec("CREATE TRIGGER claim_candidate BEFORE INSERT ON characters WHEN NEW.id=2 AND NEW.name='VisitorBaba' BEGIN UPDATE characters SET name=NEW.name WHERE id=1; END"); err != nil { t.Fatal(err) } original := visitorNameRoll @@ -125,7 +125,7 @@ func TestBrowserLaunchRetriesNameClaimedDuringSave(t *testing.T) { calls := 0 visitorNameRoll = func(int) int { calls++ - if calls == 6 { + if calls == 4 { return 1 } return 0 @@ -138,7 +138,7 @@ func TestBrowserLaunchRetriesNameClaimedDuringSave(t *testing.T) { if err := world.db.QueryRow("SELECT name FROM characters WHERE id=1").Scan(&savedName); err != nil { t.Fatal(err) } - if response.Code != http.StatusOK || calls != 6 || world.characters[2].name != "Bababe" || savedName != "Existing" { + if response.Code != http.StatusOK || calls != 4 || world.characters[2].name != "VisitorBabe" || savedName != "Existing" { t.Fatal("save-time name conflict did not roll back and retry", response.Code, calls, savedName, response.Body) } } @@ -187,12 +187,14 @@ func TestBrowserLaunchConcurrentNamesStayUnique(t *testing.T) { } } -func TestBrowserVisitorCanAdoptItsGeneratedName(t *testing.T) { +func TestBrowserVisitorAdoptionRemovesPrefix(t *testing.T) { world := newTestServer(t) + original := visitorNameRoll + t.Cleanup(func() { visitorNameRoll = original }) + visitorNameRoll = func(int) int { return 0 } cookie := accountVisitor(t, world) - name := world.characters[1].name - claimed := accountRequest(world, cookie, "claim", name, "password") + claimed := accountRequest(world, cookie, "claim", "VisitorBaba", "password") if claimed.Code != http.StatusNoContent { t.Fatal("generated name could not be kept", claimed.Code, claimed.Body) } @@ -205,8 +207,27 @@ func TestBrowserVisitorCanAdoptItsGeneratedName(t *testing.T) { Name string Visitor, Adopted bool } - if err := json.Unmarshal(response.Body.Bytes(), &state); err != nil || state.Name != name || state.Visitor || !state.Adopted { - t.Fatal("adoption depended on the name spelling", response.Body, err) + if err := json.Unmarshal(response.Body.Bytes(), &state); err != nil || state.Name != "Baba" || state.Visitor || !state.Adopted { + t.Fatal("adoption did not remove the visitor prefix", response.Body, err) + } +} + +func TestBrowserVisitorAdoptionChecksStrippedNameCollision(t *testing.T) { + world := newTestServer(t) + original := visitorNameRoll + t.Cleanup(func() { visitorNameRoll = original }) + visitorNameRoll = func(int) int { return 0 } + cookie := accountVisitor(t, world) + existing := world.newCharacter().userData() + existing.Name = "Baba" + if err := world.updateUser(existing); err != nil { + t.Fatal(err) + } + + response := accountRequest(world, cookie, "claim", "VisitorBaba", "password") + + if response.Code != http.StatusConflict || world.characters[1].name != "VisitorBaba" { + t.Fatal("stripped name collision changed the visitor", response.Code, response.Body) } } diff --git a/tests/e2e/visitor.test.mjs b/tests/e2e/visitor.test.mjs @@ -15,39 +15,58 @@ function receivedTitle(game, id) { 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 => { +test('visitor prefix works in chat and is removed on adoption', {timeout: 180_000}, async () => { + await withFixture('visitor-name', async fixture => { const context = await fixture.visitor(); + const replies = []; + context.on('page', page => page.on('websocket', socket => { + if (socket.url().endsWith('/browser-chat')) + socket.on('framereceived', ({payload}) => replies.push(Buffer.from(payload).toString())); + })); 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.match(before.name, /^Visitor[A-Z][a-z]{3,4}$/); assert.equal(before.items.length, 7); - assert.equal(receivedTitle(game, 1), 'Visitor'); + assert.equal(receivedTitle(game, 1), ''); const observer = await fixture.visitor(); + const observerReplies = []; + observer.on('page', page => page.on('websocket', socket => { + if (socket.url().endsWith('/browser-chat')) + socket.on('framereceived', ({payload}) => observerReplies.push(Buffer.from(payload).toString())); + })); await fixture.setup(observer, 'position', {playfield: 705, position: [960, 16.5, 505], rotation: [0, 0, 0, 1]}); const watching = await fixture.game(observer); + + await watching.key('Enter'); + await watching.page.keyboard.type(`/tell ${before.name} visitor name test`); + await watching.key('Enter'); + + await game.wait('tell reaches the generated visitor name', () => replies.some(reply => reply.includes('visitor name test'))); + assert(observerReplies.some(reply => reply.includes(before.name)), 'chat must receive the full camelcase name'); + await watching.save(fixture.output + '/visitor-chat'); 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'); + assert.equal(receivedTitle(watching, 1), ''); 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')))); + event.direction === 'framereceived' && event.opcode === '4d38242e')); 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'); + assert.equal(await game.page.locator('#account-name').inputValue(), before.name.slice(7)); + assert.equal(await game.page.locator('#account-name').isEditable(), true); + await game.page.locator('#account-password').fill('visitor name test'); await Promise.all([game.page.waitForEvent('load'), game.page.locator('#account-submit').click()]); await game.ready(); assert.equal(receivedTitle(game, 1), ''); @@ -58,7 +77,7 @@ test('visitor title is separate from the name and disappears on adoption', {time 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); + assert.equal((await fixture.state(context)).name, before.name.slice(7)); const cookies = await context.cookies(); const observerCookies = await observer.cookies(); @@ -70,10 +89,11 @@ test('visitor title is separate from the name and disappears on adoption', {time await adopted.key('F1'); await adopted.save(fixture.output + '/adopted-cold'); assert.deepEqual((await fixture.state(restored)).items, before.items); + assert.equal((await fixture.state(restored)).name, before.name.slice(7)); const returned = await fixture.context(); await returned.addCookies(observerCookies); const visitor = await fixture.game(returned); - assert.equal(receivedTitle(visitor, 2), 'Visitor'); + assert.equal(receivedTitle(visitor, 2), ''); await visitor.key('F1'); await visitor.save(fixture.output + '/visitor-cold'); for (const client of [game, watching, adopted, visitor]) assert.deepEqual(client.errors, []);