commit 6f909a18b104936eccc986b22175e48070502e83
parent de1cc738f68dfe6ca150a96fd491feb7484ffc0c
Author: anon <anon@example.com>
Date: Thu, 5 Nov 2026 07:28:39 +0000
Let signed-in players change passwords through Options
Diffstat:
6 files changed, 300 insertions(+), 1 deletion(-)
diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md
@@ -14,6 +14,9 @@ replacement character. The player ID, items, XP, skills, resources, location,
team and native per-character preferences remain attached to that character.
Options first offers Create character from scratch, Adopt this visitor, and
Log in to an existing character. Adoption is hidden for named characters.
+Adopted and newly created players also have Change password, with a single
+New password field. Saving keeps the current browser credential and game
+connections and does not reload the page. Visitors cannot change passwords.
Credentials appear only after choosing a flow; Back clears them. Creation
also offers the original breed/sex/head, build, height, profession and side
choices. A successful login loads that character; a failed submission leaves
@@ -48,6 +51,11 @@ leaving its old cookie authorized. Related changes commit before the response
sets a cookie or reports success; ignored writes and failed COMMITs roll back.
Ordinary character/profile/checkpoint saves leave password columns untouched.
+Password changes authorize the current browser character, regardless of any
+submitted name, and recheck that ownership after hashing. They replace only
+the existing password salt and hash; an empty password remains a login
+credential and does not turn an adopted character back into a visitor.
+
Creation builds a detached level-1 character, then atomically inserts the
character, password, player row, starter item identities and locations,
identity counters and abandoned browser credential. No shared character/item
diff --git a/server/browser_account.go b/server/browser_account.go
@@ -43,7 +43,7 @@ func (server *server) browserAccountInfo(w http.ResponseWriter, r *http.Request)
name, visitor := player.name, !claimed && player.name == fmt.Sprintf("Visitor%d", player.id)
server.mutex.Unlock()
w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": visitor, "heads": gamedata.PlayerAppearances.Heads})
+ json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": visitor, "adopted": claimed, "heads": gamedata.PlayerAppearances.Heads})
}
func (server *server) browserPassword(password string, salt []byte) []byte {
@@ -56,6 +56,10 @@ func (server *server) browserPassword(password string, salt []byte) []byte {
func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
action := r.PathValue("action")
+ if action == "password" {
+ server.changeBrowserPassword(w, r)
+ return
+ }
if action != "claim" && action != "login" && action != "create" {
http.NotFound(w, r)
return
diff --git a/server/browser_password.go b/server/browser_password.go
@@ -0,0 +1,60 @@
+package main
+
+import (
+ "crypto/rand"
+ "net/http"
+)
+
+func (server *server) changeBrowserPassword(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 4096)
+ if err := r.ParseForm(); err != nil || !r.PostForm.Has("password") || len(r.PostForm.Get("password")) > 1024 {
+ http.Error(w, "Invalid password.", http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ player := server.browserCharacter_locked(r)
+ if player == nil {
+ server.mutex.Unlock()
+ http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
+ return
+ }
+ id := player.id
+ server.mutex.Unlock()
+
+ db, err := server.database()
+ var adopted bool
+ if err == nil {
+ err = db.QueryRow("SELECT length(password_hash)>0 FROM characters WHERE id=?", id).Scan(&adopted)
+ }
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if !adopted {
+ http.Error(w, "Adopt this visitor before changing its password.", http.StatusConflict)
+ return
+ }
+
+ // Derive the new credential without blocking the game simulation.
+ salt := make([]byte, 16)
+ if _, err := rand.Read(salt); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ hash := server.browserPassword(r.PostForm.Get("password"), salt)
+
+ // Recheck ownership after hashing and preserve all current game connections.
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ player = server.browserCharacter_locked(r)
+ if player == nil || player.id != id {
+ http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
+ return
+ }
+ var savedID uint32
+ if err := db.QueryRow("UPDATE characters SET password_salt=?, password_hash=? WHERE id=? AND length(password_hash)>0 RETURNING id", salt, hash, id).Scan(&savedID); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/server/browser_password_test.go b/server/browser_password_test.go
@@ -0,0 +1,102 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestBrowserPasswordChangePreservesSessionAndSurvivesRestart(t *testing.T) {
+ for _, scenario := range []string{"adopted", "created"} {
+ t.Run(scenario, func(t *testing.T) {
+ world := newTestServer(t)
+ visitor := accountVisitor(t, world)
+ var account *httptest.ResponseRecorder
+ id, oldPassword, newPassword := uint32(1), "old password", ""
+ if scenario == "adopted" {
+ account = accountRequest(world, visitor, "claim", "Alice", oldPassword)
+ } else {
+ account = creationRequest(world, visitor, creationForm())
+ id, oldPassword, newPassword = 2, "test password", "new password"
+ }
+ if account.Code != http.StatusNoContent {
+ t.Fatal(account.Code, account.Body)
+ }
+ cookie := account.Result().Cookies()[0]
+ before := *world.characters[id]
+ conn := &combatInterestConn{}
+ client := &worldClient{id: id, ready: true, conn: conn}
+ world.clients[id] = client
+ var oldSalt []byte
+ if err := world.db.QueryRow("SELECT password_salt FROM characters WHERE id=?", id).Scan(&oldSalt); err != nil {
+ t.Fatal(err)
+ }
+
+ // A submitted name must never select a different account.
+ response := accountRequest(world, cookie, "password", "Visitor1", newPassword)
+
+ if response.Code != http.StatusNoContent || len(response.Result().Cookies()) != 0 || response.Header().Get("Cache-Control") != "no-store" ||
+ !reflect.DeepEqual(before, *world.characters[id]) || world.clients[id] != client || !client.ready || len(conn.packets) != 0 {
+ t.Fatal("password change altered the character or live session", response.Code, response.Body)
+ }
+ var salt, hash []byte
+ if err := world.db.QueryRow("SELECT password_salt,password_hash FROM characters WHERE id=?", id).Scan(&salt, &hash); err != nil {
+ t.Fatal(err)
+ }
+ if len(salt) != 16 || bytes.Equal(salt, oldSalt) || !bytes.Equal(hash, world.browserPassword(newPassword, salt)) {
+ t.Fatal("new password did not receive a fresh salted hash")
+ }
+ request := httptest.NewRequest("GET", "/browser-account", nil)
+ request.AddCookie(cookie)
+ info := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(info, request)
+ var state struct{ Adopted, Visitor bool }
+ if err := json.Unmarshal(info.Body.Bytes(), &state); err != nil || !state.Adopted || state.Visitor {
+ t.Fatal("changed account lost password eligibility", info.Code, info.Body)
+ }
+
+ restored := newTestInventoryServer(t)
+ restored.baseURL = "/"
+ if restored.browserCharacter_locked(request) == nil {
+ t.Fatal("existing browser credential did not survive restart")
+ }
+ other := accountVisitor(t, restored)
+ old := accountRequest(restored, other, "login", "Alice", oldPassword)
+ current := accountRequest(restored, other, "login", "Alice", newPassword)
+ if old.Code != http.StatusUnauthorized || current.Code != http.StatusNoContent {
+ t.Fatal("saved password did not govern subsequent logins", old.Code, current.Code)
+ }
+ })
+ }
+}
+
+func TestBrowserPasswordChangeRejectsVisitorsAndUnauthenticatedRequests(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ visitor := accountVisitor(t, world)
+ before := *world.characters[1]
+
+ unclaimed := accountRequest(world, visitor, "password", "Alice", "secret")
+ anonymous := accountRequest(world, nil, "password", "Alice", "secret")
+ stale := accountRequest(world, &http.Cookie{Name: "ao_client", Value: "expired"}, "password", "Alice", "secret")
+ oversized := accountRequest(world, visitor, "password", "Alice", strings.Repeat("x", 1025))
+ request := httptest.NewRequest("POST", "https://example.test/browser-account/password", strings.NewReader("password=secret"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.Header.Set("Origin", "https://unrelated.example")
+ request.AddCookie(visitor)
+ crossOrigin := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(crossOrigin, request)
+
+ if unclaimed.Code != http.StatusConflict || anonymous.Code != http.StatusUnauthorized || stale.Code != http.StatusUnauthorized ||
+ oversized.Code != http.StatusBadRequest || crossOrigin.Code != http.StatusForbidden || !reflect.DeepEqual(before, *world.characters[1]) {
+ t.Fatal("invalid password request accepted", unclaimed.Code, anonymous.Code, stale.Code, oversized.Code, crossOrigin.Code)
+ }
+ var length int
+ if err := world.db.QueryRow("SELECT length(password_hash) FROM characters WHERE id=1").Scan(&length); err != nil || length != 0 {
+ t.Fatal("invalid password request adopted the visitor", err, length)
+ }
+}
diff --git a/server/browser_password_ui_test.go b/server/browser_password_ui_test.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ "ao/server/assets"
+ "bytes"
+ "context"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserPasswordOptions(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for password changes through the Options overlay")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ useResources(t, assets.Files)
+ world := newTestServer(t)
+ world.baseURL = "/share/test/"
+ host := httptest.NewServer(world.httpHandler())
+ defer host.Close()
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
+ defer cancel()
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(250 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ world.advancePlayerMovement(now)
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_password_options.mjs"), host.URL+world.baseURL, filepath.Join(root, "local/password-options"))
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ if err := command.Run(); err != nil {
+ t.Fatal(err)
+ }
+
+ var salt, hash []byte
+ if err := world.db.QueryRow("SELECT password_salt,password_hash FROM characters WHERE name='Passwordtest'").Scan(&salt, &hash); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(hash, world.browserPassword("", salt)) {
+ t.Fatal("Options password change did not reach the database")
+ }
+}
diff --git a/tools/client/test_password_options.mjs b/tools/client/test_password_options.mjs
@@ -0,0 +1,66 @@
+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);
+await fs.mkdir(output, {recursive: true});
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium',
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage']});
+try {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ await page.goto(url);
+ await game.ready();
+ await page.keyboard.press('Control+Alt+M');
+ await page.waitForFunction(() => !document.querySelector('#account-choices').disabled);
+ assert.equal(await page.locator('#password-button').isVisible(), false);
+
+ // Create a character through Options and open its password form with real input.
+ await page.locator('#create-button').click();
+ await page.locator('#creation-breed').selectOption('4');
+ await page.locator('#creation-profession').selectOption('9');
+ await page.locator('#creation-side').selectOption('2');
+ await page.locator('#account-name').fill('Passwordtest');
+ await page.locator('#account-password').fill('original password');
+ await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]);
+ await game.ready();
+ const stream = game.worldStream;
+ const navigation = game.navigation;
+ const actor = game.local().id;
+ const cookie = (await context.cookies()).find(value => value.name === 'ao_client').value;
+ await page.keyboard.press('Control+Alt+M');
+ await page.locator('#password-button').click();
+ assert.equal(await page.locator('#account-name').isVisible(), false);
+ assert.equal(await page.locator('#account-name').isDisabled(), true);
+ assert.equal(await page.locator('#account-description').isVisible(), false);
+ assert.equal(await page.getByLabel('New password', {exact: true}).getAttribute('autocomplete'), 'new-password');
+ await page.locator('#account-back').click();
+
+ for (const password of ['updated password', '']) {
+ await page.locator('#password-button').click();
+ await page.getByLabel('New password', {exact: true}).fill(password);
+ const saved = page.waitForResponse(response => response.url().endsWith('/browser-account/password'));
+ await page.locator('#account-submit').click();
+ assert.equal((await saved).status(), 204);
+ await page.getByRole('status').filter({hasText: 'Password changed.'}).waitFor();
+ assert.equal(await page.locator('#account-form').isVisible(), false);
+ assert.equal(await page.locator('#account-password').inputValue(), '');
+ assert.equal((await context.cookies()).find(value => value.name === 'ao_client').value, cookie);
+ assert.equal(game.worldStream, stream);
+ assert.equal(game.navigation, navigation);
+ }
+ await page.screenshot({path: output + '/password-saved.png'});
+ await page.locator('#player-menu').getByRole('button', {name: 'Close', exact: true}).click();
+ await game.ready();
+ assert.equal(game.local().id, actor);
+ assert.equal(game.worldStream, stream);
+ assert.equal(game.navigation, navigation);
+ assert.deepEqual(game.errors, []);
+ await game.save(output + '/game');
+ console.log('PASS: visitor eligibility, created player password form, Back, nonempty and empty passwords, unchanged browser credential and live game stream');
+} finally {
+ await browser.close();
+}