Discord(et al.) embedded URLs (#2740)

## Description:

Changes URL embeds within other platforms, e.g. Discord, WhatsApp & X.

Updates game URLs to `/game/<code>` instead of `/#join=<code>` (required
for embedded URLs). An added benefit of this is that you would be able
to change a url from `openfront.io/game/RQDUy8nP?replay` to
`api.openfront.io/game/RQDUy8nP?replay` (add api. In front) and be in
the right place for the API data.

Updates URLs when joining/leaving private lobbies

Appends a random string to the end of the URL when inside a private
lobby and options change - this is to force discord to update the
embedded details.

Updates URL in different game states to ?lobby / ?live and ?replay.
These do nothing other than being used as a _cache-busting_ solution.


-----------------------------------------------
### **Lobby Info**

Discord:
<img width="556" height="487" alt="image"
src="https://github.com/user-attachments/assets/efd4a06d-506c-4036-9403-ee7c9a669e21"
/>

WhatsApp:
<img width="353" height="339" alt="image"
src="https://github.com/user-attachments/assets/3b2d0c69-988c-424f-9dee-f4e6a6868f6b"
/>


x.com:
<img width="588" height="325" alt="image"
src="https://github.com/user-attachments/assets/d9e78169-20be-4a3e-8df4-8ad41d08a750"
/>


-------------------------
### **Game Win Details**
Discord:
<img width="506" height="468" alt="image"
src="https://github.com/user-attachments/assets/69947774-c943-4a50-b470-5634ed3bf3d7"
/>

WhatsApp:
<img width="770" height="132" alt="image"
src="https://github.com/user-attachments/assets/eec28bf8-bf64-4ab8-954e-03dfdd1aae40"
/>

x.com
<img width="584" height="350" alt="image"
src="https://github.com/user-attachments/assets/168063e2-b707-422b-b7a1-0025f3ebeb92"
/>


## 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:

w.o.n
This commit is contained in:
Ryan
2026-01-14 03:48:00 +00:00
committed by GitHub
parent c80ccaece9
commit 247c78151c
15 changed files with 832 additions and 345 deletions
+267
View File
@@ -0,0 +1,267 @@
import { z } from "zod";
import { GameInfo } from "../core/Schemas";
import { GameMode } from "../core/game/Game";
export const PlayerInfoSchema = z.object({
clientID: z.string().optional(),
username: z.string().optional(),
stats: z.unknown().optional(),
});
export type PlayerInfo = z.infer<typeof PlayerInfoSchema>;
export const ExternalGameInfoSchema = z.object({
info: z
.object({
config: z
.object({
gameMap: z.string().optional(),
gameMode: z.string().optional(),
gameType: z.string().optional(),
maxPlayers: z.number().optional(),
playerTeams: z.union([z.number(), z.string()]).optional(),
})
.optional(),
players: z.array(PlayerInfoSchema).optional(),
winner: z.array(z.string()).optional(),
duration: z.number().optional(),
start: z.number().optional(),
end: z.number().optional(),
lobbyCreatedAt: z.number().optional(),
})
.optional(),
});
export type ExternalGameInfo = z.infer<typeof ExternalGameInfoSchema>;
export type PreviewMeta = {
title: string;
description: string;
image: string;
joinUrl: string;
};
function formatDuration(seconds: number): string {
if (!Number.isFinite(seconds) || seconds < 0) return "Unknown";
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
const hours = Math.floor(mins / 60);
const minutes = mins % 60;
if (hours) return `${hours}h ${minutes}m ${secs}s`;
if (minutes) return `${minutes}m ${secs}s`;
return `${secs}s`;
}
function normalizeTimestamp(timestamp: number): number {
return timestamp < 1e12 ? timestamp * 1000 : timestamp;
}
function formatDateTimeParts(timestamp: number): {
date: string;
time: string;
} {
const date = new Date(normalizeTimestamp(timestamp));
const dateLabel = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
}).format(date);
const timeLabel = new Intl.DateTimeFormat("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
timeZone: "UTC",
}).format(date);
return { date: dateLabel, time: `${timeLabel} UTC` };
}
type WinnerInfo = { names: string; count: number };
function parseWinner(
winnerArray: string[] | undefined,
players: PlayerInfo[] | undefined,
): WinnerInfo | undefined {
if (!winnerArray || winnerArray.length < 2) return undefined;
const idToName = new Map(
(players ?? []).map((p) => [p.clientID, p.username]),
);
if (winnerArray[0] === "team" && winnerArray.length >= 3) {
const playerIds = winnerArray.slice(2);
const names = playerIds.map((id) => idToName.get(id) ?? id).filter(Boolean);
return names.length > 0
? { names: names.join(", "), count: names.length }
: undefined;
}
if (winnerArray[0] === "player" && winnerArray.length >= 2) {
const clientId = winnerArray[1];
const name = idToName.get(clientId) ?? clientId;
return { names: name, count: 1 };
}
// Unknown winner format - don't display confusing output
return undefined;
}
function countActivePlayers(players: PlayerInfo[] | undefined): number {
return (players ?? []).filter((p) => {
if (!p || p.stats === null || p.stats === undefined) return false;
// Count only when `stats` has at least one property.
if (typeof p.stats === "object") {
return Object.keys(p.stats as Record<string, unknown>).length > 0;
}
return false;
}).length;
}
export function escapeHtml(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
export function buildPreview(
gameID: string,
origin: string,
workerPath: string,
lobby: GameInfo | null,
publicInfo: ExternalGameInfo | null,
): PreviewMeta {
const isFinished = !!publicInfo?.info?.end;
const isPrivate = lobby?.gameConfig?.gameType === "Private";
// route directly to the correct worker.
const joinUrl = `${origin}/${workerPath}/game/${gameID}`;
const config = publicInfo?.info?.config ?? {};
const players = publicInfo?.info?.players ?? [];
let activePlayers: number;
if (isFinished) {
activePlayers = countActivePlayers(players);
} else {
activePlayers =
countActivePlayers(players) ||
(lobby?.numClients ?? lobby?.clients?.length ?? 0);
}
const map = lobby?.gameConfig?.gameMap ?? config.gameMap;
let mode = lobby?.gameConfig?.gameMode ?? config.gameMode ?? GameMode.FFA;
const playerTeams = lobby?.gameConfig?.playerTeams ?? config.playerTeams;
const numericTeamCount =
typeof playerTeams === "number" && playerTeams > 0
? playerTeams
: undefined;
// For finished games, show "x teams of y". For lobbies, just show "x teams"
const teamBreakdownLabel = numericTeamCount
? isFinished
? `${numericTeamCount} teams of ${Math.max(
1,
Math.ceil(activePlayers / numericTeamCount),
)}`
: `${numericTeamCount} teams`
: undefined;
// Format team mode display
if (mode === "Team" && playerTeams) {
if (typeof playerTeams === "string") {
mode = playerTeams; // e.g., "Quads"
} else if (typeof playerTeams === "number") {
mode = teamBreakdownLabel ?? `${playerTeams} Teams`;
}
}
const winner = parseWinner(publicInfo?.info?.winner, players);
const duration = publicInfo?.info?.duration;
// Normalize map name to match filesystem (lowercase, no spaces or special chars)
const normalizedMap = map ? map.toLowerCase().replace(/[\s.()]+/g, "") : null;
const mapThumbnail = normalizedMap
? `${origin}/maps/${encodeURIComponent(normalizedMap)}/thumbnail.webp`
: null;
const image = mapThumbnail ?? `${origin}/images/GameplayScreenshot.png`;
const gameType = lobby?.gameConfig?.gameType ?? config.gameType;
const gameTypeLabel = gameType ? ` (${gameType})` : "";
const title = isFinished
? `${mode ?? "Game"} on ${map ?? "Unknown Map"}${gameTypeLabel}`
: mode && map
? `${mode} on ${map}${gameTypeLabel}`
: "OpenFront Game";
let description = "";
if (isFinished) {
const parts: string[] = [];
if (winner) {
parts.push(`${winner.count > 1 ? "Winners" : "Winner"}: ${winner.names}`);
parts.push(""); // Extra line break after winner
}
const matchTimestamp =
publicInfo?.info?.start ??
publicInfo?.info?.end ??
publicInfo?.info?.lobbyCreatedAt;
const detailParts: string[] = [];
const playerCountLabel = `${activePlayers} ${activePlayers === 1 ? "player" : "players"}`;
detailParts.push(playerCountLabel);
if (duration !== undefined) detailParts.push(`${formatDuration(duration)}`);
if (matchTimestamp !== undefined) {
const dateTime = formatDateTimeParts(matchTimestamp);
detailParts.push(`${dateTime.date}`);
detailParts.push(`${dateTime.time}`);
}
parts.push(detailParts.join(" • "));
description = parts.join("\n");
} else if (lobby) {
const gc = lobby.gameConfig;
if (isPrivate) {
// Private lobby: show detailed game settings
const sections: string[] = [];
// Show host
const hostClient = lobby.clients?.[0];
if (hostClient?.username) {
sections.push(`Host: ${hostClient.username}`);
}
const gameOptions: string[] = [];
if (gc?.gameMapSize && gc.gameMapSize !== "Normal") {
gameOptions.push(`${gc.gameMapSize} Map`);
}
if (gc?.infiniteGold) gameOptions.push("Infinite Gold");
if (gc?.infiniteTroops) gameOptions.push("Infinite Troops");
if (gc?.instantBuild) gameOptions.push("Instant Build");
if (gc?.randomSpawn) gameOptions.push("Random Spawn");
if (gc?.disableNations) gameOptions.push("Nations Disabled");
if (gc?.donateTroops) gameOptions.push("Troop Donations Enabled");
if (gameOptions.length > 0) {
sections.push(`Game Options: ${gameOptions.join(" | ")}`);
}
if (Array.isArray(gc?.disabledUnits) && gc.disabledUnits.length > 0) {
sections.push(
`Disabled Units: ${gc.disabledUnits.map(String).join(" | ")}`,
);
}
description = sections.join("\n\n");
} else {
// Public lobby: basic info
description = "";
}
} else {
description = `Game ${gameID}`;
}
return { title, description, image, joinUrl };
}
+161
View File
@@ -0,0 +1,161 @@
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 type { ServerConfig } from "../core/configuration/Config";
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 { renderHtmlContent, setHtmlNoCacheHeaders } from "./RenderHtml";
const requestOrigin = (req: Request, config: ServerConfig): string => {
const protoHeader = (req.headers["x-forwarded-proto"] as string) ?? "";
const proto = protoHeader.split(",")[0]?.trim() || req.protocol || "https";
const host = req.get("host") ?? `${config.subdomain()}.${config.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 = config.domain().toLowerCase();
const forceHttps = hostname === domain || hostname.endsWith(`.${domain}`);
return `${forceHttps ? "https" : proto}://${host}`;
};
export function registerGamePreviewRoute(opts: {
app: Express;
gm: GameManager;
config: ServerConfig;
workerId: number;
log: Logger;
baseDir: string;
}) {
const { app, gm, config, 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 = config.jwtIssuer();
const encodedID = encodeURIComponent(gameID);
const response = await fetch(`${apiDomain}/game/${encodedID}`, {
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, config);
const meta = buildPreview(
gameID,
origin,
config.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 renderHtmlContent(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
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");
}
});
}
+1 -24
View File
@@ -1,9 +1,7 @@
import cluster from "cluster";
import crypto from "crypto";
import ejs from "ejs";
import express from "express";
import rateLimit from "express-rate-limit";
import fs from "fs/promises";
import http from "http";
import path from "path";
import { fileURLToPath } from "url";
@@ -14,6 +12,7 @@ import { GameInfo } from "../core/Schemas";
import { generateID } from "../core/Util";
import { logger } from "./Logger";
import { MapPlaylist } from "./MapPlaylist";
import { renderHtml } from "./RenderHtml";
const config = getServerConfigFromServer();
const playlist = new MapPlaylist();
@@ -348,25 +347,3 @@ app.get("*", async function (_req, res) {
res.status(500).send("Internal Server Error");
}
});
// Helper function to render HTML with EJS templating
async function renderHtml(
res: express.Response,
htmlPath: string,
): Promise<void> {
const htmlContent = await fs.readFile(htmlPath, "utf-8");
const rendered = ejs.render(htmlContent, {
gitCommit: JSON.stringify(process.env.GIT_COMMIT ?? "undefined"),
instanceId: JSON.stringify(process.env.INSTANCE_ID ?? "undefined"),
});
res.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate",
);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
res.setHeader("ETag", "");
res.setHeader("Content-Type", "text/html");
res.send(rendered);
}
+31
View File
@@ -0,0 +1,31 @@
import ejs from "ejs";
import type { Response } from "express";
import fs from "fs/promises";
export async function renderHtmlContent(htmlPath: string): Promise<string> {
const htmlContent = await fs.readFile(htmlPath, "utf-8");
return ejs.render(htmlContent, {
gitCommit: JSON.stringify(process.env.GIT_COMMIT ?? "undefined"),
instanceId: JSON.stringify(process.env.INSTANCE_ID ?? "undefined"),
});
}
export function setHtmlNoCacheHeaders(res: Response): void {
res.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate",
);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
res.setHeader("ETag", "");
res.setHeader("Content-Type", "text/html");
}
export async function renderHtml(
res: Response,
htmlPath: string,
): Promise<void> {
const rendered = await renderHtmlContent(htmlPath);
setHtmlNoCacheHeaders(res);
res.send(rendered);
}
+25
View File
@@ -21,6 +21,7 @@ import { CreateGameInputSchema } from "../core/WorkerSchemas";
import { archive, finalizeGameRecord } from "./Archive";
import { Client } from "./Client";
import { GameManager } from "./GameManager";
import { registerGamePreviewRoute } from "./GamePreviewRoute";
import { getUserMe, verifyClientToken } from "./jwt";
import { logger } from "./Logger";
@@ -94,7 +95,22 @@ export async function startWorker() {
app.set("trust proxy", 3);
app.use(compression());
app.use(express.json());
// Configure MIME types for webp files
express.static.mime.define({ "image/webp": ["webp"] });
app.use(express.static(path.join(__dirname, "../../out")));
app.use(
"/maps",
express.static(path.join(__dirname, "../../static/maps"), {
maxAge: "1y",
setHeaders: (res, filePath) => {
if (filePath.endsWith(".webp")) {
res.setHeader("Content-Type", "image/webp");
}
},
}),
);
app.use(
rateLimit({
windowMs: 1000, // 1 second
@@ -187,6 +203,15 @@ export async function startWorker() {
res.json(game.gameInfo());
});
registerGamePreviewRoute({
app,
gm,
config,
workerId,
log,
baseDir: __dirname,
});
app.post("/api/archive_singleplayer_game", async (req, res) => {
try {
const record = req.body;