Seeing everything without breaking anything: the admin console

Live players and rooms, every hero rendered with the game's own panels, a self-hosted history, and audited levers that change a live hero through the room that owns it.

The admin console Live page listing twelve online players and one room with its tick timings
Contents
  1. The brief
  2. The rule: never write under a live sim
  3. Reusing the game's panels
  4. Sorting heroes by an act that isn't a column
  5. History without a metrics stack
  6. Two ways in
  7. Numbers
  8. What's still open
  9. Related posts

One place to see who is online, everyone who has played, and every hero down to its last item. The first /admin landed by the 16:58 checkpoint; it's ~5,400 lines across server/admin, server/game/admin, server/routers/admin and src/admin, four tables and one migration.

The brief

One Opus 5.5 agent (ADMIN), five pages and one constraint:

  • Live: who's online, in which room, room and process health
  • Accounts and Characters: searchable, sortable, with detail pages
  • History: charts plus a feed of notable events
  • Log: play sessions and an audit trail
  • Levers: kick, broadcast, mute, ban, give gold or items, send to town, grant a pet, undo a hardcore death, close a room

The constraint: an admin action on an online hero goes through the room that owns that hero.

The rule: never write under a live sim

While a hero is online, its SimPlayer is the truth, and each room save (every 30 s when dirty, on transfer, on leave) rewrites the whole Character row. A direct gold = gold + 1000 would be silently overwritten by the next save.

Each room registers an AdminRoomOps with the hub as RoomHandle.admin:

server/game/admin/roomOps.tsTypeScript
export interface AdminRoomOps {
  info(): AdminRoomInfo
  players(): AdminLivePlayer[]
  /** the live sheet (inventory, stats, derived) of a character in this room */
  sheet(characterId: string): CharacterSheet | null
  kick(characterId: string, reason: string, code: number): boolean
  /** null on success, else why not */
  giveGold(characterId: string, amount: number): string | null
  /** into the bag, or at their feet when the bag is full; returns where it went, or an error */
  giveItem(
    characterId: string,
    item: ItemInstance
  ): { ok: true; where: 'bag' | 'ground' } | { ok: false; error: string }
  toTown(characterId: string): string | null
  /** kick everyone and dispose the room */
  close(reason: string): void
}

Online: through the room. Offline: onto the hero's save chain, the same promise queue rooms use, so it can't race a logout's save still in flight.

Diagram of the gift path: console, adminProcedure, hub lookup, then either the live room or the save queue
One lookup decides the path. Online heroes change inside the sim; offline heroes change on their save chain

Both branches, including a login between the check and the write:

server/routers/admin/actions.tsTypeScript
giveItem: adminProcedure
  .input(z.object({ characterId: Id, spec: GiveItemSpecZ }))
  .mutation(async ({ ctx, input }) => {
    const c = await characterOrThrow(input.characterId)
    const item = buildGiftItem(freshRng(), input.spec)
    const ops = liveOps(c.id)
    let where: 'bag' | 'ground'
    let via: 'room' | 'db'
    if (ops) {
      const r = ops.giveItem(c.id, item)
      if (!r.ok) throw new TRPCError({ code: 'CONFLICT', message: r.error })
      where = r.where
      via = 'room'
    } else {
      const loaded = await loadCharacter(c.id, c.accountId)
      if (!loaded) throw new TRPCError({ code: 'NOT_FOUND' })
      const next = pickupItem(loaded.save.inventory, item)
      if (!next) throw new TRPCError({ code: 'CONFLICT', message: `${c.name}'s bag is full` })
      if (hub.get(c.id))
        throw new TRPCError({ code: 'CONFLICT', message: `${c.name} just logged in; try again` })
      const { inventory } = characterWriteData({ save: { ...loaded.save, inventory: next } })
      await queueCharacterWrite(c.id, Promise.resolve(), () =>
        prisma.character.update({ where: { id: c.id }, data: { inventory } })
      )
      where = 'bag'
      via = 'db'
    }
    await writeAudit(ctx.actor, 'give_item', { id: c.id, name: c.name }, { /* item, rarity, ilvl, uid, where, via */ })
Action Online Offline
kick socket closed with code 4003 and a reason; the client shows it and doesn't auto-reconnect n/a
broadcast an [Admin] … system line in chat, to every room or one n/a
mute hub flag on every online hero of the account Account.mutedUntil
ban every online hero closed with 4004 Account.bannedAt, refused in tRPC, login and onAuth
give gold / item through RoomHandle.admin, then a save request on the hero's save queue
send to town the room's own waypoint transfer (or respawn if dead) zoneId = act town, x = y = -1
undo hardcore death kick the ghost first, then clear dead clear dead
close room room.disconnect(): everyone saved, clients rejoin a fresh instance n/a

Bans cover every entrance: accountProcedure, account.login, and both rooms' onAuth. /play shows the reason instead of a spinner.

Reusing the game's panels

The character page has no new UI: it renders the game's StatsSheet, InventoryPanel, SkillTree and ItemGrid with real tooltips. They were presentational from the first hour (a ui.md rule), so the admin agent just fed them props.

A level 99 Stalker's detail page: the game's stats sheet, inventory doll and skill tree, rendered inside the admin console
Palewind, one of the forty showcase heroes, as the admin sees it: the real StatsSheet, InventoryPanel and SkillTree components, with the gift form above
  • Online: the sheet comes from AdminRoomOps.sheet, refreshed every 5 s, with buffs, pet bonus and current life
  • Offline: derived from the save, labelled "Offline: the numbers are derived from the save (no pet, shrine or Lantern bonuses)"
  • Below: quests and waypoints for all three difficulties, pet, house, event timeline, every session
The same hero's timeline: deaths and unique drops across the Shattered Isles and the Hollow Sanctum, then the session list
Death after death at level 99: the forty-hero pack against the Hollow Saint

Palewind's feed, a column of "died at level 99 in the Hollow Sanctum", is the best record of the forty-hero stress test.

Sorting heroes by an act that isn't a column

Progress lives in a JSON array of waypoint ids like a4_town. Rather than add a column and a second source of truth, it's computed in SQL, with sorts whitelisted:

server/routers/admin/players.tsTypeScript
/** highest act whose town the hero has a waypoint to (1–6) */
const ACT_SQL = Prisma.sql`COALESCE((SELECT max(substring(w FROM '^a([0-9])_')::int)
  FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(c.waypoints) = 'array'
    THEN c.waypoints ELSE '[]'::jsonb END) AS w), 1)`
 
const CHARACTER_SORTS: Record<(typeof CHARACTER_SORT_KEYS)[number], Prisma.Sql> = {
  name: Prisma.sql`c."nameLower"`,
  level: Prisma.sql`c.level`,
  act: Prisma.sql`act`,
  // … gold, playtime, deaths, kills, rift, lastPlayed, created
}

A zod enum picks a prebuilt Prisma.sql fragment, so input never reaches the SQL text. Server-side pagination, 50 per page with count(*) OVER (); the dev database had 230 heroes by evening.

The characters table: filters for class, level, act, difficulty, mode, online and recency
Five bots online (green dots) above the level 99 showcase pack. Every column sorts server-side

History without a metrics stack

No Prometheus, Grafana or third-party analytics. Three tables the game writes itself:

  • PlaySession: a pure SessionTracker on the hub's presence hooks. Re-register within the 30 s grace (transfer, trip home) extends the session and appends the zone; crash-orphaned rows close at lastSeenAt on boot.
  • GameEvent: level-ups, deaths, hardcore deaths, boss kills, unique and set drops, quests. recordGameEvent() only pushes to memory; a recorder createManys every 5 s, re-queues on failure, caps at 5,000. No I/O in the tick.
  • MetricSample: one row a minute (online, rooms, RSS, heap, tick p95), kept 30 days.

Chart rules: one axis, 2 px line with a 10% wash, columns ≤ 24 px with rounded ends, hairline grid, a tooltip on every mark, a legend only for two series, colours checked for colour-vision-deficiency separation.

Events and charts: players online, new accounts and sessions per day, heroes by class and by level
The dev database after one day: 223 accounts, 230 heroes, 985 logged sessions. The spike at level 96–99 is the showcase pack

Privacy, per decisions.md: IPs stored only as sha256(salt | ip) truncated to 16 hex characters (enough to spot a returning player on a new guest account, useless if leaked); user agents trimmed to 160 characters. The Live page samples event-loop lag from a 250 ms timer's drift, CPU from process.cpuUsage(), and per-socket bytes and ping from the transport's 5 s pings.

Two ways in

ADMIN_USERNAMES matches claimed game accounts, but a fresh database, restored backup or new environment has nobody who qualifies. So an ADMIN-LOGIN agent added a standalone login, in by the 17:38 checkpoint:

server/admin/session.tsTypeScript
/** Constant-time: both sides are hashed to 32 bytes first, so lengths never leak. Empty config = disabled. */
export function checkAdminLogin(username: string, password: string, creds = ENV_CREDS): boolean {
  if (!creds.login || !creds.password) return false
  const userOk = timingSafeEqual(sha256(username.trim().toLowerCase()), sha256(creds.login.toLowerCase()))
  const passOk = timingSafeEqual(sha256(password), sha256(creds.password))
  return userOk && passOk
}
 
function signingKey(creds: AdminCredentials): Buffer {
  return sha256(`duskbound-admin-key:${creds.login.toLowerCase()}:${creds.password}`)
}
 
export function signAdminToken(creds = ENV_CREDS, now = Date.now()): string {
  const expiry = now + ADMIN_TOKEN_TTL_MS
  return `${expiry}.${mac(expiry, creds)}`
}
  • No session table: <expiryMs>.<hmacSha256>, keyed on login plus password, so changing ADMIN_PASSWORD revokes every token
  • Rate limit: 10 failures per 5 minutes per IP (last X-Forwarded-For hop, behind Caddy)
  • Transport: localStorage['gr.adminToken'] sent as X-Admin-Token, separate from the game bearer; no game account needed
  • Either path yields a ctx.actor for the audit row:
server/trpc.tsTypeScript
export const adminProcedure = t.procedure.use(({ ctx, next }) => {
  let actor: AdminActor
  if (ctx.adminSession) actor = { id: `admin:${adminLoginName()}`, username: adminLoginName() }
  else if (ctx.account && isAdminAccount(ctx.account)) actor = ctx.account
  else if (!ctx.account) throw new TRPCError({ code: 'UNAUTHORIZED' })
  else throw new TRPCError({ code: 'FORBIDDEN', message: 'Not authorized' })
  return next({ ctx: { ...ctx, actor } })
})
The admin sign-in form: username, password, sign in
Anyone who isn't an admin gets this form. admin.me only ever answers yes or no

Credentials live in the gitignored .env locally and in Drydock's SSM parameters in production; either empty disables the login. Every procedure checks on the server; the client route guard is presentation only.

Numbers

Size ~5,450 lines plus the 20260927233618_admin migration
Tests 20 in server/admin and server/game/admin (gate, ban refusal, sessions, presence and mute, gifts, token sign/verify/expiry/tamper, password rotation, limiter)
Hooks only at // admin: lines: hub, both rooms, five sim modules, the account router, the routes
Refresh Live every 2.5 s, online sheet every 5 s
An account page: the softcore stash in the game's own ItemGrid, the separate hardcore stash, 37 pets and the session list
Account detail: the stash grid is the game's ItemGrid with real tooltips; moderation sits at the top

What's still open

Bans are per account, and a new guest takes five seconds because the game needs no email. Hashed IPs let an admin spot that by hand; there's no IP ban.