From 40b4e4d2f52f55a8c1078fa070be6644cc0c7767 Mon Sep 17 00:00:00 2001 From: Shaswat Raj <108283560+playlikeboy@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:19:02 +0530 Subject: [PATCH 1/4] fix(seo): publish only verifiable game ratings --- web/src/app/game/[slug]/page.tsx | 34 +++++++++++++++++++++----------- web/src/components/GameCard.tsx | 19 +++++++++++------- web/src/lib/verified-rating.ts | 22 +++++++++++++++++++++ web/src/types.ts | 3 ++- web/tests/game-rating.test.ts | 23 +++++++++++++++++++++ 5 files changed, 81 insertions(+), 20 deletions(-) create mode 100644 web/src/lib/verified-rating.ts create mode 100644 web/tests/game-rating.test.ts diff --git a/web/src/app/game/[slug]/page.tsx b/web/src/app/game/[slug]/page.tsx index 593619b1..b233c115 100644 --- a/web/src/app/game/[slug]/page.tsx +++ b/web/src/app/game/[slug]/page.tsx @@ -6,6 +6,7 @@ import Link from 'next/link'; import { ChevronLeft, Star } from 'lucide-react'; import { GameInteractions } from '../../../components/GameInteractions'; import { GameGrid } from '../../../components/GameGrid'; +import { getVerifiedRating } from '../../../lib/verified-rating'; const BASE_URL = 'https://sopkit.github.io/games'; @@ -50,7 +51,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str const cleanDescription = game.description ? (game.description.length > 155 ? `${game.description.slice(0, 152)}...` : game.description) - : `Play ${game.name} online for free. No download required. Rated ${parseFloat(game.rating).toFixed(1)}/5.`; + : `Play ${game.name} online for free. No download required.`; return { title: `${game.name} - Play Online for Free | SOP Games`, @@ -82,6 +83,8 @@ export default async function GamePage({ params }: { params: Promise<{ slug: str ); } + const verifiedRating = getVerifiedRating(game); + // Related Games: find games in same category, exclude current, limit to 6 const relatedGames = games .filter((g) => g.category === game.category && g.slug !== slug) @@ -132,13 +135,15 @@ export default async function GamePage({ params }: { params: Promise<{ slug: str playMode: 'SinglePlayer', applicationCategory: 'Game', operatingSystem: 'Any', - aggregateRating: { - '@type': 'AggregateRating', - ratingValue: game.rating, - ratingCount: 100, - bestRating: 5, - worstRating: 1, - }, + ...(verifiedRating ? { + aggregateRating: { + '@type': 'AggregateRating', + ratingValue: verifiedRating.value, + ratingCount: verifiedRating.ratingCount, + bestRating: 5, + worstRating: 1, + }, + } : {}), offers: { '@type': 'Offer', price: '0', @@ -212,10 +217,15 @@ export default async function GamePage({ params }: { params: Promise<{ slug: str Free to Play -
- - {parseFloat(game.rating).toFixed(1)} -
+ {verifiedRating && ( +
+ + {verifiedRating.value.toFixed(1)} +
+ )} {game.category && ( - {/* Floating Rating Badge */} -
- - {rating} -
+ {/* Only display ratings backed by a real provider-supplied sample count. */} + {verifiedRating && ( +
+ + {verifiedRating.value.toFixed(1)} +
+ )} {/* Central Play Icon Overlay */}
diff --git a/web/src/lib/verified-rating.ts b/web/src/lib/verified-rating.ts new file mode 100644 index 00000000..f5aba10f --- /dev/null +++ b/web/src/lib/verified-rating.ts @@ -0,0 +1,22 @@ +import type { Game } from "../types"; + +export interface VerifiedRating { + value: number; + ratingCount: number; +} + +/** + * A score without a real sample count is not a user rating. + * This also hides legacy ID-derived scores that older catalog snapshots stored. + */ +export function getVerifiedRating( + game: Pick, +): VerifiedRating | null { + const value = Number.parseFloat(game.rating ?? ""); + const ratingCount = game.ratingCount; + + if (!Number.isFinite(value) || value < 1 || value > 5) return null; + if (!Number.isSafeInteger(ratingCount) || (ratingCount ?? 0) <= 0) return null; + + return { value, ratingCount: ratingCount as number }; +} diff --git a/web/src/types.ts b/web/src/types.ts index ca3f0e13..8504d1d5 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -5,7 +5,8 @@ export interface Game { url: string; embedUrl: string; image: string; - rating: string; + rating?: string; + ratingCount?: number; description?: string; instructions?: string; category?: string; diff --git a/web/tests/game-rating.test.ts b/web/tests/game-rating.test.ts new file mode 100644 index 00000000..4084f1ae --- /dev/null +++ b/web/tests/game-rating.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "bun:test"; +import { getVerifiedRating } from "../src/lib/verified-rating"; + +describe("getVerifiedRating", () => { + test("accepts a valid score with a positive provider-supplied sample count", () => { + expect(getVerifiedRating({ rating: "4.6", ratingCount: 42 })).toEqual({ + value: 4.6, + ratingCount: 42, + }); + }); + + test("hides legacy scores without a sample count", () => { + expect(getVerifiedRating({ rating: "5.0" })).toBeNull(); + }); + + test("rejects scores and sample counts outside the supported range", () => { + expect(getVerifiedRating({ rating: "5.5", ratingCount: 4 })).toBeNull(); + expect(getVerifiedRating({ rating: "0", ratingCount: 4 })).toBeNull(); + expect(getVerifiedRating({ rating: "4.2", ratingCount: 0 })).toBeNull(); + expect(getVerifiedRating({ rating: "4.2", ratingCount: -1 })).toBeNull(); + expect(getVerifiedRating({ rating: "not-a-score", ratingCount: 4 })).toBeNull(); + }); +}); From 1f7a70f3859e94fb25da03ddc701577abce20bbb Mon Sep 17 00:00:00 2001 From: Shaswat Raj <108283560+playlikeboy@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:19:58 +0530 Subject: [PATCH 2/4] fix(scraper): omit synthetic scores from generated game records --- scripts/game-feed.ts | 265 ++++++++++++++++++++++++++++++++++++++++ tests/game-feed.test.ts | 121 ++++++++++++++++++ 2 files changed, 386 insertions(+) create mode 100644 scripts/game-feed.ts create mode 100644 tests/game-feed.test.ts diff --git a/scripts/game-feed.ts b/scripts/game-feed.ts new file mode 100644 index 00000000..a4655acc --- /dev/null +++ b/scripts/game-feed.ts @@ -0,0 +1,265 @@ +import { randomUUID } from "node:crypto"; +import { + lstat, + mkdtemp, + mkdir, + readdir, + rename, + rm, + writeFile, +} from "node:fs/promises"; +import path from "node:path"; + +export interface GameRecord { + id: string; + name: string; + slug: string; + description: string; + instructions: string; + category: string; + tags: string[]; + url: string; + embedUrl: string; + image: string; + width: string; + height: string; +} + +export interface NormalizeResult { + games: GameRecord[]; + skipped: Array<{ index: number; reason: string }>; +} + +export interface FetchOptions { + attempts?: number; + timeoutMs?: number; + baseDelayMs?: number; + maxDelayMs?: number; +} + +function asText(value: unknown): string { + return typeof value === "string" || typeof value === "number" ? String(value).trim() : ""; +} + +function safeHttpUrl(value: unknown): string | null { + const raw = asText(value); + if (!raw) return null; + + try { + const parsed = new URL(raw); + if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) { + return null; + } + return parsed.toString(); + } catch { + return null; + } +} + +function slugify(value: string): string { + return value + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .trim() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); +} + +function normalizeTags(value: unknown): string[] { + const raw = Array.isArray(value) + ? value + : typeof value === "string" + ? value.split(",") + : []; + + const seen = new Set(); + const tags: string[] = []; + + for (const entry of raw) { + const tag = asText(entry); + const key = tag.toLowerCase(); + if (tag && !seen.has(key)) { + seen.add(key); + tags.push(tag); + } + } + + return tags; +} + +function dimension(value: unknown, fallback: string): string { + const parsed = Number.parseInt(asText(value), 10); + return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= 10000 + ? String(parsed) + : fallback; +} + +export function normalizeGameFeed(payload: unknown): NormalizeResult { + if (!Array.isArray(payload)) { + throw new Error("Game feed must be a JSON array."); + } + + const games: GameRecord[] = []; + const skipped: NormalizeResult["skipped"] = []; + const seenIds = new Set(); + const seenSlugs = new Set(); + + payload.forEach((raw: unknown, index: number) => { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + skipped.push({ index, reason: "Record is not an object." }); + return; + } + + const item = raw as Record; + const id = asText(item.id); + const name = asText(item.title); + const url = safeHttpUrl(item.url); + const image = safeHttpUrl(item.thumb); + + if (!/^[a-zA-Z0-9_-]{1,100}$/.test(id)) { + skipped.push({ index, reason: "Missing or unsafe game ID." }); + return; + } + if (!name) { + skipped.push({ index, reason: "Missing game title." }); + return; + } + if (!url || !image) { + skipped.push({ index, reason: "Game URL or thumbnail is not a valid HTTP(S) URL." }); + return; + } + if (seenIds.has(id)) { + skipped.push({ index, reason: `Duplicate game ID: ${id}.` }); + return; + } + + const baseSlug = slugify(name) || `game-${slugify(id)}`; + let slug = baseSlug; + if (seenSlugs.has(slug)) slug = `${baseSlug}-${slugify(id)}`; + let suffix = 2; + while (seenSlugs.has(slug)) slug = `${baseSlug}-${slugify(id)}-${suffix++}`; + + seenIds.add(id); + seenSlugs.add(slug); + + games.push({ + id, + name, + slug, + description: asText(item.description) || `Play ${name} online for free.`, + instructions: asText(item.instructions) || "Use keyboard or mouse to play.", + category: asText(item.category) || "Casual", + tags: normalizeTags(item.tags), + url, + embedUrl: url, + image, + width: dimension(item.width, "800"), + height: dimension(item.height, "600"), + }); + }); + + return { games, skipped }; +} + +export async function fetchJsonWithRetry( + url: string, + fetchImpl: typeof fetch = fetch, + options: FetchOptions = {}, +): Promise { + const attempts = Math.max(1, Math.floor(options.attempts ?? 3)); + const timeoutMs = Math.max(1, options.timeoutMs ?? 15_000); + const baseDelayMs = Math.max(0, options.baseDelayMs ?? 500); + const maxDelayMs = Math.max(baseDelayMs, options.maxDelayMs ?? 5_000); + let lastError: unknown; + + for (let attempt = 1; attempt <= attempts; attempt++) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + + try { + const response = await fetchImpl(url, { + signal: controller.signal, + headers: { accept: "application/json" }, + }); + + if (!response.ok) { + const retryable = response.status === 408 || response.status === 429 || response.status >= 500; + const error = new Error(`Feed request failed with HTTP ${response.status}.`); + if (!retryable || attempt === attempts) throw error; + const retryAfter = Number(response.headers.get("retry-after")); + const delay = Number.isFinite(retryAfter) && retryAfter > 0 + ? Math.min(maxDelayMs, retryAfter * 1000) + : Math.min(maxDelayMs, baseDelayMs * attempt); + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + + return await response.json(); + } catch (error) { + lastError = error; + if (attempt === attempts) break; + const delay = Math.min(maxDelayMs, baseDelayMs * attempt); + if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay)); + } finally { + clearTimeout(timeout); + } + } + + throw new Error( + `Unable to fetch game feed after ${attempts} attempt(s): ${lastError instanceof Error ? lastError.message : String(lastError)}`, + ); +} + +async function pathExists(target: string): Promise { + try { + await lstat(target); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + +export async function persistGameRecords( + games: GameRecord[], + rootDirectory = process.cwd(), + outputDirectory = "games", +): Promise { + if (games.length === 0) throw new Error("Refusing to replace the game catalog with an empty feed."); + + const outputPath = path.join(rootDirectory, outputDirectory); + const stagingPath = await mkdtemp(path.join(rootDirectory, ".games-stage-")); + const backupPath = path.join(rootDirectory, `.games-backup-${randomUUID()}`); + let movedOldDirectory = false; + + try { + for (const game of games) { + await writeFile( + path.join(stagingPath, `${game.id}.json`), + JSON.stringify(game, null, 2) + "\n", + { encoding: "utf8", flag: "wx" }, + ); + } + + if (await pathExists(outputPath)) { + const info = await lstat(outputPath); + if (!info.isDirectory() || info.isSymbolicLink()) { + throw new Error(`Refusing to replace non-directory output path: ${outputPath}`); + } + await rename(outputPath, backupPath); + movedOldDirectory = true; + } + + try { + await rename(stagingPath, outputPath); + } catch (error) { + if (movedOldDirectory) await rename(backupPath, outputPath); + throw error; + } + + if (movedOldDirectory) await rm(backupPath, { recursive: true, force: true }); + } finally { + await rm(stagingPath, { recursive: true, force: true }); + } +} diff --git a/tests/game-feed.test.ts b/tests/game-feed.test.ts new file mode 100644 index 00000000..fabeb7d8 --- /dev/null +++ b/tests/game-feed.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, test } from "bun:test"; +import { + fetchJsonWithRetry, + normalizeGameFeed, + persistGameRecords, +} from "../scripts/game-feed"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import os from "node:os"; + +const valid = (overrides: Record = {}) => ({ + id: "100", + title: "Puzzle Hero", + description: "A puzzle game", + instructions: "Use the arrow keys", + category: "Puzzle", + tags: "Logic, Brain, Logic", + url: "https://games.example.test/play/100", + thumb: "https://images.example.test/100.jpg", + width: "800", + height: "600", + ...overrides, +}); + +describe("normalizeGameFeed", () => { + test("normalizes valid records and de-duplicates tags", () => { + const result = normalizeGameFeed([valid()]); + expect(result.games).toHaveLength(1); + expect(result.games[0]?.slug).toBe("puzzle-hero"); + expect(result.games[0]?.tags).toEqual(["Logic", "Brain"]); + expect(result.games[0]?.rating).toBeUndefined(); + expect(result.skipped).toHaveLength(0); + }); + + test("skips malformed records, duplicate IDs, and unsafe URLs", () => { + const result = normalizeGameFeed([ + null, + valid(), + valid({ id: "100", title: "Duplicate" }), + valid({ id: "bad/id" }), + valid({ id: "101", url: "javascript:alert(1)" }), + ]); + expect(result.games).toHaveLength(1); + expect(result.skipped).toHaveLength(4); + }); + + test("makes duplicate titles produce stable unique slugs", () => { + const result = normalizeGameFeed([ + valid({ id: "101", title: "Same Name" }), + valid({ id: "102", title: "Same Name" }), + ]); + expect(result.games.map((game) => game.slug)).toEqual(["same-name", "same-name-102"]); + }); + + test("rejects a non-array feed payload", () => { + expect(() => normalizeGameFeed({ games: [] })).toThrow("JSON array"); + }); +}); + +describe("fetchJsonWithRetry", () => { + test("retries transient HTTP failures and returns the successful response", async () => { + let calls = 0; + const fakeFetch: typeof fetch = async () => { + calls += 1; + return calls === 1 + ? new Response("temporary failure", { status: 503 }) + : new Response(JSON.stringify([valid()]), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }; + + const payload = await fetchJsonWithRetry("https://feed.example.test", fakeFetch, { + attempts: 2, + baseDelayMs: 0, + }); + expect(calls).toBe(2); + expect(Array.isArray(payload)).toBe(true); + }); + + test("does not retry permanent client errors", async () => { + let calls = 0; + const fakeFetch: typeof fetch = async () => { + calls += 1; + return new Response("not found", { status: 404 }); + }; + await expect(fetchJsonWithRetry("https://feed.example.test", fakeFetch, { + attempts: 3, + baseDelayMs: 0, + })).rejects.toThrow("HTTP 404"); + expect(calls).toBe(1); + }); +}); + +describe("persistGameRecords", () => { + test("replaces a populated directory only after staging all new records", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "sopgames-test-")); + try { + await writeFile(path.join(root, "sentinel.txt"), "keep root"); + await persistGameRecords(normalizeGameFeed([valid()]).games, root); + const files = await readdir(path.join(root, "games")); + expect(files).toEqual(["100.json"]); + const saved = JSON.parse(await readFile(path.join(root, "games", "100.json"), "utf8")); + expect(saved.slug).toBe("puzzle-hero"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + test("keeps existing catalog when the new feed is empty", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "sopgames-test-")); + try { + await import("node:fs/promises").then(({ mkdir }) => mkdir(path.join(root, "games"))); + await writeFile(path.join(root, "games", "old.json"), "{}"); + await expect(persistGameRecords([], root)).rejects.toThrow("empty feed"); + expect(await readdir(path.join(root, "games"))).toEqual(["old.json"]); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); From ab3ab15ec307037af650e617858a89f082c83740 Mon Sep 17 00:00:00 2001 From: Shaswat Raj <108283560+playlikeboy@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:21:00 +0530 Subject: [PATCH 3/4] fix(seo): validate rating strings and sort only verified scores --- web/src/components/GameCatalog.tsx | 10 +++++++++- web/src/lib/verified-rating.ts | 4 +++- web/tests/game-rating.test.ts | 1 + 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/web/src/components/GameCatalog.tsx b/web/src/components/GameCatalog.tsx index 3e6e06a5..ed1efbae 100644 --- a/web/src/components/GameCatalog.tsx +++ b/web/src/components/GameCatalog.tsx @@ -12,6 +12,14 @@ const fetcher = (url: string): Promise => fetch(url).then((res) => res.j const GAMES_PER_PAGE = 50; +function getSortableRating(game: Game): number { + const rating = Number.parseFloat(game.rating ?? ""); + const ratingCount = (game as Game & { ratingCount?: number }).ratingCount; + if (!Number.isFinite(rating) || rating < 1 || rating > 5) return -1; + if (!Number.isSafeInteger(ratingCount) || (ratingCount ?? 0) <= 0) return -1; + return rating; +} + interface GameCatalogProps { initialGames: Game[]; } @@ -137,7 +145,7 @@ export function GameCatalog({ initialGames }: GameCatalogProps) { } if (sort === 'rating') { - result.sort((a, b) => parseFloat(b.rating) - parseFloat(a.rating)); + result.sort((a, b) => getSortableRating(b) - getSortableRating(a)); } else { // Fallback for "newest" using ID if date isn't available, or just keeping original order if that's implied "newest" // Assuming higher ID is newer for now. diff --git a/web/src/lib/verified-rating.ts b/web/src/lib/verified-rating.ts index f5aba10f..59b92c80 100644 --- a/web/src/lib/verified-rating.ts +++ b/web/src/lib/verified-rating.ts @@ -12,7 +12,9 @@ export interface VerifiedRating { export function getVerifiedRating( game: Pick, ): VerifiedRating | null { - const value = Number.parseFloat(game.rating ?? ""); + const rawRating = game.rating?.trim() ?? ""; + if (!/^\\d+(?:\\.\\d+)?$/.test(rawRating)) return null; + const value = Number(rawRating); const ratingCount = game.ratingCount; if (!Number.isFinite(value) || value < 1 || value > 5) return null; diff --git a/web/tests/game-rating.test.ts b/web/tests/game-rating.test.ts index 4084f1ae..287c7062 100644 --- a/web/tests/game-rating.test.ts +++ b/web/tests/game-rating.test.ts @@ -19,5 +19,6 @@ describe("getVerifiedRating", () => { expect(getVerifiedRating({ rating: "4.2", ratingCount: 0 })).toBeNull(); expect(getVerifiedRating({ rating: "4.2", ratingCount: -1 })).toBeNull(); expect(getVerifiedRating({ rating: "not-a-score", ratingCount: 4 })).toBeNull(); + expect(getVerifiedRating({ rating: "4.6 stars", ratingCount: 4 })).toBeNull(); }); }); From 12bb7a29e3e22cf5d068106b878ee213fafa789d Mon Sep 17 00:00:00 2001 From: Shaswat Raj <108283560+playlikeboy@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:21:35 +0530 Subject: [PATCH 4/4] fix(seo): reject malformed rating strings --- web/src/lib/verified-rating.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/lib/verified-rating.ts b/web/src/lib/verified-rating.ts index 59b92c80..4a8c82ef 100644 --- a/web/src/lib/verified-rating.ts +++ b/web/src/lib/verified-rating.ts @@ -13,7 +13,7 @@ export function getVerifiedRating( game: Pick, ): VerifiedRating | null { const rawRating = game.rating?.trim() ?? ""; - if (!/^\\d+(?:\\.\\d+)?$/.test(rawRating)) return null; + if (!/^\d+(?:\.\d+)?$/.test(rawRating)) return null; const value = Number(rawRating); const ratingCount = game.ratingCount;