Files
OpenFrontIO/src/server/GamePreviewRoute.ts
T
Evan 275fd0dccc refactor: collapse per-env Configs into ClientEnv + ServerEnv (#3906)
## Description:

This is a refactor to simplify config handling.

Replaces the per-environment DevConfig/PreprodConfig/ProdConfig class
hierarchy with two static classes: ClientEnv (browser main thread, reads
from window.BOOTSTRAP_CONFIG) and ServerEnv (Node server, reads from
process.env). The four config classes are deleted, the abstract
DefaultServerConfig is gone, and DefaultConfig is renamed to Config.

The values that flow server → client (gameEnv, numWorkers,
turnstileSiteKey, jwtAudience, instanceId) used to be baked into the
hardcoded per-env classes. They're now real env vars on the server,
embedded into a single window.BOOTSTRAP_CONFIG object in index.html at
request time (alongside the existing gitCommit/assetManifest/cdnBase
globals, which moved into the same object), and read back by ClientEnv
on the client. The dev defaults previously hidden inside DevServerConfig
are now explicit in start:server-dev (NUM_WORKERS=2,
TURNSTILE_SITE_KEY=1x..., JWT_AUDIENCE=localhost, etc.) and in
vite.config.ts's html plugin inject.data. Production deploys plumb
NUM_WORKERS and TURNSTILE_SITE_KEY through deploy.yml (GitHub vars) into
the remote env file; JWT_AUDIENCE is derived from DOMAIN in deploy.sh.
The dynamic /api/instance endpoint is gone — INSTANCE_ID rides along in
BOOTSTRAP_CONFIG now.

ServerEnv is the only thing server code touches; ClientEnv is
browser-only. The two classes have intentional overlap (env, numWorkers,
jwtIssuer, gameCreationRate, workerIndex, etc.) since they derive
identical logic from different sources — there's a TODO in each to
consolidate via a shared helper later. The game-logic Config no longer
stores a ServerConfig/ClientEnv reference and its serverConfig() getter
is gone; the one caller (MultiTabModal) now reads ClientEnv.env()
directly. Worker init no longer carries server-config values since
nothing in the worker actually reads them.

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file
- [x] I have added relevant tests to the test directory
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced

## Please put your Discord username so you can be contacted if a bug or
regression is found:

evan
2026-05-11 19:24:01 -07:00

167 lines
5.5 KiB
TypeScript

import type { Express, Request } from "express";
import fsPromises from "fs/promises";
import { parse } from "node-html-parser";
import path from "path";
import type { Logger } from "winston";
import { z } from "zod";
import { GAME_ID_REGEX, GameInfo } from "../core/Schemas";
import { replacer } from "../core/Util";
import type { GameManager } from "./GameManager";
import {
buildPreview,
escapeHtml,
ExternalGameInfo,
ExternalGameInfoSchema,
} from "./GamePreviewBuilder";
import { setNoStoreHeaders } from "./NoStoreHeaders";
import { getAppShellContent, setHtmlNoCacheHeaders } from "./RenderHtml";
import { ServerEnv } from "./ServerEnv";
const requestOrigin = (req: Request): string => {
const protoHeader = (req.headers["x-forwarded-proto"] as string) ?? "";
const proto = protoHeader.split(",")[0]?.trim() || req.protocol || "https";
const host =
req.get("host") ?? `${ServerEnv.subdomain()}.${ServerEnv.domain()}`;
// Force https only for the configured public domain (and its subdomains).
// This avoids hardcoding hostnames while ensuring we don't force https on
// localhost or arbitrary custom hosts.
const hostname = host.split(":")[0].toLowerCase();
const domain = ServerEnv.domain().toLowerCase();
const forceHttps = hostname === domain || hostname.endsWith(`.${domain}`);
return `${forceHttps ? "https" : proto}://${host}`;
};
export function registerGamePreviewRoute(opts: {
app: Express;
gm: GameManager;
workerId: number;
log: Logger;
baseDir: string;
}) {
const { app, gm, log, baseDir } = opts;
const gameIDSchema = z.string().regex(GAME_ID_REGEX);
const fetchPublicGameInfo = async (
gameID: string,
): Promise<ExternalGameInfo | null> => {
if (!gameIDSchema.safeParse(gameID).success) return null;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 1500);
try {
const apiDomain = ServerEnv.jwtIssuer();
const encodedID = encodeURIComponent(gameID);
const response = await fetch(`${apiDomain}/game/${encodedID}`, {
headers: {
"x-api-key": ServerEnv.apiKey(),
},
signal: controller.signal,
});
if (!response.ok) return null;
const data = await response.json();
const parsed = ExternalGameInfoSchema.safeParse(data);
if (!parsed.success) {
log.warn("Invalid ExternalGameInfo from API", {
gameID,
issues: parsed.error.issues,
});
return null;
}
return parsed.data;
} catch (error) {
log.warn("failed to fetch public game info", { gameID, error });
return null;
} finally {
clearTimeout(timeout);
}
};
app.get("/game/:id", async (req, res) => {
const gameID = req.params.id;
// Validate gameID format
if (!GAME_ID_REGEX.test(gameID)) {
return res.status(400).json({ error: "Invalid game ID format" });
}
const game = gm.game(gameID);
const lobby: GameInfo | null = game ? game.gameInfo() : null;
try {
const publicInfo = await fetchPublicGameInfo(gameID); // Fetch from central API (DB/Auth)
// If we have neither live lobby info nor archived public info, we can't show anything
if (!lobby && !publicInfo) {
return res.redirect(302, "/");
}
const origin = requestOrigin(req);
const meta = await buildPreview(
gameID,
origin,
ServerEnv.workerPath(gameID),
lobby,
publicInfo,
);
// Always serve HTML with meta tags for /game/:id route
const staticHtml = path.join(baseDir, "../../static/index.html");
const rootHtml = path.join(baseDir, "../../index.html");
let filePath: string | null = null;
try {
await fsPromises.access(staticHtml);
filePath = staticHtml;
} catch {
try {
await fsPromises.access(rootHtml);
filePath = rootHtml;
} catch {
// Neither file exists
}
}
if (filePath) {
const html = await getAppShellContent(filePath);
const root = parse(html);
const head = root.querySelector("head");
if (head) {
head
.querySelectorAll('meta[property^="og:"], meta[name^="twitter:"]')
.forEach((el) => el.remove());
const tagsToInject = [
`<meta property="og:title" content="${escapeHtml(meta.title)}" />`,
`<meta property="og:description" content="${escapeHtml(meta.description || meta.title)}" />`,
`<meta property="og:url" content="${escapeHtml(meta.joinUrl)}" />`,
`<meta property="og:image" content="${escapeHtml(meta.image)}" />`,
`<meta name="twitter:card" content="summary_large_image" />`,
`<meta name="twitter:title" content="${escapeHtml(meta.title)}" />`,
`<meta name="twitter:description" content="${escapeHtml(meta.description || meta.title)}" />`,
`<meta name="twitter:image" content="${escapeHtml(meta.image)}" />`,
];
tagsToInject.forEach((tag) =>
head.insertAdjacentHTML("beforeend", tag),
);
}
setHtmlNoCacheHeaders(res);
return res.status(200).send(root.toString());
}
// Fallback to JSON if HTML file not found
setNoStoreHeaders(res);
res.setHeader("Content-Type", "application/json");
return res.send(JSON.stringify(lobby ?? publicInfo, replacer));
} catch (error) {
log.error("failed to render join preview", { error });
return res.status(500).send("Unable to render lobby preview");
}
});
}