commit ce2a5b2ae72a7f550351d91a53143340c06bb33d parent 284863f45df23e9e38d7fa21608047850259494a Author: anon <anon@example.com> Date: Sun, 8 Nov 2026 05:30:32 +0000 Require five-character passwords and confirm initial admin setup Diffstat:
23 files changed, 249 insertions(+), 65 deletions(-)
diff --git a/TODO.md b/TODO.md @@ -60,6 +60,11 @@ research separately. More screenshots and test cases do not count as new gamepla without duplicate characters/items. Hall dialogue, outfits and departure policy remain explicit reconstructions; see [character creation](docs/character-creation.md) and [Arrival Hall](docs/arrival-hall.md). + November 7: new player and admin passwords require at least five characters, + including visitor adoption and password changes. Initial admin setup requires + password confirmation. Browser checks cover rejected short passwords, matching + confirmation and live password changes; server regressions cover rejection + without account changes and five-character credentials after restart. - [x] **Give new visitors starter items and a separate Visitor title.** New visitors receive the character-creation starter kit atomically. A free-text diff --git a/client/browser/index.html b/client/browser/index.html @@ -137,8 +137,8 @@ <form id="creation-form"> <fieldset id="creation-fields"> <label>Name <input id="creation-player-name" name="username" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="12" required></label> - <label>Password <input id="creation-password" name="password" type="password" autocomplete="new-password" maxlength="1024"></label> - <label>Confirm password <input id="creation-password-confirm" type="password" autocomplete="new-password" maxlength="1024"></label> + <label>Password <input id="creation-password" name="password" type="password" autocomplete="new-password" minlength="5" maxlength="1024" required></label> + <label>Confirm password <input id="creation-password-confirm" type="password" autocomplete="new-password" minlength="5" maxlength="1024" required></label> <div id="creation-actions"> <button id="creation-submit" type="submit">OK</button> </div> @@ -477,6 +477,11 @@ show(); document.querySelector('#creation-form').onsubmit = async event => { event.preventDefault(); if (creationFields.disabled || creationSubmitted) return; + if (Array.from(document.querySelector('#creation-password').value).length < 5) { + creationError.textContent = 'Use a password of at least 5 characters.'; + document.querySelector('#creation-password').focus(); + return; + } if (document.querySelector('#creation-password').value !== document.querySelector('#creation-password-confirm').value) { creationError.textContent = 'Passwords do not match.'; document.querySelector('#creation-password-confirm').focus(); @@ -1070,6 +1075,8 @@ show(); document.querySelector('#account-title').textContent = title; document.querySelector('#account-description').textContent = description; document.querySelector('#account-submit').textContent = title; + document.querySelector('#account-password').required = action !== 'login'; + document.querySelector('#account-password').minLength = action === 'login' ? 0 : 5; document.querySelector('#account-password').autocomplete = action === 'login' ? 'current-password' : 'new-password'; document.querySelector(changingPassword ? '#account-password' : '#account-name').focus(); }; @@ -1111,6 +1118,11 @@ show(); accountForm.onsubmit = async event => { event.preventDefault(); if (accountRequest || !accountAction) return; + if (accountAction !== 'login' && Array.from(document.querySelector('#account-password').value).length < 5) { + accountError.textContent = 'Use a password of at least 5 characters.'; + document.querySelector('#account-password').focus(); + return; + } accountRequest = true; accountFields.disabled = true; accountError.textContent = ''; diff --git a/client/tests/browser_accounts.mjs b/client/tests/browser_accounts.mjs @@ -83,8 +83,8 @@ test('an adopted player can change password with adoption hidden', async () => { assert.equal(page.element('#account-current').textContent, 'Playing as Alice.'); }); -for (const password of ['updated password', '']) { - test(`password change accepts ${password ? 'a new password' : 'an empty password'} without reloading`, async () => { +for (const password of ['updated password', 'valid']) { + test(`password change accepts ${password} without reloading`, async () => { const page = accountPage(); page.choose('password'); page.element('#account-password').value = password; @@ -241,3 +241,23 @@ test('Back clears credentials before switching account flows', async () => { assert.equal(page.element('#account-password').autocomplete, 'current-password'); }); + +for (const action of ['claim', 'password']) { + for (const password of ['', 'abcd', '\u00e9\u00e9\u00e9\u00e9']) { + test(`${action} refuses short passwords: ${JSON.stringify(password)}`, async () => { + const page = accountPage(); + page.choose(action); + page.element('#account-password').value = password; + + await page.submit(); + + assert.equal(page.requests.length, 0); + assert.equal(page.element('#account-error').textContent, 'Use a password of at least 5 characters.'); + assert.equal(page.element('#account-password').required, true); + assert.equal(page.element('#account-password').minLength, 5); + page.choose('login'); + assert.equal(page.element('#account-password').required, false); + assert.equal(page.element('#account-password').minLength, 0); + }); + } +} diff --git a/client/tests/browser_controls.mjs b/client/tests/browser_controls.mjs @@ -184,6 +184,8 @@ test('rejected naming credentials leave the modal editable without advancing', a game.respond(new Response('Name already taken', {status: 409})); game.creationState({active: true, name: {value: ''}}); game.element('#creation-player-name').value = 'Taken'; + game.element('#creation-password').value = 'valid'; + game.element('#creation-password-confirm').value = 'valid'; await game.element('#creation-form').onsubmit({preventDefault() {}}); @@ -1443,3 +1445,19 @@ for (const width of [1600, 320]) { assert.equal(game.element('#player-menu').open, true); }); } + +for (const password of ['', 'abcd', '\u00e9\u00e9\u00e9\u00e9']) { + test(`short creation password is refused: ${JSON.stringify(password)}`, async () => { + const game = page(); + game.creationState({active: true, name: {value: ''}}); + game.element('#creation-password').value = password; + game.element('#creation-password-confirm').value = password; + + await game.element('#creation-form').onsubmit({preventDefault() {}}); + + assert.equal(game.requests.length, 0); + assert.deepEqual(game.creationNames, []); + assert.equal(game.element('#creation-credentials').open, true); + assert.equal(game.element('#creation-error').textContent, 'Use a password of at least 5 characters.'); + }); +} diff --git a/docs/admin.md b/docs/admin.md @@ -5,7 +5,8 @@ creates the first administrator. Complete this setup before exposing the server to other people. Later visits require that username and password. Passwords use the same salted Argon2id implementation as player accounts. Admin accounts are separate from players; there is no recovery flow. -Passwords can be empty. The Admins table links to Create admin and each account's +New passwords require at least five characters. Initial setup also requires +password confirmation. The Admins table links to Create admin and each account's Change password page. Saving a password revokes the account's other sessions while keeping your current session signed in. diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md @@ -174,8 +174,8 @@ then require Letters cannot follow digits. NUL-containing input is rejected, and names are unique without ASCII case distinctions. Original server profanity/reservation lists remain unknown. Login applies the -same normalization. Passwords may be empty and are limited to 1024 -bytes, without trimming, case folding or composition rules. +same normalization. New passwords require at least five characters and are +limited to 1024 bytes, without trimming, case folding or composition rules. Claiming a name commits its name, salt, hash and replacement browser credential in one transaction. Login verifies the password and rotates both the chosen @@ -187,8 +187,8 @@ 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. +the existing password salt and hash and enforce the same five-character minimum +as creation and adoption. Native creation builds a detached level-1 character, then atomically inserts the character, player row, starter item identities and locations, diff --git a/server/admin_auth.go b/server/admin_auth.go @@ -72,6 +72,14 @@ func (server *server) adminLogin(w http.ResponseWriter, r *http.Request) { var id int64 var salt, expected []byte if setup { + if !validNewPassword(password) { + server.adminLoginPage(w, true, name, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest) + return + } + if password != r.PostForm.Get("password_confirm") { + server.adminLoginPage(w, true, name, "Passwords do not match.", http.StatusBadRequest) + return + } salt = make([]byte, 16) if _, err := rand.Read(salt); err != nil { http.Error(w, err.Error(), 500) @@ -139,7 +147,13 @@ func (server *server) adminLoginPage(w http.ResponseWriter, setup bool, name, me if message != "" { fmt.Fprintf(w, "<p class='error' role='alert'>%s</p>", html.EscapeString(message)) } - fmt.Fprintf(w, "<form method='post' action='admin/login'><label>Username<input name='username' value='%s' autocomplete='username' maxlength='64' required></label><label>Password<input name='password' type='password' autocomplete='%s' maxlength='1024'></label><button>%s</button></form></section></main></body></html>", html.EscapeString(name), map[bool]string{true: "new-password", false: "current-password"}[setup], action) + fmt.Fprintf(w, "<form method='post' action='admin/login'><label>Username<input name='username' value='%s' autocomplete='username' maxlength='64' required></label>", html.EscapeString(name)) + if setup { + fmt.Fprint(w, "<label>Password<input name='password' type='password' autocomplete='new-password' minlength='5' maxlength='1024' required></label><label>Confirm password<input name='password_confirm' type='password' autocomplete='new-password' minlength='5' maxlength='1024' required></label>") + } else { + fmt.Fprint(w, "<label>Password<input name='password' type='password' autocomplete='current-password' maxlength='1024'></label>") + } + fmt.Fprintf(w, "<button>%s</button></form></section></main></body></html>", action) } func (server *server) adminAccountsPage(w http.ResponseWriter, r *http.Request) { @@ -177,7 +191,7 @@ func (server *server) adminAccountsPage(w http.ResponseWriter, r *http.Request) func (server *server) createAdmin(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { server.adminPageStart(w, "Create admin", "Admins") - fmt.Fprint(w, "<h1>Create admin</h1><section><form method='post' action='admin/admins/new'><label>Username<input name='username' autocomplete='username' maxlength='64' required></label><label>Password<input name='password' type='password' autocomplete='new-password' maxlength='1024'></label><button>Create admin</button> <a href='admin/admins'>Cancel</a></form></section></main></body></html>") + fmt.Fprint(w, "<h1>Create admin</h1><section><form method='post' action='admin/admins/new'><label>Username<input name='username' autocomplete='username' maxlength='64' required></label><label>Password<input name='password' type='password' autocomplete='new-password' minlength='5' maxlength='1024' required></label><button>Create admin</button> <a href='admin/admins'>Cancel</a></form></section></main></body></html>") return } r.Body = http.MaxBytesReader(w, r.Body, 8192) @@ -190,6 +204,10 @@ func (server *server) createAdmin(w http.ResponseWriter, r *http.Request) { http.Error(w, "Invalid username or password", 400) return } + if !validNewPassword(password) { + http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest) + return + } salt := make([]byte, 16) if _, err := rand.Read(salt); err != nil { http.Error(w, err.Error(), 500) @@ -231,7 +249,7 @@ func (server *server) changeAdminPassword(w http.ResponseWriter, r *http.Request return } server.adminPageStart(w, "Change password", "Admins") - fmt.Fprintf(w, "<h1>Change password</h1><section><h2>%s</h2><form method='post' action='admin/admins/%d'><label>New password<input name='password' type='password' autocomplete='new-password' maxlength='1024'></label><button>Save password</button> <a href='admin/admins'>Cancel</a></form></section></main></body></html>", html.EscapeString(username), id) + fmt.Fprintf(w, "<h1>Change password</h1><section><h2>%s</h2><form method='post' action='admin/admins/%d'><label>New password<input name='password' type='password' autocomplete='new-password' minlength='5' maxlength='1024' required></label><button>Save password</button> <a href='admin/admins'>Cancel</a></form></section></main></body></html>", html.EscapeString(username), id) return } r.Body = http.MaxBytesReader(w, r.Body, 8192) @@ -240,8 +258,8 @@ func (server *server) changeAdminPassword(w http.ResponseWriter, r *http.Request return } password := r.PostForm.Get("password") - if !r.PostForm.Has("password") || len(password) > 1024 { - http.Error(w, "Invalid password", 400) + if !validNewPassword(password) { + http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", 400) return } salt := make([]byte, 16) diff --git a/server/admin_player_password.go b/server/admin_player_password.go @@ -37,8 +37,8 @@ func (server *server) changePlayerPassword(w http.ResponseWriter, r *http.Reques message := "" if r.Method == http.MethodPost { r.Body = http.MaxBytesReader(w, r.Body, 8192) - if err := r.ParseForm(); err != nil || !r.PostForm.Has("password") || len(r.PostForm.Get("password")) > 1024 { - message = "Invalid password" + if err := r.ParseForm(); err != nil || !validNewPassword(r.PostForm.Get("password")) { + message = "Use a password of at least 5 characters and at most 1024 bytes." } else { // Password changes preserve the player's current game session. salt := make([]byte, 16) @@ -66,5 +66,5 @@ func (server *server) changePlayerPassword(w http.ResponseWriter, r *http.Reques if message != "" { fmt.Fprintf(w, "<p class='error' role='alert'>%s</p>", message) } - fmt.Fprintf(w, "<form method='post' action='admin/players/%d/password'><label>New password<input name='password' type='password' autocomplete='new-password' maxlength='1024'></label><button>Save password</button> <a href='admin/players/%d'>Cancel</a></form></section></main></body></html>", id, id) + fmt.Fprintf(w, "<form method='post' action='admin/players/%d/password'><label>New password<input name='password' type='password' autocomplete='new-password' minlength='5' maxlength='1024' required></label><button>Save password</button> <a href='admin/players/%d'>Cancel</a></form></section></main></body></html>", id, id) } diff --git a/server/admin_player_password_test.go b/server/admin_player_password_test.go @@ -11,19 +11,19 @@ import ( func TestAdminChangesPlayerPasswordWithoutDisconnecting(t *testing.T) { world := newTestServer(t) visitor := accountVisitor(t, world) - if response := accountRequest(world, visitor, "claim", "Alice", "old"); response.Code != 204 { + if response := accountRequest(world, visitor, "claim", "Alice", "old password"); response.Code != 204 { t.Fatal(response.Body) } connection := &combatInterestConn{} client := &worldClient{id: 1, ready: true, conn: connection} world.clients[1] = client handler := world.httpHandler() - setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=", nil) + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) cookie := setup.Result().Cookies()[0] path := fmt.Sprintf("/admin/players/%d/password", client.id) page := adminRequest(handler, "GET", path, "", cookie) unauthorized := adminRequest(handler, "POST", path, "password=wrong", nil) - changed := adminRequest(handler, "POST", path, "password=", cookie) + changed := adminRequest(handler, "POST", path, "password=valid", cookie) profile := adminRequest(handler, "GET", "/admin/players/1", "", cookie) var salt, hash []byte if err := world.db.QueryRow("SELECT password_salt,password_hash FROM characters WHERE id=1").Scan(&salt, &hash); err != nil { @@ -40,7 +40,7 @@ func TestAdminChangesPlayerPasswordWithoutDisconnecting(t *testing.T) { !strings.Contains(profile.Body.String(), "<p><a href='admin/players/1/teleport'>Teleport</a></p><p><a href='admin/players/1/password'>Change password</a></p>") { t.Fatal("adopted profile did not separate its details and actions", profile.Code, profile.Body) } - if len(salt) != 16 || !bytes.Equal(hash, world.browserPassword("", salt)) || world.clients[1] != client || !client.ready || len(connection.packets) != 0 { + if len(salt) != 16 || !bytes.Equal(hash, world.browserPassword("valid", salt)) || world.clients[1] != client || !client.ready || len(connection.packets) != 0 { t.Fatal("password change did not preserve the live session or store a salted hash") } @@ -48,8 +48,8 @@ func TestAdminChangesPlayerPasswordWithoutDisconnecting(t *testing.T) { restored := newTestInventoryServer(t) restored.baseURL = "/" other := accountVisitor(t, restored) - old := accountRequest(restored, other, "login", "Alice", "old") - current := accountRequest(restored, other, "login", "Alice", "") + old := accountRequest(restored, other, "login", "Alice", "old password") + current := accountRequest(restored, other, "login", "Alice", "valid") if old.Code != 401 || current.Code != 204 { t.Fatal("new credential did not survive restart", old.Code, current.Code, current.Body) } @@ -60,7 +60,7 @@ func TestAdminCannotSetVisitorPassword(t *testing.T) { world := newTestServer(t) visitor := accountVisitor(t, world) handler := world.httpHandler() - setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=", nil) + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) cookie := setup.Result().Cookies()[0] profile := adminRequest(handler, "GET", "/admin/players/1", "", cookie) diff --git a/server/admin_test.go b/server/admin_test.go @@ -26,7 +26,7 @@ func TestAdminSetupLoginLogoutAndExpiry(t *testing.T) { world := newAdminTestServer(t) world.baseURL = "/share/demo/" handler := world.httpHandler() - credentials := "username=Operator&password=" + credentials := "username=Operator&password=admin&password_confirm=admin" setup := adminRequest(handler, "GET", "/share/demo/admin/login", "", nil) created := adminRequest(handler, "POST", "https://example.test/share/demo/admin/login", credentials, nil) @@ -56,8 +56,8 @@ func TestAdminSetupLoginLogoutAndExpiry(t *testing.T) { if !strings.Contains(setup.Body.String(), "Create administrator") || cookie.Path != "/share/demo/admin" || !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode { t.Fatal("setup form or cookie scope", cookie) } - if strings.Contains(setup.Body.String(), "minlength") || strings.Contains(setup.Body.String(), "maxlength='1024' required") { - t.Fatal("setup form restricts password length") + if !strings.Contains(setup.Body.String(), "minlength='5'") || !strings.Contains(setup.Body.String(), "name='password_confirm'") { + t.Fatal("setup form lacks password constraints or confirmation") } if general.Code != 200 || slash.Code != 200 || !strings.Contains(general.Body.String(), "href='admin/sql'") || strings.Contains(general.Body.String(), "Create user") { t.Fatal("general navigation") @@ -77,7 +77,7 @@ func TestAdminChangePassword(t *testing.T) { world := newAdminTestServer(t) world.baseURL = "/share/demo/" handler := world.httpHandler() - created := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Operator&password=", nil) + created := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) cookie := created.Result().Cookies()[0] var id int64 if err := world.db.QueryRow("SELECT id FROM admin_users").Scan(&id); err != nil { @@ -93,9 +93,9 @@ func TestAdminChangePassword(t *testing.T) { t.Fatal("change password page", form.Code, form.Body) } - // Both a short password and an empty password can replace the current one. - oldPassword := "" - for _, password := range []string{"x", ""} { + // Valid replacements revoke other sessions while preserving this one. + oldPassword := "admin" + for _, password := range []string{"first", "second"} { other := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Operator&password="+oldPassword, nil) otherCookie := other.Result().Cookies()[0] changed := adminRequest(handler, "POST", path, "password="+password, cookie) @@ -115,7 +115,7 @@ func TestAdminChangePassword(t *testing.T) { oldPassword = password } missing := adminRequest(handler, "POST", path, "", cookie) - unknown := adminRequest(handler, "POST", "/share/demo/admin/admins/9999", "password=", cookie) + unknown := adminRequest(handler, "POST", "/share/demo/admin/admins/9999", "password=valid", cookie) if missing.Code != 400 || unknown.Code != 404 { t.Fatal("invalid password change", missing.Code, unknown.Code) } @@ -125,13 +125,13 @@ func TestAdminCreateAccount(t *testing.T) { world := newAdminTestServer(t) world.baseURL = "/share/demo/" handler := world.httpHandler() - setup := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Operator&password=", nil) + setup := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) cookie := setup.Result().Cookies()[0] form := adminRequest(handler, "GET", "/share/demo/admin/admins/new", "", cookie) - created := adminRequest(handler, "POST", "/share/demo/admin/admins/new", "username=Reviewer&password=", cookie) + created := adminRequest(handler, "POST", "/share/demo/admin/admins/new", "username=Reviewer&password=valid", cookie) duplicate := adminRequest(handler, "POST", "/share/demo/admin/admins/new", "username=reviewer&password=changed", cookie) invalid := adminRequest(handler, "POST", "/share/demo/admin/admins/new", "username=&password=", cookie) - login := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Reviewer&password=", nil) + login := adminRequest(handler, "POST", "/share/demo/admin/login", "username=Reviewer&password=valid", nil) list := adminRequest(handler, "GET", "/share/demo/admin/admins", "", cookie) var count int if err := world.db.QueryRow("SELECT count(*) FROM admin_users").Scan(&count); err != nil { @@ -152,7 +152,7 @@ func TestAdminCreateAccount(t *testing.T) { func TestAdminBoundaryAndCrossOriginWrites(t *testing.T) { world := newAdminTestServer(t) handler := world.httpHandler() - created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := created.Result().Cookies()[0] for _, path := range []string{"/admin", "/admin/", "/admin/admins", "/admin/admins/new", "/admin/admins/1", "/admin/players", "/admin/players/1", "/admin/players/1/teleport", "/admin/items", "/admin/items/catalog", "/admin/items/1", "/admin/sql", "/admin/stats", "/admin/map", "/admin/map-players", "/admin/map-entities", "/admin/map-assets/manifest.json", "/admin/control-map.js"} { @@ -199,7 +199,7 @@ func TestAdminConcurrentSetupCreatesOneAccount(t *testing.T) { for index := range responses { wait.Go(func() { - responses[index] = adminRequest(handler, "POST", "/admin/login", "username="+[]string{"First", "Second"}[index]+"&password=long-test-password", nil) + responses[index] = adminRequest(handler, "POST", "/admin/login", "username="+[]string{"First", "Second"}[index]+"&password=long-test-password&password_confirm=long-test-password", nil) }) } wait.Wait() @@ -216,7 +216,7 @@ func TestAdminConcurrentSetupCreatesOneAccount(t *testing.T) { func TestAdminSQLWritesReadsEscapesAndBoundsOutput(t *testing.T) { world := newAdminTestServer(t) handler := world.httpHandler() - created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := created.Result().Cookies()[0] run := func(query string) *httptest.ResponseRecorder { return adminRequest(handler, "POST", "/admin/sql", url.Values{"query": {query}}.Encode(), cookie) @@ -261,7 +261,7 @@ func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { world.characters[1005001] = &character{id: 1005001, npc: true, health: 100, playfield: 950, name: "Outside", position: [3]float32{300, 0, 300}} world.zoneLinks = map[string]map[uint32]zoneLinks{"target": {950: {Doors: []zoneDoor{{Position: [3]float32{20, 0, 20}, Destination: 800, Arrival: &zoneArrival{Position: [3]float32{40, 0, 40}}}}}}} handler := world.httpHandler() - created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := created.Result().Cookies()[0] players := adminRequest(handler, "GET", "/admin/map-players", "", cookie) @@ -298,7 +298,7 @@ func TestAdminMapFiltersAndBoundsEntities(t *testing.T) { func TestAdminSessionSurvivesDatabaseReopen(t *testing.T) { world := newAdminTestServer(t) - created := adminRequest(world.httpHandler(), "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + created := adminRequest(world.httpHandler(), "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := created.Result().Cookies()[0] hash := sha256.Sum256([]byte(cookie.Value)) @@ -321,7 +321,7 @@ func TestAdminSessionSurvivesDatabaseReopen(t *testing.T) { func TestAdminSQLDoesNotChangeGameConnectionTransactionOrPragmas(t *testing.T) { world := newAdminTestServer(t) handler := world.httpHandler() - created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + created := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := created.Result().Cookies()[0] adminRequest(handler, "POST", "/admin/sql", url.Values{"query": {"PRAGMA foreign_keys=OFF; BEGIN; UPDATE world SET game_seconds=100"}}.Encode(), cookie) @@ -389,7 +389,7 @@ func TestAdminPlayersListsLastIPAddressesAfterDatabaseReopen(t *testing.T) { } world.clients[1] = &worldClient{id: 1, ready: true, conn: &combatTestConn{}} handler := world.httpHandler() - login := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=", nil) + login := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) if err := world.closeDatabase(); err != nil { t.Fatal(err) } diff --git a/server/admin_weather_test.go b/server/admin_weather_test.go @@ -16,7 +16,7 @@ func TestAdminWeatherSendsOriginalTargetPacket(t *testing.T) { world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: connection} shutdown := startTestService(t, world) handler := world.httpHandler() - setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := setup.Result().Cookies()[0] selected := adminRequest(handler, "POST", "/admin/weather", url.Values{"weather": {"2"}}.Encode(), cookie) @@ -50,7 +50,7 @@ func TestAdminWeatherReturnsToAutomatic(t *testing.T) { world.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: connection} shutdown := startTestService(t, world) handler := world.httpHandler() - setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=", nil) + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) cookie := setup.Result().Cookies()[0] started := time.Now() selected := adminRequest(handler, "POST", "/admin/weather", "weather=2", cookie) @@ -94,7 +94,7 @@ func TestAdminWeatherDoesNotRestoreAfterRestart(t *testing.T) { world := newTestServer(t) shutdown := startTestService(t, world) handler := world.httpHandler() - setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password", nil) + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=long-test-password&password_confirm=long-test-password", nil) cookie := setup.Result().Cookies()[0] response := adminRequest(handler, "POST", "/admin/weather", "weather=4", cookie) diff --git a/server/browser_account.go b/server/browser_account.go @@ -63,6 +63,10 @@ func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) { http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a password up to 1024 bytes.", http.StatusBadRequest) return } + if action != "login" && !validNewPassword(password) { + http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest) + return + } var created *character if action == "create" { var err error diff --git a/server/browser_account_test.go b/server/browser_account_test.go @@ -123,7 +123,7 @@ func TestBrowserAccountLoginSwitchesOnlyAfterCorrectPassword(t *testing.T) { func TestBrowserAccountRejectsInvalidClaimsWithoutChangingVisitor(t *testing.T) { for _, scenario := range []struct{ name, password string }{ {"", "password"}, {"123Alice", "password"}, {"Abc", "password"}, {"Al\x00ice", "password"}, {"Ali1ce", "password"}, - {strings.Repeat("a", 255), "password"}, {"Alice", strings.Repeat("a", 1025)}, + {strings.Repeat("a", 255), "password"}, {"Alice", ""}, {"Alice", "abcd"}, {"Alice", "\u00e9\u00e9\u00e9\u00e9"}, {"Alice", strings.Repeat("a", 1025)}, } { t.Run(fmt.Sprintf("name=%q/length=%d", scenario.name, len(scenario.password)), func(t *testing.T) { world := newTestServer(t) diff --git a/server/browser_creation_test.go b/server/browser_creation_test.go @@ -204,7 +204,7 @@ func TestBrowserCreationRejectsInvalidChoicesWithoutChangingCurrentPlayer(t *tes for _, scenario := range []struct{ field, value string }{ {"head_mesh", ""}, {"head_mesh", "1"}, {"head_mesh", "4294967296"}, {"profession", "0"}, {"profession", "13"}, {"profession", "-1"}, {"side", ""}, {"side", "3"}, {"side", "-1"}, {"build", "3"}, {"build", "normal"}, {"height", "0"}, {"height", "95"}, {"height", "65536"}, - {"name", "Abc"}, {"name", "Abc1"}, {"name", "Alice1a"}, {"name", "Thirteenchars"}, {"password", strings.Repeat("a", 1025)}, + {"name", "Abc"}, {"name", "Abc1"}, {"name", "Alice1a"}, {"name", "Thirteenchars"}, {"password", ""}, {"password", "abcd"}, {"password", "\u00e9\u00e9\u00e9\u00e9"}, {"password", strings.Repeat("a", 1025)}, } { t.Run(scenario.field+"="+scenario.value, func(t *testing.T) { fields := creationForm() @@ -219,11 +219,11 @@ func TestBrowserCreationRejectsInvalidChoicesWithoutChangingCurrentPlayer(t *tes } } -func TestBrowserCreationEmptyPasswordSurvivesRestart(t *testing.T) { +func TestBrowserCreationMinimumPasswordSurvivesRestart(t *testing.T) { world := newTestServer(t) visitor := accountVisitor(t, world) fields := creationForm() - fields.Set("password", "") + fields.Set("password", "valid") created := creationRequest(world, visitor, fields) if created.Code != http.StatusNoContent { @@ -233,12 +233,12 @@ func TestBrowserCreationEmptyPasswordSurvivesRestart(t *testing.T) { restored.baseURL = "/" other := accountVisitor(t, restored) wrong := accountRequest(restored, other, "login", "Alice", "wrong") - loggedIn := accountRequest(restored, other, "login", "Alice", "") + loggedIn := accountRequest(restored, other, "login", "Alice", "valid") if wrong.Code != http.StatusUnauthorized || loggedIn.Code != http.StatusNoContent || restored.characters[2].name != "Alice" || restored.characters[2].browserTokenHash == world.characters[2].browserTokenHash || !reflect.DeepEqual(restored.characters[2].inventory.Items, world.characters[2].inventory.Items) { - t.Fatal("empty-password creation lost its login or inventory after restart", wrong.Code, loggedIn.Code) + t.Fatal("minimum-password creation lost its login or inventory after restart", wrong.Code, loggedIn.Code) } } diff --git a/server/browser_password.go b/server/browser_password.go @@ -4,12 +4,17 @@ import ( "crypto/rand" "database/sql" "net/http" + "unicode/utf8" ) +func validNewPassword(password string) bool { + return utf8.RuneCountInString(password) >= 5 && len(password) <= 1024 +} + 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) + if err := r.ParseForm(); err != nil || !validNewPassword(r.PostForm.Get("password")) { + http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest) return } credential := browserCredential(r) diff --git a/server/browser_password_test.go b/server/browser_password_test.go @@ -16,7 +16,7 @@ func TestBrowserPasswordChangePreservesSessionAndSurvivesRestart(t *testing.T) { world := newTestServer(t) visitor := accountVisitor(t, world) var account *httptest.ResponseRecorder - id, oldPassword, newPassword := uint32(1), "old password", "" + id, oldPassword, newPassword := uint32(1), "old password", "valid" if scenario == "adopted" { account = accountRequest(world, visitor, "claim", "Alice", oldPassword) } else { diff --git a/server/browser_password_ui_test.go b/server/browser_password_ui_test.go @@ -38,7 +38,7 @@ func TestBrowserPasswordOptions(t *testing.T) { 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)) { + if !bytes.Equal(hash, world.browserPassword("valid", salt)) { t.Fatal("Options password change did not reach the database") } } diff --git a/server/browser_profile_test.go b/server/browser_profile_test.go @@ -14,7 +14,7 @@ func TestBrowserProfileAdministratorBoundary(t *testing.T) { world := newAdminTestServer(t) world.baseURL = baseURL handler := world.httpHandler() - login := adminRequest(handler, "POST", baseURL+"admin/login", "username=Operator&password=", nil) + login := adminRequest(handler, "POST", baseURL+"admin/login", "username=Operator&password=admin&password_confirm=admin", nil) if login.Code != http.StatusSeeOther { t.Fatal(login.Code, login.Body) } diff --git a/server/native_creation.go b/server/native_creation.go @@ -39,6 +39,10 @@ func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Reque http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a password up to 1024 bytes.", http.StatusBadRequest) return } + if !validNewPassword(password) { + http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest) + return + } credential := browserCredential(r) var currentID uint32 var pending *browserCreationCredentials diff --git a/server/native_creation_test.go b/server/native_creation_test.go @@ -302,7 +302,7 @@ func TestNativeCreationCompetingConnectionCannotCreateTwice(t *testing.T) { } func TestNativeCreationPreparedPasswordSurvivesRestart(t *testing.T) { - for _, password := range []string{"", "chosen password"} { + for _, password := range []string{"valid", "chosen password"} { t.Run(password, func(t *testing.T) { world := newTestServer(t) cookie := accountVisitor(t, world) @@ -340,7 +340,7 @@ func TestNativeCreationRequiresBrowserCredential(t *testing.T) { } func TestNativeCreationPreparationRejectsInvalidCredentials(t *testing.T) { - for _, scenario := range []string{"invalid name", "long password", "duplicate name", "no session"} { + for _, scenario := range []string{"invalid name", "empty password", "short password", "long password", "duplicate name", "no session"} { t.Run(scenario, func(t *testing.T) { world := newTestServer(t) cookie := accountVisitor(t, world) @@ -352,6 +352,10 @@ func TestNativeCreationPreparationRejectsInvalidCredentials(t *testing.T) { switch scenario { case "invalid name": name = "A1" + case "empty password": + password = "" + case "short password": + password = "abcd" case "long password": password = strings.Repeat("x", 1025) case "duplicate name": diff --git a/server/password_policy_test.go b/server/password_policy_test.go @@ -0,0 +1,75 @@ +package main + +import ( + "net/http" + "net/url" + "strings" + "testing" +) + +func TestAdminSetupRequiresValidMatchingPassword(t *testing.T) { + for _, scenario := range []struct{ password, confirmation string }{ + {"", ""}, {"abcd", "abcd"}, {"\u00e9\u00e9\u00e9\u00e9", "\u00e9\u00e9\u00e9\u00e9"}, {"valid", ""}, {"valid", "other"}, + } { + t.Run(scenario.password+"/"+scenario.confirmation, func(t *testing.T) { + world := newAdminTestServer(t) + form := url.Values{"username": {"Operator"}, "password": {scenario.password}, "password_confirm": {scenario.confirmation}} + + response := adminRequest(world.httpHandler(), "POST", "/admin/login", form.Encode(), nil) + + if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "name='password_confirm'") || len(response.Result().Cookies()) != 0 { + t.Fatal("invalid setup accepted or lost confirmation", response.Code, response.Body) + } + var count int + if err := world.db.QueryRow("SELECT count(*) FROM admin_users").Scan(&count); err != nil || count != 0 { + t.Fatal("invalid setup created an admin", count, err) + } + }) + } +} + +func TestPasswordChangesRejectShortPasswordsWithoutChangingCredentials(t *testing.T) { + for _, action := range []string{"player", "admin player", "admin", "create admin"} { + t.Run(action, func(t *testing.T) { + world := newTestServer(t) + handler := world.httpHandler() + visitor := accountVisitor(t, world) + claimed := accountRequest(world, visitor, "claim", "Alice", "valid") + if claimed.Code != http.StatusNoContent { + t.Fatal(claimed.Code, claimed.Body) + } + playerCookie := claimed.Result().Cookies()[0] + setup := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=admin&password_confirm=admin", nil) + if setup.Code != http.StatusSeeOther { + t.Fatal(setup.Code, setup.Body) + } + adminCookie := setup.Result().Cookies()[0] + for _, password := range []string{"", "abcd", "\u00e9\u00e9\u00e9\u00e9"} { + path, cookie := "/browser-account/password", playerCookie + switch action { + case "admin player": + path, cookie = "/admin/players/1/password", adminCookie + case "admin": + path, cookie = "/admin/admins/1", adminCookie + case "create admin": + path, cookie = "/admin/admins/new", adminCookie + } + form := url.Values{"username": {"Reviewer"}, "password": {password}} + response := adminRequest(handler, "POST", path, form.Encode(), cookie) + + if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "at least 5 characters") { + t.Fatal("short password accepted or missing explanation", action, response.Code, response.Body) + } + } + playerLogin := accountRequest(world, playerCookie, "login", "Alice", "valid") + adminLogin := adminRequest(handler, "POST", "/admin/login", "username=Operator&password=admin", nil) + if playerLogin.Code != http.StatusNoContent || adminLogin.Code != http.StatusSeeOther { + t.Fatal("rejected password changed existing credentials", playerLogin.Code, adminLogin.Code) + } + var count int + if err := world.db.QueryRow("SELECT count(*) FROM admin_users").Scan(&count); err != nil || count != 1 { + t.Fatal("invalid password created another admin", count, err) + } + }) + } +} diff --git a/tools/client/test_admin.mjs b/tools/client/test_admin.mjs @@ -26,7 +26,13 @@ try { await page.goto(url + 'admin/'); await page.getByLabel('Username').fill('Operator'); - await page.getByLabel('Password').fill('long-test-password'); + await page.getByLabel('Password', {exact: true}).fill('long-test-password'); + await page.getByLabel('Confirm password', {exact: true}).fill('different-password'); + await page.getByRole('button', {name: 'Create administrator'}).click(); + await page.getByRole('alert').filter({hasText: 'Passwords do not match.'}).waitFor(); + await page.screenshot({path: output + '/setup-confirmation.png'}); + await page.getByLabel('Password', {exact: true}).fill('long-test-password'); + await page.getByLabel('Confirm password', {exact: true}).fill('long-test-password'); await page.getByRole('button', {name: 'Create administrator'}).click(); await page.getByRole('heading', {name: 'General', exact: true}).waitFor(); await page.waitForFunction(() => /^\d/.test(document.querySelector('#query-rate').textContent)); @@ -37,11 +43,11 @@ try { assert.equal(await page.locator('input[type=password]').count(), 0); await page.getByRole('link', {name: 'Create admin', exact: true}).click(); await page.getByLabel('Username', {exact: true}).fill('Reviewer'); - await page.getByLabel('Password', {exact: true}).fill('x'); + await page.getByLabel('Password', {exact: true}).fill('valid'); await page.getByRole('button', {name: 'Create admin', exact: true}).click(); await page.getByRole('row').filter({hasText: 'Reviewer'}).getByRole('link', {name: 'Change password'}).click(); await page.getByRole('heading', {name: 'Change password', exact: true}).waitFor(); - await page.getByLabel('New password', {exact: true}).fill(''); + await page.getByLabel('New password', {exact: true}).fill('other'); await page.getByRole('button', {name: 'Save password', exact: true}).click(); await page.getByRole('status').filter({hasText: 'Password saved.'}).waitFor(); await page.screenshot({path: output + '/admins.png'}); @@ -52,7 +58,7 @@ try { await page.getByRole('alert').filter({hasText: 'Incorrect username or password'}).waitFor(); assert.equal(await page.locator('section.login').count(), 1); assert.equal(await page.getByLabel('Username').inputValue(), 'Reviewer'); - await page.getByLabel('Password', {exact: true}).fill(''); + await page.getByLabel('Password', {exact: true}).fill('other'); await page.getByRole('button', {name: 'Log in', exact: true}).click(); await page.getByRole('heading', {name: 'General', exact: true}).waitFor(); await page.getByRole('link', {name: 'Players', exact: true}).click(); @@ -84,7 +90,7 @@ try { assert(Number(await page.locator('[data-map-teleport] input[name=x]').inputValue()) > 960); await page.getByRole('link', {name: 'Back to player', exact: true}).click(); await page.getByRole('link', {name: 'Change password', exact: true}).click(); - await page.getByLabel('New password', {exact: true}).fill('x'); + await page.getByLabel('New password', {exact: true}).fill('valid'); await page.getByRole('button', {name: 'Save password', exact: true}).click(); await page.getByRole('status').filter({hasText: 'Password changed.'}).waitFor(); await page.getByRole('link', {name: 'SQL', exact: true}).click(); diff --git a/tools/client/test_password_options.mjs b/tools/client/test_password_options.mjs @@ -21,6 +21,12 @@ try { // Save the current visitor through Options and open its password form with real input. await page.locator('#claim-button').click(); await page.locator('#account-name').fill('Passwordtest'); + for (const password of ['', 'abcd']) { + await page.locator('#account-password').fill(password); + await page.locator('#account-submit').click(); + assert.equal(await page.locator('#account-password').evaluate(input => input.checkValidity()), false); + assert.equal((await (await context.request.get(url + 'browser-account')).json()).adopted, false); + } await page.locator('#account-password').fill('original password'); await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]); await game.ready(); @@ -34,9 +40,15 @@ try { 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'); + for (const password of ['', 'abcd']) { + await page.locator('#account-password').fill(password); + await page.locator('#account-submit').click(); + assert.equal(await page.locator('#account-password').evaluate(input => input.checkValidity()), false); + assert.equal(await page.locator('#account-form').isVisible(), true); + } await page.locator('#account-back').click(); - for (const password of ['updated password', '']) { + for (const password of ['updated password', 'valid']) { 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')); @@ -57,7 +69,7 @@ try { assert.equal(game.navigation, navigation); assert.deepEqual(game.errors, []); await game.save(output + '/game'); - console.log('PASS: visitor eligibility, saved player password form, Back, nonempty and empty passwords, unchanged browser credential and live game stream'); + console.log('PASS: visitor eligibility, saved player password form, Back, long and minimum-length passwords, unchanged browser credential and live game stream'); } finally { await browser.close(); }