1
0
Fork 0
polaris-task-force/tests/int/minigame-dev-console-gating.int.spec.ts
Z8MB1E 938da9bf86 test(vitest): isolate:false shared forks with per-pid template clones + memoized payload boot
Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler
only reuses worker processes between isolate:false tasks, so per-file fork
spawning made clone+boot costs unavoidable at stage 2):

- config: workers branch runs pool=forks with isolate:false, cap 8 via
  VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs),
  failure-marker reporter, and idempotent setupFiles chain
- vitest-worker-setup: one template clone PER FORK PROCESS named by pid
  (VITEST_WORKER_ID churns per task, which silently re-cloned per file);
  DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3)
- vitest.setup: once-per-process serial test URI markers; afterEach
  useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock
  module factories mid-file); logging absorber for fire-and-forget event
  writes that reject after their spec's cleanup deleted fixture users
- helpers/get-test-payload.ts: memoized Payload boot shared across files
  in a fork; codemod converted all 91 self-booting specs mechanically
- pinned opt-outs (own boot + comments): game-structures-labor-route,
  mission-reminder, notification-inbox-scope (jwtSign writes leak into
  the shared instance's auth state across files)
- promotion-nominations: create the superuser before its rank ladder so
  the Users-hook Recruit rank gets leading orderable tokens (its
  top-of-ladder guard needs Col to remain ladder-max on fresh clones);
  operation-economy: itemType-scope the market-state assertion (asset
  and resource ids collide as bare integers under per-fork databases)

Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s
vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4
note: globalTeardown config no longer exists; teardown returns from
globalSetup.
2026-10-21 12:54:30 -04:00

399 lines
14 KiB
TypeScript

/**
* Dev-console gating integration specs.
*
* Every multiplayer admin action added for the Minigame Developer Console must
* (a) reject non-superusers at the server boundary regardless of what the
* client claims, and (b) apply for superusers, leaving an `[dev-admin]` audit
* line behind. Client-side hiding of the dock is cosmetic; this file pins the
* actual security boundary on the test database.
*/
import { getTestPayload } from "../helpers/get-test-payload";
import { type Payload, type User } from "payload";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";
import {
createTable as createPokerTable,
forceExpireTable as forceExpirePokerTableReg,
getSnapshotFor as getPokerSnapshot,
joinTable as joinPokerTable,
startGame as startPokerGame,
} from "@/lib/minigames/poker/tables";
import {
adjustBlackjackBankroll,
forceBlackjackNextCard,
setBlackjackDealerHand,
} from "@/app/(frontend)/minigames/blackjack/actions";
import {
clearTablesForTests as clearBlackjackTables,
createTable as createBlackjackTableReg,
getSnapshotFor as getBlackjackSnapshot,
joinTable as joinBlackjackTableReg,
startGame as startBlackjackGameReg,
} from "@/lib/minigames/blackjack/tables";
import {
bomperatorAdminCommand,
forceExpireBomperatorMatch,
} from "@/app/(frontend)/minigames/bomperator/actions";
import {
clearMatchesForTests as clearBompMatches,
createMatch as createBompMatch,
getSnapshotFor as getBompSnapshot,
joinMatch as joinBompMatch,
setAutoTickForTests,
startMatch as startBompMatch,
} from "@/lib/minigames/bomperator/registry";
import { versusAdminCommand } from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import {
clearMatchesForTests as clearVersusMatches,
createMatch as createVersusMatchReg,
getSnapshotFor as getVersusSnapshot,
joinMatch as joinVersusMatchReg,
placeFleetFor,
} from "@/lib/minigames/call-for-fire-versus/registry";
import type { FobPlacement } from "@/lib/minigames/call-for-fire-versus/constants";
import {
forceFoldPokerPlayer,
forcePokerStreet,
pokerClockControl,
setPokerRevealAll,
} from "@/app/(frontend)/minigames/poker/actions";
// Mock next/headers so the actions' authenticate() can run outside a request;
// payload.auth is spied per-test to impersonate the caller.
vi.mock("next/headers", () => ({
headers: async () => new Headers(),
}));
let payload: Payload;
let authSpy: MockInstance;
let loggerSpy: MockInstance;
const RUN = `devconsole-${Date.now().toString(36)}`;
const userIds: number[] = [];
const roleIds: number[] = [];
const pokerTableIds: string[] = [];
let superUser: User;
let plainUser: User;
// Payload types ids as string | number; the game registries take numbers.
let superId = 0;
let plainId = 0;
async function makeUser(label: string, roleDocIds?: number[]): Promise<User> {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}-discord`,
displayName: `${RUN} ${label}`,
steamId: `${RUN}-steam-${label}`,
password: "Test1234",
roles: ["user"],
...(roleDocIds && roleDocIds.length > 0 ? { roleDocs: roleDocIds } : {}),
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(Number(user.id));
return user;
}
function asSuperuser(): void {
authSpy.mockResolvedValue({ user: superUser } as never);
}
function asPlainUser(): void {
authSpy.mockResolvedValue({ user: plainUser } as never);
}
/** Mirrors the engine spec layout: 3x2 CP, 4-cell L depot, three 2-cell lines. */
function fleetAt(x: number, y: number): FobPlacement[] {
return [
{ assetId: "command-post", origin: { x, y }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 5 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 6 }, orientation: 0 },
{ assetId: "fob-2", origin: { x, y: y + 7 }, orientation: 0 },
];
}
beforeAll(async () => {
payload = await getTestPayload();
authSpy = vi.spyOn(payload, "auth");
loggerSpy = vi.spyOn(payload.logger, "info");
const superRole = await payload.create({
collection: "roles",
data: { name: `${RUN} Dev Console`, slug: `${RUN}-devconsole`, isSuperuser: true },
overrideAccess: true,
depth: 0,
});
roleIds.push(superRole.id);
superUser = await makeUser("super", [superRole.id]);
plainUser = await makeUser("plain");
superId = Number(superUser.id);
plainId = Number(plainUser.id);
});
// Registries key live tables/matches by user id, and both users stay seated in
// whatever a previous test left behind: clear every store before each test.
beforeEach(() => {
for (const tableId of pokerTableIds.splice(0)) {
forceExpirePokerTableReg(tableId, payload);
}
clearBlackjackTables();
clearBompMatches();
clearVersusMatches();
});
afterAll(async () => {
clearBompMatches();
clearVersusMatches();
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => undefined);
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => undefined);
}
authSpy.mockRestore();
loggerSpy.mockRestore();
});
/* --------------------------------------------------------------------- poker */
describe("poker dev actions: gating", () => {
function setupTable(): string {
const tableId = createPokerTable(superId, "Host");
pokerTableIds.push(tableId);
joinPokerTable(tableId, plainId, "Guest");
startPokerGame(tableId, superId);
return tableId;
}
it("rejects non-superusers on every new poker dev action", async () => {
const tableId = setupTable();
asPlainUser();
const fold = await forceFoldPokerPlayer(tableId, 1);
expect(fold.success).toBe(false);
expect(fold.error).toMatch(/administrators/i);
const street = await forcePokerStreet(tableId);
expect(street.success).toBe(false);
const reveal = await setPokerRevealAll(tableId, true);
expect(reveal.success).toBe(false);
const clock = await pokerClockControl(tableId, "reset");
expect(clock.success).toBe(false);
});
it("applies for superusers and audits each action", async () => {
const tableId = setupTable();
asSuperuser();
loggerSpy.mockClear();
const reveal = await setPokerRevealAll(tableId, true);
expect(reveal.success).toBe(true);
// Reveal-all: the host's snapshot now carries the guest's hole cards.
const revealedGuest = reveal.data?.you?.players.find((p) => p.seatId === 1);
expect(revealedGuest?.holeCards?.length ?? 0).toBe(2);
const street = await forcePokerStreet(tableId);
expect(street.success).toBe(true);
const fold = await forceFoldPokerPlayer(tableId, 1);
// The forced street may have ended the hand; either the fold lands or the
// engine rejects with a phase error, but never an auth error.
if (!fold.success) expect(fold.error).not.toMatch(/administrators/i);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(logged.some((line) => line.includes("[dev-admin]") && line.includes("game=poker"))).toBe(
true,
);
expect(logged.some((line) => line.includes("action=reveal-on"))).toBe(true);
});
it("clock control reset applies for superusers while a player is on the clock", async () => {
const tableId = setupTable();
asSuperuser();
const snapshot = getPokerSnapshot(tableId, superId);
if (snapshot.you?.phase === "betting" && snapshot.you.toActSeat !== null) {
const clock = await pokerClockControl(tableId, "reset");
expect(clock.success).toBe(true);
expect(clock.data?.turnDeadline).not.toBeNull();
}
});
});
/* ---------------------------------------------------------------- blackjack */
describe("blackjack dev actions: gating", () => {
function setupTable(): string {
const tableId = createBlackjackTableReg(superId, "Host");
joinBlackjackTableReg(tableId, plainId, "Guest");
startBlackjackGameReg(tableId, superId);
return tableId;
}
it("rejects non-superusers on every new blackjack dev action", async () => {
const tableId = setupTable();
asPlainUser();
const adjust = await adjustBlackjackBankroll(tableId, 1, 100);
expect(adjust.success).toBe(false);
expect(adjust.error).toMatch(/administrators/i);
const card = await forceBlackjackNextCard(tableId, { rank: 14, suit: "s" });
expect(card.success).toBe(false);
const dealer = await setBlackjackDealerHand(tableId, [{ rank: 10, suit: "h" }]);
expect(dealer.success).toBe(false);
});
it("applies bankroll adjustment and shoe injection for superusers", async () => {
const tableId = setupTable();
asSuperuser();
loggerSpy.mockClear();
const before = getBlackjackSnapshot(tableId, superId);
const guestBankroll = before.you?.players.find((p) => p.seatId === 1)?.bankroll ?? 0;
const adjust = await adjustBlackjackBankroll(tableId, 1, 250);
expect(adjust.success).toBe(true);
const after = adjust.data?.you?.players.find((p) => p.seatId === 1)?.bankroll ?? -1;
expect(after).toBe(guestBankroll + 250);
const card = await forceBlackjackNextCard(tableId, { rank: 14, suit: "s" });
expect(card.success).toBe(true);
// Dealer override passes the auth gate; here the round has not dealt the
// dealer in yet, so the domain rule rejects it (not the permission gate).
const dealer = await setBlackjackDealerHand(tableId, [{ rank: 10, suit: "h" }]);
if (!dealer.success) expect(dealer.error).toMatch(/dealt into this round/i);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(
logged.some((line) => line.includes("[dev-admin]") && line.includes("game=blackjack")),
).toBe(true);
});
});
/* -------------------------------------------------------------- bomperator */
describe("bomperator admin command: gating", () => {
beforeAll(() => {
setAutoTickForTests(false);
});
function setupMatch(): string {
const matchId = createBompMatch(superId, "Host");
joinBompMatch(matchId, plainId, "Guest");
startBompMatch(matchId, superId);
return matchId;
}
it("rejects non-superusers and invalid command shapes", async () => {
const matchId = setupMatch();
asPlainUser();
const denied = await bomperatorAdminCommand(matchId, { kind: "destroyCrates" });
expect(denied.success).toBe(false);
expect(denied.error).toMatch(/administrators/i);
asSuperuser();
const bogus = await bomperatorAdminCommand(matchId, {
kind: "grantPickup",
seat: 999,
pickup: "laser",
} as never);
expect(bogus.success).toBe(false);
expect(bogus.error).toMatch(/invalid admin command/i);
});
it("applies destroyCrates for a superuser and audits the line", async () => {
const matchId = setupMatch();
asSuperuser();
loggerSpy.mockClear();
const before = getBompSnapshot(matchId, superId);
expect(before.grid.some((cell) => cell === 2)).toBe(true);
const result = await bomperatorAdminCommand(matchId, { kind: "destroyCrates" });
expect(result.success).toBe(true);
const after = getBompSnapshot(matchId, superId);
expect(after.grid.some((cell) => cell === 2)).toBe(false);
expect(after.version).toBeGreaterThan(before.version);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(
logged.some(
(line) =>
line.includes("[dev-admin]") &&
line.includes("game=bomperator") &&
line.includes("action=cmd:destroyCrates") &&
line.includes(`target=${matchId}`),
),
).toBe(true);
});
it("force-expire stays superuser-only", async () => {
const matchId = createBompMatch(superId, "Host");
joinBompMatch(matchId, plainId, "Guest");
asPlainUser();
const denied = await forceExpireBomperatorMatch(matchId);
expect(denied.success).toBe(false);
asSuperuser();
const ok = await forceExpireBomperatorMatch(matchId);
expect(ok.success).toBe(true);
});
});
/* ------------------------------------------------------------- cff versus */
describe("cff-versus admin command: gating", () => {
function setupMatch(): string {
const matchId = createVersusMatchReg(superId, "Host");
joinVersusMatchReg(matchId, plainId, "Guest");
placeFleetFor(matchId, superId, fleetAt(0, 0));
placeFleetFor(matchId, plainId, fleetAt(6, 0));
return matchId;
}
it("rejects non-superusers and invalid command shapes", async () => {
const matchId = setupMatch();
asPlainUser();
const denied = await versusAdminCommand(matchId, { kind: "revealFleets", on: true });
expect(denied.success).toBe(false);
expect(denied.error).toMatch(/administrators/i);
asSuperuser();
const bogus = await versusAdminCommand(matchId, { kind: "selfDestruct" } as never);
expect(bogus.success).toBe(false);
expect(bogus.error).toMatch(/invalid admin command/i);
});
it("reveal fleets + skip turn apply for a superuser and reach both viewers", async () => {
const matchId = setupMatch();
asSuperuser();
loggerSpy.mockClear();
const revealed = await versusAdminCommand(matchId, { kind: "revealFleets", on: true });
expect(revealed.success).toBe(true);
const hostView = getVersusSnapshot(matchId, superId);
const guestView = getVersusSnapshot(matchId, plainId);
expect(hostView.opponentFleet?.length).toBeGreaterThan(0);
expect(guestView.opponentFleet?.length).toBeGreaterThan(0);
const turnBefore = hostView.turnUserId;
const skipped = await versusAdminCommand(matchId, { kind: "skipTurn" });
expect(skipped.success).toBe(true);
expect(getVersusSnapshot(matchId, superId).turnUserId).not.toBe(turnBefore);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(
logged.some(
(line) =>
line.includes("[dev-admin]") &&
line.includes("game=cff-versus") &&
line.includes("action=cmd:revealFleets"),
),
).toBe(true);
});
});