From 62407ccd84cea181fa347d9092ecdf00aa0207e0 Mon Sep 17 00:00:00 2001 From: mrWD Date: Wed, 12 Aug 2026 12:37:34 +0200 Subject: [PATCH] Add IGDB as the second catalogue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RAWG going down left console games unfindable, and the measurements in DATA-SOURCES showed why nothing keyless could rescue them: cover art is copyrighted, so the free sources have the titles and not the pictures. IGDB has both, at the cost of a second credential. The proxy gains an igdb branch. It authenticates through Twitch with a client-credentials token cached in module scope, and translates the client's ordinary GET into the POST-with-a-text-body that IGDB's query language requires — so none of that protocol reaches the browser. The search term is quoted into a string literal and the only two query shapes are search and the discover orderings, so a client cannot inject clauses. Missing credentials answer 503, the same contract RAWG already had: 'not configured here', not an outage. In the client IGDB sits between RAWG and Steam, and the order is the whole point — Steam returns nothing at all for 'zelda' or 'mario'. Not yet verified against the live API: that needs the preview deploy, where the credentials live. Numbers to follow. Co-Authored-By: Claude Opus 5 --- api/games.js | 87 ++++++++++++++++++++++++++++++++++++++++++++++ src/lib/api.ts | 59 +++++++++++++++++++++++++++++-- src/store/stats.ts | 2 +- 3 files changed, 145 insertions(+), 3 deletions(-) diff --git a/api/games.js b/api/games.js index 9e40266..4d8bee9 100644 --- a/api/games.js +++ b/api/games.js @@ -8,6 +8,8 @@ const RAWG = 'https://api.rawg.io/api/' const STEAM_STORE = 'https://store.steampowered.com/api/' +const IGDB = 'https://api.igdb.com/v4/' +const TWITCH_TOKEN = 'https://id.twitch.tv/oauth2/token' /** GET-only allowlists; nothing else upstream is reachable through us. */ const ALLOWED = { @@ -17,6 +19,57 @@ const ALLOWED = { // is unreachable: it is the only keyless list of games with cover art we have. steam: (path) => path === 'storesearch' || path === 'appdetails' || path === 'featuredcategories', + // IGDB is the second catalogue with both console games and cover art — the gap + // neither Steam nor any keyless source can fill. Only the games endpoint is opened. + igdb: (path) => path === 'games', +} + +/** + * IGDB authenticates through Twitch: a client-credentials token, good for about 60 + * days, that has to be fetched before the first query. It is cached in module scope, + * which on Vercel means per warm instance — a cold start pays one extra round trip, + * and nothing is stored anywhere it could leak. + * + * Refreshed a minute early so a token cannot expire between the check and the call. + */ +let igdbToken = null + +async function igdbAccessToken(clientId, clientSecret) { + if (igdbToken && igdbToken.expiresAt > Date.now() + 60_000) return igdbToken.value + const url = new URL(TWITCH_TOKEN) + url.searchParams.set('client_id', clientId) + url.searchParams.set('client_secret', clientSecret) + url.searchParams.set('grant_type', 'client_credentials') + const res = await fetch(url, { method: 'POST' }) + if (!res.ok) throw new Error(`twitch token ${res.status}`) + const data = await res.json() + igdbToken = { + value: data.access_token, + expiresAt: Date.now() + (Number(data.expires_in) || 3600) * 1000, + } + return igdbToken.value +} + +/** + * IGDB speaks its own query language over POST with a plain-text body, unlike the two + * GET APIs beside it. The client still calls us with an ordinary GET; the query is + * assembled here so the shape of IGDB's protocol never reaches the browser. + * + * `search` and the discover orderings are the only two forms allowed. Anything the + * client sends is quoted into a string literal, so it cannot inject clauses. + */ +function igdbBody(query) { + const fields = + 'fields name,cover.image_id,first_release_date,genres.name,platforms.name,' + + 'total_rating,aggregated_rating,summary;' + const limit = Math.min(Math.max(Number(query.limit) || 20, 1), 50) + const term = String(query.search ?? '').slice(0, 100).replace(/["\\]/g, '') + if (term) return `search "${term}"; ${fields} limit ${limit};` + if (query.upcoming === '1') { + const now = Math.floor(Date.now() / 1000) + return `${fields} where first_release_date > ${now} & cover != null; sort first_release_date asc; limit ${limit};` + } + return `${fields} where total_rating_count > 20 & cover != null; sort total_rating desc; limit ${limit};` } function cacheFor(source, path) { @@ -103,6 +156,40 @@ export default async function handler(req, res) { return } + if (source === 'igdb') { + const clientId = process.env.IGDB_CLIENT_ID + const clientSecret = process.env.IGDB_CLIENT_SECRET + // Same contract as RAWG: 503 means "this catalogue is not configured here", and + // the client moves on to the next source rather than treating it as an outage. + if (!clientId || !clientSecret) { + res.status(503).json({ error: 'IGDB credentials not configured' }) + return + } + try { + const token = await igdbAccessToken(clientId, clientSecret) + const upstream = await fetch(IGDB + path, { + method: 'POST', + headers: { + 'Client-ID': clientId, + Authorization: `Bearer ${token}`, + 'Content-Type': 'text/plain', + 'User-Agent': 'GamesTable/1.0 (+https://github.com/mrWD/games-table)', + }, + body: igdbBody(req.query), + }) + const body = await upstream.text() + res.status(upstream.status) + res.setHeader('Content-Type', 'application/json; charset=utf-8') + if (upstream.ok) res.setHeader('Cache-Control', cacheFor(source, path)) + res.send(body) + } catch { + // A failed token exchange must not poison the next request with a stale token. + igdbToken = null + res.status(502).json({ error: 'igdb unreachable' }) + } + return + } + try { const upstream = await fetch(buildUpstream(source, path, req.query, key), { headers: { 'User-Agent': 'GamesTable/1.0 (+https://github.com/mrWD/games-table)' }, diff --git a/src/lib/api.ts b/src/lib/api.ts index ecc2da5..42a5f52 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -46,7 +46,7 @@ let rawgDisabled = false const REQUEST_TIMEOUT_MS = 8000 async function proxy( - source: 'rawg' | 'steam', + source: 'rawg' | 'steam' | 'igdb', path: string, params: Record = {}, ): Promise { @@ -182,6 +182,15 @@ export async function searchGames(query: string): Promise { return viaRawg.results.map(mapRawg) } + // IGDB before Steam, and the order is the whole point: it covers consoles, so + // "zelda" and "mario" still return Nintendo titles when RAWG cannot answer. Steam + // returns nothing for either (measured — see DATA-SOURCES). + const viaIgdb = await proxy('igdb', 'games', { search: term, limit: '20' }) + if (viaIgdb?.length) { + stats.source('igdb') + return viaIgdb.map(mapIgdb) + } + // Steam only knows PC titles, so this is a narrower answer, not an equal one. const viaSteam = await proxy<{ items?: SteamSearchItem[] }>('steam', 'storesearch', { term, @@ -232,6 +241,48 @@ export async function lookupGame(id: string): Promise { } /** Explore shelves: popular now and what is coming next. */ +/** + * IGDB — the second catalogue, and the only one besides RAWG that has both console + * games and cover art. Steam has neither for consoles; the keyless sources measured in + * DATA-SOURCES have the games but not the art, because cover art is copyrighted. + * + * Ids are prefixed `igdb:` so an entry saved from here stays distinguishable from the + * same game saved via RAWG or Steam. + */ +interface IgdbGame { + id: number + name?: string + cover?: { image_id?: string } + first_release_date?: number + genres?: { name: string }[] + platforms?: { name: string }[] + total_rating?: number + aggregated_rating?: number + summary?: string +} + +function mapIgdb(g: IgdbGame): GameSummary { + return { + id: `igdb:${g.id}`, + title: g.name ?? '', + // t_cover_big is 264×374 — the size the cards actually render. + cover: g.cover?.image_id + ? `https://images.igdb.com/igdb/image/upload/t_cover_big/${g.cover.image_id}.jpg` + : null, + released: g.first_release_date + ? new Date(g.first_release_date * 1000).toISOString().slice(0, 10) + : null, + genres: (g.genres ?? []).map((x) => x.name).slice(0, 3), + platforms: (g.platforms ?? []).map((x) => x.name).slice(0, 6), + // IGDB's aggregated_rating is the critic score, which is what the badge means + // elsewhere in this app; total_rating mixes in user votes, so it is not the same + // number and is deliberately not shown as one. + metacritic: g.aggregated_rating ? Math.round(g.aggregated_rating) : null, + rating: g.total_rating ? Math.round(g.total_rating) / 20 : null, + description: g.summary, + } +} + interface SteamFeaturedItem { id: number name?: string @@ -291,7 +342,7 @@ function mapFeatured(items: SteamFeaturedItem[] | undefined): GameSummary[] { * equivalent: RAWG covers every platform, Steam only PC. The screen names its source * rather than passing a narrower list off as the same thing. */ -export type DiscoverSource = 'rawg' | 'steam' +export type DiscoverSource = 'rawg' | 'igdb' | 'steam' export interface Discover { games: GameSummary[] source: DiscoverSource @@ -303,6 +354,8 @@ export async function popularGames(): Promise { page_size: '12', }) if (data?.results?.length) return { games: data.results.map(mapRawg), source: 'rawg' } + const viaIgdb = await proxy('igdb', 'games', { limit: '12' }) + if (viaIgdb?.length) return { games: viaIgdb.map(mapIgdb), source: 'igdb' } const featured = await steamFeatured() return { games: mapFeatured(featured?.new_releases?.items), source: 'steam' } } @@ -316,6 +369,8 @@ export async function upcomingGames(): Promise { page_size: '12', }) if (data?.results?.length) return { games: data.results.map(mapRawg), source: 'rawg' } + const viaIgdb = await proxy('igdb', 'games', { upcoming: '1', limit: '12' }) + if (viaIgdb?.length) return { games: viaIgdb.map(mapIgdb), source: 'igdb' } const featured = await steamFeatured() return { games: mapFeatured(featured?.coming_soon?.items), source: 'steam' } } diff --git a/src/store/stats.ts b/src/store/stats.ts index 93836b3..a7012f1 100644 --- a/src/store/stats.ts +++ b/src/store/stats.ts @@ -9,7 +9,7 @@ import { persist } from 'zustand/middleware' * data never leaves the device and is not part of the library backup. */ -export type SourceName = 'rawg' | 'steam' +export type SourceName = 'rawg' | 'igdb' | 'steam' /** Keeping ~13 weeks is enough for the activity strip without growing forever. */ const MAX_DAYS = 90