Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(multiplayer): carry a verified three.ws handle onto the player schema

nirholasc38b925442bc
diff --git a/api/_lib/presence-store.js b/api/_lib/presence-store.js
index 9606631fc..7cbcd89d3 100644
--- a/api/_lib/presence-store.js
+++ b/api/_lib/presence-store.js
@@ -66,7 +66,11 @@ function safeParse(s) {
// session cookie or call back to verify. The crew tag (W09) rides inside the
// signed payload too, so the game server can stamp a TRUSTWORTHY crew badge over
// the avatar without a DB of its own and without trusting a client option.
-// Format: base64url(JSON{uid,exp,crew,crewName}).base64url(hmac).
+// The bearer's public profile handle (username + display name) rides the same
+// way: it is what lets a realm room publish a VERIFIED three.ws identity on the
+// player schema, so peers can open the real profile, follow, and DM — a client
+// option could claim anyone's handle, a signed ticket cannot.
+// Format: base64url(JSON{uid,exp,crew,crewName,u,dn}).base64url(hmac).
export async function signPresenceTicket(userId) {
const exp = Math.floor(Date.now() / 1000) + TICKET_TTL_SEC;
// Fold in the bearer's crew tag if they're in one. Defensive: a missing crews
@@ -81,15 +85,30 @@ export async function signPresenceTicket(userId) {
const c = await crewTagFor(userId);
if (c) { crew = c.tag; crewName = c.name; }
} catch { /* crew is optional metadata; presence works without it */ }
- const payload = base64url(JSON.stringify({ uid: userId, exp, crew, crewName }));
+ // Fold in the bearer's public handle, same defensive posture: an account with
+ // no username yet (or a DB hiccup) still gets a valid presence-only ticket.
+ let u = '';
+ let dn = '';
+ try {
+ const { sql } = await import('./db.js');
+ const [row] = await sql`
+ select username, display_name from users
+ where id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (row?.username) u = row.username;
+ if (row?.display_name) dn = String(row.display_name).slice(0, 24);
+ } catch { /* profile handle is optional metadata; presence works without it */ }
+ const payload = base64url(JSON.stringify({ uid: userId, exp, crew, crewName, u, dn }));
const sig = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, payload);
return { token: `${payload}.${sig}`, expiresIn: TICKET_TTL_SEC };
}
-// Verify a ticket and return { uid, crew, crewName }, or null. Mirrored
-// byte-for-byte on the multiplayer side (multiplayer/src/presence-token.js); keep
-// the two in sync. (No API caller today — the multiplayer server is the verifier;
-// this stays here as the canonical reference implementation.)
+// Verify a ticket and return { uid, crew, crewName, username, displayName }, or
+// null. Mirrored byte-for-byte on the multiplayer side
+// (multiplayer/src/presence-token.js); keep the two in sync. (No API caller
+// today — the multiplayer server is the verifier; this stays here as the
+// canonical reference implementation.)
export async function verifyPresenceTicket(token) {
if (typeof token !== 'string' || !token.includes('.')) return null;
const [payload, sig] = token.split('.');
@@ -99,7 +118,13 @@ export async function verifyPresenceTicket(token) {
const data = safeParse(Buffer.from(payload, 'base64url').toString('utf8'));
if (!data || !data.uid || !data.exp) return null;
if (data.exp < Math.floor(Date.now() / 1000)) return null;
- return { uid: data.uid, crew: data.crew || '', crewName: data.crewName || '' };
+ return {
+ uid: data.uid,
+ crew: data.crew || '',
+ crewName: data.crewName || '',
+ username: data.u || '',
+ displayName: data.dn || '',
+ };
}
function base64url(s) {
diff --git a/multiplayer/src/guest-token.js b/multiplayer/src/guest-token.js
index 11b0991ef..e42d206e6 100644
--- a/multiplayer/src/guest-token.js
+++ b/multiplayer/src/guest-token.js
@@ -92,6 +92,12 @@ export function verifyGuestToken(token) {
if (typeof payload.exp !== 'number' || payload.exp * 1000 < Date.now()) return null;
const now = Date.now() / 1000;
if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;
- if (typeof payload.gid !== 'string' || !payload.gid.startsWith(GUEST_PREFIX)) return null;
+ // `gs_…` ids are server-minted. `guest-…` ids are the legacy client-minted
+ // localStorage ids: a bare one is never trusted, but once the room has sealed
+ // it into a signed token (the one-time migration in WalkRoom._resolveIdentity)
+ // the HMAC proves the server vouched for it, so honoring it here is what lets
+ // a pre-token guest keep their progression.
+ if (typeof payload.gid !== 'string') return null;
+ if (!payload.gid.startsWith(GUEST_PREFIX) && !payload.gid.startsWith('guest-')) return null;
return payload.gid;
}
diff --git a/multiplayer/src/presence-token.js b/multiplayer/src/presence-token.js
index 424505955..17f993208 100644
--- a/multiplayer/src/presence-token.js
+++ b/multiplayer/src/presence-token.js
@@ -5,9 +5,11 @@
// another account's presence.
//
// Keep byte-for-byte in sync with the API signer:
-// token = base64url(JSON{uid,exp}) + '.' + base64url(HMAC_SHA256(secret, payload))
+// token = base64url(JSON{uid,exp,crew,crewName,u,dn}) + '.' + base64url(HMAC_SHA256(secret, payload))
// secret = MULTIPLAYER_SHARED_SECRET (falls back to HOLDER_PASS_SECRET, then a
// public dev secret — the same fallback chain the API uses).
+// `u`/`dn` are the bearer's three.ws username + display name; older tickets
+// omit them and still verify (they surface as empty strings).
import crypto from 'node:crypto';
@@ -26,8 +28,11 @@ function timingSafeEqualStr(a, b) {
return crypto.timingSafeEqual(ab, bb);
}
-// Verify a presence ticket → the trusted account id (uid), or null if the
+// Verify a presence ticket → the trusted identity it carries, or null if the
// signature is wrong, the payload is malformed, or the ticket has expired.
+// Returns { uid, username, displayName, crew, crewName }: uid is the account
+// id (users.id UUID); username/displayName are the bearer's public three.ws
+// handle, empty for tickets minted before the profile fields existed.
export function verifyPresenceTicket(token) {
if (typeof token !== 'string' || !token.includes('.')) return null;
const [payload, sig] = token.split('.');
@@ -42,7 +47,13 @@ export function verifyPresenceTicket(token) {
}
if (!data || !data.uid || !data.exp) return null;
if (data.exp < Math.floor(Date.now() / 1000)) return null;
- return data.uid;
+ return {
+ uid: data.uid,
+ username: typeof data.u === 'string' ? data.u : '',
+ displayName: typeof data.dn === 'string' ? data.dn : '',
+ crew: typeof data.crew === 'string' ? data.crew : '',
+ crewName: typeof data.crewName === 'string' ? data.crewName : '',
+ };
}
// Maximum age (seconds) an /internal/notify signature stays valid. The API mints
@@ -101,6 +112,32 @@ export function verifyStageSignature(payload, ts, sig) {
return timingSafeEqualStr(sig, expected);
}
+// ── Live-event announcements ─────────────────────────────────────────────────
+// /internal/announce lets an operator (via scripts/announce-play.mjs, which
+// holds the same shared secret) broadcast a message to every live walk_world
+// room during an event. Same HMAC discipline as the other internal webhooks:
+// the signature binds the exact body + a fresh timestamp, so a captured tuple
+// can't be replayed with different content or outside the freshness window.
+// Keep byte-compatible with the signer in scripts/announce-play.mjs.
+const ANNOUNCE_MAX_AGE_S = 120;
+
+export function verifyAnnounceSignature(payload, ts, sig) {
+ if (typeof sig !== 'string' || !sig) return false;
+ const tsNum = Number(ts);
+ if (!Number.isFinite(tsNum)) return false;
+ const nowS = Math.floor(Date.now() / 1000);
+ if (Math.abs(nowS - tsNum) > ANNOUNCE_MAX_AGE_S) return false;
+ const payloadHash = crypto
+ .createHash('sha256')
+ .update(JSON.stringify(payload ?? {}))
+ .digest('base64url');
+ const expected = crypto
+ .createHmac('sha256', secret())
+ .update(`announce:${tsNum}:${payloadHash}`)
+ .digest('base64url');
+ return timingSafeEqualStr(sig, expected);
+}
+
// Sign an outbound room → API request (the host loop fetching the next beat from
// /api/stage/host). Mirrored by verifyStageRequest in api/_lib/stage-bridge.js.
export function signStageRequest(payload) {
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index f65bec5db..bfdc881cc 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -35,7 +35,9 @@ import { socialHub } from '../social-hub.js';
import { verifyPresenceTicket } from '../presence-token.js';
import { verifyPlayPass } from '../play-pass.js';
import { containsHateSlur } from '../display-name-safety.js';
+import { newGuestId, signGuestToken, verifyGuestToken } from '../guest-token.js';
import { installUnknownMessageGuard, PLAY_PASS_EVICT_CODE } from '../room-compat.js';
+import { registerWalkRoom, unregisterWalkRoom } from '../walk-registry.js';
import {
restoreProfile, serializeProfile, profileSnapshot,
addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,
@@ -63,6 +65,7 @@ import {
import {
fishingSpotInRange, treeInRange, rockInRange, firepitInRange,
DANGER_ZONES, SPAWN_POINT, dangerZoneAt, isSafeZone, isDangerZone, randomPointInZone,
+ PLAZA_STAGE,
} from '../world-features.js';
import { registerActivityHandlers, ACTIVITY_COOLDOWN_MS } from '../activities.js';
import { registerSpinHandlers } from '../spin-wheel.js';
@@ -196,15 +199,31 @@ const PROTECTED_RADIUS_CELLS = 3; // keep this many cells clear around each p
// renders at world z = -12 → grid z = round(-12 / 1.5) = -8. Protect both columns
// at every height so neither can be buried or walled in.
const BLOCK_SIZE_M = 1.5; // client BLOCK: one grid cell ↔ metres
-const PROTECTED_POINTS = [{ x: 0, z: 0 }, { x: 0, z: -8 }];
+// Each disc carries its own radius (in cells) so a landmark bigger than the
+// default keeps a guard that matches its real footprint. The plaza stage's disc
+// is derived from world-features.PLAZA_STAGE, so moving the venue moves its
+// protection with it and the two can never drift.
+const PROTECTED_POINTS = [
+ { x: 0, z: 0, r: PROTECTED_RADIUS_CELLS },
+ { x: 0, z: -8, r: PROTECTED_RADIUS_CELLS },
+ {
+ x: Math.round(PLAZA_STAGE.x / BLOCK_SIZE_M),
+ z: Math.round(PLAZA_STAGE.z / BLOCK_SIZE_M),
+ r: Math.ceil(PLAZA_STAGE.r / BLOCK_SIZE_M),
+ },
+];
// The prop/object build channel (obj:spawn kind:'block') works in world METRES, not
// grid cells, so its grief guard has its own protected discs and density tile. The
// protected world points are the spawn (origin) and the rendered totem (world z=-12);
// the radius matches the voxel discs (PROTECTED_RADIUS_CELLS cells). PER_TILE_PROP_CAP
// stops a builder piling props onto one spot to bury a landmark or wall an area off —
// the per-player count (MAX_OBJECTS_PER_PLAYER) and world cap bound the rest.
-const PROTECTED_POINTS_M = [{ x: 0, z: 0 }, { x: 0, z: -12 }];
const PROTECTED_RADIUS_M = PROTECTED_RADIUS_CELLS * BLOCK_SIZE_M;
+const PROTECTED_POINTS_M = [
+ { x: 0, z: 0, r: PROTECTED_RADIUS_M },
+ { x: 0, z: -12, r: PROTECTED_RADIUS_M },
+ { x: PLAZA_STAGE.x, z: PLAZA_STAGE.z, r: PLAZA_STAGE.r },
+];
const PROP_TILE_M = BLOCK_SIZE_M; // density tile size for props, in metres
const PER_TILE_PROP_CAP = 4; // durable props allowed on one tile
// Creator moderation: a clear-area sweep is bounded so even the creator's
@@ -519,6 +538,8 @@ export class WalkRoom extends Room {
this.setState(new WalkState());
this.setPatchRate(PATCH_RATE_MS);
this.autoDispose = true;
+ // Reachable by the operator /internal/announce webhook for live events.
+ registerWalkRoom(this);
// Version-skew tolerance: a message type this build doesn't know must be
// ignored, never close the session (Colyseus's default 4002 kill looked
// like "session expired" to pre-fix clients). See room-compat.js.
@@ -766,18 +787,44 @@ export class WalkRoom extends Room {
// holder gate. Register it so friends see this player as online in this
// coin world and can DM them live. Spoof-proof — the account id comes from
// the verified ticket, never a raw client option.
- const accountUid = verifyPresenceTicket(options?.presence);
- if (accountUid) {
- client.userData = { ...(client.userData || {}), accountUid };
- socialHub.register(accountUid, client, this.state.coinName || 'Mainland');
+ const presence = verifyPresenceTicket(options?.presence);
+ if (presence?.uid) {
+ client.userData = { ...(client.userData || {}), accountUid: presence.uid };
+ socialHub.register(presence.uid, client, this.state.coinName || 'Mainland');
+ // Verified three.ws profile (W10): publish the ticket's username on the
+ // schema so every peer can open this player's real profile, follow them,
+ // and DM them. Trustworthy by construction — it came out of the signed
+ // ticket, so nobody can wear a handle they don't own. A signed-in player
+ // who never picked a nameplate gets their account display name instead of
+ // an anonymous guest-xxxx handle.
+ player.username = clean(presence.username, 30);
+ if (!clean(options?.name, 24) && presence.displayName && !containsHateSlur(presence.displayName)) {
+ player.name = clean(presence.displayName, 24) || player.name;
+ }
}
- // Economy profile (off-schema). Keyed to a stable account: the wallet verified
- // in onAuth when the platform gate is on, else a client-persisted guest id, so
- // a player's pack/purse/skills survive a disconnect and follow them between
- // coin worlds. Hydrate the durable record before the synchronous load so a
- // returning player on a fresh process isn't reset to the starter kit.
- const playerId = clean(client.userData?.account, 80) || clean(options?.pid, 80) || client.sessionId;
+ // Economy profile (off-schema). Keyed to a VERIFIED account only: the wallet
+ // from onAuth when the platform gate is on, else a wallet proven by a signed
+ // play pass the client volunteered, else a server-minted guest id sealed in
+ // an HMAC guest token (guest-token.js). A raw `pid` join option is never an
+ // account key anymore — it let any client load, spend, and overwrite any
+ // victim's saved profile (gold, bank, items, cosmetics) just by asserting
+ // their id. Legacy `guest-…` pids migrate once (see _resolveIdentity).
+ const identity = await this._resolveIdentity(client, options);
+ const playerId = identity.playerId;
+ if (identity.wallet && !client.userData?.account) {
+ // The play pass proved this wallet even though the platform gate is off —
+ // bind it as the session account so ownership + moderation checks and the
+ // on-schema account field agree with the persistence key.
+ client.userData = { ...(client.userData || {}), account: identity.wallet };
+ player.account = clean(identity.wallet, 64);
+ }
+ if (identity.guestToken) {
+ // Hand the (re-)signed token back so the client persists it and replays
+ // it on the next join. Re-issued every join so an active guest's 90-day
+ // expiry never creeps up on them.
+ client.send('guestToken', { token: identity.guestToken });
+ }
try { await hydratePlayer(playerId); } catch { /* memory-only fallback */ }
// A slower-arriving leave could fire while we awaited; bail if so.
if (!this.state.players.has(client.sessionId)) return;
@@ -859,6 +906,33 @@ export class WalkRoom extends Room {
this._sendKingSync(client);
}
+ // Retire the reconnecting client's OWN previous session.
+ //
+ // A socket that dies uncleanly (phone slept, tab froze, wifi handover) stays
+ // half-open: the transport still reads it as OPEN and only reaps it when its
+ // ping retries expire, several seconds later. The client reconnects well inside
+ // that window, so the room briefly holds two sessions for one person — the
+ // returning player sees a frozen ghost of themselves at spawn, and so does
+ // everyone else. Liveness cannot be probed synchronously here (that is exactly
+ // what the half-open socket hides), so the reconnecting client tells us which
+ // session was its own and we retire that one.
+ //
+ // `prevSession` alone would be a kick primitive: session ids are published on
+ // the player schema, so anyone could name a stranger's. It is only honoured
+ // together with a matching persistent player key — the wallet the server itself
+ // verified in onAuth, or a guest id that is never broadcast to peers. A second
+ // tab or a second device is untouched: each carries its own prior session id.
+ _evictPriorSession(client, playerKey, prevSession) {
+ if (!playerKey || !prevSession || prevSession === client.sessionId) return;
+ for (const other of this.clients) {
+ if (other === client || other.sessionId !== prevSession) continue;
+ if (other.userData?.playerKey !== playerKey) continue;
+ console.log(`[walk_world ${this.roomId}] retiring superseded session ${other.sessionId}`);
+ try { other.leave(1000); } catch { /* already gone */ }
+ return;
+ }
+ }
+
onLeave(client) {
if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);
// Tag mini-game (R08): capture wasIt BEFORE state.players.delete below, so
@@ -924,6 +998,7 @@ export class WalkRoom extends Room {
}
async onDispose() {
+ unregisterWalkRoom(this);
// Persist the final build so the community's creation survives the room
// being torn down when the last player leaves. Awaited (Colyseus waits on
// the returned promise) so the Redis write lands before the room is gone —
@@ -1298,7 +1373,7 @@ export class WalkRoom extends Room {
: res.reason === 'daily-done' ? 'That job is done for today — check back tomorrow.'
: res.reason === 'done' ? 'You’ve already completed that job.'
: 'That job isn’t available to you yet.';
- client.send('notice', { kind: 'quest', text });
+ client.send('notice', { kind: 'quest', ok: false, text });
return;
}
if (isHeist(id)) {
@@ -1314,7 +1389,7 @@ export class WalkRoom extends Room {
this._sendQuestsToCrew(inst, client.sessionId);
}
this._persistEcon(client.sessionId);
- client.send('notice', { kind: 'quest', text: `Accepted: ${mission.title}` });
+ client.send('notice', { kind: 'quest', ok: true, text: `Accepted: ${mission.title}` });
this._sendQuests(client);
}
@@ -1343,7 +1418,7 @@ export class WalkRoom extends Room {
if (!this._actionOk(client.sessionId, 'questInteract')) return;
const zone = interactZoneInRange(player.x, player.z);
if (!zone) {
- client.send('notice', { kind: 'quest', text: 'There’s nothing to use here.' });
+ client.send('notice', { kind: 'quest', ok: false, text: 'There’s nothing to use here.' });
return;
}
const inVehicle = !!this._vehicleDrivenBy(client.sessionId);
@@ -1444,14 +1519,14 @@ export class WalkRoom extends Room {
_heistFinaleReady(client, inst, mission, obj) {
const need = Math.max(1, mission.party | 0 || 1);
if (inst.members.size < need) {
- client.send('notice', { kind: 'quest', text: `This job needs a crew of ${need} — recruit before the finale.` });
+ client.send('notice', { kind: 'quest', ok: false, text: `This job needs a crew of ${need} — recruit before the finale.` });
return false;
}
for (const sid of inst.members) {
const p = this.state.players.get(sid);
const zone = p ? zoneAt(p.x, p.z) : null;
if (!zone || zone.id !== obj.zone) {
- client.send('notice', { kind: 'quest', text: 'Your whole crew must be at the door for this.' });
+ client.send('notice', { kind: 'quest', ok: false, text: 'Your whole crew must be at the door for this.' });
return false;
}
}
@@ -1698,12 +1773,12 @@ export class WalkRoom extends Room {
const active = profile.hotbar[profile.activeSlot];
if (!active || active.item !== 'rod') {
- client.send('notice', { kind: 'tool', text: 'Equip a fishing rod to cast.' });
+ client.send('notice', { kind: 'tool', ok: false, text: 'Equip a fishing rod to cast.' });
return;
}
const spot = fishingSpotInRange(player.x, player.z);
if (!spot) {
- client.send('notice', { kind: 'fish', text: 'Move next to the water to cast.' });
+ client.send('notice', { kind: 'fish', ok: false, text: 'Move next to the water to cast.' });
return;
}
if (!hasRoomFor(profile, 'fish')) {
@@ -1726,12 +1801,12 @@ export class WalkRoom extends Room {
const xp = Math.round((10 + Math.floor(Math.random() * 6) + lvl * 0.3) * quality) * caught;
this._grantXp(client, profile, 'fishing', xp);
this._sendInv(client, profile);
- client.send('notice', { kind: 'fish', caught, text: caught > 1 ? `Caught ${caught} ${itemLabel('fish').toLowerCase()}!` : `Caught a ${itemLabel('fish').toLowerCase()}.` });
+ client.send('notice', { kind: 'fish', ok: true, caught, text: caught > 1 ? `Caught ${caught} ${itemLabel('fish').toLowerCase()}!` : `Caught a ${itemLabel('fish').toLowerCase()}.` });
// Quest progress: a real catch advances any active "collect fish" objective.
this._questEvent(client, profile, { type: 'collect', item: 'fish', qty: caught });
} else {
this._grantXp(client, profile, 'fishing', 2);
- client.send('notice', { kind: 'fish', caught: 0, text: 'The fish got away.' });
+ client.send('notice', { kind: 'fish', ok: false, caught: 0, text: 'The fish got away.' });
}
this._persistEcon(client.sessionId);
}
@@ -1764,7 +1839,7 @@ export class WalkRoom extends Room {
if (!this._actionOk(client.sessionId, 'equip')) return;
const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';
if (!getCosmetic(id)) {
- client.send('notice', { kind: 'cosmetic', text: 'That cosmetic doesn’t exist.' });
+ client.send('notice', { kind: 'cosmetic', ok: false, text: 'That cosmetic doesn’t exist.' });
return;
}
let equipped = equipCosmetic(profile, id);
@@ -1785,7 +1860,7 @@ export class WalkRoom extends Room {
}
}
if (!equipped) {
- client.send('notice', { kind: 'cosmetic', text: 'You don’t own that cosmetic yet.' });
+ client.send('notice', { kind: 'cosmetic', ok: false, text: 'You don’t own that cosmetic yet.' });
return;
}
const player = this.state.players.get(client.sessionId);
@@ -1839,12 +1914,12 @@ export class WalkRoom extends Room {
const res = consumeSlot(profile, slot);
if (!res.ok) {
const text = res.reason === 'full' ? 'You’re already at full health.' : 'That can’t be eaten.';
- client.send('notice', { kind: 'eat', text });
+ client.send('notice', { kind: 'eat', ok: false, text });
return;
}
profile.cd.consume = now + CONSUME_COOLDOWN_MS;
this._sendInv(client, profile);
- client.send('notice', { kind: 'eat', text: `+${res.gained} HP.` });
+ client.send('notice', { kind: 'eat', ok: true, text: `+${res.gained} HP.` });
this._persistEcon(client.sessionId);
}
@@ -1870,11 +1945,11 @@ export class WalkRoom extends Room {
const item = typeof payload?.item === 'string' ? payload.item.slice(0, 32) : '';
const entry = buyEntry(item);
if (!entry) {
- client.send('notice', { kind: 'store', text: 'That item isn’t for sale.' });
+ client.send('notice', { kind: 'store', ok: false, text: 'That item isn’t for sale.' });
return;
}
if (profile.gold < entry.price) {
- client.send('notice', { kind: 'store', text: `Not enough cash — ${entry.price} needed.` });
+ client.send('notice', { kind: 'store', ok: false, text: `Not enough cash — ${entry.price} needed.` });
return;
}
if (!hasRoomFor(profile, entry.item)) {
@@ -1889,7 +1964,7 @@ export class WalkRoom extends Room {
}
profile.gold -= entry.price;
this._sendInv(client, profile);
- client.send('notice', { kind: 'store', text: `Bought ${bought > 1 ? bought + ' ' : ''}${itemLabel(entry.item)} for ${entry.price} cash.` });
+ client.send('notice', { kind: 'store', ok: true, text: `Bought ${bought > 1 ? bought + ' ' : ''}${itemLabel(entry.item)} for ${entry.price} cash.` });
this._persistEcon(client.sessionId);
}
@@ -1902,11 +1977,11 @@ export class WalkRoom extends Room {
if (!this._actionOk(client.sessionId, 'storeSell')) return;
const slot = resolveSlot(profile, payload?.slot);
if (!slot || !slot.item) {
- client.send('notice', { kind: 'store', text: 'Nothing there to sell.' });
+ client.send('notice', { kind: 'store', ok: false, text: 'Nothing there to sell.' });
return;
}
if (!isSellable(slot.item)) {
- client.send('notice', { kind: 'store', text: `The store won’t buy ${itemLabel(slot.item).toLowerCase()}.` });
+ client.send('notice', { kind: 'store', ok: false, text: `The store won’t buy ${itemLabel(slot.item).toLowerCase()}.` });
return;
}
const want = Number.isFinite(payload?.qty) && payload.qty > 0 ? Math.min(payload.qty | 0, slot.qty) : slot.qty;
@@ -1916,7 +1991,7 @@ export class WalkRoom extends Room {
const total = sellPrice(item) * removed;
profile.gold += total;
this._sendInv(client, profile);
- client.send('notice', { kind: 'store', text: `Sold ${removed} ${itemLabel(item).toLowerCase()} for ${total} cash.` });
+ client.send('notice', { kind: 'store', ok: true, text: `Sold ${removed} ${itemLabel(item).toLowerCase()} for ${total} cash.` });
this._persistEcon(client.sessionId);
}
@@ -1933,12 +2008,13 @@ export class WalkRoom extends Room {
if (!amount) return;
const moved = bankTransfer(profile, amount);
if (moved === 0) {
- client.send('notice', { kind: 'bank', text: amount > 0 ? 'No cash on hand to deposit.' : 'Nothing banked to withdraw.' });
+ client.send('notice', { kind: 'bank', ok: false, text: amount > 0 ? 'No cash on hand to deposit.' : 'Nothing banked to withdraw.' });
return;
}
this._sendProfile(client);
client.send('notice', {
kind: 'bank',
+ ok: true,
text: moved > 0 ? `Deposited ${moved} cash — protected from drops.` : `Withdrew ${-moved} cash.`,
});
this._persistEcon(client.sessionId);
@@ -1978,20 +2054,20 @@ export class WalkRoom extends Room {
const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';
const price = boutiquePrice(id);
if (!price) {
- client.send('notice', { kind: 'boutique', text: 'That item isn’t in the boutique.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'That item isn’t in the boutique.' });
return;
}
if (ownedCosmeticSet(profile).has(id)) {
- client.send('notice', { kind: 'boutique', text: 'You already own that.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'You already own that.' });
return;
}
const wallet = typeof payload?.wallet === 'string' ? payload.wallet.trim() : '';
if (!isWalletAddress(wallet)) {
- client.send('notice', { kind: 'boutique', text: 'Connect a Solana wallet to buy with $THREE.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'Connect a Solana wallet to buy with $THREE.' });
return;
}
if (!tokenConfigured()) {
- client.send('notice', { kind: 'boutique', text: 'The $THREE boutique is offline right now.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'The $THREE boutique is offline right now.' });
return;
}
let built;
@@ -2007,7 +2083,7 @@ export class WalkRoom extends Room {
console.warn('[walk_world] boutique quote failed:', err?.message);
}
if (!built) {
- client.send('notice', { kind: 'boutique', text: 'Could not price that purchase — try again in a moment.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'Could not price that purchase — try again in a moment.' });
return;
}
client.send('boutiqueQuote', { id, price, quoteToken: built.quoteToken, txBase64: built.txBase64 });
@@ -2029,31 +2105,31 @@ export class WalkRoom extends Room {
result = await verifyTokenPurchase({ quoteToken, txSig, purpose: 'boutique' });
} catch (err) {
console.warn('[walk_world] boutique settle failed:', err?.message);
- client.send('notice', { kind: 'boutique', text: 'Could not verify that payment — try again.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'Could not verify that payment — try again.' });
return;
}
if (!result?.ok) {
- client.send('notice', { kind: 'boutique', text: `Payment didn’t verify (${result?.reason || 'unknown'}).` });
+ client.send('notice', { kind: 'boutique', ok: false, text: `Payment didn’t verify (${result?.reason || 'unknown'}).` });
return;
}
this._pruneBoutiqueNonces();
if (this._boutiqueNonces.has(result.nonce)) {
- client.send('notice', { kind: 'boutique', text: 'That purchase already settled.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'That purchase already settled.' });
return;
}
this._boutiqueNonces.set(result.nonce, Date.now());
const cosmeticId = result.quote?.cosmeticId;
if (ownedCosmeticSet(profile).has(cosmeticId)) {
- client.send('notice', { kind: 'boutique', text: 'Payment verified — you already owned this.' });
+ client.send('notice', { kind: 'boutique', ok: true, text: 'Payment verified — you already owned this.' });
return;
}
const granted = cosmeticId ? grantCosmetic(profile, cosmeticId) : false;
if (!granted) {
- client.send('notice', { kind: 'boutique', text: 'Payment verified, but that item couldn’t be unlocked. Contact support.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'Payment verified, but that item couldn’t be unlocked. Contact support.' });
return;
}
this._sendProfile(client);
- client.send('notice', { kind: 'boutique', text: `Unlocked ${getCosmetic(cosmeticId)?.name || 'the item'} — check your wardrobe.` });
+ client.send('notice', { kind: 'boutique', ok: true, text: `Unlocked ${getCosmetic(cosmeticId)?.name || 'the item'} — check your wardrobe.` });
this._persistEcon(client.sessionId);
}
@@ -2071,6 +2147,44 @@ export class WalkRoom extends Room {
for (const [nonce, ts] of this._spinNonces) if (ts < cutoff) this._spinNonces.delete(nonce);
}
+ // Resolve the stable persistence identity for a joining session. Trust order:
+ // 1. The wallet onAuth verified (platform gate on).
+ // 2. A wallet sealed in a valid play pass the client sent voluntarily —
+ // possession of the HMAC-signed pass proves the wallet even when the
+ // gate is off, so signed-in players keep one profile across deploys.
+ // 3. A guest id sealed in a signed guest token (minted below on a prior
+ // join). The token, not the id, is the credential.
+ // 4. One-time migration for legacy clients that persisted a bare `guest-…`
+ // localStorage pid: honored ONLY if the saved record has never been
+ // token-upgraded (so a bare claim on an upgraded id gets a fresh guest,
+ // not the victim's profile), never for wallet-shaped ids, and sealed
+ // into a signed token on the spot.
+ // 5. A brand-new server-minted guest id.
+ // Lanes 3-5 return a fresh token for the client to persist and replay.
+ async _resolveIdentity(client, options) {
+ const authed = clean(client.userData?.account, 80);
+ if (authed) return { playerId: authed, wallet: '', guestToken: '' };
+ const pass = verifyPlayPass(options?.playPass);
+ const wallet = clean(pass?.wallet, 80);
+ if (wallet) return { playerId: wallet, wallet, guestToken: '' };
+ const sealed = verifyGuestToken(options?.guestToken);
+ if (sealed) return { playerId: sealed, wallet: '', guestToken: signGuestToken(sealed) };
+ const legacy =
+ typeof options?.pid === 'string' && /^guest-[a-z0-9]{4,60}$/i.test(options.pid) ? options.pid : '';
+ if (legacy) {
+ try { await hydratePlayer(legacy); } catch { /* memory-only fallback */ }
+ const rec = loadPlayer(legacy);
+ if (!rec?.guestUpgraded) {
+ // Stamp the record so this bare id can never be claimed again; the
+ // device that holds it from here on holds the signed token instead.
+ savePlayer(legacy, { ...(rec || {}), guestUpgraded: true });
+ return { playerId: legacy, wallet: '', guestToken: signGuestToken(legacy) };
+ }
+ }
+ const gid = newGuestId();
+ return { playerId: gid, wallet: '', guestToken: signGuestToken(gid) };
+ }
+
// Write this session's economy profile through to the account-keyed store,
// merging onto any existing record so unrelated fields for the same account
// are preserved. Synchronous + debounced.
@@ -2714,11 +2828,12 @@ export class WalkRoom extends Room {
return !!player && !!player.account && player.account === this.coinCreator;
}
- // True if (x,z) is inside a protected disc (spawn or totem) — placement there is
- // refused at every height so neither landmark can be buried or fenced in.
+ // True if (x,z) is inside a protected disc (spawn, totem, or the plaza stage) —
+ // placement there is refused at every height so no landmark can be buried or
+ // fenced in.
_isProtectedColumn(x, z) {
for (const p of PROTECTED_POINTS) {
- if (Math.hypot(x - p.x, z - p.z) <= PROTECTED_RADIUS_CELLS) return true;
+ if (Math.hypot(x - p.x, z - p.z) <= p.r) return true;
}
return false;
}
@@ -2740,7 +2855,7 @@ export class WalkRoom extends Room {
// off. Returns an obj:reject reason, or null when the placement is allowed.
_propPlacementBlock(x, z) {
for (const p of PROTECTED_POINTS_M) {
- if (Math.hypot(x - p.x, z - p.z) <= PROTECTED_RADIUS_M) return 'protected';
+ if (Math.hypot(x - p.x, z - p.z) <= p.r) return 'protected';
}
const tx = Math.round(x / PROP_TILE_M);
const tz = Math.round(z / PROP_TILE_M);
diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.js
index de4547444..84e770398 100644
--- a/multiplayer/src/schemas.js
+++ b/multiplayer/src/schemas.js
@@ -52,6 +52,11 @@ export class Player extends Schema {
// type would lose precision past 2^53 but float64 covers epoch ms safely.
this.it = false;
this.itSince = 0;
+ // Verified three.ws username (W10) — set only from a signed presence
+ // ticket, never from a raw client option, so peers can trust it enough to
+ // open the real /u/<username> profile, follow, and DM this player. Empty
+ // for guests and wallet-only sessions.
+ this.username = '';
}
}
// IMPORTANT: append-only. Field indices are positional in @colyseus/schema's
@@ -83,6 +88,9 @@ defineTypes(Player, {
// render the glow ring + 🏃 marker without a separate broadcast channel.
it: 'boolean',
itSince: 'float64',
+ // Append-only (W10): verified three.ws username from the signed presence
+ // ticket. See the constructor note.
+ username: 'string',
});
// A single placed voxel in a coin's world. Keyed in the blocks MapSchema by its
diff --git a/src/game/community-net.js b/src/game/community-net.js
index c6adfc31c..f31a3f750 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -29,7 +29,12 @@ function persistedPid(account) {
} catch { return ''; }
}
const RECONNECT_MAX_MS = 60_000;
-const MAX_RECONNECT_ATTEMPTS = 6;
+// Attempts reset to 0 on every successful join, so this bounds ONE outage, not
+// the session. Six attempts gave up ~2.5 minutes in — shorter than a server
+// redeploy or instance replacement, which permanently stranded everyone present
+// in single-player mid-session. Fourteen rides out ~11 minutes (the tail retries
+// only once a minute) before parking on 'offline' with the manual retry().
+const MAX_RECONNECT_ATTEMPTS = 14;
const SEND_HZ = 15;
const SEND_INTERVAL_MS = 1000 / SEND_HZ;
const POSITION_EPSILON = 0.01;
@@ -275,9 +280,20 @@ export class CommunityNet {
// Pre-join cosmetic loadout (W03). Server-validated against ownership
// before it dresses the player, so peers can trust the broadcast look.
cosmetics: this.cosmetics,
- // Stable persistence key for the off-schema economy (used only when the
- // server hasn't verified a wallet account of its own — i.e. un-gated/dev).
+ // Legacy persistence key. Modern servers ignore it as an account key (a
+ // bare pid could claim any profile) except for the one-time migration of
+ // an old `guest-…` id into a signed guest token; older servers still read
+ // it, so keep sending it until every deploy is on the token flow.
pid: this.pid,
+ // Our own previous session id, sent only when this is a reconnect. A
+ // socket that died uncleanly is still half-open server-side for several
+ // seconds, so without this the room holds a frozen ghost of us at spawn
+ // until its ping retries expire. The server retires that exact session,
+ // and only when the persistent player key above matches ours too.
+ ...(this.sessionId ? { prevSession: this.sessionId } : {}),
+ // Signed guest token (server-minted, HMAC-sealed guest id). This — not
+ // the raw pid — is what proves a guest owns their saved progression.
+ ...(this._guestToken() ? { guestToken: this._guestToken() } : {}),
// Signed presence ticket (W09). WalkRoom verifies it and registers the
// account with the social hub under this world's name, so friends see
// "Online · <coin> Town" and DMs route to this socket. Omitted entirely
@@ -305,7 +321,15 @@ export class CommunityNet {
this.room = room;
this.sessionId = this.room.sessionId;
- this.room.onMessage('chat', (msg) => this._emit('chat', msg));
+ // Guest identity (see guest-token.js server-side): the room seals our guest
+ // id into a signed token and hands it back on every join. Persist it — the
+ // token is the credential that lets this device reclaim its progression.
+ this.room.onMessage('guestToken', (msg) => {
+ if (msg && typeof msg.token === 'string' && msg.token) {
+ try { localStorage.setItem('tws-guest-token', msg.token); } catch { /* storage blocked: session-only guest */ }
+ }
+ });
+ this.room.onMessage('chat', (msg) => this._emit('chat', msg));
this.room.onMessage('interact', (msg) => this._emit('interact', msg));
// Friends (W09): live DM + request/accept events pushed by the social hub
// to whichever realm room the account is currently registered in.
@@ -486,6 +510,17 @@ export class CommunityNet {
});
this.room.onError((code, message) => log.warn('[community-net] room.onError', code, message));
+ // A reconnect gives us a fresh session the server spawns at the origin,
+ // so every send-suppression heuristic from the previous connection is
+ // now wrong. Clearing _lastSent is load-bearing: without it a player who
+ // reconnects while standing still never sends a move (the position is
+ // unchanged from the pre-drop one), so the server keeps them at spawn and
+ // every peer sees them teleported to 0,0,0 until they happen to walk.
+ // The RTT sample is dropped for the same reason — its send is gone.
+ this._lastSent = null;
+ this._lastSentAt = 0;
+ this._pingSentAt = 0;
+ this.ping = null;
this._reconnectAttempts = 0;
this._setStatus('online');
this._emit('ready', {
@@ -717,6 +752,31 @@ export class CommunityNet {
this._reconnectAttempts = 0;
this.connect();
}
+
+ // Is the wire actually carrying traffic right now? `status === 'online'` alone
+ // is a claim about the last thing that happened, not about the socket.
+ isLive() { return this.status === 'online' && this.room?.connection?.isOpen === true; }
+
+ // Call when the page comes back to the foreground. A backgrounded tab is the
+ // one case where the client's own status can be a lie: iOS Safari suspends the
+ // whole page, the OS reaps the TCP connection, and no 'close' event is ever
+ // delivered — so the client still reads 'online' while every send silently
+ // drops into a dead socket and no peer update ever arrives again. Probing the
+ // connection on resume converts that invisible half-death into the normal
+ // reconnect path. It also short-circuits the backoff when the retries were
+ // burned (or throttled) while the tab was hidden, so returning to the tab is
+ // always the fastest way back into the world.
+ resume() {
+ if (this._destroyed || !this.url) return;
+ if (this.status === 'online' && this.room?.connection?.isOpen !== true) {
+ log.warn('[community-net] socket died while backgrounded — reconnecting');
+ this._closeRoom();
+ this._setStatus('offline');
+ this.retry();
+ return;
+ }
+ if (this.status === 'offline' || this.status === 'failed') this.retry();
+ }
destroy() {
this._destroyed = true;
if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }