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(event): a server-gated event quest line with a durable leaderboard

nirholas57c8bc1c4d7b
diff --git a/api/_lib/event-config.js b/api/_lib/event-config.js
new file mode 100644
index 000000000..ad554bc29
--- /dev/null
+++ b/api/_lib/event-config.js
@@ -0,0 +1,49 @@
+// The live event's config, read from the repo's own public/event.json.
+//
+// public/event.json is the single source of truth for the platform event: the
+// countdown pill, the in-world meetup layer, the game server's quest gate
+// (multiplayer/src/event-window.js, which reads the same file over HTTP because its
+// container ships without public/) and now the leaderboard endpoints. The API
+// process serves that file from disk, so it reads it from disk — no HTTP hop to
+// itself, and no second copy of the times anywhere.
+//
+// Parsing is delegated to parseEventWindow so the API and the game server agree on
+// what "the event" is down to the millisecond, including the "missing endsAt means
+// six hours" default.
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { parseEventWindow, isEventLive } from '../../multiplayer/src/event-window.js';
+
+const CACHE_TTL_MS = 60_000;
+
+let _cached = null;
+let _readAt = 0;
+
+/**
+ * The current event window ({ id, name, startsAt, endsAt }) or null when the config
+ * is absent or malformed. Cached for a minute; a deploy replaces the file, and an
+ * event window is measured in hours, so a minute of staleness is invisible.
+ */
+export function eventConfig(now = Date.now()) {
+ if (_cached !== null && now - _readAt < CACHE_TTL_MS) return _cached;
+ try {
+ const raw = readFileSync(resolve(process.cwd(), 'public/event.json'), 'utf8');
+ _cached = parseEventWindow(JSON.parse(raw));
+ } catch (err) {
+ console.warn('[event-config] public/event.json unreadable:', err?.message || err);
+ _cached = null;
+ }
+ _readAt = now;
+ return _cached;
+}
+
+/** Is the configured event running right now? */
+export function eventLiveNow(now = Date.now()) {
+ return isEventLive(eventConfig(now), now);
+}
+
+/** The configured event's id, or null. The leaderboard is keyed by it. */
+export function eventId(now = Date.now()) {
+ return eventConfig(now)?.id || null;
+}
diff --git a/api/_lib/event-leaderboard-store.js b/api/_lib/event-leaderboard-store.js
new file mode 100644
index 000000000..d59bfc6f4
--- /dev/null
+++ b/api/_lib/event-leaderboard-store.js
@@ -0,0 +1,139 @@
+// Event leaderboard — durable storage for the live event quest line's standing.
+//
+// The authoritative game server (multiplayer WalkRoom) reports every finished event
+// quest here through api/internal/event-score.js; api/play/event-leaderboard.js and
+// the in-world panel read the ranked table back. The ranking itself lives in
+// multiplayer/src/event-leaderboard.js so both sides sort identically — this module
+// is purely the store.
+//
+// Shape: one Redis HASH per event (`event:lb:<eventId>`), field = the player's
+// account key, value = the JSON record. A HASH (rather than the ZSET clash-store
+// uses) because a row carries more than a score — display name, cash earned, the
+// per-mission breakdown, the timestamp that breaks ties — and the population is one
+// event's worth of players, small enough that HGETALL plus an in-process sort is a
+// single cheap round-trip. Distinct accounts write distinct fields, and one account
+// can only be in one live session (playerStore enforces that upstream), so a per-
+// field read-modify-write never races with itself.
+//
+// The key carries a TTL a few days past the event so the store self-prunes: the
+// standing outlives the event long enough for the owner to settle prizes, then goes
+// away on its own with no sweeper.
+//
+// Redis being unconfigured (local dev, tests) or failing at call time degrades to an
+// in-process table with the same semantics, exactly like clash-store: a briefly
+// non-durable leaderboard beats a 5xx that takes the panel dark mid-event.
+
+import { getRedis } from './redis.js';
+import { applyEventRun, emptyEventRecord, normalizeEventRecord } from '../../multiplayer/src/event-leaderboard.js';
+
+const redis = getRedis();
+
+// Keep a finished event's standing around for a week — long enough for the owner to
+// read the winners off it and settle prizes by hand.
+export const BOARD_TTL_S = 7 * 24 * 60 * 60;
+
+const EVENT_ID_RE = /^[A-Za-z0-9_.-]{1,64}$/;
+const ACCOUNT_RE = /^[A-Za-z0-9_:.-]{1,96}$/;
+
+function boardKey(eventId) {
+ return `event:lb:${eventId}`;
+}
+
+export function isValidEventId(id) {
+ return typeof id === 'string' && EVENT_ID_RE.test(id);
+}
+
+export function isValidAccount(id) {
+ return typeof id === 'string' && ACCOUNT_RE.test(id);
+}
+
+// --- in-memory fallback ------------------------------------------------------
+const mem = new Map(); // key → Map(account → record)
+
+function memBoard(key) {
+ let m = mem.get(key);
+ if (!m) { m = new Map(); mem.set(key, m); }
+ return m;
+}
+
+let _degradedAt = 0;
+function redisDegraded(err) {
+ const now = Date.now();
+ if (now - _degradedAt > 60_000) {
+ _degradedAt = now;
+ console.warn('[event-leaderboard] redis degraded — serving from in-memory fallback:', err?.message || err);
+ }
+}
+
+function parseRecord(raw, account) {
+ if (!raw) return null;
+ try {
+ const obj = typeof raw === 'string' ? JSON.parse(raw) : raw;
+ return obj && typeof obj === 'object' ? normalizeEventRecord(obj, account) : null;
+ } catch {
+ return null;
+ }
+}
+
+// --- writes ------------------------------------------------------------------
+
+/**
+ * Fold one finished event quest into a player's row and return the updated record.
+ * Idempotent per call, not per mission: each completion is a real, separate run, so
+ * a player who finishes the same repeatable job three times scores three.
+ *
+ * @param {{ eventId: string, account: string, name?: string, missionId?: string, gold?: number, at?: number }} run
+ * @returns {Promise<{ record: object, durable: boolean }>}
+ */
+export async function recordEventRun({ eventId, account, name = '', missionId = '', gold = 0, at = Date.now() }) {
+ const key = boardKey(eventId);
+
+ if (redis) {
+ try {
+ const existing = parseRecord(await redis.hget(key, account), account);
+ const rec = applyEventRun(existing || emptyEventRecord(account, name), { missionId, gold, at, name });
+ await redis.hset(key, { [account]: JSON.stringify(rec) });
+ await redis.expire(key, BOARD_TTL_S);
+ return { record: rec, durable: true };
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+
+ const board = memBoard(key);
+ const rec = applyEventRun(board.get(account) || emptyEventRecord(account, name), { missionId, gold, at, name });
+ board.set(account, rec);
+ return { record: rec, durable: false };
+}
+
+// --- reads -------------------------------------------------------------------
+
+/**
+ * Every recorded row for an event, unranked (callers fold them through
+ * rankEventBoard / eventBoardView). Returns an empty array for an event nobody has
+ * scored in yet, which is the leaderboard's designed empty state, never an error.
+ *
+ * @returns {Promise<{ records: object[], durable: boolean }>}
+ */
+export async function readEventRecords(eventId) {
+ const key = boardKey(eventId);
+
+ if (redis) {
+ try {
+ const all = await redis.hgetall(key);
+ const records = Object.entries(all || {})
+ .map(([account, raw]) => parseRecord(raw, account))
+ .filter(Boolean);
+ return { records, durable: true };
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
+
+ return { records: [...memBoard(key).values()], durable: false };
+}
+
+// Test seam: clear the in-process fallback between cases.
+export function __resetEventBoards() {
+ mem.clear();
+}
diff --git a/api/internal/event-score.js b/api/internal/event-score.js
new file mode 100644
index 000000000..f1787b980
--- /dev/null
+++ b/api/internal/event-score.js
@@ -0,0 +1,81 @@
+// POST /api/internal/event-score — the multiplayer server → API bridge for the live
+// event leaderboard.
+//
+// When a player finishes one of the event quest line's jobs (multiplayer/src/
+// quests.js, `event: true`), the authoritative Colyseus room reports it here. Only
+// completions that the room's own quest engine granted ever reach this endpoint, and
+// only inside the event window that the room re-derives server-side — a client can
+// neither claim a run nor forge one for another player.
+//
+// Trust model mirrors api/internal/quest-notify.js: a valid world-service token
+// (signed by multiplayer/src/persistence.js, svc:'world') is required, so a browser
+// cannot POST a score. The endpoint additionally refuses any event id that is not
+// the currently configured event, and any run reported outside that event's window,
+// so even a leaked token cannot stuff a board for an event that is not running.
+//
+// The response echoes the player's updated row: the room forwards it to the client
+// so a completion toast can say "that's your 4th run" without a second read.
+
+import { json, method, wrap, error, readJson, cors } from '../_lib/http.js';
+import { extractBearer } from '../_lib/auth.js';
+import { verifyWorldServiceToken } from '../_lib/world-service-auth.js';
+import { eventConfig } from '../_lib/event-config.js';
+import { recordEventRun, isValidAccount } from '../_lib/event-leaderboard-store.js';
+import { isEventLive } from '../../multiplayer/src/event-window.js';
+import { isEventMission } from '../../multiplayer/src/quests.js';
+
+export default wrap(async (req, res) => {
+ // Server-to-server only — no browser origin ever calls this directly.
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const service = await verifyWorldServiceToken(extractBearer(req));
+ if (!service) return error(res, 401, 'unauthorized', 'valid world service token required');
+
+ let body;
+ try {
+ body = await readJson(req, 4096);
+ } catch (err) {
+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid body');
+ }
+
+ const now = Date.now();
+ const event = eventConfig(now);
+ if (!event) return error(res, 409, 'no_event', 'no event is configured');
+
+ const eventId = typeof body?.eventId === 'string' ? body.eventId.trim() : '';
+ if (eventId && eventId !== event.id) {
+ return error(res, 409, 'event_mismatch', 'reported event is not the configured event');
+ }
+ if (!isEventLive(event, now)) {
+ return error(res, 409, 'event_closed', 'the event window is not open');
+ }
+
+ const account = typeof body?.account === 'string' ? body.account.trim() : '';
+ if (!isValidAccount(account)) return error(res, 400, 'validation_error', 'account required');
+
+ const missionId = typeof body?.missionId === 'string' ? body.missionId.slice(0, 64) : '';
+ if (!isEventMission(missionId)) {
+ return error(res, 400, 'validation_error', 'missionId must be an event mission');
+ }
+
+ const name = typeof body?.name === 'string' ? body.name.slice(0, 24) : '';
+ const gold = Number.isFinite(body?.gold) ? Math.max(0, Math.round(body.gold)) : 0;
+
+ const { record, durable } = await recordEventRun({
+ eventId: event.id,
+ account,
+ name,
+ missionId,
+ gold,
+ at: now,
+ });
+
+ return json(res, 200, {
+ ok: true,
+ durable,
+ eventId: event.id,
+ runs: record.runs,
+ cash: record.cash,
+ });
+});
diff --git a/api/play/event-leaderboard.js b/api/play/event-leaderboard.js
new file mode 100644
index 000000000..67c7baa09
--- /dev/null
+++ b/api/play/event-leaderboard.js
@@ -0,0 +1,76 @@
+// GET /api/play/event-leaderboard
+//
+// The live standing for the platform event's in-world quest line: who has completed
+// the most event jobs inside the window, tiebroken by the event gold they earned.
+// One read, two consumers — the in-world panel (the multiplayer room proxies this
+// call for its clients) and the web event page — so the ranking a player sees at the
+// jobs board is byte-for-byte the ranking the site shows.
+//
+// Query:
+// account optional — a player's account key; pins their own row in `you`, even
+// when they are outside the top N. Omitted for an anonymous
+// web read.
+// limit optional — how many rows to return (default 10, max 100).
+//
+// Scores are written only by the authoritative game server through
+// api/internal/event-score.js; this endpoint is read-only and never grants anything.
+// Prizes are NOT settled here: the board ranks, and the owner pays the winners
+// manually after the event. Nothing in this path touches a wallet or a chain.
+//
+// Shape (always 200 when an event is configured — an event nobody has played yet is
+// an empty board, not an error):
+// {
+// event: { id, name, startsAt, endsAt, live },
+// top: [{ rank, name, runs, cash, lastAt }],
+// you: { rank, name, runs, cash, lastAt, inTop } | null,
+// players, totalRuns, prizes: { settlement: 'manual', … }
+// }
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { eventConfig } from '../_lib/event-config.js';
+import { readEventRecords, isValidAccount } from '../_lib/event-leaderboard-store.js';
+import { isEventLive } from '../../multiplayer/src/event-window.js';
+import { eventBoardView, TOP_LIMIT } from '../../multiplayer/src/event-leaderboard.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const now = Date.now();
+ const event = eventConfig(now);
+ if (!event) return error(res, 404, 'no_event', 'no event is configured');
+
+ const url = new URL(req.url, 'http://localhost');
+ const rawAccount = (url.searchParams.get('account') || '').trim();
+ // An unparseable account is treated as an anonymous read rather than a 400: the
+ // board itself is public, and refusing the whole page over one bad query param
+ // would be a worse answer than serving the ranking without a pinned row.
+ const account = isValidAccount(rawAccount) ? rawAccount : '';
+ const limit = Number.parseInt(url.searchParams.get('limit') || '', 10) || TOP_LIMIT;
+
+ const { records } = await readEventRecords(event.id);
+ const view = eventBoardView(records, { account, limit });
+
+ return json(res, 200, {
+ event: {
+ id: event.id,
+ name: event.name,
+ startsAt: new Date(event.startsAt).toISOString(),
+ endsAt: new Date(event.endsAt).toISOString(),
+ live: isEventLive(event, now),
+ },
+ ...view,
+ prizes: {
+ settlement: 'manual',
+ summary: 'Winners are announced from this board and settled by the three.ws team after the event. No prize is paid automatically.',
+ },
+ }, {
+ // Live standings during an event: short edge cache so a refresh feels current
+ // without every viewer hitting the store.
+ 'cache-control': 'public, max-age=5, s-maxage=10, stale-while-revalidate=60',
+ });
+});
diff --git a/api/play/population.js b/api/play/population.js
new file mode 100644
index 000000000..d56039cbe
--- /dev/null
+++ b/api/play/population.js
@@ -0,0 +1,92 @@
+// GET /api/play/population — how many people are standing in the /play worlds
+// right now.
+//
+// ?coin=<mint> narrow to one community's worlds (the /event landing page
+// passes the $THREE mint so its LIVE panel counts the people
+// actually at the event, not the whole platform)
+//
+// The multiplayer server is the only thing that knows: /play presence lives in
+// Colyseus rooms, not in Postgres or Redis, so there is nothing here to query.
+// This handler proxies the standalone server's public /population aggregate
+// (multiplayer/src/index.js), which reads the matchmaker's driver-backed room
+// listing and therefore counts every instance under horizontal scaling.
+//
+// The proxy exists so the browser gets a same-origin, CDN-cacheable endpoint and
+// the multiplayer host stays an internal detail. It returns a count and nothing
+// else: no session ids, no names, no wallets, no positions cross this boundary.
+//
+// When the multiplayer server is unreachable or has not shipped /population yet,
+// this answers 200 with `{ ok: false, reason: 'unavailable' }` rather than an
+// error. Callers render the live state without a number in that case; a landing
+// page must never invent a population, and must never break because a count is
+// missing.
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { env } from '../_lib/env.js';
+
+export const maxDuration = 10;
+
+const UPSTREAM_TIMEOUT_MS = 3000;
+
+// Mints and contract addresses only: the value is forwarded to another service,
+// so it is constrained here rather than trusted. Base58 (Solana) and 0x-hex
+// (EVM coin worlds) both pass; anything else is treated as "no filter".
+function safeCoin(raw) {
+ const s = typeof raw === 'string' ? raw.trim() : '';
+ if (!s) return '';
+ if (/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s)) return s;
+ if (/^0x[0-9a-fA-F]{40}$/.test(s)) return s;
+ return '';
+}
+
+async function readUpstream(base, coin) {
+ const url = new URL('/population', base);
+ if (coin) url.searchParams.set('coin', coin);
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), UPSTREAM_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, { signal: ac.signal, headers: { accept: 'application/json' } });
+ if (!res.ok) return null;
+ const body = await res.json();
+ if (!body || body.ok !== true) return null;
+ return {
+ players: Math.max(0, Math.floor(Number(body.players) || 0)),
+ rooms: Math.max(0, Math.floor(Number(body.rooms) || 0)),
+ };
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const coin = safeCoin(new URL(req.url, 'http://localhost').searchParams.get('coin'));
+ const base = env.MULTIPLAYER_INTERNAL_URL;
+
+ if (!base) {
+ return json(res, 200, { ok: false, reason: 'unavailable', coin: coin || null });
+ }
+
+ const upstream = await readUpstream(base, coin);
+ if (!upstream) {
+ return json(res, 200, { ok: false, reason: 'unavailable', coin: coin || null });
+ }
+
+ // 5s at the edge matches the multiplayer server's own cache window, so the
+ // number is never staler than the source it came from.
+ res.setHeader('cache-control', 'public, max-age=5, s-maxage=5');
+ return json(res, 200, {
+ ok: true,
+ coin: coin || null,
+ players: upstream.players,
+ rooms: upstream.rooms,
+ });
+});
diff --git a/multiplayer/src/event-leaderboard.js b/multiplayer/src/event-leaderboard.js
new file mode 100644
index 000000000..a4793d9fb
--- /dev/null
+++ b/multiplayer/src/event-leaderboard.js
@@ -0,0 +1,109 @@
+// Event leaderboard — the pure ranking math behind the live event quest line.
+//
+// The event jobs (quests.js, `event: true`) pay in ordinary in-world gold; this is
+// the standing that says who ran the most of them inside the window. Like
+// war-standings.js it is dependency-free and side-effect-free: a record in, a
+// ranked table out. The durable store (api/_lib/event-leaderboard-store.js) and the
+// read endpoint (api/play/event-leaderboard.js) both fold their rows through THESE
+// functions, so the panel a player sees in-world and the JSON the web reads can
+// never rank the same data two different ways.
+//
+// Ranking, in order:
+// 1. runs — event quests completed inside the window (the headline)
+// 2. cash — total event gold earned (the tiebreak: harder jobs pay more)
+// 3. lastAt — earliest to reach that score wins (a tie broken by the clock is
+// fairer than one broken by an id, and it rewards finishing early)
+// 4. account — a stable last resort so the order is total and reproducible
+//
+// Prizes are NOT paid here or anywhere in code. The board ranks; the owner settles
+// after the event.
+
+// How many rows the in-world panel and the public read endpoint show by default.
+export const TOP_LIMIT = 10;
+
+// A zeroed record for one player. `name` is the display name at the time of their
+// most recent run, so a rename during the event shows the newest one.
+export function emptyEventRecord(account, name = '') {
+ return {
+ account: String(account || ''),
+ name: String(name || '').slice(0, 24),
+ runs: 0,
+ cash: 0,
+ lastAt: 0,
+ missions: {},
+ };
+}
+
+// Fold one finished event quest into a record, mutating and returning it. Every
+// value is clamped here rather than at the call sites, so a malformed report can
+// dirty a row but never poison the ranking with NaN or a negative score.
+export function applyEventRun(rec, { missionId = '', gold = 0, at = 0, name = '' } = {}) {
+ rec.runs = Math.max(0, (rec.runs | 0) + 1);
+ rec.cash = Math.max(0, (rec.cash | 0) + Math.max(0, Math.round(Number(gold) || 0)));
+ const ts = Math.max(0, Math.round(Number(at) || 0));
+ if (ts > rec.lastAt) rec.lastAt = ts;
+ if (name) rec.name = String(name).slice(0, 24);
+ const id = String(missionId || '').slice(0, 64);
+ if (id) rec.missions[id] = (rec.missions[id] | 0) + 1;
+ return rec;
+}
+
+// Normalize a persisted/transported row back into a full record. Tolerant of
+// partial and legacy blobs — a corrupt row degrades to a zeroed one rather than
+// throwing inside a read that the whole panel depends on.
+export function normalizeEventRecord(row, account = '') {
+ const rec = emptyEventRecord(row?.account || account, row?.name || '');
+ rec.runs = Math.max(0, Number(row?.runs) | 0);
+ rec.cash = Math.max(0, Number(row?.cash) | 0);
+ rec.lastAt = Math.max(0, Number(row?.lastAt) | 0);
+ if (row?.missions && typeof row.missions === 'object') {
+ for (const [id, n] of Object.entries(row.missions)) {
+ const count = Number(n) | 0;
+ if (count > 0) rec.missions[String(id).slice(0, 64)] = count;
+ }
+ }
+ return rec;
+}
+
+// Sort records into the ranked, rank-stamped array both surfaces render. Records
+// with zero runs are dropped: the board is "who ran the event", not "who logged in".
+export function rankEventBoard(records = []) {
+ const rows = records
+ .map((r) => normalizeEventRecord(r))
+ .filter((r) => r.account && r.runs > 0);
+ rows.sort((a, b) =>
+ b.runs - a.runs
+ || b.cash - a.cash
+ || a.lastAt - b.lastAt
+ || a.account.localeCompare(b.account));
+ rows.forEach((row, i) => { row.rank = i + 1; });
+ return rows;
+}
+
+// One row shaped for the wire: the account id itself never leaves the server (it is
+// a wallet address or a guest key), only its rank, display name and score.
+function publicRow(row) {
+ return {
+ rank: row.rank,
+ name: row.name || 'Anonymous',
+ runs: row.runs,
+ cash: row.cash,
+ lastAt: row.lastAt,
+ };
+}
+
+// The payload the in-world panel and the read endpoint both serve: the top N, the
+// requesting player's own row (pinned, whatever their rank), and the totals that let
+// a UI say "12 of 41 runners" without a second call. `account` may be omitted for an
+// anonymous read (the web page) — `you` is then null.
+export function eventBoardView(records = [], { account = '', limit = TOP_LIMIT } = {}) {
+ const ranked = rankEventBoard(records);
+ const cap = Math.max(1, Math.min(100, limit | 0 || TOP_LIMIT));
+ const mine = account ? ranked.find((r) => r.account === account) : null;
+ return {
+ top: ranked.slice(0, cap).map(publicRow),
+ you: mine ? { ...publicRow(mine), inTop: mine.rank <= cap } : null,
+ players: ranked.length,
+ totalRuns: ranked.reduce((sum, r) => sum + r.runs, 0),
+ };
+}
diff --git a/multiplayer/src/event-score.js b/multiplayer/src/event-score.js
new file mode 100644
index 000000000..0e7fa6af1
--- /dev/null
+++ b/multiplayer/src/event-score.js
@@ -0,0 +1,110 @@
+// Event leaderboard bridge — the game server's client for the event standing.
+//
+// The board is stored on the API side (api/_lib/event-leaderboard-store.js) rather
+// than in this process because a player's runs have to survive a room disposal, a
+// redeploy mid-event, and be readable by the web at the same time. This module is
+// the two calls that need: report a finished event quest, and read the ranked board
+// back for the in-world panel.
+//
+// Writes sign the same short-lived world-service token persistence.js and
+// quest-notify.js use (svc:'world'), so only this trusted process can score a run.
+// Reads are the public endpoint, cached here for READ_CACHE_MS: an event crowd all
+// opening the panel at once costs one upstream read per few seconds, not one per
+// player. The per-player row is NOT cached with the board (it is per-account), so
+// the cache key includes the account.
+//
+// Everything is best-effort and never throws: a flaky API must degrade the panel to
+// its error state, never break the mission-complete flow that already paid the
+// player in-world.
+
+import crypto from 'node:crypto';
+
+const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
+const TOKEN_TTL_SEC = 120;
+const REQUEST_TIMEOUT_MS = 8000;
+const READ_CACHE_MS = 4000;
+
+// Mirrors persistence.js's signServiceToken byte-for-byte.
+function signServiceToken() {
+ const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL_SEC;
+ const payload = Buffer.from(JSON.stringify({ svc: 'world', exp }), 'utf8').toString('base64url');
+ const sig = crypto.createHmac('sha256', secret()).update(payload).digest('base64url');
+ return `${payload}.${sig}`;
+}
+
+function secret() {
+ return (
+ process.env.MULTIPLAYER_SHARED_SECRET ||
+ process.env.HOLDER_PASS_SECRET ||
+ 'dev-insecure-multiplayer-secret'
+ );
+}
+
+/**
+ * Report one finished event quest. Returns the player's updated totals, or null if
+ * the report did not land (offline API, closed window, unconfigured secret) — the
+ * caller has already paid the player their in-world gold either way.
+ *
+ * @param {{ eventId: string, account: string, name?: string, missionId: string, gold?: number }} run
+ */
+export async function reportEventRun({ eventId, account, name = '', missionId, gold = 0 }) {
+ if (!account || !missionId) return null;
+ try {
+ const res = await fetch(`${API_BASE}/api/internal/event-score`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${signServiceToken()}`,
+ },
+ body: JSON.stringify({ eventId, account, name, missionId, gold }),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ if (!res.ok) {
+ console.warn(`[event-score] report → ${res.status}`);
+ return null;
+ }
+ const body = await res.json();
+ // A fresh run invalidates every cached view of this board.
+ _cache.clear();
+ return body;
+ } catch (err) {
+ console.warn('[event-score] failed to report event run:', err?.message || err);
+ return null;
+ }
+}
+
+const _cache = new Map(); // `${eventId}|${account}` → { at, body }
+
+/**
+ * Read the ranked board (top rows plus this account's own row). Returns the API's
+ * payload, or null when it is unreachable — the client renders its error state
+ * rather than a stale or invented ranking.
+ */
+export async function fetchEventBoard({ account = '', limit = 10 } = {}) {
+ const key = `${account}|${limit}`;
+ const hit = _cache.get(key);
+ const now = Date.now();
+ if (hit && now - hit.at < READ_CACHE_MS) return hit.body;
+ try {
+ const qs = new URLSearchParams({ limit: String(limit) });
+ if (account) qs.set('account', account);
+ const res = await fetch(`${API_BASE}/api/play/event-leaderboard?${qs}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ if (!res.ok) {
+ console.warn(`[event-score] board read → ${res.status}`);
+ return null;
+ }
+ const body = await res.json();
+ _cache.set(key, { at: now, body });
+ // Bound the cache: one entry per online player at most, cleared on any write.
+ if (_cache.size > 512) {
+ for (const [k, v] of _cache) if (now - v.at > READ_CACHE_MS) _cache.delete(k);
+ }
+ return body;
+ } catch (err) {
+ console.warn('[event-score] failed to read event board:', err?.message || err);
+ return null;
+ }
+}
diff --git a/multiplayer/src/event-window.js b/multiplayer/src/event-window.js
new file mode 100644
index 000000000..123ac02a8
--- /dev/null
+++ b/multiplayer/src/event-window.js
@@ -0,0 +1,104 @@
+// Live-event window — the server's own read of public/event.json.
+//
+// The countdown pill, the in-world meetup layer and the /play agenda all derive
+// their timing from ONE config file (public/event.json). The event quest line and
+// its leaderboard have to be gated on exactly the same window, and that gate must
+// be server-side: a client that lies about the clock still gets an empty board.
+//
+// This process ships without the repo's `public/` directory (multiplayer/Dockerfile
+// copies only src/), so the config is read over HTTP from the site that serves it
+// — the same origin persistence.js and quest-notify.js already talk to. The times
+// are never transcribed into code here: parse what the file says, or run nothing.
+//
+// Failure is CLOSED. A missing, unreachable or malformed config means "there is no
+// event", which hides the event jobs and their payouts rather than opening them on
+// a bad read. The last good config is cached for CACHE_TTL_MS so the hot path
+// (every board read, every mission accept) is a synchronous Map lookup, and a
+// refresh in flight never blocks gameplay.
+
+const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
+const CONFIG_PATH = '/event.json';
+const CACHE_TTL_MS = 60_000; // re-read the config at most once a minute
+const FETCH_TIMEOUT_MS = 6000;
+
+// Parse the event config into the minimal window this server cares about. Mirrors
+// the client's parseEvent (src/game/meetup-schedule.js) on the fields that matter
+// for gating: same id, same start, same "missing end = 6h" default. Returns null
+// for anything unusable, so callers treat "no event" and "bad config" identically.
+export function parseEventWindow(doc) {
+ if (!doc || typeof doc !== 'object') return null;
+ const startsAt = Date.parse(doc.startsAt);
+ if (!Number.isFinite(startsAt)) return null;
+ const rawEnd = Date.parse(doc.endsAt);
+ const endsAt = Number.isFinite(rawEnd) && rawEnd > startsAt ? rawEnd : startsAt + 6 * 3600 * 1000;
+ return {
+ id: String(doc.id || 'event').slice(0, 64),
+ name: String(doc.name || 'Community event').slice(0, 120),
+ startsAt,
+ endsAt,
+ };
+}
+
+// Is `now` inside the event's live window? Half-open [startsAt, endsAt) so the
+// final millisecond can't pay out twice under a clock that lands exactly on the end.
+export function isEventLive(win, now = Date.now()) {
+ if (!win) return false;
+ const t = Number(now);
+ if (!Number.isFinite(t)) return false;
+ return t >= win.startsAt && t < win.endsAt;
+}
+
+let _cached = null; // the last successfully parsed window (may be a past event)
+let _fetchedAt = 0; // when the config was last read (ok or not)
+let _inFlight = null; // dedupe concurrent refreshes across rooms
+
+async function readConfig() {
+ const res = await fetch(`${API_BASE}${CONFIG_PATH}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+}
+
+// Refresh the cached window if it's stale. Never throws and never rejects: a failed
+// read leaves the previous cache in place (and leaves it null on a cold start, which
+// is the closed gate). Call from the room's periodic tick or await it when you want
+// the freshest answer.
+export async function refreshEventWindow(now = Date.now()) {
+ if (_inFlight) return _inFlight;
+ if (_cached !== null && now - _fetchedAt < CACHE_TTL_MS) return _cached;
+ _inFlight = readConfig()
+ .then((doc) => {
+ _cached = parseEventWindow(doc);
+ _fetchedAt = Date.now();
+ return _cached;
+ })
+ .catch((err) => {
+ _fetchedAt = Date.now();
+ console.warn(`[event-window] ${API_BASE}${CONFIG_PATH} unreadable: ${err?.message || err}`);
+ return _cached;
+ })
+ .finally(() => { _inFlight = null; });
+ return _inFlight;
+}
+
+// The cached window, synchronously. Kicks off a background refresh when stale so the
+// caller never waits on the network mid-gameplay; the answer it gets is at most
+// CACHE_TTL_MS old, which is far finer than an event window measured in hours.
+export function eventWindow(now = Date.now()) {
+ if (now - _fetchedAt >= CACHE_TTL_MS) refreshEventWindow(now).catch(() => {});
+ return _cached;
+}
+
+// The one question the quest engine asks: is the event running right now?
+export function eventLiveNow(now = Date.now()) {
+ return isEventLive(eventWindow(now), now);
+}
+
+// Test seam: drop the cache so a suite can prime it with its own config instead of
+// hitting the network. Not used by the running server.
+export function __setEventWindowCache(win, fetchedAt = Date.now()) {
+ _cached = win;
+ _fetchedAt = fetchedAt;
+}
diff --git a/multiplayer/src/quest-zones.js b/multiplayer/src/quest-zones.js
index 508f5bf92..60027d9a0 100644
--- a/multiplayer/src/quest-zones.js
+++ b/multiplayer/src/quest-zones.js
@@ -35,6 +35,16 @@ export const QUEST_ZONES = [
{ id: 'depot-east', kind: 'goto', x: 90, z: 6, r: 8, label: 'East Depot', glyph: '🚚' },
{ id: 'depot-west', kind: 'goto', x: -90, z: -6, r: 8, label: 'West Depot', glyph: '🚚' },
+ // Event landmarks (the Meetup Grand Tour). Deliberately sited ON the three
+ // places the event agenda already sends people — the totem the showdown is
+ // held at, the Fortune's Folly wheel (world-features.WHEEL) and the trading
+ // screen — so the tour walks the party route instead of inventing empty
+ // waypoints. Generous radii: these are crowded during the event and a marker
+ // you have to thread a crowd to hit is a bad objective.
+ { id: 'event-totem', kind: 'goto', x: 0, z: -12, r: 6, label: 'The Totem', glyph: '🎉' },
+ { id: 'event-wheel', kind: 'goto', x: 0, z: 22, r: 5, label: 'Fortune’s Folly', glyph: '🎡' },
+ { id: 'event-screen', kind: 'goto', x: 0, z: -30, r: 6, label: 'The Trading Screen', glyph: '📈' },
+
// Vault heist district: two alarm terminals flanking the vault door.
{ id: 'vault-terminal-a', kind: 'interact', action: 'terminal', x: 50, z: 16, r: 2.8, label: 'Alarm Terminal A', glyph: '🖥️' },
{ id: 'vault-terminal-b', kind: 'interact', action: 'terminal', x: 50, z: -16, r: 2.8, label: 'Alarm Terminal B', glyph: '🖥️' },
diff --git a/multiplayer/src/quests.js b/multiplayer/src/quests.js
index f15211a8b..b4e602fed 100644
--- a/multiplayer/src/quests.js
+++ b/multiplayer/src/quests.js
@@ -18,8 +18,15 @@
// collect — gather N of an item (emitted by the fishing handler)
// goto — enter a named world zone (emitted by movement zone-entry)
// interact — act at a quest object/zone (emitted by the questInteract handler)
+// defeat — kill N foes in the wilds (emitted by the combat handler on a kill)
// Heists compose these as a SHARED instance (see WalkRoom): the same objective shape,
// advanced by any crew member, finishing only when the party is assembled at the finale.
+//
+// A mission flagged `event: true` only exists inside the live window of the platform
+// event (public/event.json, read server-side by event-window.js). The gate is applied
+// HERE — in the offer/accept/prune rules every caller already goes through — so no
+// surface can accidentally serve an event job out of window: outside it, the job is
+// not on the board, cannot be accepted, and any stale run is dropped unpaid.
import { SKILLS } from './economy.js';
@@ -190,8 +197,89 @@ export const MISSIONS = {
// 900 gold total, split among the crew (e.g. 450 each for a duo).
reward: { gold: 900, xp: { skill: 'combat', amount: 200 } },
},
+
+ // — Event quest line —————————————————————————————————————————————————————
+ // Four jobs that only exist while the platform event is live, one per thing the
+ // world already does well: gather, drive, fight, tour. All repeatable, because
+ // the event leaderboard ranks players by how many of these they finish inside
+ // the window — a closed-ended set would decide the ranking in the first ten
+ // minutes. Payouts are richer than the everyday board (it's a two-hour window,
+ // not an all-day grind) but still ordinary in-world gold: the leaderboard's
+ // prizes are settled by the owner after the event, never paid on-chain by code.
+ 'event-plaza-catch': {
+ id: 'event-plaza-catch',
+ title: 'Meetup Fish Fry',
+ giver: 'Cook Mara',
+ summary: 'The plaza pit is feeding the whole meetup — land 8 fish before the doors close.',
+ kind: 'job',
+ repeat: 'repeatable',
+ party: 1,
+ event: true,
+ objectives: [
+ { type: 'collect', item: 'fish', count: 8, label: '🎉 Catch 8 fish for the meetup' },
+ ],
+ reward: { gold: 320, xp: { skill: 'fishing', amount: 260 } },
+ },
+ 'event-supply-run': {
+ id: 'event-supply-run',
+ title: 'Meetup Supply Run',
+ giver: 'Dispatcher Vance',
+ summary: 'Drive the party supplies from the North Depot across to the East Depot.',
+ kind: 'job',
+ repeat: 'repeatable',
+ party: 1,
+ event: true,
+ objectives: [
+ { type: 'goto', zone: 'depot-north', vehicle: true, label: '🎉 🚗 Load the party supplies at the North Depot' },
+ { type: 'goto', zone: 'depot-east', vehicle: true, label: '🎉 🚗 Run them out to the East Depot' },
+ ],
+ reward: { gold: 300 },
+ },
+ 'event-wilds-patrol': {
+ id: 'event-wilds-patrol',
+ title: 'Southern Wilds Patrol',
+ giver: 'Warden Okoro',
+ summary: 'Something is stirring south of town. Put down 4 foes in the Southern Wilds.',
+ kind: 'job',
+ repeat: 'repeatable',
+ party: 1,
+ event: true,
+ objectives: [
+ {
+ type: 'defeat', target: 'mob', count: 4, dangerZone: 'southern-wilds',
+ label: '🎉 ⚔️ Defeat 4 foes in the Southern Wilds',
+ },
+ ],
+ reward: { gold: 340, xp: { skill: 'combat', amount: 280 } },
+ },
+ 'event-landmark-tour': {
+ id: 'event-landmark-tour',
+ title: 'Meetup Grand Tour',
+ giver: 'The Host',
+ summary: 'Show your face at all three meetup landmarks: the totem, the wheel and the big screen.',
+ kind: 'job',
+ repeat: 'repeatable',
+ party: 1,
+ event: true,
+ objectives: [
+ { type: 'goto', zone: 'event-totem', label: '🎉 Rally at the Totem' },
+ { type: 'goto', zone: 'event-wheel', label: '🎉 Swing by Fortune’s Folly' },
+ { type: 'goto', zone: 'event-screen', label: '🎉 Finish at the Trading Screen' },
+ ],
+ reward: { gold: 220 },
+ },
};
+// The event quest line, in board order — the ids the leaderboard counts and the
+// only missions the event window gates.
+export const EVENT_MISSION_IDS = Object.values(MISSIONS)
+ .filter((m) => m.event)
+ .map((m) => m.id);
+
+export function isEventMission(id) {
+ return !!MISSIONS[id]?.event;
+}
+
// The pool of mission ids eligible for the rotating daily board. A deterministic
// subset is offered each UTC day so the board feels fresh without authoring a
// calendar. Only 'daily' missions belong here.
@@ -355,10 +443,14 @@ function prereqMet(state, mission) {
}
// Is `mission` acceptable by this player right now? (Not already active, prereqs
-// met, and the repeat rule satisfied: a one-shot not yet done, a daily not yet
-// done today, a repeatable always.)
-export function canAccept(state, mission, dayKey = utcDayKey()) {
+// met, the event window open if it's an event job, and the repeat rule satisfied:
+// a one-shot not yet done, a daily not yet done today, a repeatable always.)
+// `ctx.eventLive` is the SERVER's read of the event clock (event-window.js); it
+// defaults to false so any caller that forgets it gets the closed gate, never an
+// accidentally open one.
+export function canAccept(state, mission, dayKey = utcDayKey(), ctx = {}) {
if (!mission) return false;
+ if (mission.event && !ctx.eventLive) return false;
if (state.active[mission.id]) return false;
if (!prereqMet(state, mission)) return false;
if (mission.repeat === 'once') return !(state.completed[mission.id]?.count > 0);
@@ -370,16 +462,19 @@ export function canAccept(state, mission, dayKey = utcDayKey()) {
// shaped for the client. Daily offers are the day's rotated subset; the rest are
// the always-available repeatable/one-shot jobs. Heists are surfaced too (the
// client shows a "needs a crew" hint).
-export function boardOffers(state, dayKey = utcDayKey()) {
+export function boardOffers(state, dayKey = utcDayKey(), ctx = {}) {
rolloverDaily(state, dayKey);
const dailyIds = new Set(dailyJobIds(dayKey));
const offers = [];
for (const mission of Object.values(MISSIONS)) {
if (mission.repeat === 'daily' && !dailyIds.has(mission.id)) continue; // not in today's rotation
if (state.active[mission.id]) continue; // already accepted
- if (!canAccept(state, mission, dayKey)) continue;
+ if (!canAccept(state, mission, dayKey, ctx)) continue;
offers.push(offerView(mission, state));
}
+ // Event jobs lead the board while the window is open — they expire with it, the
+ // everyday work does not.
+ offers.sort((a, b) => (b.event ? 1 : 0) - (a.event ? 1 : 0));
return offers;
}
@@ -392,22 +487,39 @@ function offerView(mission, state) {
kind: mission.kind,
repeat: mission.repeat,
party: mission.party || 1,
+ event: !!mission.event,
reward: { ...mission.reward },
objectives: mission.objectives.map((o) => ({ type: o.type, label: o.label, count: objCount(o) })),
completedCount: state.completed[mission.id]?.count | 0,
};
}
+// Drop any active event run once the window has closed. An event job can neither
+// advance nor pay outside its window, so leaving it in the log would be a tracker
+// entry that quietly never completes. Returns the mission ids that were dropped so
+// the room can tell the player why their tracker emptied.
+export function pruneClosedEventRuns(state, ctx = {}) {
+ if (ctx.eventLive) return [];
+ const dropped = [];
+ for (const id of Object.keys(state.active || {})) {
+ if (!MISSIONS[id]?.event) continue;
+ delete state.active[id];
+ dropped.push(id);
+ }
+ return dropped;
+}
+
// ---------------------------------------------------------------------------
// Accept / abandon
// ---------------------------------------------------------------------------
-export function acceptMission(state, id, dayKey = utcDayKey()) {
+export function acceptMission(state, id, dayKey = utcDayKey(), ctx = {}) {
const mission = MISSIONS[id];
if (!mission) return { ok: false, reason: 'unknown' };
rolloverDaily(state, dayKey);
if (state.active[id]) return { ok: false, reason: 'active' };
- if (!canAccept(state, mission, dayKey)) {
+ if (mission.event && !ctx.eventLive) return { ok: false, reason: 'event-closed' };
+ if (!canAccept(state, mission, dayKey, ctx)) {
const reason = mission.repeat === 'daily' ? 'daily-done'
: mission.repeat === 'once' ? 'done'
: 'locked';
@@ -432,6 +544,7 @@ export function abandonMission(state, id) {
// collect: { type:'collect', item, qty }
// goto: { type:'enter-zone', zone }
// interact: { type:'interact', zone, action }
+// defeat: { type:'defeat', target:'mob'|'player', zone } zone = DANGER_ZONES id
// `event.qty` (collect) defaults to 1.
export function objectiveMatches(obj, event) {
if (!obj || !event) return false;
@@ -454,6 +567,15 @@ export function objectiveMatches(obj, event) {
if (Array.isArray(obj.zones)) return obj.zones.includes(event.zone);
return !obj.zone || event.zone === obj.zone;
}
+ if (obj.type === 'defeat') {
+ if (event.type !== 'defeat') return false;
+ // `target` narrows to PvE mobs vs. players; `dangerZone` pins the kill to one
+ // named wilderness (world-features.DANGER_ZONES), judged from the SERVER's
+ // position for the kill, so farming a different zone never counts.
+ if (obj.target && event.target !== obj.target) return false;
+ if (obj.dangerZone && event.zone !== obj.dangerZone) return false;
+ return true;
+ }
return false;
}
@@ -554,6 +676,7 @@ export function runView(run, mission) {
giver: mission.giver,
kind: mission.kind,
party: mission.party || 1,
+ event: !!mission.event,
reward: { ...mission.reward },
stage: run.stage,
objectives,
@@ -563,15 +686,16 @@ export function runView(run, mission) {
// The full quest payload sent to a client (board offers + active runs). Heist runs
// are layered on by the room (shared-instance progress), so this covers solo runs;
// the room merges any live heist run before sending.
-export function questSnapshot(state, dayKey = utcDayKey()) {
+export function questSnapshot(state, dayKey = utcDayKey(), ctx = {}) {
const active = [];
for (const [id, run] of Object.entries(state.active)) {
const mission = MISSIONS[id];
if (mission) active.push(runView(run, mission));
}
return {
- offers: boardOffers(state, dayKey),
+ offers: boardOffers(state, dayKey, ctx),
active,
day: dayKey,
+ eventLive: !!ctx.eventLive,
};
}
diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.js
index e7859c2e4..74c09be64 100644
--- a/multiplayer/src/world-features.js
+++ b/multiplayer/src/world-features.js
@@ -124,6 +124,33 @@ export const WHEEL_REACH = 3.0;
export function nearestWheel(x, z) { return nearestNode(x, z, WHEEL, WHEEL_REACH); }
export function wheelInRange(x, z) { return nodeInRange(x, z, WHEEL, WHEEL_REACH); }
+// The Plaza Stage — the Living Stages venue standing in every coin world's plaza
+// (F17). `r` is the footprint of the built structure (platform + backdrop), which
+// is what the client renders and what WalkRoom protects from being buried or
+// walled in (its protected discs are derived from this point, so the landmark and
+// the grief guard can never drift apart).
+//
+// Sited in the north-east plaza: a short walk from the wheel at (0,22) and clear
+// of every other feature — the east pond (~22 m), the east firepit (~14 m), the
+// plaza rod pickup (~15 m) — and well outside all three danger zones, so the
+// crowd that gathers for a show is standing in safe town.
+export const PLAZA_STAGE = { id: 'plaza-stage', x: 18, z: 26, r: 5 };
+
+// How far beyond the structure a player counts as ATTENDING the show: this is the
+// radius that joins (and leaves) the stage room, and it must comfortably contain
+// the seat ring StageRoom deals out (golden-angle seats at 6.0/7.6/9.2 m from the
+// stage origin), so a seated attendee is never standing outside their own show.
+export const STAGE_ATTEND_REACH = 8; // ⇒ 13 m from the stage centre
+
+// How far away the marquee is still legible. Walking inside this ring is what
+// first wakes the stage up (one show-state read); everything heavier waits for
+// STAGE_ATTEND_REACH.
+export const STAGE_MARQUEE_REACH = 21; // ⇒ 26 m from the stage centre
+
+export function nearestStage(x, z) { return nearestNode(x, z, [PLAZA_STAGE], STAGE_ATTEND_REACH); }
+export function stageInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAGE], STAGE_ATTEND_REACH); }
+export function stageMarqueeInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAGE], STAGE_MARQUEE_REACH); }
+
// Fishing-rod pickups — a spare rod waiting on the bank for anyone without one
// (or anyone who wants a backup to store). Every player already starts with a
// rod in the hotbar and it's never lost on death, so these exist for