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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(play): serve the holder pass expiry from the signer instead of a second hardcoded copy
nirholas45c5cfff865c
diff --git a/api/_lib/play-pass.js b/api/_lib/play-pass.jsindex 76810ee5b..cfa5dbb1e 100644--- a/api/_lib/play-pass.js+++ b/api/_lib/play-pass.js@@ -42,7 +42,14 @@ const NONCE_TTL_S = 5 * 60;// Lifetime of a minted pass — long enough to finish loading into the world after// the check, short enough that a wallet that offloads its tokens can't ride an// old pass for long. The game server re-checks balance on a cadence too.-const PASS_TTL_S = 10 * 60;+//+// Exported because /verify and /refresh put this lifetime ON THE WIRE as+// `expiresAt`, and the browser schedules its silent renewal off that value+// (src/game/play-auth.js loadStoredPass/refreshPlayPass). A second copy of the+// number in those handlers would mean shortening the TTL here quietly leaves+// every client holding a pass it believes is fresh and the game server has+// already rejected, so both read it from here.+export const PASS_TTL_S = 10 * 60;const DEV_SECRET = 'three-ws-holder-pass-dev-secret';diff --git a/api/play/economy.js b/api/play/economy.jsindex 5c24d384e..fdbe0a420 100644--- a/api/play/economy.js+++ b/api/play/economy.js@@ -60,10 +60,13 @@ function summarizePaytable(segments) {}// Cash prizes read as the headline outcomes, so surface them first, richest first.// Item prizes then sort by quantity so the table climbs rather than jumping around.+ // `item` is null for any wedge that awards no item, and the comparator has to hold+ // for a future wedge kind that has none (a blank, an XP grant), so it orders on the+ // coalesced string rather than dereferencing a field this same function nulls.return [...rows.values()].sort((a, b) => {if (a.kind !== b.kind) return a.kind === 'gold' ? -1 : 1;if (a.kind === 'gold') return b.gold - a.gold;- if (a.item !== b.item) return a.item.localeCompare(b.item);+ if (a.item !== b.item) return String(a.item || '').localeCompare(String(b.item || ''));return a.qty - b.qty;});}diff --git a/api/play/refresh.js b/api/play/refresh.jsindex 522111d89..66d9f4277 100644--- a/api/play/refresh.js+++ b/api/play/refresh.js@@ -20,7 +20,7 @@ import { z } from 'zod';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { getBalances } from '../_lib/balances.js';-import { verifyPlayPass, signPlayPass, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';+import { verifyPlayPass, signPlayPass, PASS_TTL_S, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -75,8 +75,12 @@ export default wrap(async (req, res) => {// fresh pass; one that dropped below gets an honest, actionable refusal.if (balance >= minBalance) {const playPass = signPlayPass({ wallet: address, mint: PLAY_GATE_MINT, balance });+ // Same lifetime the signer sealed into the pass. The renewal loop reschedules+ // itself off this value, so restating the number here is how a shortened TTL+ // would turn into silent mid-session kicks.+ const expiresAt = new Date(Date.now() + PASS_TTL_S * 1000).toISOString();return json(res, 200, {- data: { ok: true, wallet: address, balance, mint: PLAY_GATE_MINT, symbol, decimals, playPass, expiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString() },+ data: { ok: true, wallet: address, balance, mint: PLAY_GATE_MINT, symbol, decimals, playPass, expiresAt },});}diff --git a/api/play/verify.js b/api/play/verify.jsindex dcf84831d..db76e6968 100644--- a/api/play/verify.js+++ b/api/play/verify.js@@ -25,7 +25,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { clientIp, limits } from '../_lib/rate-limit.js';import { getBalances } from '../_lib/balances.js';import { cacheGet, cacheSet } from '../_lib/cache.js';-import { verifyNonce, signPlayPass, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';+import { verifyNonce, signPlayPass, PASS_TTL_S, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';const bs58 = bs58mod.default || bs58mod;const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -126,8 +126,13 @@ export default wrap(async (req, res) => {// to acquire the token; clear of it → a signed pass the game server trusts.if (balance >= minBalance) {const playPass = signPlayPass({ wallet: address, mint: PLAY_GATE_MINT, balance });+ // Read the lifetime off the signer rather than restating it: the browser+ // schedules its silent renewal from this `expiresAt`, so a second copy of+ // the number here would drift the client's idea of freshness away from the+ // pass the game server actually honours.+ const expiresAt = new Date(Date.now() + PASS_TTL_S * 1000).toISOString();return json(res, 200, {- data: { ok: true, wallet: address, balance, mint: PLAY_GATE_MINT, symbol, decimals, playPass, expiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString() },+ data: { ok: true, wallet: address, balance, mint: PLAY_GATE_MINT, symbol, decimals, playPass, expiresAt },});}// Acquire URL: for the native SOL mint, a DEX swap (SOL→SOL) is nonsensical —diff --git a/tests/api/play-population.test.js b/tests/api/play-population.test.jsnew file mode 100644index 000000000..a49e11a6c--- /dev/null+++ b/tests/api/play-population.test.js@@ -0,0 +1,235 @@+// Unit tests for GET /api/play/population, the same-origin proxy in front of the+// multiplayer server's own /population aggregate.+//+// The contract this handler exists to keep is narrow and easy to break silently:+//+// 1. It NEVER invents a number. A missing upstream, an unreachable upstream, a+// slow upstream and an upstream that answers `ok:false` all resolve to the+// same honest `{ ok: false, reason: 'unavailable' }` at 200, because the+// /event landing page renders its LIVE panel off this call and a landing page+// must neither break nor make a population up.+// 2. It forwards NOTHING but a count. Session ids, names, wallets and positions+// exist on the other side of this boundary and must not cross it.+// 3. The `coin` filter is constrained before it is forwarded, since the value+// lands in another service's query string.+//+// `fetch` is stubbed per test to stand in for the upstream. That is the seam the+// handler owns; the upstream's own /population route is covered separately in+// tests/multiplayer-server-boot.test.js, so nothing here restates its behaviour.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const rlState = { success: true, limit: 60, remaining: 59, reset: 0 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => rlState) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const envState = { MULTIPLAYER_INTERNAL_URL: 'http://mp.internal:2567' };+vi.mock('../../api/_lib/env.js', () => ({+ env: {+ get MULTIPLAYER_INTERNAL_URL() {+ return envState.MULTIPLAYER_INTERNAL_URL;+ },+ },+}));++const handler = (await import('../../api/play/population.js')).default;++const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function mockRes() {+ const chunks = [];+ return {+ statusCode: 0,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ writeHead(status, headers) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers || {})) this.setHeader(k, v);+ return this;+ },+ end(body) { if (body) chunks.push(body); return this; },+ get parsed() { return JSON.parse(chunks.join('')); },+ };+}++const mockReq = (url = '/api/play/population', method = 'GET') => ({+ method,+ url,+ headers: { host: 'three.ws' },+ socket: { remoteAddress: '127.0.0.1' },+});++async function get(url) {+ const res = mockRes();+ await handler(mockReq(url), res);+ return res;+}++/** Stand in for the upstream, and record the URL it was called with. */+function upstream(reply) {+ const calls = [];+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {+ calls.push(String(url));+ return reply();+ });+ return calls;+}++const jsonReply = (body, ok = true, status = 200) => () =>+ ({ ok, status, json: async () => body });++beforeEach(() => {+ rlState.success = true;+ envState.MULTIPLAYER_INTERNAL_URL = 'http://mp.internal:2567';+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('GET /api/play/population: the live count', () => {+ it('serves the upstream count and caches it no longer than the source does', async () => {+ upstream(jsonReply({ ok: true, players: 7, rooms: 2 }));+ const res = await get('/api/play/population');+ expect(res.statusCode).toBe(200);+ expect(res.parsed).toEqual({ ok: true, coin: null, players: 7, rooms: 2 });+ // The multiplayer server caches its own aggregate for 5s; anything longer+ // here would serve a number staler than its source.+ expect(res.headers['cache-control']).toBe('public, max-age=5, s-maxage=5');+ });++ it('forwards a well-formed coin filter and echoes it back', async () => {+ const calls = upstream(jsonReply({ ok: true, players: 3, rooms: 1 }));+ const res = await get(`/api/play/population?coin=${MINT}`);+ expect(res.parsed).toEqual({ ok: true, coin: MINT, players: 3, rooms: 1 });+ expect(calls).toHaveLength(1);+ expect(new URL(calls[0]).searchParams.get('coin')).toBe(MINT);+ });++ it('accepts an EVM coin world as well as a Solana mint', async () => {+ const evm = '0x1234567890abcdef1234567890abcdef12345678';+ const calls = upstream(jsonReply({ ok: true, players: 1, rooms: 1 }));+ const res = await get(`/api/play/population?coin=${evm}`);+ expect(res.parsed.coin).toBe(evm);+ expect(new URL(calls[0]).searchParams.get('coin')).toBe(evm);+ });++ it('drops a coin value that is not an address instead of forwarding it', async () => {+ const calls = upstream(jsonReply({ ok: true, players: 4, rooms: 1 }));+ const res = await get('/api/play/population?coin=../../etc/passwd');+ expect(res.parsed.coin).toBeNull();+ expect(new URL(calls[0]).searchParams.has('coin')).toBe(false);+ });++ it('never forwards anything but a count', async () => {+ upstream(jsonReply({+ ok: true,+ players: 2,+ rooms: 1,+ sessions: ['s1', 's2'],+ names: ['alice', 'bob'],+ wallets: [MINT],+ positions: [{ x: 1, z: 2 }],+ }));+ const res = await get('/api/play/population');+ expect(Object.keys(res.parsed).sort()).toEqual(['coin', 'ok', 'players', 'rooms']);+ });++ it('floors negative or fractional upstream counts to a sane integer', async () => {+ upstream(jsonReply({ ok: true, players: -5, rooms: 2.7 }));+ const res = await get('/api/play/population');+ expect(res.parsed).toMatchObject({ players: 0, rooms: 2 });+ });+});++describe('GET /api/play/population: degrading without inventing a number', () => {+ it('answers unavailable, not an error, when no upstream is configured', async () => {+ envState.MULTIPLAYER_INTERNAL_URL = '';+ const fetchSpy = vi.spyOn(globalThis, 'fetch');+ const res = await get(`/api/play/population?coin=${MINT}`);+ expect(res.statusCode).toBe(200);+ expect(res.parsed).toEqual({ ok: false, reason: 'unavailable', coin: MINT });+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('answers unavailable when the upstream connection fails', async () => {+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'));+ const res = await get('/api/play/population');+ expect(res.statusCode).toBe(200);+ expect(res.parsed).toEqual({ ok: false, reason: 'unavailable', coin: null });+ });++ it('answers unavailable on an upstream 5xx', async () => {+ upstream(jsonReply({ error: 'boom' }, false, 502));+ const res = await get('/api/play/population');+ expect(res.parsed).toEqual({ ok: false, reason: 'unavailable', coin: null });+ });++ it('answers unavailable when the upstream body is not an ok aggregate', async () => {+ upstream(jsonReply({ ok: false }));+ const res = await get('/api/play/population');+ expect(res.parsed).toEqual({ ok: false, reason: 'unavailable', coin: null });+ });++ it('answers unavailable when the upstream body is not JSON at all', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => { throw new SyntaxError('Unexpected token <'); },+ });+ const res = await get('/api/play/population');+ expect(res.parsed).toEqual({ ok: false, reason: 'unavailable', coin: null });+ });++ it('does not cache an unavailable answer, so the next request retries', async () => {+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('down'));+ const res = await get('/api/play/population');+ expect(res.headers['cache-control']).not.toMatch(/max-age=[1-9]/);+ });++ it('aborts a hanging upstream rather than holding the request open', async () => {+ vi.spyOn(globalThis, 'fetch').mockImplementation((_url, opts) =>+ new Promise((_resolve, reject) => {+ opts.signal.addEventListener('abort', () => reject(new Error('aborted')));+ }));+ vi.useFakeTimers();+ try {+ const res = mockRes();+ const pending = handler(mockReq('/api/play/population'), res);+ await vi.advanceTimersByTimeAsync(3000);+ await pending;+ expect(res.parsed).toEqual({ ok: false, reason: 'unavailable', coin: null });+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('GET /api/play/population: HTTP posture', () => {+ it('is a public GET-only endpoint', async () => {+ const res = mockRes();+ await handler(mockReq('/api/play/population', 'POST'), res);+ expect(res.statusCode).toBe(405);+ expect(res.parsed.error).toBe('method_not_allowed');+ });++ it('answers a preflight without running the proxy', async () => {+ const fetchSpy = vi.spyOn(globalThis, 'fetch');+ const res = mockRes();+ await handler({ ...mockReq(), method: 'OPTIONS', headers: { host: 'three.ws', origin: 'https://three.ws' } }, res);+ expect(res.statusCode).toBe(204);+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('refuses a rate-limited caller before touching the upstream', async () => {+ rlState.success = false;+ const fetchSpy = vi.spyOn(globalThis, 'fetch');+ const res = await get('/api/play/population');+ expect(res.statusCode).toBe(429);+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/play-refresh.test.js b/tests/api/play-refresh.test.jsnew file mode 100644index 000000000..6b8ab094c--- /dev/null+++ b/tests/api/play-refresh.test.js@@ -0,0 +1,274 @@+// Unit tests for POST /api/play/refresh, the silent mid-session renewal of a+// wallet's /play credential.+//+// Refresh is the one endpoint that mints a play pass without a wallet signature,+// so the properties worth pinning down are the ones that keep that safe:+//+// 1. Only a pass WE signed, still unexpired, and issued for THIS gate's token+// can be renewed. A forged, expired, or foreign-mint pass falls back to a+// full sign-in (401) rather than being trusted.+// 2. The wallet is never taken from the request body. It comes out of the+// sealed pass, so a caller cannot renew into a different wallet.+// 3. The balance floor is re-read on-chain every renewal, so a wallet that+// offloaded its tokens loses the pass instead of riding it.+// 4. The `expiresAt` on the wire matches the lifetime actually sealed into the+// pass. The browser schedules its next renewal off that value, so a drift+// between the two shows up as silent mid-session kicks.+//+// balances.js is stubbed because the chain read is not this handler's logic and is+// already exercised against real RPC in tests/play-gate.test.js. Everything else+// here (pass signing, HMAC verification, expiry) runs the real module.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++process.env.NODE_ENV = 'development';+process.env.HOLDER_PASS_SECRET = 'play-refresh-test-secret';+process.env.PLAY_GATE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+process.env.PLAY_GATE_MIN = '1';++const balanceState = { result: null, error: null };+vi.mock('../../api/_lib/balances.js', () => ({+ getBalances: vi.fn(async () => {+ if (balanceState.error) throw balanceState.error;+ return balanceState.result;+ }),+}));++const rlState = { success: true, limit: 60, remaining: 59, reset: 0 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { authedReadIp: vi.fn(async () => rlState) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const handler = (await import('../../api/play/refresh.js')).default;+const { signPlayPass, verifyPlayPass, PASS_TTL_S } = await import('../../api/_lib/play-pass.js');+const { getBalances } = await import('../../api/_lib/balances.js');++const MINT = process.env.PLAY_GATE_MINT;+const SOL_MINT = 'So11111111111111111111111111111111111111112';+const WALLET = 'THREEsynthetic1111111111111111111111111111';++function mockRes() {+ const r = {+ statusCode: 200, _headers: {}, _body: '',+ setHeader(k, v) { this._headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this._headers[String(k).toLowerCase()]; },+ writeHead(status, headers) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers || {})) this.setHeader(k, v);+ return this;+ },+ end(b) { this._body = b || ''; return this; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+ return r;+}++function mockReq({ method = 'POST', body = null, origin = 'https://three.ws' } = {}) {+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];+ const r = Readable.from(chunks);+ r.method = method;+ r.url = '/api/play/refresh';+ r.headers = { origin, host: 'three.ws', 'content-type': 'application/json' };+ r.socket = { remoteAddress: '127.0.0.1' };+ return r;+}++async function post(body) {+ const res = mockRes();+ await handler(mockReq({ body }), res);+ return res;+}++/** A solana balance payload holding `amount` of the gate token. */+function holding(amount) {+ return {+ chain: 'solana',+ address: WALLET,+ native: { symbol: 'SOL', amount: 0.5, decimals: 9 },+ tokens: [{ mint: MINT, symbol: 'three', amount, decimals: 6 }],+ };+}++beforeEach(() => {+ rlState.success = true;+ balanceState.error = null;+ balanceState.result = holding(25);+ vi.mocked(getBalances).mockClear();+});++describe('POST /api/play/refresh: what may be renewed', () => {+ it('renews a valid pass and re-reads the wallet it sealed, not one from the body', async () => {+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass, wallet: 'someOtherWalletEntirely' });+ expect(res.statusCode).toBe(200);+ const d = res.json.data;+ expect(d.ok).toBe(true);+ expect(d.wallet).toBe(WALLET);+ expect(getBalances).toHaveBeenCalledWith({ chain: 'solana', address: WALLET });+ });++ it('issues a genuinely new pass rather than echoing the old one back', async () => {+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 3 });+ const res = await post({ playPass: pass });+ const fresh = res.json.data.playPass;+ expect(typeof fresh).toBe('string');+ const opened = verifyPlayPass(fresh);+ expect(opened).toBeTruthy();+ expect(opened.wallet).toBe(WALLET);+ expect(opened.mint).toBe(MINT);+ // The renewed pass carries the balance just read on-chain, not the stale one+ // the presented pass was sealed with.+ expect(opened.balance).toBe(25);+ });++ it('advertises exactly the lifetime it sealed into the pass', async () => {+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ const d = res.json.data;+ const sealedExp = verifyPlayPass(d.playPass).exp * 1000;+ const advertised = new Date(d.expiresAt).getTime();+ // One source of truth for the TTL: the wire value and the sealed expiry must+ // agree to within the clock tick between signing and serialising.+ expect(Math.abs(advertised - sealedExp)).toBeLessThan(2000);+ expect(Math.round((advertised - Date.now()) / 1000)).toBeCloseTo(PASS_TTL_S, -1);+ });++ it('refuses a forged pass so the client falls back to a full sign-in', async () => {+ const res = await post({ playPass: 'eyJrIjoicGxheS1wYXNzIn0.deadbeefdeadbeefdeadbeef' });+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('pass_invalid');+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('refuses a pass whose signature was tampered with', async () => {+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const [body] = pass.split('.');+ const res = await post({ playPass: `${body}.${'A'.repeat(43)}` });+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('pass_invalid');+ });++ it('refuses a pass minted for a different gate token', async () => {+ const pass = signPlayPass({ wallet: WALLET, mint: SOL_MINT, balance: 999 });+ const res = await post({ playPass: pass });+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('pass_invalid');+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('refuses an expired pass', async () => {+ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now - (PASS_TTL_S + 60) * 1000);+ const stale = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ vi.mocked(Date.now).mockRestore();+ const res = await post({ playPass: stale });+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('pass_invalid');+ });+});++describe('POST /api/play/refresh: the balance floor', () => {+ it('refuses renewal when the wallet has dropped below the floor', async () => {+ balanceState.result = holding(0.25);+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ // A 200 with an honest refusal, not an error: the client renders "top up",+ // it does not retry a failed request.+ expect(res.statusCode).toBe(200);+ const d = res.json.data;+ expect(d.ok).toBe(false);+ expect(d.reason).toBe('balance_too_low');+ expect(d.balance).toBe(0.25);+ expect(d.minBalance).toBe(1);+ expect(d.playPass).toBeUndefined();+ expect(d.acquireUrl).toContain(MINT);+ });++ it('treats a wallet that holds none of the token as zero, not as an error', async () => {+ balanceState.result = { chain: 'solana', address: WALLET, native: { symbol: 'SOL', amount: 2 }, tokens: [] };+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ expect(res.json.data).toMatchObject({ ok: false, reason: 'balance_too_low', balance: 0 });+ });++ it('surfaces an RPC outage as a 502 rather than renewing on a missing read', async () => {+ balanceState.error = new Error('rpc unreachable');+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ expect(res.statusCode).toBe(502);+ expect(res.json.error).toBe('balance_unavailable');+ });++ it('passes a 503 from the balance layer through unchanged', async () => {+ balanceState.error = Object.assign(new Error('all providers in cooldown'), { status: 503 });+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ expect(res.statusCode).toBe(503);+ expect(res.json.error).toBe('balance_unavailable');+ });+});++describe('POST /api/play/refresh: HTTP posture', () => {+ it('rejects a body with no pass', async () => {+ const res = await post({});+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('validation_error');+ });++ it('rejects a pass too short to be one we issued', async () => {+ const res = await post({ playPass: 'short' });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('validation_error');+ });++ it('rejects a non-POST request', async () => {+ const res = mockRes();+ await handler(mockReq({ method: 'GET' }), res);+ expect(res.statusCode).toBe(405);+ });++ it('never lets a credential response be cached', async () => {+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ it('answers a credentialed preflight without doing any work', async () => {+ const res = mockRes();+ await handler(mockReq({ method: 'OPTIONS' }), res);+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-credentials')).toBe('true');+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('refuses a rate-limited caller before verifying anything', async () => {+ rlState.success = false;+ const pass = signPlayPass({ wallet: WALLET, mint: MINT, balance: 25 });+ const res = await post({ playPass: pass });+ expect(res.statusCode).toBe(429);+ expect(getBalances).not.toHaveBeenCalled();+ });+});++describe('POST /api/play/refresh: with no game token pinned', () => {+ it('tells the client the gate is off instead of minting a pass', async () => {+ // PLAY_GATE_MINT is read once at module load, so an unpinned gate needs a+ // fresh module graph rather than a mutated env var.+ vi.resetModules();+ const saved = process.env.PLAY_GATE_MINT;+ delete process.env.PLAY_GATE_MINT;+ delete process.env.THREE_MINT;+ try {+ const gateless = (await import('../../api/play/refresh.js')).default;+ const res = mockRes();+ await gateless(mockReq({ body: { playPass: 'a'.repeat(40) } }), res);+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('gate_disabled');+ } finally {+ process.env.PLAY_GATE_MINT = saved;+ vi.resetModules();+ }+ });+});diff --git a/tests/play-gate.test.js b/tests/play-gate.test.jsindex 33f78754d..1d0d9a9e7 100644--- a/tests/play-gate.test.js+++ b/tests/play-gate.test.js@@ -4,7 +4,7 @@// GET /api/play/nonce — gate config + fresh nonce// POST /api/play/verify — ed25519 sig check, balance gate, pass issuance-import { describe, it, expect, beforeAll } from 'vitest';+import { describe, it, expect, beforeAll, vi } from 'vitest';import { Readable } from 'node:stream';import { ed25519 } from '@noble/curves/ed25519.js';import bs58mod from 'bs58';@@ -189,11 +189,39 @@ describe('POST /api/play/verify', () => {});it('returns 400 gate_disabled when no mint is configured', async () => {- // This test must run in a separate Node process to get a fresh module- // environment — env is read at module load time. We simulate via a worker.- // Instead, directly test the error path is present in source (the unit test- // for this lives in play-pass.test.js for the isolated-process case).- expect(true).toBe(true); // documented: covered by play-pass.test.js + _gd.mjs+ // PLAY_GATE_MINT is read once, at module load. Mutating the env var on the+ // already-imported module would prove nothing, so drop the module graph and+ // re-import both endpoints with the gate unpinned.+ vi.resetModules();+ const savedMint = process.env.PLAY_GATE_MINT;+ const savedThree = process.env.THREE_MINT;+ delete process.env.PLAY_GATE_MINT;+ delete process.env.THREE_MINT;+ try {+ const gatelessVerify = (await import('../api/play/verify.js')).default;+ const res = mockRes();+ await gatelessVerify(mockReq({+ method: 'POST',+ body: { address: 'a'.repeat(40), signature: 'b'.repeat(80), nonce: 'c'.repeat(40) },+ }), res);+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('gate_disabled');++ // And the nonce endpoint tells the client to skip sign-in entirely rather+ // than sending it into a verify that can only refuse it.+ const gatelessNonce = (await import('../api/play/nonce.js')).default;+ const nr = mockRes();+ await gatelessNonce(mockReq({ method: 'GET' }), nr);+ expect(nr.statusCode).toBe(200);+ expect(nr.json.data.required).toBe(false);+ expect(nr.json.data.mint).toBe('');+ } finally {+ if (savedMint === undefined) delete process.env.PLAY_GATE_MINT;+ else process.env.PLAY_GATE_MINT = savedMint;+ if (savedThree === undefined) delete process.env.THREE_MINT;+ else process.env.THREE_MINT = savedThree;+ vi.resetModules();+ }});it('rejects missing required fields', async () => {