import { serve } from '@hono/node-server' import { serveStatic } from '@hono/node-server/serve-static' import { Hono, type Context } from 'hono' import { cors } from 'hono/cors' import { WebSocketServer, type WebSocket, type RawData } from 'ws' import { validateDeclaration } from '../../engine/lobby.js' import { CURATED_MAPS, DEFAULT_SPRITE_DID, DEV_SOLO, MIN_PLAYERS_EFFECTIVE, PLAYTEST } from './config.js' import type { OutputSchema as ListMapsOutput } from '../../lexgen/types/town/deception/listMaps.js' import type { GameDeclaration } from '../../engine/lobby.js' import { validateStationActivity } from '../../engine/validate.js' import { timerFor } from '../../engine/config.js' import type { Action } from '../../engine/actions.js' import type { ActivityKind, Did, Facing, GameState, Station, Vec } from '../../engine/types.js' import { decodeFrame, errorFrame, messageFrame, type FrameHeader } from '../../wire/index.js' import { stationInteraction } from '../../engine/selectors.js' import { validateJoin, validateStart, validateMove, validateInteract, validateChooseAction, validateCancelAction, validateDeposit, validateDrop, validateInspectDebris, validateCastVote, validateSetView, validatePing, } from '../../lexgen/types/town/deception/clientFrame.js' import { Registry, type Room, type Subscriber, type ResolvedWorld } from './rooms.js' import { startLogin, completeCallback, didForSid, agentForDid, logout, clientMetadataJson, jwksJson, parseCookies, sidCookie, clearSidCookie, SID_COOKIE, appUrl, } from './oauth.js' import { writeGameDeclaration, writeResults, copyDefaultSprite } from './persist.js' import { getShop, shopConfigured, listInventory, transfer, ShopError, type Party, } from './shop.js' import { startJetstream } from './jetstream.js' import { resolveGameWorld } from './maps.js' import { resolveSprite } from './atproto.js' import { DeductionRegistry, DeductionRoom } from './deduction/room.js' import { suspectPool } from './deduction/pool.js' // The registry fires writeResults (signed PDS fan-out) once each round ends (§8). Once every // player has had their action log written, the game is over for good — tear the room down so its // state/backlog don't linger in memory. The final #snapshot was already delivered synchronously at // roundEnded, so live clients keep their end screen; only future (re)connects are turned away. const registry: Registry = new Registry({ onEnded: (room) => { writeResults(room) .catch((err) => console.error(`[persist] writeResults failed for ${room.code}:`, err instanceof Error ? err.message : err), ) .finally(() => registry.remove(room)) }, }) /** Single-player deduction rooms live in their own registry (codes are 'D'-prefixed); they hold no * PDS record and never touch the deception room lifecycle. */ const deductionRegistry = new DeductionRegistry() /** The server-verified DID for a request, from its session cookie (null = unauthenticated). */ function didFromCookieHeader(cookieHeader: string | null | undefined): string | null { return didForSid(parseCookies(cookieHeader)[SID_COOKIE]) } // Defense-in-depth: validate each incoming intent frame's body against its generated lexicon schema // (the frame member name rides in the header `t`) before the engine validators run. type FrameValidator = (v: unknown) => { success: boolean } const FRAME_VALIDATORS: Record = { '#join': validateJoin, '#start': validateStart, '#move': validateMove, '#interact': validateInteract, '#chooseAction': validateChooseAction, '#cancelAction': validateCancelAction, '#deposit': validateDeposit, '#drop': validateDrop, '#inspectDebris': validateInspectDebris, '#castVote': validateCastVote, '#setView': validateSetView, '#ping': validatePing, } // --- HTTP control plane ----------------------------------------------------- const app = new Hono() app.use('/api/*', cors()) app.get('/api/hello', (c) => c.json({ message: 'hello from deception.town' })) // XRPC query: the curated set of playable maps (AT-URI + display name) for a client's map chooser. // Read access is public — picking a map needs no session. The set comes from server config, not the // network (see CURATED_MAPS / SABOTAGE_FARM_MAP_URI). app.get('/xrpc/town.deception.listMaps', (c) => { const body: ListMapsOutput = { maps: CURATED_MAPS } return c.json(body) }) // --- OAuth (backend, server-held sessions; §8.3 server-write path) ---------- // Client (app) metadata + JWKS for the confidential client (hosted mode). In loopback dev mode the // metadata is encoded in the client_id and these are mostly informational. app.get('/client-metadata.json', async (c) => c.json((await clientMetadataJson()) as object)) app.get('/jwks.json', async (c) => c.json((await jwksJson()) as object)) // Begin login: redirect the browser to its PDS authorization server. app.get('/oauth/login', async (c) => { const handle = c.req.query('handle') if (!handle) return c.json({ error: 'missing-handle' }, 400) try { const url = await startLogin(handle) return c.redirect(url) } catch (err) { return c.json({ error: 'authorize-failed', message: err instanceof Error ? err.message : String(err) }, 400) } }) // PDS redirects back here with the auth code. Store the session, hand the browser an opaque cookie. app.get('/oauth/callback', async (c) => { const params = new URLSearchParams(new URL(c.req.url).search) try { const { sid } = await completeCallback(params) c.header('set-cookie', sidCookie(sid)) return c.redirect(appUrl + '/') } catch (err) { console.error('[oauth] callback failed:', err instanceof Error ? err.message : err) return c.redirect(appUrl + '/?error=oauth') } }) // Who am I? The SPA calls this on load to learn its signed-in DID. `hasSprite` tells the client // whether the player already has an actor.rpg.sprite/self record — when false, the SPA shows the // sprite-setup gate (create your own at rpg.actor, or clone the default actor) before letting them play. app.get('/api/session', async (c) => { const did = didFromCookieHeader(c.req.header('cookie')) if (!did) return c.json({ did: null, devSolo: DEV_SOLO, playtest: PLAYTEST }, 200) const hasSprite = (await resolveSprite(did)) != null return c.json({ did, hasSprite, devSolo: DEV_SOLO, playtest: PLAYTEST }) }) // Clone the default actor into the caller's repo as their actor.rpg.sprite/self. Used by the // sprite-setup gate when a player opts for the default instead of building one at rpg.actor. Requires // the sprite-write scope, which login only requests when the player had no sprite — exactly this case. app.post('/api/sprite/default', async (c) => { const did = didFromCookieHeader(c.req.header('cookie')) if (!did) return c.json({ error: 'unauthorized' }, 401) try { const agent = await agentForDid(did) const uri = await copyDefaultSprite(agent, did, DEFAULT_SPRITE_DID) return c.json({ uri }) } catch (err) { console.error('[sprite] default clone failed:', err instanceof Error ? err.message : err) return c.json({ error: 'pds-write-failed', message: err instanceof Error ? err.message : String(err) }, 502) } }) app.post('/oauth/logout', async (c) => { await logout(parseCookies(c.req.header('cookie'))[SID_COOKIE]) c.header('set-cookie', clearSidCookie()) return c.json({ ok: true }) }) // --- thrift shop (easter egg) ----------------------------------------------- // An item swap with the central shop account. Donate moves one of the caller's equipment.rpg.item // records into the shop's repo (deleting their copy); withdraw moves a shop item into the caller's // repo (deleting the shop's). Both run the validated create-before-delete transfer in shop.ts. /** Map a thrown ShopError (or anything) to an HTTP response. */ function shopFail(c: Context, err: unknown) { if (err instanceof ShopError) return c.json({ error: err.code, message: err.message }, err.status as 400) console.error('[shop] request failed:', err instanceof Error ? err.message : err) return c.json({ error: 'shop-failed', message: err instanceof Error ? err.message : String(err) }, 502) } // The shop's current shelf (its equipment.rpg.item records). Public — browsing needs no session. app.get('/api/shop/items', async (c) => { try { const shop = await getShop() return c.json({ shopDid: shop.did, items: await listInventory(shop.did, shop.agent) }) } catch (err) { return shopFail(c, err) } }) // The caller's own equipment.rpg.item records (what they could donate). app.get('/api/shop/mine', async (c) => { const did = didFromCookieHeader(c.req.header('cookie')) if (!did) return c.json({ error: 'unauthorized' }, 401) try { const agent = await agentForDid(did) return c.json({ did, items: await listInventory(did, agent) }) } catch (err) { return shopFail(c, err) } }) // Donate: caller (giver) → shop (receiver). app.post('/api/shop/deposit', async (c) => { const did = didFromCookieHeader(c.req.header('cookie')) if (!did) return c.json({ error: 'unauthorized' }, 401) const rkey = asString((await c.req.json().catch(() => ({})))?.rkey) if (!rkey) return c.json({ error: 'bad-request', message: 'rkey required' }, 400) try { const shop = await getShop() const player: Party = { did, agent: await agentForDid(did) } const result = await transfer(player, { did: shop.did, agent: shop.agent }, rkey) return c.json(result) } catch (err) { return shopFail(c, err) } }) // Withdraw: shop (giver) → caller (receiver). app.post('/api/shop/withdraw', async (c) => { const did = didFromCookieHeader(c.req.header('cookie')) if (!did) return c.json({ error: 'unauthorized' }, 401) const rkey = asString((await c.req.json().catch(() => ({})))?.rkey) if (!rkey) return c.json({ error: 'bad-request', message: 'rkey required' }, 400) try { const shop = await getShop() const player: Party = { did, agent: await agentForDid(did) } const result = await transfer({ did: shop.did, agent: shop.agent }, player, rkey) return c.json(result) } catch (err) { return shopFail(c, err) } }) // Lets the client hide the shop entry when the server has no shop account configured. app.get('/api/shop/status', (c) => c.json({ configured: shopConfigured() })) // --- rooms ------------------------------------------------------------------ // Create a game. The authenticated caller is the host: we write a town.deception.game record to // THEIR PDS on their behalf, then optimistically stand up the room locally (keyed by the record's // AT-URI) so play can begin without waiting for the Jetstream echo to come back (§10). app.post('/api/rooms', async (c) => { const hostDid = didFromCookieHeader(c.req.header('cookie')) if (!hostDid) return c.json({ error: 'unauthorized' }, 401) let body: { players?: unknown; roundDurationSec?: unknown; resourceCount?: unknown; map?: unknown } try { body = await c.req.json() } catch { return c.json({ error: 'bad-json' }, 400) } const submitted = Array.isArray(body.players) ? body.players.filter((p): p is string => typeof p === 'string') : [] // The creator is the host (roster[0]); ensure they're in the roster exactly once. const players = [hostDid, ...submitted.filter((p) => p !== hostDid)] const code = registry.mintCode() const decl: GameDeclaration = { players, roundDurationSec: typeof body.roundDurationSec === 'number' ? body.roundDurationSec : 600, resourceCount: typeof body.resourceCount === 'number' ? body.resourceCount : 4, code, mapUri: typeof body.map === 'string' ? body.map : undefined, createdAt: new Date().toISOString(), } const check = validateDeclaration(decl, MIN_PLAYERS_EFFECTIVE) if (!check.ok) return c.json({ error: check.reason }, 400) // Resolve the map (if any) BEFORE writing anything: an invalid map fails creation up front, so we // never leave a dangling town.deception.game record in the host's PDS for an unplayable game. let world: ResolvedWorld | undefined if (decl.mapUri) { const res = await resolveGameWorld(decl.mapUri) if (!res.ok) return c.json({ error: res.reason }, 400) world = res.world } let uri: string try { const agent = await agentForDid(hostDid) uri = await writeGameDeclaration(agent, hostDid, decl) } catch (err) { console.error('[rooms] game record write failed:', err instanceof Error ? err.message : err) return c.json({ error: 'pds-write-failed', message: err instanceof Error ? err.message : String(err) }, 502) } const room = registry.getByUri(uri) ?? registry.create(decl, uri, world) return c.json({ code: room.code, uri, hostDid: room.hostDid, players: decl.players }) }) // Lobby info for a join screen. app.get('/api/rooms/:code', (c) => { const room = registry.get(c.req.param('code')) if (!room) return c.json({ error: 'not-found' }, 404) return c.json({ code: room.code, hostDid: room.hostDid, players: room.decl.players, phase: room.state.phase, mapUri: room.tilemapUri ?? room.decl.mapUri ?? null, }) }) // Play-test interest is no longer a PDS write: the interest page just links the player to the // play-testing group chat (client-side, VITE_PLAYTEST_CHAT_URL). Nothing to handle server-side. // --- single-player deduction ------------------------------------------------ // Start a deduction investigation: resolve the chosen map, draw a suspect pool, and generate a case // (DEDUCTION.md). Holds the room in memory only (no PDS record — it's solo). Returns the room code // the client then opens a /ws/deduction socket against. app.post('/api/deduction', async (c) => { const did = didFromCookieHeader(c.req.header('cookie')) if (!did) return c.json({ error: 'unauthorized' }, 401) let body: { map?: unknown } try { body = await c.req.json() } catch { return c.json({ error: 'bad-json' }, 400) } const mapUri = typeof body.map === 'string' ? body.map : undefined if (!mapUri) return c.json({ error: 'map-required' }, 400) const res = await resolveGameWorld(mapUri) if (!res.ok) return c.json({ error: res.reason }, 400) let pool try { pool = await suspectPool() } catch (err) { return c.json({ error: 'pool-unavailable', message: err instanceof Error ? err.message : String(err) }, 502) } const code = deductionRegistry.mintCode() const created = DeductionRoom.create(code, did, { world: res.world, pool }) if (!created.ok) return c.json({ error: created.reason }, 422) deductionRegistry.add(created.room) return c.json({ code: created.room.code, mapUri: created.room.tilemapUri }) }) app.get('/api/deduction/:code', (c) => { const room = deductionRegistry.get(c.req.param('code')) if (!room) return c.json({ error: 'not-found' }, 404) return c.json({ code: room.code, mapUri: room.tilemapUri }) }) // Static: the built SPA (vite → dist/client). Registered last so every API/oauth/xrpc/jwks route // above takes precedence; serveStatic falls through (next()) when no file matches the path. The // catch-all then serves index.html so client-side deep links resolve. In dev this is inert — the // browser talks to the Vite server, which proxies the dynamic routes here. cwd is /app in the // container (the server runs as `node dist/server/index.js`), so ./dist/client is /app/dist/client. app.use('*', serveStatic({ root: './dist/client' })) app.get('*', serveStatic({ path: './dist/client/index.html' })) const port = Number(process.env.PORT ?? 3000) const server = serve({ fetch: app.fetch, port }, (info) => { console.log(`deception.town api + ws listening on http://localhost:${info.port}`) }) // Discover games declared anywhere on the network (and dedupe our own optimistic creates) (§10). startJetstream(registry) // --- WebSocket: subscription (down) + intent backchannel (up) ---------------- // Two WS servers share one HTTP server: the deception subscription socket (/ws) and the single-player // deduction socket (/ws/deduction — own registry, same framing). They MUST be `noServer` and routed by // pathname ourselves: passing `server` to more than one `ws` server makes each abort every upgrade // whose `path` it doesn't own with a 400, so they'd kill each other's handshakes. We route once here. const wss = new WebSocketServer({ noServer: true }) const deductionWss = new WebSocketServer({ noServer: true }) ;(server as unknown as import('node:http').Server).on('upgrade', (req, socket, head) => { const pathname = new URL(req.url ?? '/', 'http://localhost').pathname const target = pathname === '/ws/deduction' ? deductionWss : pathname === '/ws' ? wss : null if (!target) { socket.destroy() return } target.handleUpgrade(req, socket, head, (ws) => target.emit('connection', ws, req)) }) // Heartbeat: ping every socket each sweep; a socket that didn't pong (or send anything) since the // last sweep is considered dead and terminated, which fires its 'close' handler (→ playerDisconnected). type LiveSocket = WebSocket & { isAlive?: boolean } const HEARTBEAT_MS = 30_000 const heartbeat = setInterval(() => { for (const client of [...wss.clients, ...deductionWss.clients]) { const ws = client as LiveSocket if (ws.isAlive === false) { ws.terminate() continue } ws.isAlive = false ws.ping() } }, HEARTBEAT_MS) wss.on('close', () => clearInterval(heartbeat)) wss.on('connection', (ws: WebSocket, req) => { ws.binaryType = 'arraybuffer' const live = ws as LiveSocket live.isAlive = true ws.on('pong', () => { live.isAlive = true }) const url = new URL(req.url ?? '/', 'http://localhost') const code = url.searchParams.get('code') ?? '' // Identity is the server-verified DID from the session cookie — NOT a URL param (§5.5). Handle // remains a cosmetic client hint; the sprite is resolved server-side from the player's repo. const did = didFromCookieHeader(req.headers.cookie) const handle = url.searchParams.get('handle') ?? did ?? 'anon' const cursorParam = url.searchParams.get('cursor') const room = registry.get(code) if (!room) { ws.send(errorFrame('GameNotFound', code)) ws.close() return } const isPlayer = !!did && room.decl.players.includes(did) const viewer: Did | null = did const sub: Subscriber = { id: room.newSubscriberId(), did: viewer, isPlayer, send: (bytes) => { if (ws.readyState === ws.OPEN) ws.send(bytes) }, } room.add(sub) // Downstream: snapshot (or replay from a resume cursor). if (cursorParam == null) { sub.send(room.snapshotFrame(viewer)) } else { const frames = room.replayFrames(viewer, Number(cursorParam)) if (frames) { frames.forEach(sub.send) } else { sub.send(errorFrame('FutureCursor', cursorParam)) sub.send(room.snapshotFrame(viewer)) } } // Bind the player into the world: join during the lobby, or reconnect a held slot. The sprite is // resolved authoritatively from the player's actor.rpg.sprite/self record (async, cached). if (isPlayer && did) { const existing = room.state.players[did] if (!existing && room.state.phase === 'lobby') { void resolveSprite(did).then((spriteRef) => { if (room.isJoined(did) || room.state.phase !== 'lobby') return // raced with another socket / start const pos: Vec = room.spawnFor(room.connectedPlayers().length) room.dispatch({ type: 'playerJoined', serverTime: room.now(), did, handle, spriteRef, pos }) }) } else if (existing && existing.status === 'disconnected') { room.dispatch({ type: 'playerReconnected', serverTime: room.now(), did }) } } ws.on('message', (data: RawData) => { live.isAlive = true handleFrame(room, sub, toBytes(data)) }) ws.on('close', () => { room.remove(sub.id) // only mark the player disconnected once their last socket is gone (tabs / replay sockets) if (isPlayer && did && room.state.players[did]?.status === 'alive' && !room.hasSubscriberFor(did)) { room.dispatch({ type: 'playerDisconnected', serverTime: room.now(), did }) } }) }) // --- WebSocket: single-player deduction -------------------------------------- deductionWss.on('connection', (ws: WebSocket, req) => { ws.binaryType = 'arraybuffer' const live = ws as LiveSocket live.isAlive = true ws.on('pong', () => { live.isAlive = true }) const url = new URL(req.url ?? '/', 'http://localhost') const code = url.searchParams.get('code') ?? '' const did = didFromCookieHeader(req.headers.cookie) const room = deductionRegistry.get(code) if (!room) { ws.send(errorFrame('GameNotFound', code)) ws.close() return } // A deduction room is private to its creator: only they may subscribe. if (!did || did !== room.playerDid) { ws.send(errorFrame('Unauthorized', 'not your investigation')) ws.close() return } const sub: Subscriber = { id: room.newSubscriberId(), did, isPlayer: true, send: (bytes) => { if (ws.readyState === ws.OPEN) ws.send(bytes) }, } room.add(sub) for (const frame of room.initialFrames(did)) sub.send(frame) ws.on('message', (data: RawData) => { live.isAlive = true let header: FrameHeader let body: Record try { const f = decodeFrame(toBytes(data)) header = f.header body = (f.body ?? {}) as Record } catch { sub.send(errorFrame('BadFrame')) return } if (header.op !== 1) return room.onIntent(sub, header.t, body) }) ws.on('close', () => room.remove(sub.id)) }) // --- intent handling (the trust boundary, §5.4) ----------------------------- function handleFrame(room: Room, sub: Subscriber, bytes: Uint8Array): void { let header: FrameHeader let body: Record try { const f = decodeFrame(bytes) header = f.header body = (f.body ?? {}) as Record } catch { sub.send(errorFrame('BadFrame')) return } if (header.op !== 1) return const t = header.t // Defense-in-depth: reject frames whose body doesn't match the lexicon schema. const validator = FRAME_VALIDATORS[t] if (validator && !validator(body).success) { sub.send(errorFrame('BadFrame', t)) return } const did = sub.did const now = room.now() const state = room.state // Spectator-safe frames first. if (t === '#ping' || t === '#setView') return if (!sub.isPlayer || !did) { sub.send(errorFrame('Unauthorized', 'not a roster player')) return } switch (t) { case '#join': // Identity is bound at connect; nothing to do. return case '#start': { const err = room.start(did) if (err) sub.send(errorFrame('CannotStart', err)) return } case '#move': { const vec = asVec(body.vec) if (vec) { room.dispatch({ type: 'setDestination', serverTime: now, did, target: vec }) return } // Key-held movement: steer toward a short LOOKAHEAD target — a few frames of travel ahead in // the pressed direction, from the player's CURRENT position. Each new #move recomputes from // the live position, so holding a key streams fresh targets (smooth continuous motion) and // releasing lets the player coast to the last one and stop (§3.3). aStar snaps a target that // lands in a wall to the nearest walkable cell, so steering into geometry just slides/stops. const dir = asFacing(body.dir) const p = state.players[did] if (dir && p && p.status === 'alive' && !p.active) { const lookahead = state.config.moveSpeedPxPerSec * MOVE_LOOKAHEAD_SEC const target = stepInDir(p.pos, dir, lookahead) room.dispatch({ type: 'setDestination', serverTime: now, did, target }) } return } case '#chooseAction': { const stationId = asString(body.stationId) const actionType = body.actionType as ActivityKind // which resource — required for collect / pretendCollect / deposit / fakeDeposit; ignored else const resourceId = asString(body.resourceId) ?? undefined // "discard and X": drop the carried item first (free), then perform the action const discard = body.discard === true if (!stationId) return sub.send(errorFrame('BadFrame', 'stationId')) const v = validateStationActivity(state, did, stationId, actionType, resourceId, discard) if (!v.ok) return sub.send(errorFrame('IllegalAction', v.reason)) // the discard half: emit the drop immediately before the action so the actionStarted lands // empty-handed (the slot picked by validate is carry-agnostic, so it stays valid). if (discard) { const p = state.players[did] if (p?.carrying) { room.dispatch({ type: 'itemDropped', serverTime: now, did, debrisId: room.mintDebrisId(), pos: p.pos }) } } room.dispatch({ type: 'actionStarted', serverTime: now, did, stationId, slot: v.slot, kind: actionType, resourceId, endsAt: now + timerFor(actionType, state.config), }) return } case '#interact': { // Server-local query: reply to THIS subscriber only with the per-viewer station menu // (worker + any saboteur options, the collect affordance, the station state as they see it). // No action is dispatched — opening a station mutates nothing. const stationId = asString(body.stationId) if (!stationId) return sub.send(errorFrame('BadFrame', 'stationId')) const st = state.stations[stationId] const p = state.players[did] if (!st || !p) return sub.send(errorFrame('IllegalAction', 'no-station')) const a = st.area const inside = p.pos.x >= a.x && p.pos.x <= a.x + a.w && p.pos.y >= a.y && p.pos.y <= a.y + a.h if (state.phase !== 'round' || p.status !== 'alive' || !inside) { return sub.send(errorFrame('IllegalAction', 'not-at-station')) } const menu = stationInteraction(state, did, stationId) if (menu) sub.send(messageFrame('#interaction', { stationId, menu })) return } case '#cancelAction': if (state.players[did]?.active) room.dispatch({ type: 'actionCancelled', serverTime: now, did }) return case '#deposit': { const p = state.players[did] if (!p?.carrying) return sub.send(errorFrame('IllegalAction', 'empty-handed')) const st = stationAt(state, p.pos, (s) => s.deposit.length > 0) if (!st) return sub.send(errorFrame('IllegalAction', 'not-at-deposit')) // a fake carry disposes via fakeDeposit (vanishes, never banks); a real one via deposit const kind: ActivityKind = p.carrying.authentic ? 'deposit' : 'fakeDeposit' const resourceId = p.carrying.resourceId const v = validateStationActivity(state, did, st.id, kind, resourceId) if (!v.ok) return sub.send(errorFrame('IllegalAction', v.reason)) room.dispatch({ type: 'actionStarted', serverTime: now, did, stationId: st.id, slot: v.slot, kind, resourceId, endsAt: now + timerFor(kind, state.config), }) return } case '#drop': { const p = state.players[did] if (p?.carrying) { room.dispatch({ type: 'itemDropped', serverTime: now, did, debrisId: room.mintDebrisId(), pos: p.pos }) } return } case '#inspectDebris': { const debrisId = asString(body.debrisId) if (debrisId && state.debris[debrisId]) { room.dispatch({ type: 'debrisInspected', serverTime: now, did, debrisId }) } return } case '#castVote': { const targetDid = asString(body.targetDid) if (state.vote && targetDid) room.dispatch({ type: 'voteCast', serverTime: now, voterDid: did, targetDid }) return } default: sub.send(errorFrame('UnknownFrame', t)) } } // --- helpers ---------------------------------------------------------------- function toBytes(data: RawData): Uint8Array { if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data)) if (Buffer.isBuffer(data)) return new Uint8Array(data) return new Uint8Array(data as ArrayBuffer) } function asString(v: unknown): string | null { return typeof v === 'string' ? v : null } function asVec(v: unknown): Vec | null { if (typeof v !== 'object' || v === null) return null const o = v as { x?: unknown; y?: unknown } if (typeof o.x !== 'number' || typeof o.y !== 'number') return null return { x: o.x, y: o.y } } // How far ahead a key-held #move steers — seconds of travel projected in the pressed direction. // Must exceed the client's key-repeat interval so a held key keeps a fresh target (no stutter). const MOVE_LOOKAHEAD_SEC = 0.5 function asFacing(v: unknown): Facing | null { return v === 'north' || v === 'south' || v === 'east' || v === 'west' ? v : null } function stepInDir(pos: Vec, dir: Facing, dist: number): Vec { switch (dir) { case 'north': return { x: pos.x, y: pos.y - dist } case 'south': return { x: pos.x, y: pos.y + dist } case 'east': return { x: pos.x + dist, y: pos.y } case 'west': return { x: pos.x - dist, y: pos.y } } } function stationAt(state: GameState, pos: Vec, accept: (st: Station) => boolean) { for (const st of Object.values(state.stations)) { if (!accept(st)) continue const a = st.area if (pos.x >= a.x && pos.x <= a.x + a.w && pos.y >= a.y && pos.y <= a.y + a.h) return st } return undefined } // avoid an "unused export" when bundling; the action union is referenced for type-safety only export type { Action }