Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(dino): PeerState.dino + sanitize + hub cast handler for live spectating (dino Task 1)

enesbd72e9ed4e12
diff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.ts
index fc1b0896f..c4c9fdd81 100644
--- a/src/core/presence/hub.test.ts
+++ b/src/core/presence/hub.test.ts
@@ -8,7 +8,14 @@ import {
TYPING_THROTTLE_MS
} from './hub'
import { IPC } from '../../shared/ipc'
-import { PRESENCE_COLORS, REF_MAX_LEN, type PeerDiff, type PeerState } from '../../shared/presence'
+import {
+ PRESENCE_COLORS,
+ REF_MAX_LEN,
+ DINO_MAX_OBSTACLES,
+ type DinoSnapshot,
+ type PeerDiff,
+ type PeerState
+} from '../../shared/presence'
let fake: FakePlatform
@@ -44,6 +51,7 @@ describe('PresenceHub join/leave', () => {
chat: null,
typing: null,
projectId: null,
+ dino: null,
kind: 'browser'
},
{
@@ -55,6 +63,7 @@ describe('PresenceHub join/leave', () => {
chat: null,
typing: null,
projectId: null,
+ dino: null,
kind: 'phone'
}
])
@@ -321,6 +330,141 @@ describe('PresenceHub signals', () => {
})
})
+describe('PresenceHub dino (live spectator cast)', () => {
+ function snap(over: Partial<DinoSnapshot> = {}): DinoSnapshot {
+ return {
+ y: -12,
+ ducking: false,
+ crashed: false,
+ started: true,
+ score: 42,
+ speed: 6,
+ groundScroll: 100,
+ obstacles: [{ kind: 'cactus', x: 300, y: 0, sx: 0, sw: 20, sh: 40, flap: 0 }],
+ ...over
+ }
+ }
+
+ it('a valid dino cast sets the sender dino and broadcasts an update diff carrying { dino }', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ const payload = { nodeId: 'dino-a', snap: snap() }
+ hub.setDino(1, payload)
+ expect(hub.peers()[0].dino).toEqual(payload)
+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { dino: payload } })
+ })
+
+ it('clamps obstacles to the first DINO_MAX_OBSTACLES in the table AND the broadcast diff', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ const many = Array.from({ length: DINO_MAX_OBSTACLES + 8 }, (_, i) => ({
+ kind: 'cactus' as const,
+ x: i,
+ y: 0,
+ sx: 0,
+ sw: 20,
+ sh: 40,
+ flap: 0
+ }))
+ hub.setDino(1, { nodeId: 'dino-a', snap: snap({ obstacles: many }) })
+ expect(hub.peers()[0].dino?.snap.obstacles).toHaveLength(DINO_MAX_OBSTACLES)
+ // The first N are kept (x: 0..N-1), the tail is dropped.
+ expect(hub.peers()[0].dino?.snap.obstacles.map((o) => o.x)).toEqual(
+ Array.from({ length: DINO_MAX_OBSTACLES }, (_, i) => i)
+ )
+ const diff = diffs().at(-1) as { patch: { dino: { snap: DinoSnapshot } } }
+ expect(diff.patch.dino.snap.obstacles).toHaveLength(DINO_MAX_OBSTACLES)
+ })
+
+ it('drops a malformed payload — dino becomes null (never applied garbage)', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ hub.setDino(1, { nodeId: 'dino-a', snap: snap() })
+ expect(hub.peers()[0].dino).not.toBeNull()
+
+ // Missing nodeId → the whole cast is invalid → the field clears.
+ hub.setDino(1, { snap: snap() })
+ expect(hub.peers()[0].dino).toBeNull()
+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { dino: null } })
+
+ // A non-object and a bad-number snap likewise never apply garbage.
+ hub.setDino(1, { nodeId: 'dino-a', snap: snap() })
+ hub.setDino(1, 'nope')
+ expect(hub.peers()[0].dino).toBeNull()
+ })
+
+ it('coerces non-finite snap numbers to 0 and drops a bad-kind obstacle', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ hub.setDino(1, {
+ nodeId: 'dino-a',
+ snap: {
+ y: Number.NaN,
+ ducking: 1,
+ crashed: false,
+ started: true,
+ score: Number.POSITIVE_INFINITY,
+ speed: 6,
+ groundScroll: 0,
+ obstacles: [
+ { kind: 'ufo', x: 1, y: 0, sx: 0, sw: 1, sh: 1, flap: 0 },
+ { kind: 'bird', x: 2, y: 0, sx: 0, sw: 1, sh: 1, flap: 1 }
+ ]
+ }
+ })
+ const dino = hub.peers()[0].dino
+ expect(dino?.snap.y).toBe(0)
+ expect(dino?.snap.score).toBe(0)
+ expect(dino?.snap.ducking).toBe(true)
+ // The 'ufo' obstacle is dropped; only the valid 'bird' survives.
+ expect(dino?.snap.obstacles).toEqual([{ kind: 'bird', x: 2, y: 0, sx: 0, sw: 1, sh: 1, flap: 1 }])
+ })
+
+ it('leave drops the peer and its dino from the table', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ hub.setDino(1, { nodeId: 'dino-a', snap: snap() })
+ hub.leave(1)
+ expect(hub.peers()).toEqual([])
+ })
+
+ it('a repeated stop (null → null) is a silent no-op, and an unknown client is ignored', () => {
+ const hub = new PresenceHub()
+ hub.join(1, 'browser')
+ hub.setDino(1, null)
+ const after = diffs().length // never played → still null → nothing broadcast
+ expect(diffs()).toHaveLength(after)
+ hub.setDino(1, { nodeId: 'dino-a', snap: snap() })
+ hub.setDino(1, null) // real stop → broadcasts once
+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { dino: null } })
+ const stopped = diffs().length
+ hub.setDino(1, null) // repeat stop → no-op
+ expect(diffs()).toHaveLength(stopped)
+ hub.setDino(42, { nodeId: 'x', snap: snap() }) // never joined → no ghost peer
+ expect(hub.peers()).toHaveLength(1)
+ })
+
+ it('the cast entry point is rate-limited, and a stop is an exempt clear (drains no token)', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(0)
+ const hub = new PresenceHub()
+ hub.registerIpc()
+ hub.join(1, 'browser')
+ const budget = PRESENCE_RATE_BUDGETS[IPC.presenceDino]
+
+ const before = diffs().length
+ for (let i = 0; i < 1000; i++) {
+ fake.senderListeners[IPC.presenceDino](1, { nodeId: 'dino-a', snap: snap({ score: i }) })
+ }
+ expect(diffs().length - before).toBe(budget.burst) // the bucket, not one cast more
+
+ // A stop is an edge (a dropped one leaves a frozen ghost) → exempt, lands even when drained.
+ fake.senderListeners[IPC.presenceDino](1, null)
+ expect(hub.peers()[0].dino).toBeNull()
+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { dino: null } })
+ })
+})
+
describe('PresenceHub noteTyping (Stage 2 caller; wired here)', () => {
it('throttles to one broadcast per node per 500ms and re-fires for a different node', () => {
vi.useFakeTimers()
@@ -694,10 +838,11 @@ describe('registerIpc', () => {
IPC.presenceCursor,
IPC.presenceFocus,
IPC.presenceChat,
+ IPC.presenceDino,
IPC.presenceProject
])
hub.registerIpc()
- expect(registered).toHaveLength(5)
+ expect(registered).toHaveLength(6)
})
})
diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.ts
index 7d73a2a68..6e41956ca 100644
--- a/src/core/presence/hub.ts
+++ b/src/core/presence/hub.ts
@@ -16,6 +16,7 @@ import {
capCodePoints,
defaultNameFor,
nextFreeColor,
+ sanitizeDinoPayload,
sanitizeIdentity,
type ClientId,
type PeerDiff,
@@ -52,6 +53,8 @@ export const TYPING_THROTTLE_MS = 500
export const PRESENCE_RATE_BUDGETS: Record<string, { perSec: number; burst: number }> = {
[IPC.presenceCursor]: { perSec: 20, burst: 40 },
[IPC.presenceChat]: { perSec: 25, burst: 50 },
+ // The dino snapshot is a ~20 Hz cast like chat/cursor; sized the same as chat.
+ [IPC.presenceDino]: { perSec: 25, burst: 50 },
[IPC.presenceFocus]: { perSec: 10, burst: 20 },
[IPC.presenceProject]: { perSec: 20, burst: 60 },
[IPC.presenceHello]: { perSec: 2, burst: 5 }
@@ -80,6 +83,9 @@ function isClearingCast(channel: string, payload: unknown): boolean {
if (channel === IPC.presenceCursor) return !payload
if (channel === IPC.presenceChat) return typeof payload !== 'string'
if (channel === IPC.presenceFocus) return typeof payload !== 'string' || payload === ''
+ // A dino "stop" (the authority quit / closed the node) is an EDGE — nothing supersedes it, and a
+ // dropped one leaves a frozen ghost game on every spectator. Mirror setDino's own null rule.
+ if (channel === IPC.presenceDino) return sanitizeDinoPayload(payload) === null
return false
}
@@ -92,14 +98,17 @@ export function allocateRelayClientId(): ClientId {
return nextRelayId++
}
-/** A peer copy safe to hand out: the nested `cursor`/`typing` objects are cloned too, so a caller
- * holding a peers()/join-diff result cannot reach back into the hub's table through them.
- * (The setters already assign fresh objects, so these two are the only nested state.) */
+/** A peer copy safe to hand out: the nested `cursor`/`typing`/`dino` objects are cloned too, so a
+ * caller holding a peers()/join-diff result cannot reach back into the hub's table through them.
+ * (The setters already assign fresh objects, so these are the only nested state.) */
function copyPeer(p: PeerState): PeerState {
return {
...p,
cursor: p.cursor ? { ...p.cursor } : null,
- typing: p.typing ? { ...p.typing } : null
+ typing: p.typing ? { ...p.typing } : null,
+ dino: p.dino
+ ? { nodeId: p.dino.nodeId, snap: { ...p.dino.snap, obstacles: [...p.dino.snap.obstacles] } }
+ : null
}
}
@@ -125,6 +134,7 @@ export class PresenceHub {
// Unknown until the client reports its active project (a phone never does in Stage 1) —
// so it is drawn on nobody's canvas and lives in the facepile only.
projectId: null,
+ dino: null,
kind
}
this.table.set(clientId, peer)
@@ -248,6 +258,22 @@ export class PresenceHub {
this.emit({ op: 'update', clientId, patch: { chat: next } })
}
+ /** The live dino game this client is the AUTHORITY for; a malformed/absent payload clears it
+ * (stopped playing / closed the node / took-over elsewhere). THE single ingest point, so the
+ * sanitize + obstacle clamp (sanitizeDinoPayload) lives here and cannot drift — the hub applies
+ * ONLY the sanitized value, never the raw cast. Spectators render `snap` for the matching node
+ * id. A repeated clear (null → null) is a silent no-op, exactly like the other setters. */
+ setDino(clientId: ClientId, payload: unknown): void {
+ const peer = this.table.get(clientId)
+ if (!peer) return
+ const next = sanitizeDinoPayload(payload)
+ // Stop repeats (null → null) fan out nothing. A non-null snapshot changes every frame, so it
+ // is always reflected — no deep compare (that would cost more than the broadcast it saves).
+ if (next === null && peer.dino === null) return
+ peer.dino = next
+ this.emit({ op: 'update', clientId, patch: { dino: next } })
+ }
+
/** Which project (canvas) this client is on. Everyone else uses it to decide whether this
* peer's cursor/focus belongs on THEIR screen (peersOnProject) — a project is a separate
* canvas with its own nodes and its own flow coordinates. null = no project open.
@@ -346,6 +372,12 @@ export class PresenceHub {
if (!this.allow(senderId, IPC.presenceChat, text)) return
this.setChat(senderId, text)
})
+ // The dino snapshot is a dumb-reflector cast like chat: rate-limit (a stop is an exempt clear —
+ // see isClearingCast), then sanitize/clamp and set. The sanitize guard cannot be bypassed.
+ p.onWithSender(IPC.presenceDino, (senderId: number, payload: unknown) => {
+ if (!this.allow(senderId, IPC.presenceDino, payload)) return
+ this.setDino(senderId, payload)
+ })
p.onWithSender(IPC.presenceProject, (senderId: number, projectId: string | null) => {
// NOT exempted, unlike the clears: every project cast may carry a NEW id, so it always
// broadcasts — an unlimited one would hand a hostile tab the same N-way amplifier the buckets
diff --git a/src/renderer/state/presence-session.test.ts b/src/renderer/state/presence-session.test.ts
index be59ac6de..3cd33d1b3 100644
--- a/src/renderer/state/presence-session.test.ts
+++ b/src/renderer/state/presence-session.test.ts
@@ -78,6 +78,7 @@ describe('createPresenceSession — per-instance isolation', () => {
chat: null,
typing: null,
projectId: 'web',
+ dino: null,
kind: 'browser'
})
sa.store.setState({ myId: 1, peers: { 1: peer(1), 5: peer(5) } })
diff --git a/src/renderer/state/presence.test.ts b/src/renderer/state/presence.test.ts
index 8099330ab..265c63a28 100644
--- a/src/renderer/state/presence.test.ts
+++ b/src/renderer/state/presence.test.ts
@@ -27,6 +27,7 @@ function peer(clientId: number, over: Partial<PeerState> = {}): PeerState {
chat: null,
typing: null,
projectId: 'web',
+ dino: null,
kind: 'browser',
...over
}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index fbb6f9f02..15e8059d6 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -79,6 +79,9 @@ export const IPC = {
presenceCursor: 'presence:cursor',
presenceFocus: 'presence:focus',
presenceChat: 'presence:chat',
+ // The authority's live dino game snapshot (a cast, ~20 Hz). Ephemeral, like chat: spectators on
+ // the same project render it; the hub sanitizes/clamps it (sanitizeDinoPayload).
+ presenceDino: 'presence:dino',
// Which project (canvas) the client is looking at. Cursors/focus are only meaningful to a
// viewer on the same project — each project has its own nodes and coordinate space.
presenceProject: 'presence:project',
diff --git a/src/shared/presence.test.ts b/src/shared/presence.test.ts
index 17cd61d29..f78f564d9 100644
--- a/src/shared/presence.test.ts
+++ b/src/shared/presence.test.ts
@@ -6,6 +6,9 @@ import {
nextFreeColor,
peersOnProject,
sanitizeIdentity,
+ sanitizeDinoPayload,
+ DINO_MAX_OBSTACLES,
+ REF_MAX_LEN,
CHAT_MAX_LEN,
NAME_MAX_LEN,
type PeerDiff,
@@ -22,6 +25,7 @@ function peer(clientId: number, projectId: string | null): PeerState {
chat: null,
typing: null,
projectId,
+ dino: null,
kind: 'browser'
}
}
@@ -202,3 +206,100 @@ describe('peersOnProject (the one project filter: cursors, bubbles, node chips)'
expect(peersOnProject(peers, 'web').some((p) => p.projectId === null)).toBe(false)
})
})
+
+describe('sanitizeDinoPayload (the one door for an untrusted dino cast)', () => {
+ const validSnap = {
+ y: -10,
+ ducking: false,
+ crashed: false,
+ started: true,
+ score: 7,
+ speed: 6,
+ groundScroll: 33,
+ obstacles: [{ kind: 'cactus', x: 200, y: 0, sx: 4, sw: 20, sh: 40, flap: 0 }]
+ }
+
+ it('passes a well-formed payload through, capping the nodeId', () => {
+ const out = sanitizeDinoPayload({ nodeId: 'dino-a', snap: validSnap })
+ expect(out).toEqual({ nodeId: 'dino-a', snap: validSnap })
+ // The nodeId is a reflected ref like focus → capped at REF_MAX_LEN.
+ const long = sanitizeDinoPayload({ nodeId: 'n'.repeat(REF_MAX_LEN + 500), snap: validSnap })
+ expect(long?.nodeId).toBe('n'.repeat(REF_MAX_LEN))
+ })
+
+ it('clamps obstacles to the first DINO_MAX_OBSTACLES', () => {
+ const many = Array.from({ length: DINO_MAX_OBSTACLES + 10 }, (_, i) => ({
+ kind: 'bird' as const,
+ x: i,
+ y: 0,
+ sx: 0,
+ sw: 1,
+ sh: 1,
+ flap: 0
+ }))
+ const out = sanitizeDinoPayload({ nodeId: 'd', snap: { ...validSnap, obstacles: many } })
+ expect(out?.snap.obstacles).toHaveLength(DINO_MAX_OBSTACLES)
+ expect(out?.snap.obstacles.map((o) => o.x)).toEqual(
+ Array.from({ length: DINO_MAX_OBSTACLES }, (_, i) => i)
+ )
+ })
+
+ it('coerces non-finite numbers to 0 and booleans, for the snap and each obstacle', () => {
+ const out = sanitizeDinoPayload({
+ nodeId: 'd',
+ snap: {
+ y: Number.NaN,
+ ducking: 'yes',
+ crashed: 0,
+ started: 1,
+ score: Number.POSITIVE_INFINITY,
+ speed: '6',
+ groundScroll: null,
+ obstacles: [{ kind: 'cactus', x: 'oops', y: Number.NaN, sx: 1, sw: 2, sh: 3, flap: 4 }]
+ }
+ })
+ expect(out?.snap).toMatchObject({
+ y: 0,
+ ducking: true,
+ crashed: false,
+ started: true,
+ score: 0,
+ speed: 6, // Number('6') → 6
+ groundScroll: 0
+ })
+ expect(out?.snap.obstacles[0]).toEqual({ kind: 'cactus', x: 0, y: 0, sx: 1, sw: 2, sh: 3, flap: 4 })
+ })
+
+ it('drops an obstacle whose kind is not cactus|bird', () => {
+ const out = sanitizeDinoPayload({
+ nodeId: 'd',
+ snap: {
+ ...validSnap,
+ obstacles: [
+ { kind: 'ufo', x: 1, y: 0, sx: 0, sw: 1, sh: 1, flap: 0 },
+ { kind: 'bird', x: 2, y: 0, sx: 0, sw: 1, sh: 1, flap: 0 },
+ { x: 3, y: 0, sx: 0, sw: 1, sh: 1, flap: 0 } // no kind
+ ]
+ }
+ })
+ expect(out?.snap.obstacles).toEqual([{ kind: 'bird', x: 2, y: 0, sx: 0, sw: 1, sh: 1, flap: 0 }])
+ })
+
+ it('returns null for anything malformed (missing/empty nodeId, non-object, missing snap)', () => {
+ expect(sanitizeDinoPayload(null)).toBeNull()
+ expect(sanitizeDinoPayload('nope')).toBeNull()
+ expect(sanitizeDinoPayload(42)).toBeNull()
+ expect(sanitizeDinoPayload({})).toBeNull()
+ expect(sanitizeDinoPayload({ snap: validSnap })).toBeNull() // no nodeId
+ expect(sanitizeDinoPayload({ nodeId: '', snap: validSnap })).toBeNull() // empty nodeId
+ expect(sanitizeDinoPayload({ nodeId: 5, snap: validSnap })).toBeNull() // non-string nodeId
+ expect(sanitizeDinoPayload({ nodeId: 'd' })).toBeNull() // no snap
+ expect(sanitizeDinoPayload({ nodeId: 'd', snap: null })).toBeNull() // null snap
+ expect(sanitizeDinoPayload({ nodeId: 'd', snap: 'bad' })).toBeNull() // non-object snap
+ })
+
+ it('tolerates a missing/non-array obstacles field (empty list, not null)', () => {
+ expect(sanitizeDinoPayload({ nodeId: 'd', snap: { ...validSnap, obstacles: undefined } })?.snap.obstacles).toEqual([])
+ expect(sanitizeDinoPayload({ nodeId: 'd', snap: { ...validSnap, obstacles: 'x' } })?.snap.obstacles).toEqual([])
+ })
+})
diff --git a/src/shared/presence.ts b/src/shared/presence.ts
index 812419f24..aa1253d6f 100644
--- a/src/shared/presence.ts
+++ b/src/shared/presence.ts
@@ -32,9 +32,43 @@ export interface PeerState {
* project has its OWN node set and flow coordinate space, so cursor/focus only mean anything
* to a viewer on the same project — see peersOnProject. */
projectId: string | null
+ /** The live dino game this peer is the AUTHORITY for, or null. Ephemeral like `chat`: cleared
+ * when the peer stops playing / closes the node / leaves. A spectator renders `snap` for the
+ * matching node id instead of running its own sim. Sanitized/clamped at the hub
+ * (sanitizeDinoPayload) so a malformed/oversized cast can never flood the wire. */
+ dino: { nodeId: string; snap: DinoSnapshot } | null
kind: 'browser' | 'phone' | 'desktop'
}
+/** One on-screen obstacle in a dino snapshot (a cactus or a bird), with the sprite-sheet source
+ * rect a spectator needs to draw it (sx/sw/sh) and the bird wing phase (flap). */
+export interface DinoObstacleSnap {
+ kind: 'cactus' | 'bird'
+ x: number
+ y: number
+ sx: number
+ sw: number
+ sh: number
+ flap: number
+}
+
+/** The minimal per-frame state a spectator needs to draw one dino frame. Small (a handful of
+ * numbers + ≤ DINO_MAX_OBSTACLES obstacles); broadcast by the authority ~20 Hz, never persisted. */
+export interface DinoSnapshot {
+ y: number
+ ducking: boolean
+ crashed: boolean
+ started: boolean
+ score: number
+ speed: number
+ groundScroll: number
+ obstacles: DinoObstacleSnap[]
+}
+
+/** Max obstacles a snapshot may carry. The hub clamps to this (like CHAT_MAX_LEN) so a malformed
+ * or oversized cast can't flood the wire — a real run only has a handful on screen at once. */
+export const DINO_MAX_OBSTACLES = 12
+
export type PeerDiff =
| { op: 'join'; peer: PeerState }
/** `clientId` is the identity key and is carried by the diff itself — a patch can never
@@ -147,3 +181,59 @@ export function sanitizeIdentity(raw: unknown, fallback: PeerIdentity): PeerIden
typeof r.color === 'string' && PRESENCE_COLORS.includes(r.color) ? r.color : fallback.color
return { name: name || fallback.name, color }
}
+
+/** Coerce an untrusted value into a finite number: a non-number, NaN or ±Infinity → 0. Snapshot
+ * numbers are drawn straight onto a canvas, so a NaN/Infinity off the wire must never survive. */
+function finiteNum(v: unknown): number {
+ const n = Number(v)
+ return Number.isFinite(n) ? n : 0
+}
+
+/** One obstacle off the wire → a safe DinoObstacleSnap, or null to DROP it (bad/absent kind). */
+function sanitizeDinoObstacle(raw: unknown): DinoObstacleSnap | null {
+ if (typeof raw !== 'object' || raw === null) return null
+ const o = raw as Record<string, unknown>
+ if (o.kind !== 'cactus' && o.kind !== 'bird') return null
+ return {
+ kind: o.kind,
+ x: finiteNum(o.x),
+ y: finiteNum(o.y),
+ sx: finiteNum(o.sx),
+ sw: finiteNum(o.sw),
+ sh: finiteNum(o.sh),
+ flap: finiteNum(o.flap)
+ }
+}
+
+/** THE one door for an untrusted dino cast (the hub applies ONLY this value). Returns null unless
+ * the payload is `{ nodeId: non-empty string, snap: {...} }`; caps the nodeId at REF_MAX_LEN like
+ * focus, coerces every snap number to finite (garbage → 0) and every flag to boolean, and CLAMPS
+ * obstacles to the first DINO_MAX_OBSTACLES (each sanitized; a bad-kind one is dropped). Anything
+ * malformed → null, so the flood/garbage guard cannot be bypassed. */
+export function sanitizeDinoPayload(
+ payload: unknown
+): { nodeId: string; snap: DinoSnapshot } | null {
+ if (typeof payload !== 'object' || payload === null) return null
+ const p = payload as Record<string, unknown>
+ if (typeof p.nodeId !== 'string' || p.nodeId === '') return null
+ const nodeId = capCodePoints(p.nodeId, REF_MAX_LEN)
+ if (typeof p.snap !== 'object' || p.snap === null) return null
+ const s = p.snap as Record<string, unknown>
+ const rawObstacles = Array.isArray(s.obstacles) ? s.obstacles : []
+ const obstacles: DinoObstacleSnap[] = []
+ for (const raw of rawObstacles.slice(0, DINO_MAX_OBSTACLES)) {
+ const ob = sanitizeDinoObstacle(raw)
+ if (ob) obstacles.push(ob)
+ }
+ const snap: DinoSnapshot = {
+ y: finiteNum(s.y),
+ ducking: Boolean(s.ducking),
+ crashed: Boolean(s.crashed),
+ started: Boolean(s.started),
+ score: finiteNum(s.score),
+ speed: finiteNum(s.speed),
+ groundScroll: finiteNum(s.groundScroll),
+ obstacles
+ }
+ return { nodeId, snap }
+}