diff --git a/src/app/(frontend)/minigames/blackjack/actions.ts b/src/app/(frontend)/minigames/blackjack/actions.ts index 9efa5e3a..a5e3ba0d 100644 --- a/src/app/(frontend)/minigames/blackjack/actions.ts +++ b/src/app/(frontend)/minigames/blackjack/actions.ts @@ -7,17 +7,21 @@ import config from "@payload-config"; import { getPayload } from "payload"; -import type { BlackjackActionKind } from "@/lib/minigames/blackjack/types"; +import type { Payload } from "payload"; +import type { BlackjackActionKind, Card } from "@/lib/minigames/blackjack/types"; import { isSuperuser } from "@/utils/access-control/hasPermission"; import { + adjustBankroll, applyBlackjackAction, createTable, forceExpireTable, getSnapshotFor, + injectNextCard, joinTableWithBuyIn, leaveTableWithBuyIn, listSummaries, renameTable, + setDealerHand, spectateTable, startGameWithBuyIn, type BlackjackSnapshot, @@ -69,6 +73,13 @@ function userName(user: UserLike): string { return `Player ${user.id}`; } +/** Audit line for every multiplayer admin action taken from the dev console. */ +function auditDevAction(payload: Payload, userId: number, action: string, target: string): void { + payload.logger.info( + `[dev-admin] user=${userId} game=blackjack action=${action} target=${target}`, + ); +} + export async function createBlackjackTable(): Promise> { try { const { user } = await authenticate(); @@ -95,6 +106,7 @@ export async function forceExpireBlackjackTable(tableId: string): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = adjustBankroll(tableId, Number(user.id), seatId, delta); + auditDevAction(payload, Number(user.id), "adjust-bankroll", `${tableId}/seat-${seatId}`); + return { success: true, data: snapshot }; + } catch (error) { + return toError(error); + } +} + +export async function forceBlackjackNextCard( + tableId: string, + card: Card, +): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = injectNextCard(tableId, Number(user.id), card); + auditDevAction(payload, Number(user.id), "force-next-card", tableId); + return { success: true, data: snapshot }; + } catch (error) { + return toError(error); + } +} + +export async function setBlackjackDealerHand( + tableId: string, + cards: Card[], +): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = setDealerHand(tableId, Number(user.id), cards); + auditDevAction(payload, Number(user.id), "set-dealer-hand", tableId); + return { success: true, data: snapshot }; + } catch (error) { + return toError(error); + } +} diff --git a/src/app/(frontend)/minigames/bomperator/actions.ts b/src/app/(frontend)/minigames/bomperator/actions.ts index 94a1dbc1..d2e79cc2 100644 --- a/src/app/(frontend)/minigames/bomperator/actions.ts +++ b/src/app/(frontend)/minigames/bomperator/actions.ts @@ -17,14 +17,17 @@ import config from "@payload-config"; import { getPayload } from "payload"; +import type { Payload } from "payload"; import { SignJWT } from "jose"; import { isSuperuser } from "@/utils/access-control/hasPermission"; import type { + BomperatorAdminCommand, BomperatorMatchSummary, BomperatorView, } from "@/lib/minigames/bomperator/types"; import type { BomperatorInput } from "@/lib/minigames/bomperator/engine"; import { + applyAdminCommandFor, createMatch, endMatch, forceExpireMatch, @@ -36,7 +39,7 @@ import { submitInput, } from "@/lib/minigames/bomperator/registry"; -export type { BomperatorMatchSummary, BomperatorView, BomperatorInput }; +export type { BomperatorAdminCommand, BomperatorMatchSummary, BomperatorView, BomperatorInput }; interface ActionResult { success: boolean; @@ -81,6 +84,48 @@ function userName(user: UserLike): string { return `Operator ${user.id}`; } +/** Audit line for every multiplayer admin action taken from the dev console. */ +function auditDevAction(payload: Payload, userId: number, action: string, target: string): void { + payload.logger.info( + `[dev-admin] user=${userId} game=bomperator action=${action} target=${target}`, + ); +} + +const ADMIN_COMMAND_KINDS = new Set([ + "destroyCrates", + "grantPickup", + "eliminate", + "freeze", + "suddenDeathNow", + "setRoundTimer", + "endRound", +]); + +/** Reject anything that is not a known command shape before it reaches the engine. */ +function isValidAdminCommand(cmd: unknown): cmd is BomperatorAdminCommand { + if (typeof cmd !== "object" || cmd === null) return false; + const kind = (cmd as { kind?: unknown }).kind; + if (typeof kind !== "string" || !ADMIN_COMMAND_KINDS.has(kind)) return false; + const record = cmd as Record; + switch (kind) { + case "grantPickup": + return ( + typeof record.seat === "number" && + ["bomb", "range", "speed", "kick"].includes(String(record.pickup)) + ); + case "eliminate": + return typeof record.seat === "number"; + case "freeze": + return typeof record.frozen === "boolean"; + case "setRoundTimer": + return typeof record.ticks === "number" && Number.isFinite(record.ticks); + case "endRound": + return record.winnerSeat === null || typeof record.winnerSeat === "number"; + default: + return true; + } +} + /* ------------------------------------------------------------------ arena */ /** Internal (server-reachable) base URL of the arena process. */ @@ -288,6 +333,7 @@ export async function forceExpireBomperatorMatch( if (!allowed) { return { success: false, error: "Only administrators can force-end matches." }; } + auditDevAction(payload, Number(user.id), "force-expire-match", matchId); if (ARENA_ENABLED) { await arenaCall("POST", "/matches/force-expire", { matchId }); return { success: true }; @@ -298,3 +344,33 @@ export async function forceExpireBomperatorMatch( return toError(error); } } + +/** + * Dev-console admin command for a live Ordnance Disposal match. Superuser-only; + * the command is validated against the known set before it reaches either + * transport (arena REST proxy or in-process registry). Cheats ride the normal + * snapshot fan-out, so every client sees them by next tick. + */ +export async function bomperatorAdminCommand( + matchId: string, + cmd: BomperatorAdminCommand, +): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + if (!isValidAdminCommand(cmd)) { + return { success: false, error: "Invalid admin command." }; + } + auditDevAction(payload, Number(user.id), `cmd:${cmd.kind}`, matchId); + if (ARENA_ENABLED) { + return await arenaCall("POST", "/matches/admin", { matchId, cmd }); + } + applyAdminCommandFor(matchId, cmd); + return { success: true }; + } catch (error) { + return toError(error); + } +} diff --git a/src/app/(frontend)/minigames/bomperator/page.tsx b/src/app/(frontend)/minigames/bomperator/page.tsx index 25ea6634..4c1b40f5 100644 --- a/src/app/(frontend)/minigames/bomperator/page.tsx +++ b/src/app/(frontend)/minigames/bomperator/page.tsx @@ -7,6 +7,7 @@ import { Bomb } from "lucide-react"; import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; import { BomperatorArena } from "@/components/frontend/minigames/bomperator/BomperatorArena"; export const metadata: Metadata = { @@ -35,6 +36,8 @@ export default async function BomperatorPage({ searchParams }: BomperatorPagePro return ; } + const superuser = await isSuperuser(payload, user); + const profileRes = await payload.find({ collection: "profiles", where: { user: { equals: Number(user.id) } }, @@ -81,6 +84,7 @@ export default async function BomperatorPage({ searchParams }: BomperatorPagePro initialStats={stats} currentUserId={Number(user.id)} initialMatchId={initialMatchId} + isSuperuser={superuser} /> ); diff --git a/src/app/(frontend)/minigames/call-for-fire-versus/actions.ts b/src/app/(frontend)/minigames/call-for-fire-versus/actions.ts index b5a0f785..1bf00ec1 100644 --- a/src/app/(frontend)/minigames/call-for-fire-versus/actions.ts +++ b/src/app/(frontend)/minigames/call-for-fire-versus/actions.ts @@ -8,14 +8,17 @@ import config from "@payload-config"; import { getPayload } from "payload"; +import type { Payload } from "payload"; import { isSuperuser } from "@/utils/access-control/hasPermission"; import type { + VersusAdminCommand, VersusMatchSummary, VersusMatchView, } from "@/lib/minigames/call-for-fire-versus/types"; import type { FobPlacement } from "@/lib/minigames/call-for-fire-versus/constants"; import type { VersusShotInput } from "@/lib/minigames/call-for-fire-versus/engine"; import { + applyAdminCommandFor, createMatch, fireShotFor, forceExpireMatch, @@ -26,7 +29,7 @@ import { placeFleetFor, } from "@/lib/minigames/call-for-fire-versus/registry"; -export type { VersusMatchSummary, VersusMatchView, VersusShotInput, FobPlacement }; +export type { VersusAdminCommand, VersusMatchSummary, VersusMatchView, VersusShotInput, FobPlacement }; interface ActionResult { success: boolean; @@ -71,6 +74,31 @@ function userName(user: UserLike): string { return `Operator ${user.id}`; } +/** Audit line for every multiplayer admin action taken from the dev console. */ +function auditDevAction(payload: Payload, userId: number, action: string, target: string): void { + payload.logger.info( + `[dev-admin] user=${userId} game=cff-versus action=${action} target=${target}`, + ); +} + +/** Reject anything that is not a known command shape before it reaches the engine. */ +function isValidAdminCommand(cmd: unknown): cmd is VersusAdminCommand { + if (typeof cmd !== "object" || cmd === null) return false; + const record = cmd as Record; + switch (record.kind) { + case "revealFleets": + return typeof record.on === "boolean"; + case "forceShotResult": + return ( + record.outcome === null || record.outcome === "hit" || record.outcome === "miss" + ); + case "skipTurn": + return true; + default: + return false; + } +} + export async function createVersusMatch(): Promise> { try { const { user } = await authenticate(); @@ -149,9 +177,36 @@ export async function forceExpireVersusMatch(matchId: string): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + if (!isValidAdminCommand(cmd)) { + return { success: false, error: "Invalid admin command." }; + } + auditDevAction(payload, Number(user.id), `cmd:${cmd.kind}`, matchId); + applyAdminCommandFor(matchId, cmd); + return { success: true }; + } catch (error) { + return toError(error); + } +} diff --git a/src/app/(frontend)/minigames/call-for-fire-versus/page.tsx b/src/app/(frontend)/minigames/call-for-fire-versus/page.tsx index 5a7b24f6..f090c272 100644 --- a/src/app/(frontend)/minigames/call-for-fire-versus/page.tsx +++ b/src/app/(frontend)/minigames/call-for-fire-versus/page.tsx @@ -7,6 +7,7 @@ import { Swords } from "lucide-react"; import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; import { CallForFireVersusArena } from "@/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena"; export const metadata: Metadata = { @@ -35,6 +36,8 @@ export default async function CallForFireVersusPage({ searchParams }: VersusPage return ; } + const superuser = await isSuperuser(payload, user); + const profileRes = await payload.find({ collection: "profiles", where: { user: { equals: Number(user.id) } }, @@ -81,6 +84,7 @@ export default async function CallForFireVersusPage({ searchParams }: VersusPage initialStats={stats} currentUserId={Number(user.id)} initialMatchId={initialMatchId} + isSuperuser={superuser} /> ); diff --git a/src/app/(frontend)/minigames/call-for-fire/page.tsx b/src/app/(frontend)/minigames/call-for-fire/page.tsx index 918a8828..18293170 100644 --- a/src/app/(frontend)/minigames/call-for-fire/page.tsx +++ b/src/app/(frontend)/minigames/call-for-fire/page.tsx @@ -7,6 +7,7 @@ import { Target } from "lucide-react"; import { CallForFireArena } from "@/components/frontend/minigames/call-for-fire/CallForFireArena"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; export const metadata: Metadata = { title: "Call for Fire (Polaris Task Force)", @@ -23,6 +24,8 @@ export default async function CallForFirePage() { redirect(`/login?returnTo=${encodeURIComponent("/minigames/call-for-fire")}`); } + const superuser = await isSuperuser(payload, user); + const release = await getMinigameReleaseState(payload, "callForFire"); const profileRes = await payload.find({ @@ -66,7 +69,11 @@ export default async function CallForFirePage() {

- + ); } diff --git a/src/app/(frontend)/minigames/eod/page.tsx b/src/app/(frontend)/minigames/eod/page.tsx index 2afb02ac..05f5ec97 100644 --- a/src/app/(frontend)/minigames/eod/page.tsx +++ b/src/app/(frontend)/minigames/eod/page.tsx @@ -6,6 +6,7 @@ import { redirect } from "next/navigation"; import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; import { Bomb } from "lucide-react"; import { EodArena } from "@/components/frontend/minigames/eod/EodArena"; @@ -29,6 +30,8 @@ export default async function EodPage() { return ; } + const superuser = await isSuperuser(payload, user); + const profileRes = await payload.find({ collection: "profiles", where: { user: { equals: user.id as number } }, @@ -70,7 +73,7 @@ export default async function EodPage() {

- + ); } diff --git a/src/app/(frontend)/minigames/flappy/page.tsx b/src/app/(frontend)/minigames/flappy/page.tsx index 510c4ccd..d4ee24d5 100644 --- a/src/app/(frontend)/minigames/flappy/page.tsx +++ b/src/app/(frontend)/minigames/flappy/page.tsx @@ -8,6 +8,7 @@ import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBann import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; import { Bird } from "lucide-react"; import { FlappyArena } from "@/components/frontend/minigames/flappy/FlappyArena"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; export const metadata: Metadata = { title: "Flight Simulator: Polaris Task Force", @@ -29,6 +30,8 @@ export default async function FlappyPage() { return ; } + const superuser = await isSuperuser(payload, user); + const profileRes = await payload.find({ collection: "profiles", where: { user: { equals: user.id as number } }, @@ -63,12 +66,11 @@ export default async function FlappyPage() {

Flight Simulator

- An unofficial side activity. Earn 1 XP per 15 obstacles - passed in a single run. + An unofficial side activity. Earn 1 XP per 15 obstacles passed in a single run.

- + ); } diff --git a/src/app/(frontend)/minigames/opord/page.tsx b/src/app/(frontend)/minigames/opord/page.tsx index 71071c59..484ecb63 100644 --- a/src/app/(frontend)/minigames/opord/page.tsx +++ b/src/app/(frontend)/minigames/opord/page.tsx @@ -6,6 +6,7 @@ import { redirect } from "next/navigation"; import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; import { ScrollText } from "lucide-react"; import { OpordArena } from "@/components/frontend/minigames/opord/OpordArena"; @@ -24,6 +25,8 @@ export default async function OpordPage() { redirect(`/login?returnTo=${encodeURIComponent("/minigames/opord")}`); } + const superuser = await isSuperuser(payload, user); + const release = await getMinigameReleaseState(payload, "opord"); if (release.upcoming && release.game) { return ; @@ -71,7 +74,11 @@ export default async function OpordPage() {

- + ); } diff --git a/src/app/(frontend)/minigames/poker/actions.ts b/src/app/(frontend)/minigames/poker/actions.ts index ace523b1..d77fa5fb 100644 --- a/src/app/(frontend)/minigames/poker/actions.ts +++ b/src/app/(frontend)/minigames/poker/actions.ts @@ -8,16 +8,21 @@ import config from "@payload-config"; import { getPayload } from "payload"; +import type { Payload } from "payload"; import type { Card, PokerActionKind, PrivatePlayerView } from "@/lib/minigames/poker/types"; import { isSuperuser } from "@/utils/access-control/hasPermission"; import { adjustStack, applyPlayerAction, + clockControl, createTable, forceExpireTable, + forceFold, + forceStreet, getSnapshotFor, joinTableWithBuyIn, leaveTableWithBuyIn, + setRevealAll, spectateTable, listSummaries, renameTable, @@ -74,6 +79,15 @@ function userName(user: UserLike): string { return `Player ${user.id}`; } +/** + * Audit line for every multiplayer admin action taken from the dev console. + * Deliberately a logger line, not a game event: these are operator tooling + * traces, not player-facing history (dev console plan decision). + */ +function auditDevAction(payload: Payload, userId: number, action: string, target: string): void { + payload.logger.info(`[dev-admin] user=${userId} game=poker action=${action} target=${target}`); +} + export async function createPokerTable(): Promise> { try { const { user } = await authenticate(); @@ -100,6 +114,7 @@ export async function forceExpirePokerTable(tableId: string): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = forceFold(tableId, Number(user.id), seatId); + auditDevAction(payload, Number(user.id), "force-fold", `${tableId}/seat-${seatId}`); + return { success: true, data: snapshot }; + } catch (error) { + return toError(error); + } +} + +export async function forcePokerStreet(tableId: string): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = forceStreet(tableId, Number(user.id)); + auditDevAction(payload, Number(user.id), "force-street", tableId); + return { success: true, data: snapshot }; + } catch (error) { + return toError(error); + } +} + +export async function setPokerRevealAll( + tableId: string, + enabled: boolean, +): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = setRevealAll(tableId, Number(user.id), enabled); + auditDevAction(payload, Number(user.id), enabled ? "reveal-on" : "reveal-off", tableId); + return { success: true, data: snapshot }; + } catch (error) { + return toError(error); + } +} + +export async function pokerClockControl( + tableId: string, + mode: "reset" | "now", +): Promise> { + try { + const { payload, user } = await authenticate(); + const allowed = await isSuperuser(payload, user); + if (!allowed) { + return { success: false, error: "Only administrators can use dev controls." }; + } + const snapshot = clockControl(tableId, Number(user.id), mode); + auditDevAction(payload, Number(user.id), `clock-${mode}`, tableId); return { success: true, data: snapshot }; } catch (error) { return toError(error); diff --git a/src/app/(frontend)/minigames/qualification/page.tsx b/src/app/(frontend)/minigames/qualification/page.tsx index 95d79d6a..51c5f1ae 100644 --- a/src/app/(frontend)/minigames/qualification/page.tsx +++ b/src/app/(frontend)/minigames/qualification/page.tsx @@ -6,6 +6,7 @@ import { redirect } from "next/navigation"; import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; import { Crosshair } from "lucide-react"; import type { AimTrainerStats } from "@/app/(frontend)/minigames/qualification/actions"; @@ -26,6 +27,8 @@ export default async function QualificationPage() { redirect(`/login?returnTo=${encodeURIComponent("/minigames/qualification")}`); } + const superuser = await isSuperuser(payload, user); + const release = await getMinigameReleaseState(payload, "qualification"); if (release.upcoming && release.game) { return ; @@ -75,7 +78,7 @@ export default async function QualificationPage() {

- + ); } diff --git a/src/app/(frontend)/minigames/radio/page.tsx b/src/app/(frontend)/minigames/radio/page.tsx index 38079f3b..2353f7dc 100644 --- a/src/app/(frontend)/minigames/radio/page.tsx +++ b/src/app/(frontend)/minigames/radio/page.tsx @@ -6,6 +6,7 @@ import { redirect } from "next/navigation"; import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon"; import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner"; import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry"; +import { isSuperuser } from "@/utils/access-control/hasPermission"; import { Radio } from "lucide-react"; import { RadioArena } from "@/components/frontend/minigames/radio/RadioArena"; @@ -24,6 +25,8 @@ export default async function RadioPage() { redirect(`/login?returnTo=${encodeURIComponent("/minigames/radio")}`); } + const superuser = await isSuperuser(payload, user); + const release = await getMinigameReleaseState(payload, "radio"); if (release.upcoming && release.game) { return ; @@ -79,7 +82,11 @@ export default async function RadioPage() {

- + ); } diff --git a/src/arena/games/bomperator.ts b/src/arena/games/bomperator.ts index c96f824e..a39d9679 100644 --- a/src/arena/games/bomperator.ts +++ b/src/arena/games/bomperator.ts @@ -33,6 +33,7 @@ import { TICK_MS, } from "@/lib/minigames/bomperator/constants"; import { + applyAdminCommand, applyInput, createMatchState, dissolveMatch, @@ -41,7 +42,12 @@ import { tick as engineTick, type BomperatorInput, } from "@/lib/minigames/bomperator/engine"; -import type { BomperatorMatchSummary, BomperatorState, BomperatorView } from "@/lib/minigames/bomperator/types"; +import type { + BomperatorAdminCommand, + BomperatorMatchSummary, + BomperatorState, + BomperatorView, +} from "@/lib/minigames/bomperator/types"; import { buildBomperatorView } from "@/lib/minigames/bomperator/views"; import type { ServerMessage } from "../protocol"; import type { RealtimeGameModule } from "./types"; @@ -568,6 +574,24 @@ export class BomperatorGameModule implements RealtimeGameModule { this.disposeMatch(record); } + /** + * Dev-console command entry point (WS transport). Mirrors the registry's + * applyAdminCommandFor exactly: pure command application, version bump, + * snapshot fan-out over sockets, immediate completion handling. + */ + adminCommand(matchId: string, cmd: BomperatorAdminCommand): void { + const record = this.matches.get(matchId); + if (!record) throw new Error("Match not found."); + record.state = applyAdminCommand(record.state, cmd); + record.version += 1; + record.lastActivityAt = Date.now(); + this.pushSnapshots(record); + if (record.state.phase === "complete") { + this.stopTickLoop(record); + this.awardCompleted(record); + } + } + listSummaries(viewerId?: number): BomperatorMatchSummary[] { return [...this.matches.values()].map((record) => ({ matchId: record.id, diff --git a/src/arena/server.ts b/src/arena/server.ts index 21332352..85060d10 100644 --- a/src/arena/server.ts +++ b/src/arena/server.ts @@ -248,6 +248,17 @@ export async function startArena(options: ArenaOptions = {}): Promise game.forceExpire(str("matchId"))); return; } + if (url.pathname === "/matches/admin" && req.method === "POST") { + // Dev-console commands (superuser-gated in the Next action that proxies + // here; this endpoint shares the same x-arena-secret trust as the rest). + const cmd = body.cmd as { kind?: unknown } | undefined; + if (!cmd || typeof cmd.kind !== "string") { + sendJson(res, 200, { success: false, error: "Invalid admin command." }); + return; + } + await run(() => game.adminCommand(str("matchId"), cmd as never)); + return; + } sendJson(res, 404, { success: false, error: "Not found." }); } diff --git a/src/components/frontend/minigames/blackjack/BlackjackArena.tsx b/src/components/frontend/minigames/blackjack/BlackjackArena.tsx index 1839874b..255d999f 100644 --- a/src/components/frontend/minigames/blackjack/BlackjackArena.tsx +++ b/src/components/frontend/minigames/blackjack/BlackjackArena.tsx @@ -14,6 +14,8 @@ import type { BlackjackPhase } from "@/lib/minigames/blackjack"; import { useRealtimePresence } from "@/hooks/useRealtimePresence"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { ChipBankCard } from "@/components/frontend/minigames/ChipBankCard"; +import { BlackjackDevControls } from "@/components/frontend/minigames/dev/BlackjackDevControls"; +import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock"; import { BlackjackGuide } from "./BlackjackGuide"; import { BLACKJACK_STATE_EVENT, @@ -332,6 +334,19 @@ export function BlackjackArena({ + + {view === "table" && snapshot && ( + + {snapshot.you && ( + + )} + + )} ); } diff --git a/src/components/frontend/minigames/bomperator/BomperatorArena.tsx b/src/components/frontend/minigames/bomperator/BomperatorArena.tsx index db728e4c..d5a1d251 100644 --- a/src/components/frontend/minigames/bomperator/BomperatorArena.tsx +++ b/src/components/frontend/minigames/bomperator/BomperatorArena.tsx @@ -11,6 +11,8 @@ import { import { toast } from "sonner"; import { useRealtimePresence } from "@/hooks/useRealtimePresence"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { BomperatorDevControls } from "@/components/frontend/minigames/dev/BomperatorDevControls"; +import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock"; import { BomperatorLobby } from "./BomperatorLobby"; import { BomperatorGame } from "./BomperatorGame"; import { @@ -41,10 +43,12 @@ export function BomperatorArena({ initialStats, currentUserId, initialMatchId, + isSuperuser = false, }: { initialStats: BomperatorStats; currentUserId: number | string; initialMatchId?: string; + isSuperuser?: boolean; }) { const [view, setView] = useState(initialMatchId ? "match" : "lobby"); const [match, setMatch] = useState(null); @@ -246,6 +250,17 @@ export function BomperatorArena({ ) : (

Loading match…

)} + + {view === "match" && match && ( + + + + )} ); } diff --git a/src/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena.tsx b/src/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena.tsx index 4bcfbba8..312a7d5d 100644 --- a/src/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena.tsx +++ b/src/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena.tsx @@ -8,6 +8,8 @@ import { } from "@/app/(frontend)/minigames/call-for-fire-versus/actions"; import { useRealtimePresence } from "@/hooks/useRealtimePresence"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock"; +import { VersusDevControls } from "@/components/frontend/minigames/dev/VersusDevControls"; import { VersusLobby } from "./VersusLobby"; import { VersusMatch } from "./VersusMatch"; @@ -33,10 +35,12 @@ export function CallForFireVersusArena({ initialStats, currentUserId, initialMatchId, + isSuperuser = false, }: { initialStats: VersusStats; currentUserId: number | string; initialMatchId?: string; + isSuperuser?: boolean; }) { const [view, setView] = useState(initialMatchId ? "match" : "lobby"); const [match, setMatch] = useState(null); @@ -164,6 +168,17 @@ export function CallForFireVersusArena({ ) : (

Loading match…

)} + + {view === "match" && match && ( + + + + )} ); } diff --git a/src/components/frontend/minigames/call-for-fire/CallForFireArena.tsx b/src/components/frontend/minigames/call-for-fire/CallForFireArena.tsx index c7bee7d9..bbbd28ef 100644 --- a/src/components/frontend/minigames/call-for-fire/CallForFireArena.tsx +++ b/src/components/frontend/minigames/call-for-fire/CallForFireArena.tsx @@ -9,19 +9,24 @@ import { useRealtimePresence } from "@/hooks/useRealtimePresence"; import { useSidebar } from "@/components/ui/sidebar"; import { AllTimeLeaderboard } from "@/components/frontend/minigames/AllTimeLeaderboard"; import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard"; +import { CallForFireDevControls } from "@/components/frontend/minigames/dev/CallForFireDevControls"; +import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock"; import { CallForFireLeaderboard } from "./CallForFireLeaderboard"; -import { FireMissionBoard } from "./FireMissionBoard"; +import { FireMissionBoard, type CallForFireDevSnapshot } from "./FireMissionBoard"; export function CallForFireArena({ initialStats, currentUserId, + isSuperuser = false, }: { initialStats: CallForFireStats; currentUserId: number | string; + isSuperuser?: boolean; }) { const [refreshKey, setRefreshKey] = useState(0); const [playing, setPlaying] = useState(false); const [selectedDifficulty, setSelectedDifficulty] = useState("patrol"); + const [missionSnapshot, setMissionSnapshot] = useState(null); const { isMobile, setOpenMobile } = useSidebar(); const activeTeams = useRealtimePresence("callForFire", playing, true); const onPhaseChange = useCallback((phase: "ready" | "playing" | "over") => { @@ -39,6 +44,8 @@ export function CallForFireArena({ onGameRecorded={() => setRefreshKey((key) => key + 1)} onPhaseChange={onPhaseChange} onDifficultyChange={setSelectedDifficulty} + isSuperuser={isSuperuser} + onDevSnapshotChange={setMissionSnapshot} /> + + + ); } diff --git a/src/components/frontend/minigames/call-for-fire/FireMissionBoard.tsx b/src/components/frontend/minigames/call-for-fire/FireMissionBoard.tsx index cbb1f887..5229eb3d 100644 --- a/src/components/frontend/minigames/call-for-fire/FireMissionBoard.tsx +++ b/src/components/frontend/minigames/call-for-fire/FireMissionBoard.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react"; import { Crosshair, Radio, RotateCcw, Target, Timer } from "lucide-react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; @@ -26,6 +26,11 @@ import { import { PROFILE_UPDATE_EVENT } from "@/hooks/useGameTick"; import { useSessionExpired } from "@/hooks/useSessionExpired"; import { LoginLink } from "@/components/frontend/auth/LoginLink"; +import { + CALL_FOR_FIRE_DEV_GAME_KEY, + CALL_FOR_FIRE_DEV_SETTINGS_EVENT, +} from "@/components/frontend/minigames/dev/CallForFireDevControls"; +import { readDevSetting } from "@/components/frontend/minigames/dev/devSettings"; import { cn } from "@/lib/utils"; type Phase = "ready" | "playing" | "over"; @@ -51,6 +56,49 @@ type Impact = { const DIFFICULTY_KEYS: readonly CallForFireDifficulty[] = ["patrol", "checkpoint", "compound"]; const CORRECTION_STEP = 50; +/** Observer net keeps the last six transmissions unless dev free corrections is on. */ +const RADIO_LOG_LIMIT = 6; + +/** Plain, cheap summary of the live run served to the developer dock's State tab. */ +export interface CallForFireDevSnapshot { + readonly phase: Phase; + readonly difficulty: CallForFireDifficulty; + readonly gridSize: number; + readonly lethalRadiusM: number; + readonly roundsUsed: number; + readonly roundsLeft: number; + readonly correctionsFired: number; + readonly secondsLeft: number; + readonly lastImpact: (GridPoint & { readonly grid: string }) | null; + readonly target: (GridPoint & { readonly grid: string }) | null; + readonly dev: { + readonly showTarget: boolean; + readonly freeCorrections: boolean; + readonly seed: number | null; + }; +} + +/** + * Deterministic PRNG (mulberry32) used only when a developer seed is set. + * Without a seed, mission generation keeps calling Math.random(), so normal + * play is byte-for-byte the same behavior as before. + */ +function mulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let value = state; + value = Math.imul(value ^ (value >>> 15), value | 1); + value ^= value + Math.imul(value ^ (value >>> 7), value | 61); + return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function readDevSeed(): number | null { + const stored = readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, "seed", null); + return typeof stored === "number" && Number.isFinite(stored) ? Math.trunc(stored) : null; +} + function formatClock(totalSeconds: number): string { const minutes = Math.floor(totalSeconds / 60); const seconds = totalSeconds % 60; @@ -62,11 +110,15 @@ export function FireMissionBoard({ onGameRecorded, onPhaseChange, onDifficultyChange, + isSuperuser = false, + onDevSnapshotChange, }: { initialStats: CallForFireStats; onGameRecorded: () => void; onPhaseChange: (phase: Phase) => void; onDifficultyChange: (difficulty: CallForFireDifficulty) => void; + isSuperuser?: boolean; + onDevSnapshotChange: (snapshot: CallForFireDevSnapshot) => void; }) { const router = useRouter(); const { expired, expiredRef } = useSessionExpired(); @@ -86,6 +138,10 @@ export function FireMissionBoard({ const submittingRef = useRef(false); const statsRef = useRef(serverStats); const secondsLeftRef = useRef(0); + const [devShowTarget, setDevShowTarget] = useState(false); + const [devFreeCorrections, setDevFreeCorrections] = useState(false); + const [devSeed, setDevSeed] = useState(null); + const devSeedRef = useRef(null); const config = CALL_FOR_FIRE_DIFFICULTIES[difficulty]; const roundsLeft = config.maxRounds - roundsUsed; @@ -103,6 +159,31 @@ export function FireMissionBoard({ onPhaseChange("ready"); }, [onPhaseChange]); + // Dev dock settings live in localStorage and are broadcast on a window event, + // so toggling them in the dock updates this board without prop plumbing. They + // only affect local rendering (target overlay, observer net history, client + // round cap) and the RNG at mission generation, never the submitted payload. + useEffect(() => { + if (!isSuperuser) { + setDevShowTarget(false); + setDevFreeCorrections(false); + setDevSeed(null); + devSeedRef.current = null; + return; + } + const sync = () => { + setDevShowTarget(readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, "showTarget", false)); + setDevFreeCorrections(readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, "freeCorrections", false)); + const nextSeed = readDevSeed(); + if (devSeedRef.current === nextSeed) return; + devSeedRef.current = nextSeed; + setDevSeed(nextSeed); + }; + sync(); + window.addEventListener(CALL_FOR_FIRE_DEV_SETTINGS_EVENT, sync); + return () => window.removeEventListener(CALL_FOR_FIRE_DEV_SETTINGS_EVENT, sync); + }, [isSuperuser]); + const reset = useCallback( (nextDifficulty: CallForFireDifficulty = difficulty) => { if (submittingRef.current) return; @@ -218,12 +299,11 @@ export function FireMissionBoard({ const begin = useCallback(() => { if (expiredRef.current || submittingRef.current) return; - const nextScenario = createScenario(difficulty); + const rng = devSeed === null ? Math.random : mulberry32(devSeed); + const nextScenario = createScenario(difficulty, rng); const report = observerReport(nextScenario.target, nextScenario.spotting); setScenario(nextScenario); - setImpacts([ - { point: nextScenario.spotting, effective: false, spotting: true }, - ]); + setImpacts([{ point: nextScenario.spotting, effective: false, spotting: true }]); setLastImpact(nextScenario.spotting); setRadioLog([ `Splash, over. Spotting round ${gridDesignation(nextScenario.spotting)}: ${report.message}`, @@ -235,7 +315,7 @@ export function FireMissionBoard({ setDeflectionM(0); setLastRun(null); setPhaseSafe("playing"); - }, [config.maxSeconds, difficulty, expiredRef, setPhaseSafe]); + }, [config.maxSeconds, devSeed, difficulty, expiredRef, setPhaseSafe]); const fireMission = useCallback(() => { if (phase !== "playing" || submittingRef.current || expiredRef.current) return; @@ -244,11 +324,9 @@ export function FireMissionBoard({ const impactPoint = applyCorrection(lastImpact, { rangeM, deflectionM }, config.size); const distance = distanceMeters(scenario.target, impactPoint); const effective = isEffectiveHit(scenario.target, impactPoint, config.lethalRadiusM); - const nextImpacts = [ - ...impacts, - { point: impactPoint, effective, spotting: false }, - ]; + const nextImpacts = [...impacts, { point: impactPoint, effective, spotting: false }]; const nextUsed = roundsUsed + 1; + const radioLimit = devFreeCorrections ? Number.MAX_SAFE_INTEGER : RADIO_LOG_LIMIT; setImpacts(nextImpacts); setLastImpact(impactPoint); setRoundsUsed(nextUsed); @@ -260,7 +338,7 @@ export function FireMissionBoard({ [ ...log, `Splash, over. Effective on grid ${gridDesignation(impactPoint)}. Target destroyed.`, - ].slice(-6), + ].slice(-radioLimit), ); setPhaseSafe("over"); void recordResult(true, nextUsed, elapsedSeconds, distance); @@ -269,13 +347,10 @@ export function FireMissionBoard({ const report = observerReport(scenario.target, impactPoint); setRadioLog((log) => - [ - ...log, - `Impact grid ${gridDesignation(impactPoint)}: ${report.message}`, - ].slice(-6), + [...log, `Impact grid ${gridDesignation(impactPoint)}: ${report.message}`].slice(-radioLimit), ); - if (nextUsed >= config.maxRounds) { + if (!devFreeCorrections && nextUsed >= config.maxRounds) { setPhaseSafe("over"); void recordResult(false, nextUsed, elapsedSeconds, distance); } @@ -283,6 +358,7 @@ export function FireMissionBoard({ config.lethalRadiusM, config.maxRounds, config.size, + devFreeCorrections, elapsedSeconds, expiredRef, impacts, @@ -302,6 +378,48 @@ export function FireMissionBoard({ : "border-destructive/40 bg-destructive/10" : "border-border bg-card"; + // Dev dock payload: cheap plain object describing the live run. Client-only, + // and the dock renders nothing unless the page computed a superuser. + const correctionsFired = Math.max(0, roundsUsed - 1); + const devSnapshot = useMemo( + () => ({ + phase, + difficulty, + gridSize: config.size, + lethalRadiusM: config.lethalRadiusM, + roundsUsed, + roundsLeft: Math.max(0, roundsLeft), + correctionsFired, + secondsLeft, + lastImpact: lastImpact ? { ...lastImpact, grid: gridDesignation(lastImpact) } : null, + target: scenario ? { ...scenario.target, grid: gridDesignation(scenario.target) } : null, + dev: { + showTarget: devShowTarget, + freeCorrections: devFreeCorrections, + seed: devSeed, + }, + }), + [ + config.lethalRadiusM, + config.size, + correctionsFired, + devFreeCorrections, + devSeed, + devShowTarget, + difficulty, + lastImpact, + phase, + roundsLeft, + roundsUsed, + scenario, + secondsLeft, + ], + ); + + useEffect(() => { + onDevSnapshotChange(devSnapshot); + }, [devSnapshot, onDevSnapshotChange]); + return (
{expired && ( @@ -418,7 +536,7 @@ export function FireMissionBoard({ {phase === "over" && !lastRun && Recording fire mission…} {lastRun?.won && ( - Score {lastRun.score} · accuracy {Math.round(lastRun.finalDistanceM)}m · + + Score {lastRun.score} · accuracy {Math.round(lastRun.finalDistanceM)}m · + {lastRun.xpEarned} XP earned. )} @@ -474,7 +592,11 @@ export function FireMissionBoard({ row={row} size={config.size} impacts={impacts} - target={phase === "over" ? scenario?.target : undefined} + target={ + phase === "over" || (isSuperuser && devShowTarget) + ? scenario?.target + : undefined + } disabled={phase !== "playing" || expired} /> ))} @@ -521,7 +643,9 @@ export function FireMissionBoard({ Observer net
{radioLog.length === 0 ? ( -

Net quiet. Awaiting your first call.

+

+ Net quiet. Awaiting your first call. +

) : (
    {radioLog.map((line, index) => ( @@ -541,8 +665,8 @@ export function FireMissionBoard({

    - Read the spotting report, correct range and deflection, and walk the rounds onto the target - before time runs out + Read the spotting report, correct range and deflection, and walk the rounds onto the + target before time runs out

    @@ -600,16 +724,28 @@ function ImpactRow({ key={`${row}-${column}`} role="gridcell" aria-label={`grid ${gridDesignation({ x: column, y: row })}${ - impact ? (impact.effective ? " effective impact" : impact.spotting ? " spotting round" : " impact") : "" + isTarget ? " target location" : "" + }${ + impact + ? impact.effective + ? " effective impact" + : impact.spotting + ? " spotting round" + : " impact" + : "" }`} className={cn( "flex size-[var(--cell-size)] items-center justify-center rounded-sm border text-xs font-bold transition-colors", "border-border bg-card", impact?.effective && "border-emerald-400 bg-emerald-600/80 text-emerald-50 shadow-[0_0_8px_rgb(16_185_129_/_0.6)]", - impact && !impact.effective && impact.spotting && + impact && + !impact.effective && + impact.spotting && "border-sky-400/80 bg-sky-500/20 text-sky-200", - impact && !impact.effective && !impact.spotting && + impact && + !impact.effective && + !impact.spotting && "border-amber-500/70 bg-amber-500/20 text-amber-200", isTarget && "border-destructive bg-destructive/25 text-red-300", disabled && "opacity-90", @@ -620,6 +756,8 @@ function ImpactRow({ className={cn("size-3.5", impact.spotting && "text-sky-300")} strokeWidth={impact.spotting ? 2.5 : 2} /> + ) : isTarget ? ( +