mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-08 00:51:05 +00:00
5d21be826d
Part of #4040 (v1 scope: listing + browser + per-subscriber limit; custom lobby name/description left for a follow-up). ## What Subscribers can toggle their **private lobby** to be **publicly listed**; a browsable **"Open Lobbies"** list appears in the Join Lobby modal. Hard limit of **one listed lobby per subscriber**, enforced cluster-wide. ## How **Semantics** — a listed lobby stays `GameType.Private`: the host keeps full control and starts the game manually; the toggle only controls visibility. The `listed` flag lives on `GameServer` (not `GameConfig`), so it cannot be smuggled in through `update_game_config` and never touches core/sim/records. **Distribution** — reuses the existing public-lobby pipeline end to end: a new `"hosted"` `PublicGameType` bucket flows worker → master IPC → `/lobbies` websocket → `PublicLobbySocket`. Master scheduling now iterates only `SCHEDULED_PUBLIC_GAME_TYPES` (`ffa`/`team`/`special`), so it never sets countdowns on or schedules replacements for hosted lobbies. Lobbies delist automatically when the game starts/fills/dies (phase change). The broadcast fingerprint now includes browser-visible config, so host edits (map/mode) refresh the list even though the gameID doesn't change. **Gating** — new authenticated endpoint `POST /api/game/:id/listing`: - creator-only (403), private + not-started only (409) - fresh subscription check via server-side `getUserMe` using the shared `hasActiveSubscription()` helper (`active`/`trialing`); skipped in `GameEnv.Dev` (same precedent as Turnstile) so it's testable locally - one-lobby-per-creator (409): a SHA-256 hash of the creator's persistentID rides worker↔master IPC (`PublicGameInfo.creatorID`); the master dedupes as a race backstop. The hash — and host-only config (whitelist, name reveals) — are **stripped from every client payload** (broadcast + primed snapshot). **Client** — subscriber-gated "List lobby publicly" toggle in the host modal (server rejection reverts the toggle and shows a translated message); "Open Lobbies" rows (map, mode, player count) in the Join Lobby modal that reuse the existing private-join flow. **Compat** — `PublicGames.games` is now a `partialRecord`, so newer clients tolerate servers that don't send every bucket. Note: already-open old clients will fail to parse broadcasts containing the new `hosted` key until refreshed (closed Zod enum) — same class of break as previous wire-schema changes. ## Testing - `tests/server/HostedLobbyListing.test.ts` (15 tests): listed-lobby filtering, flag not settable via config intent, master aggregation + creator dedupe + no scheduling of hosted, creatorID stripping (broadcast + primed snapshot), `creatorHasListedLobby` (broadcast + local), fingerprint refresh on config change - `hasActiveSubscription` cases in `ApiSchemas.test.ts`; hosted counts-delta patch in `LobbySocket.test.ts` - Full suite green (1723 + 141 tests), tsc/eslint/prettier clean - **E2E in the real app** (headless Chromium, two browser contexts): host lists lobby → appears in second browser's Join Lobby list (creatorID absent from payload) → join succeeds (2 players in lobby) → same creator's second lobby rejected 409 with toggle revert → unlist removes it from a fresh browser's list. Curl negatives: missing auth 400, bad token 401, non-creator 403, missing game 404, bad body 400. ## Known follow-ups - Custom lobby name/description in the browser (needs the censor pipeline) — rest of #4040 - A listed lobby whose host closes the tab stays advertised indefinitely (an empty private lobby never leaves the Lobby phase) — pre-existing lifecycle, now more visible; consider delisting on creator disconnect 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
267 lines
7.1 KiB
TypeScript
267 lines
7.1 KiB
TypeScript
import {
|
|
GoogleUser,
|
|
GoogleUserSchema,
|
|
hasActiveSubscription,
|
|
PlayerGameModeFilterSchema,
|
|
PlayerGameResultSchema,
|
|
PlayerGameTypeFilterSchema,
|
|
PlayerProfileSchema,
|
|
PublicPlayerGameSchema,
|
|
PublicPlayerGamesResponseSchema,
|
|
UserMeResponse,
|
|
} from "../src/core/ApiSchemas";
|
|
|
|
describe("GoogleUserSchema", () => {
|
|
it("accepts a valid email", () => {
|
|
const result = GoogleUserSchema.safeParse({ email: "user@example.com" });
|
|
expect(result.success).toBe(true);
|
|
if (result.success) {
|
|
expect(result.data.email).toBe("user@example.com");
|
|
}
|
|
});
|
|
|
|
it("rejects a missing email", () => {
|
|
expect(GoogleUserSchema.safeParse({}).success).toBe(false);
|
|
});
|
|
|
|
it("rejects a non-string email", () => {
|
|
expect(GoogleUserSchema.safeParse({ email: 123 }).success).toBe(false);
|
|
});
|
|
|
|
it("infers the GoogleUser type from the schema", () => {
|
|
// Compile-time check that GoogleUser is derived from the schema.
|
|
const user: GoogleUser = { email: "typed@example.com" };
|
|
expect(user.email).toBe("typed@example.com");
|
|
});
|
|
});
|
|
|
|
describe("PlayerProfileSchema", () => {
|
|
const base = {
|
|
createdAt: "2024-01-15T12:00:00.000Z",
|
|
stats: {},
|
|
};
|
|
|
|
it("accepts a profile without a games array (moved to its own endpoint)", () => {
|
|
const result = PlayerProfileSchema.safeParse(base);
|
|
expect(result.success).toBe(true);
|
|
});
|
|
|
|
it("ignores a legacy games field rather than failing the parse", () => {
|
|
const result = PlayerProfileSchema.safeParse({
|
|
...base,
|
|
games: [{ gameId: "g1" }],
|
|
});
|
|
// Zod strips unknown keys by default, so an old server response that still
|
|
// carries games[] parses cleanly without the field surfacing.
|
|
expect(result.success).toBe(true);
|
|
if (result.success) {
|
|
expect("games" in result.data).toBe(false);
|
|
}
|
|
});
|
|
|
|
it("rejects a non-ISO createdAt", () => {
|
|
expect(
|
|
PlayerProfileSchema.safeParse({ ...base, createdAt: "yesterday" })
|
|
.success,
|
|
).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("PlayerGameModeFilterSchema", () => {
|
|
it.each(["ffa", "team", "hvn", "ranked"])("accepts %s", (value) => {
|
|
expect(PlayerGameModeFilterSchema.safeParse(value).success).toBe(true);
|
|
});
|
|
|
|
it("rejects 'all' (filter omission is encoded by absence, not a value)", () => {
|
|
expect(PlayerGameModeFilterSchema.safeParse("all").success).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("PlayerGameTypeFilterSchema", () => {
|
|
it.each(["public", "private", "singleplayer"])("accepts %s", (value) => {
|
|
expect(PlayerGameTypeFilterSchema.safeParse(value).success).toBe(true);
|
|
});
|
|
|
|
it("rejects an unknown type value", () => {
|
|
expect(PlayerGameTypeFilterSchema.safeParse("ranked").success).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("PlayerGameResultSchema", () => {
|
|
it.each(["victory", "defeat", "incomplete"])("accepts %s", (value) => {
|
|
expect(PlayerGameResultSchema.safeParse(value).success).toBe(true);
|
|
});
|
|
|
|
it("rejects an unknown result value", () => {
|
|
expect(PlayerGameResultSchema.safeParse("win").success).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("PublicPlayerGameSchema", () => {
|
|
const validGame = {
|
|
gameId: "g1",
|
|
start: "2024-06-01T00:00:00.000Z",
|
|
durationSeconds: 1234,
|
|
map: "World",
|
|
mode: "Team",
|
|
type: "Public",
|
|
playerTeams: "Duos",
|
|
rankedType: "unranked",
|
|
result: "victory" as const,
|
|
totalPlayers: 8,
|
|
username: "alice",
|
|
clanTag: "ABC",
|
|
};
|
|
|
|
it("accepts a fully-populated game", () => {
|
|
expect(PublicPlayerGameSchema.safeParse(validGame).success).toBe(true);
|
|
});
|
|
|
|
it("accepts clanTag: null (not repping a clan)", () => {
|
|
expect(
|
|
PublicPlayerGameSchema.safeParse({ ...validGame, clanTag: null }).success,
|
|
).toBe(true);
|
|
});
|
|
|
|
it("rejects a missing username", () => {
|
|
const withoutUsername: Record<string, unknown> = { ...validGame };
|
|
delete withoutUsername.username;
|
|
expect(PublicPlayerGameSchema.safeParse(withoutUsername).success).toBe(
|
|
false,
|
|
);
|
|
});
|
|
|
|
it("accepts playerTeams: null (FFA / non-team games)", () => {
|
|
expect(
|
|
PublicPlayerGameSchema.safeParse({ ...validGame, playerTeams: null })
|
|
.success,
|
|
).toBe(true);
|
|
});
|
|
|
|
it("accepts totalPlayers: null (historical rows)", () => {
|
|
expect(
|
|
PublicPlayerGameSchema.safeParse({ ...validGame, totalPlayers: null })
|
|
.success,
|
|
).toBe(true);
|
|
});
|
|
|
|
it("rejects a negative durationSeconds", () => {
|
|
expect(
|
|
PublicPlayerGameSchema.safeParse({ ...validGame, durationSeconds: -1 })
|
|
.success,
|
|
).toBe(false);
|
|
});
|
|
|
|
it("rejects a non-ISO start", () => {
|
|
expect(
|
|
PublicPlayerGameSchema.safeParse({ ...validGame, start: "June 1 2024" })
|
|
.success,
|
|
).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("PublicPlayerGamesResponseSchema", () => {
|
|
const validGame = {
|
|
gameId: "g1",
|
|
start: "2024-06-01T00:00:00.000Z",
|
|
durationSeconds: 1234,
|
|
map: "World",
|
|
mode: "Free For All",
|
|
type: "Public",
|
|
playerTeams: null,
|
|
rankedType: "unranked",
|
|
result: "defeat" as const,
|
|
totalPlayers: 20,
|
|
username: "bob",
|
|
clanTag: null,
|
|
};
|
|
|
|
it("accepts a non-empty page with an opaque cursor", () => {
|
|
const result = PublicPlayerGamesResponseSchema.safeParse({
|
|
results: [validGame],
|
|
nextCursor: "opaque-cursor-abc123",
|
|
});
|
|
expect(result.success).toBe(true);
|
|
if (result.success) {
|
|
expect(result.data.nextCursor).toBe("opaque-cursor-abc123");
|
|
}
|
|
});
|
|
|
|
it("accepts an empty page with a null cursor", () => {
|
|
expect(
|
|
PublicPlayerGamesResponseSchema.safeParse({
|
|
results: [],
|
|
nextCursor: null,
|
|
}).success,
|
|
).toBe(true);
|
|
});
|
|
|
|
it("rejects when nextCursor is missing (must be string or null)", () => {
|
|
expect(
|
|
PublicPlayerGamesResponseSchema.safeParse({ results: [] }).success,
|
|
).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("hasActiveSubscription", () => {
|
|
function userMeWith(
|
|
subscription: UserMeResponse["player"]["subscription"],
|
|
): UserMeResponse {
|
|
return {
|
|
user: {},
|
|
player: {
|
|
publicId: "p1",
|
|
adfree: false,
|
|
achievements: { singleplayerMap: [] },
|
|
friends: [],
|
|
subscription,
|
|
},
|
|
};
|
|
}
|
|
|
|
it("is true for an active subscription", () => {
|
|
expect(
|
|
hasActiveSubscription(
|
|
userMeWith({
|
|
tier: "supporter",
|
|
status: "active",
|
|
currentPeriodEnd: null,
|
|
cancelAtPeriodEnd: false,
|
|
}),
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("is true while trialing", () => {
|
|
expect(
|
|
hasActiveSubscription(
|
|
userMeWith({
|
|
tier: "supporter",
|
|
status: "trialing",
|
|
currentPeriodEnd: null,
|
|
cancelAtPeriodEnd: false,
|
|
}),
|
|
),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("is false for canceled or past_due subscriptions", () => {
|
|
for (const status of ["canceled", "past_due", "incomplete"]) {
|
|
expect(
|
|
hasActiveSubscription(
|
|
userMeWith({
|
|
tier: "supporter",
|
|
status,
|
|
currentPeriodEnd: null,
|
|
cancelAtPeriodEnd: false,
|
|
}),
|
|
),
|
|
).toBe(false);
|
|
}
|
|
});
|
|
|
|
it("is false without a subscription", () => {
|
|
expect(hasActiveSubscription(userMeWith(null))).toBe(false);
|
|
});
|
|
});
|