commit d207c6ca73d57d16ef4f050d230579412f77b60e
parent 5a25d667713742620bbb5a445f040d9387fde096
Author: anon <anon@example.com>
Date: Sat, 24 Oct 2026 20:03:57 +0000
Add desktop Options and persistent browser player login
Diffstat:
24 files changed, 1138 insertions(+), 36 deletions(-)
diff --git a/README.md b/README.md
@@ -41,7 +41,7 @@ from other devices.
## 3. Modify and compile the server and game logic
-Install Go 1.24 or newer, then clone and run:
+Install Go 1.26 or newer, then clone and run:
```sh
git clone https://<game-host>/share/demo/code/ao.git
diff --git a/TODO.md b/TODO.md
@@ -965,21 +965,34 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
## Browser options and player login
-- [ ] Show the Opt overlay button in desktop WASM mode as well as mobile.
+- [x] Show the Opt overlay button in desktop WASM mode as well as mobile.
Place it just left of the native blue toolbar in the top-right corner. Hide
the desktop button until the pointer is within roughly 150 CSS pixels; keep
it visible while hovered or while Options is open. Check placement at different
viewport sizes and UI scales, keyboard access, and returning focus to native
controls without disrupting Tab targeting. Keep mobile access usable.
-- [ ] Let a VisitorX player choose a player name and password from the Opt
+- [x] Let a VisitorX player choose a player name and password from the Opt
window. Check: claiming the name preserves that visitor's character and
possessions; duplicate/invalid names or a failed save leave it unchanged.
Store password hashes and verify credentials survive reconnect and restart.
-- [ ] Add player-name/password login to the Opt window. Successful login should
+- [x] Add player-name/password login to the Opt window. Successful login should
leave the current VisitorX session and load the chosen existing player.
Check correct and incorrect credentials, session replacement, reconnect and
restart; failed login must leave the current visitor usable, and switching
must not mix the two players' state or browser preferences.
+ Automated transaction/session tests and hardware WASM checks are recorded
+ in [browser accounts](docs/browser-accounts.md), including a normal-shutdown
+ callback fix found during session replacement.
+- [ ] Add Create character to Options. Guide players through the original
+ character-creation choices, including breed, profession and side, then start
+ the new character in the appropriate training grounds. Research the 14.9.1
+ creation sequence and starting state; test every supported choice and failed
+ or interrupted creation without changing an existing character.
+- [ ] Make the Options account flows explicit: Create character from scratch,
+ Adopt this visitor and choose its name, or Log in to an existing character.
+ Show username/password fields only after selecting the relevant flow, with
+ clear labels and a way back. Check visitor/named players, mobile layout,
+ keyboard navigation and failed submissions without confusing the flows.
## Research resources
@@ -1268,11 +1281,10 @@ and server restarts. Turn every reproduced bug into a focused regression test.
- [x] Repair the browser-profile worker test fixture. Its VM context supplies
`URL`/`location` and checks build/upload URLs relative to the worker location.
`node client/tests/browser_profile.mjs` now exercises all existing assertions.
-- [ ] Align the declared Go test/toolchain requirement with `WaitGroup.Go`
- usage. The module declares Go1.24 while existing concurrency tests use the
- Go1.25 API; full `go vet` reports `stdversion` errors. The other analyzers
- pass with that analyzer disabled. Keep the supported build/test instructions
- and `go.mod` coherent.
+- [x] Align the declared Go test/toolchain requirement with `WaitGroup.Go`
+ usage. The module and build instructions require Go 1.26, matching the
+ account password-hashing dependency and existing concurrency tests.
+ `go vet ./server/...` passes without disabling analyzers.
- Exercise the native client path, not only a server helper or admin edit.
- Persist durable state as part of the feature; verify reconnect and restart.
- Reject invalid, stale and repeated requests without unintended state changes.
diff --git a/client/Makefile.wasm b/client/Makefile.wasm
@@ -115,9 +115,9 @@ build/wasm/web/storage-test.html: tests/browser_storage.c runtime/browser_host.c
@mkdir -p $(@D)
$(CC) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js -o $@ --js-library runtime/browser_profile.js
-build/wasm/web/loop-test.html: tests/browser_loop.c runtime/browser_loop.c runtime/browser_loop.h runtime/guest_memory.c runtime/recomp_state.c Makefile.wasm
+build/wasm/web/loop-test.html: tests/browser_loop.c runtime/browser_loop.c runtime/browser_loop.h runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js Makefile.wasm
@mkdir -p $(@D)
- $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sOFFSCREENCANVAS_SUPPORT -o $@
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sOFFSCREENCANVAS_SUPPORT --js-library runtime/browser_host.js -o $@
build/wasm/web/pacing-test.html: tests/browser_pacing.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
diff --git a/client/browser/index.html b/client/browser/index.html
@@ -18,6 +18,9 @@
#game-toolbar[hidden], #touch-controls[hidden], #chat-compose[hidden], #chat-actions[hidden] { display: none; }
#game-toolbar, #touch-controls { animation: fade-overlays 4s linear forwards; }
#game-surface[data-overlays-active] #game-toolbar, #game-surface[data-overlays-active] #touch-controls { animation: none; opacity: 1; }
+ #game-toolbar[data-desktop] { top: 0; animation: none; opacity: 1; pointer-events: none; }
+ #game-toolbar[data-desktop] #menu-button { min-height: 24px; padding: 2px 6px; border-radius: 3px; font-size: 12px; opacity: 0; pointer-events: none; }
+ #game-toolbar[data-desktop][data-menu-visible] #menu-button, #game-toolbar[data-desktop] #menu-button:focus-visible { opacity: 1; pointer-events: auto; }
@keyframes fade-overlays { from { opacity: 1; } to { opacity: 0; } }
#chat-actions { display: flex; gap: 8px; }
#touch-controls button { pointer-events: auto; touch-action: none; }
@@ -35,7 +38,7 @@
#download-fill { width: 0; height: 100%; background: #9ab9cc; }
#loading[hidden], #download-progress[hidden] { display: none; }
#reconnect { position: fixed; top: calc(50% + 24px); left: 50%; transform: translateX(-50%); padding: 8px 16px; }
- dialog { width: min(320px, calc(100vw - 64px)); padding: 24px; border: 1px solid #777; border-radius: 8px; background: #202428; color: #eee; box-shadow: 0 8px 40px #0008; }
+ dialog { width: min(320px, calc(100vw - 64px)); max-height: calc(100dvh - 64px); overflow: auto; padding: 24px; border: 1px solid #777; border-radius: 8px; background: #202428; color: #eee; box-shadow: 0 8px 40px #0008; }
dialog::backdrop { background: #0006; }
dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 16px; }
dialog h1 { margin: 0; font-size: 20px; }
@@ -45,6 +48,10 @@
dialog label { display: block; margin: 12px 0; }
#menu-error { color: #ffb0a0; }
#menu-error:empty { display: none; }
+ #account-form { margin-top: 20px; border-top: 1px solid #777; }
+ #account-form input { box-sizing: border-box; display: block; width: 100%; margin-top: 6px; padding: 8px; }
+ #account-error { color: #ffb0a0; }
+ #account-error:empty { display: none; }
</style>
<div id="game-surface">
<canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
@@ -56,7 +63,7 @@
<button form="chat-compose">Send</button>
<button id="chat-cancel" type="button">Cancel</button>
</div>
- <button id="menu-button">Opt</button>
+ <button id="menu-button" aria-label="Options" title="Options (Ctrl+Alt+M)">Opt</button>
<button id="chat-button" disabled>Chat</button>
</div>
<div id="touch-controls" hidden>
@@ -90,6 +97,14 @@
<label><input id="touch-enabled" type="checkbox"> Touch controls</label>
<p>Left pad: move. Swipe: steer. Two fingers: orbit and pinch to zoom. Hold: right click.</p>
</div>
+ <form id="account-form" hidden>
+ <p id="account-current"></p>
+ <label>Player name <input id="account-name" name="name" autocomplete="username" maxlength="254" pattern="[A-Za-z][A-Za-z0-9]*" required></label>
+ <label>Password <input id="account-password" name="password" type="password" autocomplete="current-password" maxlength="1024" required></label>
+ <button id="claim-button" name="action" value="claim">Choose name</button>
+ <button id="login-button" name="action" value="login">Log in</button>
+ <p id="account-error" role="status"></p>
+ </form>
</dialog>
<script>
const status = document.querySelector('#loading');
@@ -105,6 +120,7 @@
pixelMode.value = localStorage.getItem('ao-pixel-mode') === 'retina' ? 'retina' : 'css';
let runtimeReady = false, gameReady = false, restarting = false;
let sessionReplaced = false;
+ let accountRequest = false, accountClosed = null;
let recording = null, reportURL = null;
function log(message) {
console.log(message);
@@ -121,6 +137,7 @@
console.error(message);
},
onGameClosed: replaced => {
+ if (accountRequest) { accountClosed = replaced; return; }
if (replaced) {
sessionReplaced = true;
document.querySelector('#reconnect').hidden = false;
@@ -368,6 +385,11 @@ show();
const chatActions = document.querySelector('#chat-actions');
const movePad = document.querySelector('#move-pad');
const autorunButton = document.querySelector('#autorun-button');
+ const gameToolbar = document.querySelector('#game-toolbar');
+ const menuButton = document.querySelector('#menu-button');
+ let menuPointer = null;
+ if (!isMobileBrowser) gameToolbar.dataset.desktop = '';
+ document.querySelector('#chat-button').hidden = !isMobileBrowser;
const heldKeys = new Set();
const overlayTouches = new Set();
let canvasTouch = null, moveTouch = null;
@@ -465,12 +487,37 @@ show();
updateTouchControls();
}
function updateTouchControls() {
- const ready = isMobileBrowser && gameReady && touchRegions?.regions.some(region => region.world);
- document.querySelector('#game-toolbar').hidden = !ready;
- touchControls.hidden = !ready || !touchEnabled.checked || playerMenu.open || !chatForm.hidden;
+ const ready = gameReady && touchRegions?.regions.some(region => region.world);
+ gameToolbar.hidden = !ready;
+ touchControls.hidden = !isMobileBrowser || !ready || !touchEnabled.checked || playerMenu.open || !chatForm.hidden;
+ if (!isMobileBrowser && touchRegions) {
+ // Use the native top strip's hit rectangles so resolution changes retain its alignment.
+ let left = touchRegions.screenWidth;
+ for (const region of touchRegions.regions) {
+ if (!region.world && !region.chat && region.top <= 0 && region.bottom > 0 && region.left > touchRegions.screenWidth / 2)
+ left = Math.min(left, region.left);
+ }
+ gameToolbar.style.right = `${(touchRegions.screenWidth - left) * canvas.clientWidth / touchRegions.screenWidth + 6}px`;
+ updateMenuVisibility();
+ }
if (overlayTouches.size || playerMenu.open || !chatForm.hidden) gameSurface.dataset.overlaysActive = '';
else delete gameSurface.dataset.overlaysActive;
}
+ function updateMenuVisibility() {
+ if (isMobileBrowser) return;
+ const bounds = menuButton.getBoundingClientRect();
+ const distance = menuPointer ? Math.hypot(Math.max(bounds.left - menuPointer[0], 0, menuPointer[0] - bounds.right),
+ Math.max(bounds.top - menuPointer[1], 0, menuPointer[1] - bounds.bottom)) : Infinity;
+ if (playerMenu.open || distance <= 150) gameToolbar.dataset.menuVisible = '';
+ else delete gameToolbar.dataset.menuVisible;
+ }
+ document.addEventListener('pointermove', event => {
+ if (event.pointerType !== 'mouse') return;
+ menuPointer = [event.clientX, event.clientY];
+ updateMenuVisibility();
+ }, true);
+ document.addEventListener('pointerleave', () => { menuPointer = null; updateMenuVisibility(); });
+ window.addEventListener('blur', () => { menuPointer = null; updateMenuVisibility(); });
// Reveal before canvas handlers consume the gesture; fade after the last finger lifts.
document.addEventListener('pointerdown', event => {
if (!isMobileBrowser || event.pointerType === 'mouse') return;
@@ -783,6 +830,7 @@ show();
playerMenu.showModal();
updateTouchControls();
updateResolution();
+ Module.onOptionsOpen?.();
}
document.querySelector('#menu-button').onclick = openMenu;
document.querySelector('#view-button').onclick = () => {
@@ -867,4 +915,53 @@ show();
window.visualViewport?.addEventListener('scroll', updateChatViewport);
startGame().catch(error => Module.onAbort(error.message));
</script>
+<script id="account-controls">
+ const accountForm = document.querySelector('#account-form');
+ const accountError = document.querySelector('#account-error');
+ const claimButton = document.querySelector('#claim-button');
+ const loginButton = document.querySelector('#login-button');
+ Module.onOptionsOpen = async () => {
+ accountForm.hidden = false;
+ accountError.textContent = '';
+ claimButton.hidden = claimButton.disabled = true;
+ loginButton.disabled = true;
+ try {
+ const response = await fetch('browser-account');
+ if (!response.ok) { accountError.textContent = await response.text(); return; }
+ const player = await response.json();
+ document.querySelector('#account-current').textContent = player.visitor ?
+ `Playing as ${player.name}. Choose a name and password to keep this player, or log in to an existing player.` : `Playing as ${player.name}.`;
+ claimButton.hidden = !player.visitor;
+ claimButton.disabled = !player.visitor;
+ loginButton.disabled = false;
+ } catch (error) {
+ accountForm.hidden = false;
+ accountError.textContent = 'Could not load player details. Open Options again to retry.';
+ }
+ };
+ accountForm.onsubmit = async event => {
+ event.preventDefault();
+ if (accountRequest) return;
+ accountRequest = true;
+ claimButton.disabled = loginButton.disabled = true;
+ accountError.textContent = '';
+ try {
+ const response = await fetch('browser-account/' + event.submitter.value, {method: 'POST',
+ body: new URLSearchParams({name: document.querySelector('#account-name').value,
+ password: document.querySelector('#account-password').value})});
+ if (response.ok) { location.reload(); return; }
+ accountError.textContent = await response.text();
+ } catch (error) {
+ accountError.textContent = 'Could not contact the server. Please try again.';
+ }
+ accountRequest = false;
+ claimButton.disabled = claimButton.hidden;
+ loginButton.disabled = false;
+ if (accountClosed !== null) {
+ const replaced = accountClosed;
+ accountClosed = null;
+ Module.onGameClosed(replaced);
+ }
+ };
+</script>
</html>
diff --git a/client/runtime/browser_host.js b/client/runtime/browser_host.js
@@ -1,4 +1,14 @@
addToLibrary({
+ emscripten_request_animation_frame_loop__deps: ['$callUserCallback', '$getWasmTableEntry'],
+ emscripten_request_animation_frame_loop: (callback, userData) => {
+ // Guest shutdown can exit from a frame; let Emscripten handle its exit sentinel.
+ function tick(timestamp) {
+ callUserCallback(() => {
+ if (getWasmTableEntry(callback)(timestamp, userData)) requestAnimationFrame(tick);
+ });
+ }
+ return requestAnimationFrame(tick);
+ },
browser_preferences_directory__deps: ['$UTF8ToString', '$stringToNewUTF8'],
browser_preferences_directory: base => stringToNewUTF8('/persistent/' + encodeURIComponent(UTF8ToString(base))),
$AOAssetRequest: async (url, options) => {
diff --git a/client/tests/browser_accounts.mjs b/client/tests/browser_accounts.mjs
@@ -0,0 +1,149 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import test from 'node:test';
+
+function accountPage() {
+ const elements = new Map(), requests = [], replies = [], reloads = [], timers = [];
+ class Element extends EventTarget {
+ hidden = false;
+ disabled = false;
+ open = true;
+ value = '';
+ style = {};
+ dataset = {};
+ close() { this.open = false; }
+ }
+ const document = new EventTarget();
+ document.querySelector = selector => {
+ if (!elements.has(selector)) elements.set(selector, new Element());
+ return elements.get(selector);
+ };
+ const window = new EventTarget();
+ const context = vm.createContext({
+ document, window, navigator: {userAgent: 'Desktop'}, console, URLSearchParams,
+ localStorage: {getItem() { return null; }},
+ location: {reload: () => reloads.push(true)},
+ setTimeout: callback => timers.push(callback),
+ updateTouchControls() {},
+ fetch: async (url, options) => {
+ requests.push({url, options});
+ const reply = replies.shift();
+ if (reply instanceof Error) throw reply;
+ return await reply;
+ }
+ });
+ const html = fs.readFileSync(new URL('../browser/index.html', import.meta.url), 'utf8');
+ vm.runInContext(html.match(/<script>([\s\S]*?)<\/script>/)[1], context);
+ vm.runInContext(html.match(/<script id="account-controls">([\s\S]*?)<\/script>/)[1], context);
+ return {context, requests, replies, reloads, timers, element: document.querySelector,
+ open: () => context.Module.onOptionsOpen(),
+ submit: action => document.querySelector('#account-form').onsubmit({preventDefault() {}, submitter: {value: action}})};
+}
+
+function response(status, body) {
+ return {ok: status >= 200 && status < 300, json: async () => body, text: async () => body};
+}
+
+test('Options offers a visitor a name and password without exposing credentials', async () => {
+ const page = accountPage();
+ page.replies.push(response(200, {name: 'Visitor1', visitor: true}));
+
+ await page.open();
+
+ assert.equal(page.element('#claim-button').hidden, false);
+ assert.equal(page.element('#claim-button').disabled, false);
+ assert.equal(page.element('#login-button').disabled, false);
+ assert.equal(page.element('#account-form').hidden, false);
+ assert.match(page.element('#account-current').textContent, /Playing as Visitor1/);
+ assert.equal(page.element('#account-password').value, '');
+ assert.equal(page.requests[0].url, 'browser-account');
+});
+
+test('a named player can log in but cannot claim the character again', async () => {
+ const page = accountPage();
+ page.replies.push(response(200, {name: 'Alice', visitor: false}));
+
+ await page.open();
+
+ assert.equal(page.element('#claim-button').hidden, true);
+ assert.equal(page.element('#claim-button').disabled, true);
+ assert.equal(page.element('#login-button').disabled, false);
+ assert.equal(page.element('#account-current').textContent, 'Playing as Alice.');
+});
+
+for (const action of ['claim', 'login']) {
+ test(`${action} posts exact credentials and reloads after success despite a session replacement notification`, async () => {
+ const page = accountPage();
+ page.element('#account-name').value = 'Alice';
+ page.element('#account-password').value = ' spaced password ';
+ let finish;
+ page.replies.push(new Promise(resolve => { finish = resolve; }));
+
+ const pending = page.submit(action);
+ page.context.Module.onGameClosed(true);
+
+ assert.equal(page.element('#player-menu').open, true);
+ assert.equal(page.element('#claim-button').disabled, true);
+ assert.equal(page.element('#login-button').disabled, true);
+ assert.deepEqual(page.reloads, []);
+ assert.equal(page.requests[0].url, 'browser-account/' + action);
+ assert.equal(page.requests[0].options.method, 'POST');
+ assert.equal(page.requests[0].options.body.get('name'), 'Alice');
+ assert.equal(page.requests[0].options.body.get('password'), ' spaced password ');
+
+ await page.submit(action);
+ finish(response(204, ''));
+ await pending;
+
+ assert.equal(page.requests.length, 1);
+ assert.deepEqual(page.reloads, [true]);
+ assert.deepEqual(page.timers, []);
+ });
+}
+
+test('failed login keeps the current game and form available without reloading', async () => {
+ const page = accountPage();
+ page.replies.push(response(401, 'Incorrect player name or password.'));
+
+ await page.submit('login');
+
+ assert.deepEqual(page.reloads, []);
+ assert.equal(page.element('#account-error').textContent, 'Incorrect player name or password.');
+ assert.equal(page.element('#player-menu').open, true);
+ assert.equal(page.element('#claim-button').disabled, false);
+ assert.equal(page.element('#login-button').disabled, false);
+});
+
+test('network failure reports a retryable error and preserves a pending takeover', async () => {
+ const page = accountPage();
+ let fail;
+ page.replies.push(new Promise((_, reject) => { fail = reject; }));
+
+ const pending = page.submit('login');
+ page.context.Module.onGameClosed(true);
+ fail(new Error('Connection lost'));
+ await pending;
+
+ assert.match(page.element('#account-error').textContent, /Please try again/);
+ assert.equal(page.element('#player-menu').open, false);
+ assert.equal(page.element('#loading').textContent, 'This character connected elsewhere.');
+ assert.equal(page.element('#reconnect').hidden, false);
+ assert.deepEqual(page.reloads, []);
+});
+
+for (const reply of [response(401, 'Reconnect to continue.'), new Error('Offline')]) {
+ test('an unavailable account lookup leaves its error visible and controls disabled', async () => {
+ const page = accountPage();
+ page.element('#account-form').hidden = true;
+ page.replies.push(reply);
+
+ await page.open();
+
+ assert.equal(page.element('#account-form').hidden, false);
+ assert.equal(page.element('#claim-button').disabled, true);
+ assert.equal(page.element('#login-button').disabled, true);
+ assert(page.element('#account-error').textContent.length > 0);
+ assert.deepEqual(page.reloads, []);
+ });
+}
diff --git a/client/tests/browser_controls.mjs b/client/tests/browser_controls.mjs
@@ -1051,7 +1051,7 @@ test('desktop resolution settings remain available without enabling mobile overl
game.element('#player-menu').close();
assert.equal(game.element('#touch-controls').hidden, true);
- assert.equal(game.element('#game-toolbar').hidden, true);
+ assert.equal(game.element('#game-toolbar').hidden, false);
assert.equal(game.element('#mobile-options').hidden, true);
assert.deepEqual(game.keys, []);
assert.equal(game.element('#touch-enabled').checked, false);
@@ -1074,7 +1074,7 @@ test('desktop touch input and saved preferences cannot activate mobile controls'
game.fire('#canvas', 'pointerup');
game.fire('#chat-button', 'click');
- assert.equal(game.element('#game-toolbar').hidden, true);
+ assert.equal(game.element('#game-toolbar').hidden, false);
assert.equal(game.element('#touch-controls').hidden, true);
assert.equal(game.element('#chat-compose').hidden, true);
assert.equal(touch.defaultPrevented, false);
@@ -1259,7 +1259,44 @@ test('iPhone and iPadOS browsers enable the mobile controls', () => {
assert.equal(tablet.element('#game-toolbar').hidden, false);
assert.deepEqual(tablet.cursorHidden, [true]);
assert.equal(tablet.element('#touch-controls').hidden, false);
- assert.equal(desktop.element('#game-toolbar').hidden, true);
+ assert.equal(desktop.element('#game-toolbar').hidden, false);
assert.deepEqual(desktop.cursorHidden, [false]);
assert.equal(desktop.element('#touch-controls').hidden, true);
});
+
+test('desktop Options follows native toolbar coordinates and the 150 CSS pixel reveal distance', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)'}});
+ game.element('#menu-button').getBoundingClientRect = () => ({left: 608, top: 0, right: 644, bottom: 24});
+ game.touchRegions({screenWidth: 1688, screenHeight: 780, regions: [
+ {left: 1300, top: 0, right: 1688, bottom: 32},
+ {left: 0, top: 0, right: 1688, bottom: 780, world: true}
+ ]});
+ const toolbar = game.element('#game-toolbar');
+
+ game.fire('#canvas', 'pointermove', {pointerType: 'mouse', clientX: 457, clientY: 12});
+
+ assert.equal(toolbar.style.right, '200px');
+ assert.equal(toolbar.dataset.desktop, '');
+ assert.equal(toolbar.dataset.menuVisible, undefined);
+ assert.equal(game.element('#chat-button').hidden, true);
+ assert.equal(game.element('#touch-controls').hidden, true);
+
+ game.fire('#canvas', 'pointermove', {pointerType: 'mouse', clientX: 458, clientY: 12});
+
+ assert.equal(toolbar.dataset.menuVisible, '');
+
+ game.fire('#canvas', 'pointermove', {pointerType: 'mouse', clientX: 499, clientY: 133});
+
+ assert.equal(toolbar.dataset.menuVisible, undefined);
+
+ game.fire('#menu-button', 'click');
+ game.fire('#canvas', 'pointermove', {pointerType: 'mouse', clientX: 0, clientY: 390});
+
+ assert.equal(game.element('#player-menu').open, true);
+ assert.equal(toolbar.dataset.menuVisible, '');
+
+ game.element('#player-menu').close();
+
+ assert.equal(toolbar.dataset.menuVisible, undefined);
+ assert.equal(game.document.activeElement, game.canvas);
+});
diff --git a/client/tests/browser_loop.c b/client/tests/browser_loop.c
@@ -2,7 +2,9 @@
#include "recomp_types.h"
#include "guest_memory.h"
#include <assert.h>
+#include <math.h>
#include <stdio.h>
+#include <stdlib.h>
#include <emscripten/threading.h>
static unsigned ticks, frames, completed, closed;
@@ -13,7 +15,12 @@ int browser_graphics_ready(void)
return ticks != 2;
}
-void ao_frame_begin(double timestamp) { assert(timestamp > 0); }
+void ao_frame_begin(double timestamp)
+{
+ static double previous;
+ assert(isfinite(timestamp) && (ticks == 1 || timestamp >= previous));
+ previous = timestamp;
+}
void ao_frame_complete(void) { ++completed; }
void ao_game_closed(void) { ++closed; }
@@ -42,6 +49,7 @@ void sub_28005684(void)
assert(g_ebp == 0x23456789);
assert(frames == 3 && completed == 3 && ticks == 5 && closed == 1);
puts("PASS: browser callbacks preserve guest frames, skip lost graphics and resume shutdown without JSPI");
+ exit(0);
}
int main(void)
diff --git a/client/tests/browser_loop.mjs b/client/tests/browser_loop.mjs
@@ -0,0 +1,41 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import test from 'node:test';
+
+function fixture(callback) {
+ const frames = [];
+ let library, calls = 0;
+ vm.runInNewContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), {
+ addToLibrary: value => { library = value; },
+ requestAnimationFrame: tick => frames.push(tick),
+ getWasmTableEntry: address => { assert.equal(address, 7); return callback; },
+ callUserCallback: callback => { ++calls; callback(); }
+ });
+ return {start: () => library.emscripten_request_animation_frame_loop(7, 19),
+ frames, calls: () => calls};
+}
+
+test('frame callbacks use the runtime boundary and stop when the guest returns false', () => {
+ const inputs = [];
+ const game = fixture((timestamp, data) => { inputs.push([timestamp, data]); return inputs.length < 2; });
+
+ const handle = game.start();
+ game.frames.shift()(125);
+ game.frames.shift()(150);
+
+ assert.equal(handle, 1);
+ assert.deepEqual(inputs, [[125, 19], [150, 19]]);
+ assert.equal(game.calls(), 2);
+ assert.equal(game.frames.length, 0);
+});
+
+test('an exception reaches the runtime boundary without scheduling another frame', () => {
+ const failure = new WebAssembly.RuntimeError('guest failure');
+ const game = fixture(() => { throw failure; });
+ game.start();
+
+ assert.throws(() => game.frames.shift()(125), error => error === failure);
+ assert.equal(game.calls(), 1);
+ assert.equal(game.frames.length, 0);
+});
diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md
@@ -0,0 +1,103 @@
+# Browser Options and player login
+
+The browser Opt button is available on desktop and mobile. On desktop it sits
+six CSS pixels left of the native top toolbar, using the client's published hit
+rectangles rather than assuming a fixed toolbar width. It appears when the
+pointer is within 150 CSS pixels of its rectangle and remains visible while
+Options is open or the button has keyboard focus. Ctrl+Alt+M also opens Options.
+Closing the dialog returns focus to the canvas; Tab remains native targeting.
+Mobile retains its existing toolbar and touch controls. The dialog scrolls on
+small screens.
+
+A Visitor can choose a player name and password in Options without creating a
+replacement character. The player ID, items, XP, skills, resources, location,
+team and native per-character preferences remain attached to that character.
+The login button accepts an existing player name and password. A successful
+login loads that character; a failed login leaves the current player usable.
+
+## Account state and transactions
+
+Private `characters.password_salt` and `password_hash` columns store a random
+16-byte salt and 32-byte Argon2id result. They are excluded from the profile
+editor, native packets and browser account responses. Hashing uses two passes,
+19456 KiB and one lane, following the
+[OWASP Argon2id configuration](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html).
+The implementation is Go's `golang.org/x/crypto/argon2`. Its current release
+requires Go 1.26, which is now the declared build/test minimum. Password hashing
+runs outside the simulation/database locks; a separate mutex bounds its memory
+use without serializing the simulation with expensive password work.
+
+The browser name form accepts ASCII letters and digits with a leading letter,
+up to the existing native 254-byte name capacity. Visitor-prefixed names are
+reserved. Names are unique without ASCII case distinctions. These are browser
+prototype constraints; the original character creator's exact naming rules
+remain a separate research task. Passwords are nonempty and 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
+player's browser credential and the current player's abandoned credential in
+one transaction. It retains the abandoned character's game state, without
+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.
+
+The authenticated cookie is HttpOnly, SameSite=Lax and Secure over HTTPS, using
+the configured URL prefix. Account responses are not cached. Mutating account
+requests use Go's same-origin request protection. World/chat connections carry
+the credential snapshot from HTTP authentication through their native handshake;
+reliable-stream attachment rechecks it. Replaced sessions stop accepting game
+input, and both their world and chat streams close with the existing takeover
+notification. The dialog suppresses that old-session notification while its own
+account request completes, then reloads with the new cookie.
+
+Native files remain in their existing per-character browser directories. Browser
+presentation choices such as pixel resolution and touch-control visibility
+remain device preferences. This flow supplies browser login for one character,
+not the original multi-character account/character creator.
+
+## Verification
+
+Focused HTTP/database and transport regressions cover claiming without losing
+items or progress, salted password verification, case-insensitive lookup,
+invalid and duplicate names, wrong passwords, concurrent claims, repeated
+claims, credential replacement, restart, profile/checkpoint saves, same-origin
+protection, mounted cookie paths, failed/ignored writes and failed COMMITs.
+A failed second credential update rolls back the first. Session regressions
+cover revocation before the reliable hello, after attachment and before native
+world/chat authentication.
+
+The browser tests exercise visitor/named forms, exact credential submission,
+duplicate-submit prevention, failed login/network retry, takeover races and
+visible lookup failures. Control regressions cover desktop placement, the
+150-pixel boundary, retained modal access and return to canvas focus, alongside
+the existing mobile/input cases.
+
+The original `Clientr.exe!sub_28005684` CRT startup calls MSVCRT `exit` after
+WinMain cleanup. The browser keeps that cleanup and the maintained
+`linux_imports.c:crt_exit` adapter's termination callbacks, stdio flushing and
+graphics shutdown. Its animation callback runs through Emscripten's
+`callUserCallback`, which handles the normal pthread exit sentinel while
+propagating real failures. The compiled browser-loop fixture calls `exit(0)`
+after its shutdown assertions; it reproduces an uncaught `unwind` without the
+wrapper and passes with zero browser errors with it. The Linux import fixture
+also verifies callbacks, flushed bytes and the requested process exit status.
+
+Two hardware Chromium clients on the GPU exercised visitor claims, wrong
+passwords, mixed-case login, remote session replacement and cold server recovery.
+Native memory snapshots confirmed distinct 100/200 XP totals and item instance
+IDs 1/2 after switching and restart. An Ignore list saved under character 2
+remained separate from character 1, then restored through switching and restart;
+the native command correctly removed its existing entry. Movement worked after
+cold password recovery. The fixed full-client run recorded zero browser/worker
+errors.
+
+Desktop checks at 1280x900 and 1024x768 verified the six-pixel toolbar gap,
+the reveal boundary, keyboard Options access and return to canvas focus with
+Tab targeting retained. A touch-enabled Chromium viewport at 390x844 with
+device pixel ratio 2 exercised the visible mobile button, visitor form, failed
+login without losing the visitor, and successful named login. The same flow
+passed at 390x500 with the dialog scrolling to reach its inputs and buttons.
+Captures, native snapshots, wire traffic and browser reports are retained under
+`local/browser-account-smoke/`; automated logs and the isolated shutdown
+reproduction are under `local/browser-account-research/`.
diff --git a/docs/repository-packaging.md b/docs/repository-packaging.md
@@ -35,7 +35,7 @@ with a fresh clone; do not merge the old history back into the repository.
Clone the repository normally; the complete matching `server/assets/client/`
bundle is checked in. No WASM toolchain is needed for server work. Build with
-`go build -o ao-server ./server` using Go 1.24 or newer. Distribute the resulting
+`go build -o ao-server ./server` using Go 1.26 or newer. Distribute the resulting
binary by itself; it can run from an empty directory. Open
`http://127.0.0.1:8080/`. The server listens on all interfaces; use its HTTPS
port from other machines.
diff --git a/go.mod b/go.mod
@@ -1,9 +1,12 @@
module ao
-go 1.24
+go 1.26.0
require (
github.com/coder/websocket v1.8.15
github.com/mattn/go-sqlite3 v1.14.52
go.yaml.in/yaml/v3 v3.0.5
+ golang.org/x/crypto v0.58.0
)
+
+require golang.org/x/sys v0.49.0 // indirect
diff --git a/go.sum b/go.sum
@@ -4,3 +4,7 @@ github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdo
github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
+golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
diff --git a/server/browser_account.go b/server/browser_account.go
@@ -0,0 +1,199 @@
+package main
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "golang.org/x/crypto/argon2"
+)
+
+func (server *server) setBrowserCookie(w http.ResponseWriter, r *http.Request, token string) {
+ http.SetCookie(w, &http.Cookie{Name: "ao_client", Value: token, Path: server.baseURL,
+ HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode, MaxAge: 31536000})
+}
+
+func (server *server) browserAccountInfo(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ player := server.browserCharacter_locked(r)
+ if player == nil {
+ http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
+ return
+ }
+ db, err := server.database()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ var claimed bool
+ if err := db.QueryRow("SELECT length(password_hash)>0 FROM characters WHERE id=?", player.id).Scan(&claimed); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]any{"name": player.name, "visitor": !claimed && player.name == fmt.Sprintf("Visitor%d", player.id)})
+}
+
+func (server *server) browserPassword(password string, salt []byte) []byte {
+ // Bound memory use without holding the simulation or database locks.
+ server.passwordMutex.Lock()
+ defer server.passwordMutex.Unlock()
+ return argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32)
+}
+
+func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ action := r.PathValue("action")
+ if action != "claim" && action != "login" {
+ http.NotFound(w, r)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 4096)
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "Invalid account form.", http.StatusBadRequest)
+ return
+ }
+ name, password := r.PostForm.Get("name"), r.PostForm.Get("password")
+ validName := len(name) > 0 && len(name) <= 254
+ for index, letter := range name {
+ if (letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z') && (index == 0 || letter < '0' || letter > '9') {
+ validName = false
+ }
+ }
+ if !validName || len(password) == 0 || len(password) > 1024 {
+ http.Error(w, "Use a name starting with a letter, followed by letters or digits, and a nonempty password (up to 1024 bytes).", http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ current := server.browserCharacter_locked(r)
+ if current == nil {
+ server.mutex.Unlock()
+ http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
+ return
+ }
+ currentID := current.id
+ server.mutex.Unlock()
+
+ // Derive a new salted hash, or verify the existing hash before changing state.
+ db, err := server.database()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ id := currentID
+ salt, expected := make([]byte, 16), make([]byte, 32)
+ if action == "claim" {
+ rand.Read(salt)
+ } else {
+ err = db.QueryRow("SELECT id, password_salt, password_hash FROM characters WHERE name=? COLLATE NOCASE AND length(password_hash)>0", name).Scan(&id, &salt, &expected)
+ if err != nil && err != sql.ErrNoRows {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if err == sql.ErrNoRows {
+ id = 0
+ }
+ }
+ hash := server.browserPassword(password, salt)
+ if action == "login" && (id == 0 || subtle.ConstantTimeCompare(hash, expected) != 1) {
+ http.Error(w, "Incorrect player name or password.", http.StatusUnauthorized)
+ return
+ }
+
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ current = server.browserCharacter_locked(r)
+ if current == nil || current.id != currentID {
+ http.Error(w, "Your browser session changed. Reconnect to continue.", http.StatusUnauthorized)
+ return
+ }
+ player := server.characters[id]
+ if action == "claim" {
+ if current.name != fmt.Sprintf("Visitor%d", currentID) {
+ http.Error(w, "This player already has a name.", http.StatusConflict)
+ return
+ }
+ if strings.HasPrefix(strings.ToLower(name), "visitor") {
+ http.Error(w, "Visitor names are reserved. Choose another name.", http.StatusBadRequest)
+ return
+ }
+ for _, other := range server.characters {
+ if !other.npc && strings.EqualFold(other.name, name) {
+ http.Error(w, "That player name is already in use.", http.StatusConflict)
+ return
+ }
+ }
+ var existing []byte
+ if err := db.QueryRow("SELECT password_hash FROM characters WHERE id=?", id).Scan(&existing); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if len(existing) != 0 {
+ http.Error(w, "This player already has a password.", http.StatusConflict)
+ return
+ }
+ } else if player == nil || !strings.EqualFold(player.name, name) {
+ http.Error(w, "Incorrect player name or password.", http.StatusUnauthorized)
+ return
+ }
+
+ // Commit account creation and both credential changes before publishing success.
+ token := rand.Text()
+ credential := fmt.Sprintf("%x", sha256.Sum256([]byte(token)))
+ abandoned := fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text())))
+ tx, err := db.Begin()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ defer tx.Rollback()
+ if action == "claim" {
+ err = updateRecord(tx, "characters", id, "name, password_salt, password_hash, browser_token_hash", []any{name, salt, hash, credential})
+ } else {
+ err = updateRecord(tx, "characters", id, "browser_token_hash", []any{credential})
+ }
+ if err == nil && currentID != id {
+ err = updateRecord(tx, "characters", currentID, "browser_token_hash", []any{abandoned})
+ }
+ if err == nil {
+ err = tx.Commit()
+ }
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if action == "claim" {
+ player.name, player.savedProfile.Name = name, name
+ }
+ player.browserTokenHash, player.savedProfile.BrowserTokenHash = credential, credential
+ if currentID != id {
+ current.browserTokenHash, current.savedProfile.BrowserTokenHash = abandoned, abandoned
+ }
+ for _, client := range server.clients {
+ if client.id == id || client.id == currentID {
+ client.ready = false
+ if client.stream == nil {
+ client.disconnect(client.conn)
+ }
+ }
+ }
+ for _, stream := range server.browserStreams {
+ if stream.character == id || stream.character == currentID {
+ stream.mutex.Lock()
+ stream.replaced = true
+ stream.mutex.Unlock()
+ go stream.close()
+ }
+ }
+ server.setBrowserCookie(w, r, token)
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/server/browser_account_session_test.go b/server/browser_account_session_test.go
@@ -0,0 +1,152 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "encoding/json"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/coder/websocket"
+)
+
+func TestBrowserAccountRejectsRevokedConnectionBeforeWorldOrChatInitialization(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ credential := world.characters[1].browserTokenHash
+ if response := accountRequest(world, cookie, "claim", "Alice", "password"); response.Code != 204 {
+ t.Fatal(response.Body.String())
+ }
+ host, peer := net.Pipe()
+ defer host.Close()
+ defer peer.Close()
+ input := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(input, 0xdfdf)
+ conn := &combatInterestConn{combatTestConn: combatTestConn{Conn: host}, input: bytes.NewReader(input)}
+
+ err := world.serveWorldClient(&worldClient{id: 1, conn: conn, browserTokenHash: credential, loading: true})
+
+ if err == nil || len(conn.packets) != 0 || world.clients[1] != nil {
+ t.Fatal("revoked credential initialized a world session", err)
+ }
+ world.clients[1] = &worldClient{id: 1, ready: true}
+ conn = &combatInterestConn{input: bytes.NewReader(chatTestAuth(1))}
+
+ err = world.serveChatClient(&chatClient{id: 1, conn: conn, browserTokenHash: credential})
+
+ if err == nil || world.chats[1] != nil || len(conn.packets) != 1 {
+ t.Fatal("revoked credential initialized chat after its seed", err)
+ }
+}
+
+func TestBrowserAccountRevokesReliableStreamsAtEveryHandshakeBoundary(t *testing.T) {
+ for _, path := range []string{"browser-world", "browser-chat"} {
+ for _, started := range []bool{false, true} {
+ t.Run(path+"/"+map[bool]string{false: "before hello", true: "before native authentication"}[started], func(t *testing.T) {
+ world := newTestServer(t)
+ closeTestBrowserStreams(t, world)
+ cookie := accountVisitor(t, world)
+ host := httptest.NewServer(world.httpHandler())
+ defer host.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ socket, _, err := websocket.Dial(ctx, host.URL+"/"+path, &websocket.DialOptions{
+ HTTPHeader: http.Header{"Cookie": {cookie.String()}}, Subprotocols: []string{"ao-stream-v1"},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer socket.CloseNow()
+ hello, _ := json.Marshal(map[string]string{"stream": "00000000-0000-0000-0000-000000000001", "received": "0", "acknowledged": "0"})
+ if started {
+ if err := socket.Write(ctx, websocket.MessageText, hello); err != nil {
+ t.Fatal(err)
+ }
+ kind, _, err := socket.Read(ctx)
+ if err != nil || kind != websocket.MessageText {
+ t.Fatal("stream did not acknowledge its attachment", err)
+ }
+ }
+
+ response := accountRequest(world, cookie, "claim", "Alice", "password")
+ if !started {
+ if err := socket.Write(ctx, websocket.MessageText, hello); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var closed error
+ for closed == nil {
+ _, _, closed = socket.Read(ctx)
+ }
+
+ if response.Code != 204 || websocket.CloseStatus(closed) != 4001 || ctx.Err() != nil {
+ t.Fatalf("credential replacement failed: HTTP %d close=%v", response.Code, closed)
+ }
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if world.clients[1] != nil || world.chats[1] != nil || len(world.browserStreams) != 0 {
+ t.Fatal("revoked transport retained an authenticated session")
+ }
+ })
+ }
+ }
+}
+
+func TestBrowserAccountLoginRollsBackTheSecondCredentialChange(t *testing.T) {
+ for _, failure := range []string{"ABORT", "IGNORE"} {
+ t.Run(failure, func(t *testing.T) {
+ world := newTestServer(t)
+ first := accountVisitor(t, world)
+ if response := accountRequest(world, first, "claim", "Alice", "password"); response.Code != 204 {
+ t.Fatal(response.Body.String())
+ }
+ second := accountVisitor(t, world)
+ firstHash, secondHash := world.characters[1].browserTokenHash, world.characters[2].browserTokenHash
+ statement := "CREATE TRIGGER reject_visitor BEFORE UPDATE OF browser_token_hash ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(" + failure
+ if failure == "ABORT" {
+ statement += ", 'visitor'"
+ }
+ if _, err := world.db.Exec(statement + "); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ response := accountRequest(world, second, "login", "Alice", "password")
+ restored := newTestInventoryServer(t)
+
+ if response.Code != 500 || len(response.Result().Cookies()) != 0 || world.characters[1].browserTokenHash != firstHash ||
+ world.characters[2].browserTokenHash != secondHash || restored.characters[1].browserTokenHash != firstHash || restored.characters[2].browserTokenHash != secondHash {
+ t.Fatal("failure abandoning the visitor retained the target credential change")
+ }
+ })
+ }
+}
+
+func TestBrowserAccountPasswordSurvivesOrdinaryCharacterSaves(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ if response := accountRequest(world, cookie, "claim", "Alice", "password"); response.Code != 204 {
+ t.Fatal(response.Body.String())
+ }
+ player := world.characters[1]
+ player.stats.ImprovementPoints = 500
+ player.position[0] = 950
+
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.savePosition_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+ restored.baseURL = "/"
+ visitor := accountVisitor(t, restored)
+ response := accountRequest(restored, visitor, "login", "Alice", "password")
+
+ if response.Code != 204 || restored.characters[1].stats.ImprovementPoints != 500 || restored.characters[1].position[0] != 950 {
+ t.Fatalf("ordinary save lost credentials or character state: %d %s", response.Code, response.Body.String())
+ }
+}
diff --git a/server/browser_account_test.go b/server/browser_account_test.go
@@ -0,0 +1,262 @@
+package main
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func accountVisitor(t *testing.T, world *server) *http.Cookie {
+ t.Helper()
+ response := httptest.NewRecorder()
+ world.browserLaunch(response, httptest.NewRequest("POST", "https://example.test/browser-launch", nil))
+ if response.Code != 200 || len(response.Result().Cookies()) != 1 {
+ t.Fatalf("visitor launch: %d %s", response.Code, response.Body.String())
+ }
+ return response.Result().Cookies()[0]
+}
+
+func accountRequest(world *server, cookie *http.Cookie, action, name, password string) *httptest.ResponseRecorder {
+ request := httptest.NewRequest("POST", "https://example.test"+world.baseURL+"browser-account/"+action,
+ strings.NewReader(url.Values{"name": {name}, "password": {password}}.Encode()))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if cookie != nil {
+ request.AddCookie(cookie)
+ }
+ response := httptest.NewRecorder()
+ world.httpHandler().ServeHTTP(response, request)
+ return response
+}
+
+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}}}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ before := *player
+ world.clients[1] = &worldClient{id: 1, ready: true, conn: &combatInterestConn{}}
+
+ response := accountRequest(world, cookie, "claim", "Alice", "test password")
+ restored := newTestInventoryServer(t)
+ var salt, hash []byte
+ if err := restored.db.QueryRow("SELECT password_salt, password_hash FROM characters WHERE id=1").Scan(&salt, &hash); err != nil {
+ t.Fatal(err)
+ }
+
+ if response.Code != 204 || response.Header().Get("Cache-Control") != "no-store" || player.name != "Alice" || restored.characters[1].name != "Alice" ||
+ 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())
+ }
+ if len(salt) != 16 || len(hash) != 32 || bytes.Contains(hash, []byte("test password")) ||
+ !bytes.Equal(world.browserPassword("test password", salt), hash) || bytes.Equal(world.browserPassword("wrong password", salt), hash) {
+ t.Fatal("password was not stored as a salted Argon2id hash")
+ }
+ claimedCookie := response.Result().Cookies()[0]
+ if claimedCookie.Value == cookie.Value || !claimedCookie.HttpOnly || !claimedCookie.Secure || claimedCookie.SameSite != http.SameSiteLaxMode {
+ t.Fatal("claim did not rotate a protected browser credential")
+ }
+ request := httptest.NewRequest("GET", "/", nil)
+ request.AddCookie(cookie)
+ if restored.browserCharacter_locked(request) != nil {
+ t.Fatal("old visitor credential remained valid")
+ }
+ request = httptest.NewRequest("GET", "/", nil)
+ request.AddCookie(claimedCookie)
+ if restored.browserCharacter_locked(request) != restored.characters[1] || player.savedProfile.Name != "Alice" {
+ t.Fatal("claimed browser ownership did not survive restart")
+ }
+}
+
+func TestBrowserAccountLoginSwitchesOnlyAfterCorrectPassword(t *testing.T) {
+ world := newTestServer(t)
+ first := accountVisitor(t, world)
+ claimed := accountRequest(world, first, "claim", "Alice", "test password")
+ if claimed.Code != 204 {
+ t.Fatal(claimed.Body.String())
+ }
+ first = claimed.Result().Cookies()[0]
+ visitor := accountVisitor(t, world)
+ before := *world.characters[2]
+ firstHash, visitorHash := world.characters[1].browserTokenHash, before.browserTokenHash
+
+ rejected := accountRequest(world, visitor, "login", "Alice", "wrong")
+
+ if rejected.Code != 401 || len(rejected.Result().Cookies()) != 0 || world.characters[1].browserTokenHash != firstHash ||
+ world.characters[2].browserTokenHash != visitorHash || !reflect.DeepEqual(*world.characters[2], before) {
+ t.Fatal("failed login changed either player")
+ }
+
+ response := accountRequest(world, visitor, "login", "aLiCe", "test password")
+ restored := newTestInventoryServer(t)
+
+ if response.Code != 204 || len(response.Result().Cookies()) != 1 || world.characters[1].browserTokenHash == firstHash || world.characters[2].browserTokenHash == visitorHash ||
+ world.characters[1].name != "Alice" || world.characters[2].name != "Visitor2" || world.characters[2].position != before.position {
+ t.Fatalf("login did not replace the credentials without moving players: %d %s", response.Code, response.Body.String())
+ }
+ request := httptest.NewRequest("GET", "/", nil)
+ request.AddCookie(response.Result().Cookies()[0])
+ if restored.browserCharacter_locked(request) != restored.characters[1] {
+ t.Fatal("new login did not survive restart")
+ }
+ for _, stale := range []*http.Cookie{first, visitor} {
+ request := httptest.NewRequest("GET", "/", nil)
+ request.AddCookie(stale)
+ if restored.browserCharacter_locked(request) != nil {
+ t.Fatal("replaced credential remained valid")
+ }
+ }
+}
+
+func TestBrowserAccountRejectsInvalidClaimsWithoutChangingVisitor(t *testing.T) {
+ for _, scenario := range []struct{ name, password string }{
+ {"", "password"}, {"123Alice", "password"}, {"Alice Bob", "password"}, {"Al\x00ice", "password"}, {"Al\u00e9ce", "password"},
+ {strings.Repeat("a", 255), "password"}, {"Visitor42", "password"}, {"vIsItOrAlice", "password"}, {"Alice", ""}, {"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)
+ cookie := accountVisitor(t, world)
+ before := *world.characters[1]
+
+ response := accountRequest(world, cookie, "claim", scenario.name, scenario.password)
+
+ if response.Code != 400 || len(response.Result().Cookies()) != 0 || !reflect.DeepEqual(*world.characters[1], before) {
+ t.Fatalf("invalid claim changed visitor: %d %s", response.Code, response.Body.String())
+ }
+ })
+ }
+}
+
+func TestBrowserAccountDuplicateNamesAndRepeatedClaim(t *testing.T) {
+ world := newTestServer(t)
+ first := accountVisitor(t, world)
+ firstClaim := accountRequest(world, first, "claim", "Alice", "password")
+ if firstClaim.Code != 204 {
+ t.Fatal(firstClaim.Body.String())
+ }
+ second := accountVisitor(t, world)
+
+ duplicate := accountRequest(world, second, "claim", "ALICE", "other password")
+ repeated := accountRequest(world, firstClaim.Result().Cookies()[0], "claim", "Bob", "replacement password")
+ login := accountRequest(world, second, "login", "Alice", "password")
+
+ if duplicate.Code != 409 || repeated.Code != 409 || login.Code != 204 || world.characters[1].name != "Alice" || world.characters[2].name != "Visitor2" {
+ t.Fatalf("name collision changed accounts: %d %d %d", duplicate.Code, repeated.Code, login.Code)
+ }
+}
+
+func TestBrowserAccountConcurrentClaimCommitsOnce(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ var requests sync.WaitGroup
+ responses := make([]*httptest.ResponseRecorder, 8)
+
+ for index := range responses {
+ requests.Add(1)
+ go func() {
+ defer requests.Done()
+ responses[index] = accountRequest(world, cookie, "claim", "Alice", "password")
+ }()
+ }
+ requests.Wait()
+
+ committed := 0
+ for _, response := range responses {
+ if response.Code == 204 {
+ committed++
+ } else if response.Code != 401 {
+ t.Fatalf("unexpected concurrent claim: %d %s", response.Code, response.Body.String())
+ }
+ }
+ if committed != 1 || world.characters[1].name != "Alice" {
+ t.Fatalf("concurrent claim committed %d times", committed)
+ }
+}
+
+func TestBrowserAccountFailureLeavesBothCredentialsAndPasswordUnchanged(t *testing.T) {
+ for _, action := range []string{"claim", "login"} {
+ for _, failure := range []struct{ name, statement string }{
+ {"update", "CREATE TRIGGER reject_account BEFORE UPDATE OF browser_token_hash ON characters BEGIN SELECT RAISE(ABORT, 'account'); END"},
+ {"ignored update", "CREATE TRIGGER reject_account BEFORE UPDATE OF browser_token_hash ON characters BEGIN SELECT RAISE(IGNORE); END"},
+ {"commit", "CREATE TABLE pending_account (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_account AFTER UPDATE OF browser_token_hash ON characters BEGIN INSERT INTO pending_account VALUES (999999); END"},
+ } {
+ t.Run(action+"/"+failure.name, func(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ if action == "login" {
+ if response := accountRequest(world, cookie, "claim", "Alice", "password"); response.Code != 204 {
+ t.Fatal(response.Body.String())
+ }
+ cookie = accountVisitor(t, world)
+ }
+ before := newTestInventoryServer(t)
+ if _, err := world.db.Exec(failure.statement); err != nil {
+ t.Fatal(err)
+ }
+
+ response := accountRequest(world, cookie, action, "Alice", "password")
+ restored := newTestInventoryServer(t)
+
+ if response.Code != 500 || len(response.Result().Cookies()) != 0 {
+ t.Fatalf("failed persistence reported success: %d %s", response.Code, response.Body.String())
+ }
+ for id, player := range before.characters {
+ if player.npc {
+ continue
+ }
+ if restored.characters[id].name != player.name || restored.characters[id].browserTokenHash != player.browserTokenHash ||
+ world.characters[id].browserTokenHash != player.browserTokenHash || world.characters[id].name != player.name {
+ t.Fatal("failed transaction published a name or credential")
+ }
+ }
+ if action == "claim" {
+ var hash []byte
+ if err := world.db.QueryRow("SELECT password_hash FROM characters WHERE id=1").Scan(&hash); err != nil || len(hash) != 0 {
+ t.Fatal("failed claim retained a password hash", err)
+ }
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_account"); err != nil {
+ t.Fatal(err)
+ }
+
+ response = accountRequest(world, cookie, action, "Alice", "password")
+
+ if response.Code != 204 {
+ t.Fatalf("retry failed: %d %s", response.Code, response.Body.String())
+ }
+ })
+ }
+ }
+}
+
+func TestBrowserAccountRoutesProtectOriginAndMountCookie(t *testing.T) {
+ world := newTestServer(t)
+ world.baseURL = "/game/"
+ cookie := accountVisitor(t, world)
+ request := httptest.NewRequest("POST", "https://example.test/game/browser-account/claim", strings.NewReader("name=Alice&password=password"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.Header.Set("Origin", "https://other.test")
+ request.AddCookie(cookie)
+ response := httptest.NewRecorder()
+
+ world.httpHandler().ServeHTTP(response, request)
+ claimed := accountRequest(world, cookie, "claim", "Alice", "password")
+
+ if response.Code != 403 || claimed.Code != 204 || claimed.Result().Cookies()[0].Path != "/game/" {
+ t.Fatalf("origin or mounted cookie: %d %d", response.Code, claimed.Code)
+ }
+ wanted := fmt.Sprintf("%x", sha256.Sum256([]byte(claimed.Result().Cookies()[0].Value)))
+ if world.characters[1].browserTokenHash != wanted {
+ t.Fatal("mounted claim lost browser ownership")
+ }
+}
diff --git a/server/browser_launch.go b/server/browser_launch.go
@@ -26,7 +26,7 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) {
server.mutex.Lock()
defer server.mutex.Unlock()
- // A browser owns one persistent visitor, independent of other online players.
+ // A browser owns one persistent character, independent of other online players.
character := server.browserCharacter_locked(r)
if character == nil {
token := rand.Text()
@@ -45,8 +45,7 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
- http.SetCookie(w, &http.Cookie{Name: "ao_client", Value: token, Path: server.baseURL,
- HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode, MaxAge: 31536000})
+ server.setBrowserCookie(w, r, token)
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Cache-Control", "no-store")
diff --git a/server/browser_socket.go b/server/browser_socket.go
@@ -20,8 +20,10 @@ func (server *server) browserConnection(w http.ResponseWriter, r *http.Request,
server.mutex.Lock()
character := server.browserCharacter_locked(r)
var id uint32
+ var credential string
if character != nil {
id = character.id
+ credential = character.browserTokenHash
}
server.mutex.Unlock()
if id == 0 {
@@ -35,19 +37,19 @@ func (server *server) browserConnection(w http.ResponseWriter, r *http.Request,
}
defer socket.CloseNow()
if socket.Subprotocol() == "ao-stream-v1" {
- server.resumeBrowserStream(socket, id, chat)
+ server.resumeBrowserStream(socket, id, credential, chat)
return
}
// Preserve the TCP byte stream across arbitrary binary WebSocket boundaries.
connection := websocket.NetConn(context.Background(), socket, websocket.MessageBinary)
if chat {
- if err := server.serveChatClient(&chatClient{conn: connection, id: id}); err != nil {
+ if err := server.serveChatClient(&chatClient{conn: connection, id: id, browserTokenHash: credential}); err != nil {
log.Printf("Browser chat connection: %v", err)
}
return
}
- if err := server.serveWorldClient(&worldClient{conn: connection, id: id, loading: true}); err != nil {
+ if err := server.serveWorldClient(&worldClient{conn: connection, id: id, loading: true, browserTokenHash: credential}); err != nil {
log.Printf("Browser world connection: %v", err)
}
}
diff --git a/server/browser_stream.go b/server/browser_stream.go
@@ -216,7 +216,7 @@ func (stream *browserStream) receive(socket *websocket.Conn, message []byte) boo
return err == nil
}
-func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint32, chat bool) {
+func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint32, credential string, chat bool) {
socket.SetReadLimit(65536)
// The cookie authenticates every attachment; offsets identify replayed bytes.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
@@ -237,6 +237,11 @@ func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint
return
}
server.mutex.Lock()
+ if server.characters[character].browserTokenHash != credential {
+ server.mutex.Unlock()
+ socket.Close(4001, "Browser credential was replaced")
+ return
+ }
if server.browserStreams == nil {
server.browserStreams = make(map[string]*browserStream)
}
@@ -267,9 +272,9 @@ func (server *server) resumeBrowserStream(socket *websocket.Conn, character uint
defer game.Close()
var result error
if chat {
- result = server.serveChatClient(&chatClient{conn: game, stream: stream, id: character})
+ result = server.serveChatClient(&chatClient{conn: game, stream: stream, id: character, browserTokenHash: credential})
} else {
- result = server.serveWorldClient(&worldClient{conn: game, stream: stream, id: character, loading: true})
+ result = server.serveWorldClient(&worldClient{conn: game, stream: stream, id: character, loading: true, browserTokenHash: credential})
}
if result != nil && result != io.EOF {
log.Printf("Browser session ended: %v", result)
diff --git a/server/chat.go b/server/chat.go
@@ -12,10 +12,11 @@ import (
type chatClient struct {
clientOutput
- conn net.Conn
- stream *browserStream
- id uint32
- teamID uint32 // Announced channel membership; protected by server.mutex.
+ conn net.Conn
+ stream *browserStream
+ browserTokenHash string
+ id uint32
+ teamID uint32 // Announced channel membership; protected by server.mutex.
}
func chatPacket(kind uint16, body []byte) []byte {
@@ -82,6 +83,11 @@ func (server *server) initializeChat(client *chatClient, id uint32) error {
server.chatLogMutex.Unlock()
return fmt.Errorf("chat requires an authenticated world character")
}
+ if client.browserTokenHash != "" && client.browserTokenHash != character.browserTokenHash {
+ server.mutex.Unlock()
+ server.chatLogMutex.Unlock()
+ return fmt.Errorf("browser credential was replaced")
+ }
name := character.name
previous := server.chats[id]
client.id = id
@@ -192,7 +198,8 @@ func (server *server) serveChatClient(client *chatClient) error {
return err
}
server.mutex.Lock()
- connected := server.chats[id] == client && server.clients[id] != nil
+ connected := server.chats[id] == client && server.clients[id] != nil &&
+ (client.browserTokenHash == "" || client.browserTokenHash == server.characters[id].browserTokenHash)
server.mutex.Unlock()
if !connected {
return fmt.Errorf("chat world session ended")
diff --git a/server/http.go b/server/http.go
@@ -46,6 +46,8 @@ func (server *server) httpHandler() http.Handler {
})
mux.HandleFunc("GET /browser-assets/{path...}", browserAsset)
mux.HandleFunc("POST /browser-launch", server.browserLaunch)
+ mux.HandleFunc("GET /browser-account", server.browserAccountInfo)
+ mux.Handle("POST /browser-account/{action}", http.NewCrossOriginProtection().Handler(http.HandlerFunc(server.browserAccount)))
mux.HandleFunc("GET /browser-world", server.browserWorld)
mux.HandleFunc("GET /browser-chat", server.browserChat)
mux.HandleFunc("GET /browser-manifest", browserManifest)
diff --git a/server/main.go b/server/main.go
@@ -323,6 +323,11 @@ func (server *server) serveWorldClient(client *worldClient) error {
server.updateMutex.Unlock()
return fmt.Errorf("browser character requires a browser credential")
}
+ if client.browserTokenHash != "" && client.browserTokenHash != character.browserTokenHash {
+ server.mutex.Unlock()
+ server.updateMutex.Unlock()
+ return fmt.Errorf("browser credential was replaced")
+ }
combatUpdates := make(map[*worldClient][][]byte)
replaceActor := false
if previous := server.clients[character.id]; previous != nil {
diff --git a/server/state.go b/server/state.go
@@ -66,6 +66,7 @@ type worldClient struct {
clientOutput
conn net.Conn
stream *browserStream
+ browserTokenHash string
ready bool
loading bool
id uint32
@@ -105,6 +106,7 @@ func (client *worldClient) send(packet []byte) error {
}
type server struct {
+ passwordMutex sync.Mutex
databaseMutex sync.Mutex
db *sql.DB
savedNPCs map[uint32]savedNPC
diff --git a/server/world.sql b/server/world.sql
@@ -99,6 +99,8 @@ CREATE TABLE IF NOT EXISTS characters (
navigation_map_navigation INTEGER NOT NULL DEFAULT 5,
running INTEGER NOT NULL DEFAULT 0,
browser_token_hash TEXT NOT NULL DEFAULT '',
+ password_salt BLOB NOT NULL DEFAULT X'',
+ password_hash BLOB NOT NULL DEFAULT X'',
resurrection_terminal INTEGER NOT NULL DEFAULT 0,
implant_changes_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
treatment_locked_until DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
@@ -122,6 +124,7 @@ CREATE TABLE IF NOT EXISTS characters (
regeneration_at DATETIME NOT NULL DEFAULT '0001-01-01 00:00:00+00:00',
regeneration_seconds INTEGER NOT NULL DEFAULT 0
);
+CREATE UNIQUE INDEX IF NOT EXISTS player_login_names ON characters(name COLLATE NOCASE) WHERE length(password_hash)>0;
CREATE TABLE IF NOT EXISTS players (
id INTEGER PRIMARY KEY REFERENCES characters(id) ON DELETE CASCADE CHECK (id BETWEEN 1 AND 999999),
credits INTEGER NOT NULL DEFAULT 0,