diff --git a/nginx.conf b/nginx.conf index b9b51e91ad9..24a9c804d5c 100644 --- a/nginx.conf +++ b/nginx.conf @@ -175,6 +175,28 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } + # Short, hand-typeable alias for the Steam account-linking route. + # + # This is the one URL in the product a player types by hand, and they + # type it in a degraded situation: the desktop app could not open a + # browser, so the browser being used may be on another device entirely + # (a phone is realistic). "#" sits behind a symbol layer on a phone + # keyboard, so the canonical /#steam-link is a poor thing to dictate. + # + # 302 rather than 301: a permanent redirect is cached hard by browsers + # and would outlive any decision to retarget /link. + location = /link { + return 302 /#steam-link; + } + + # Same target, trailing slash. `location =` is an exact match, so /link + # alone would 404 on /link/ -- and browsers and address-bar autocomplete + # both append slashes. For a URL whose whole purpose is surviving being + # hand-typed on an unfamiliar device, that is not a variant to lose. + location = /link/ { + return 302 /#steam-link; + } + # Binary files caching location ~* \.(bin|dat|exe|dll|so|dylib)$ { proxy_pass http://127.0.0.1:3000; diff --git a/src/client/SteamLink.ts b/src/client/SteamLink.ts index 3e5b1732c31..58972628e65 100644 --- a/src/client/SteamLink.ts +++ b/src/client/SteamLink.ts @@ -11,6 +11,21 @@ const LINK_HASH = "#steam-link"; const PENDING_LINK_KEY = "steam-link-pending"; +// Matches the link ticket's own server-side TTL. A stash older than this +// belongs to a ticket that is already dead, so resuming it can only produce +// a confirmation modal that errors -- which is worse than doing nothing, +// because it teaches players to dismiss that dialog without reading it, and +// that dialog is the security step of the whole flow. +// +// The server owns the authoritative value; this is a manually-kept copy, and +// so is the desktop shell's own (its gate has a TICKET_TTL_MS with the same +// 10 minutes). Changing the server's TTL means changing all three -- there is +// no shared source to import across three separate deployables. Erring long +// here is the safe direction: a stash that outlives its ticket resumes into a +// clean error, whereas one that expires early silently drops a link the +// player could still have completed. +const PENDING_LINK_TTL_MS = 10 * 60 * 1000; + // Pulls the opaque link token out of the URL hash the desktop shell opens the // browser at. Returns null for any hash that isn't the steam-link one // (including no token param), so callers can call this unconditionally on @@ -77,7 +92,7 @@ export type PendingLink = export function stashPendingLink(token: string): void { localStorage.setItem( PENDING_LINK_KEY, - JSON.stringify({ kind: "token", token }), + JSON.stringify({ kind: "token", token, stashedAt: Date.now() }), ); } @@ -87,15 +102,19 @@ export function stashPendingLink(token: string): void { export function stashPendingCodeEntry(): void { localStorage.setItem( PENDING_LINK_KEY, - JSON.stringify({ kind: "code_entry" }), + JSON.stringify({ kind: "code_entry", stashedAt: Date.now() }), ); } // Consumed on read: once taken, a stale/already-handled entry can't re-fire -// on a later page load. Malformed/legacy storage (this used to hold a bare, -// unquoted token string before the kind discriminator existed) degrades to -// null rather than throwing — a leftover value from before this change must -// not crash every subsequent page load for whoever still has one. +// on a later page load. Also expires on read: an entry older than +// PENDING_LINK_TTL_MS is discarded (still consumed, just returned as null) +// rather than resumed, since its link ticket is already dead server-side by +// then. Malformed/legacy storage (this used to hold a bare, unquoted token +// string before the kind discriminator existed, and before that, no +// timestamp at all) degrades to null rather than throwing — a leftover value +// from before this change must not crash every subsequent page load for +// whoever still has one. export function takePendingLink(): PendingLink | null { const raw = localStorage.getItem(PENDING_LINK_KEY); if (raw === null) return null; @@ -104,7 +123,22 @@ export function takePendingLink(): PendingLink | null { try { const parsed: unknown = JSON.parse(raw); if (typeof parsed === "object" && parsed !== null && "kind" in parsed) { - const candidate = parsed as { kind: unknown; token?: unknown }; + const candidate = parsed as { + kind: unknown; + token?: unknown; + stashedAt?: unknown; + }; + + // A missing or non-numeric stashedAt means a pre-TTL entry (or a + // corrupted one). Its age cannot be established, so it is treated as + // expired rather than resumed -- see PENDING_LINK_TTL_MS. + if ( + typeof candidate.stashedAt !== "number" || + Date.now() - candidate.stashedAt > PENDING_LINK_TTL_MS + ) { + return null; + } + if (candidate.kind === "token" && typeof candidate.token === "string") { return { kind: "token", token: candidate.token }; } diff --git a/tests/client/SteamLink.test.ts b/tests/client/SteamLink.test.ts index 7dffcd01ee9..ce065da7291 100644 --- a/tests/client/SteamLink.test.ts +++ b/tests/client/SteamLink.test.ts @@ -141,6 +141,66 @@ describe("pending link stash", () => { expect(() => takePendingLink()).not.toThrow(); expect(takePendingLink()).toBeNull(); }); + + it("discards a token stash older than the ticket TTL, and still consumes it", () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(new Date("2026-08-05T12:00:00Z")); + stashPendingLink("tok123"); + + // One millisecond past the ticket's own 10-minute life. The ticket is + // already dead server-side, so resuming would open a confirm modal + // that can only error. + vi.setSystemTime(new Date("2026-08-05T12:10:00.001Z")); + expect(takePendingLink()).toBeNull(); + + // Consumed even when rejected -- otherwise a stale entry is re-read + // and re-rejected on every page load forever. + vi.setSystemTime(new Date("2026-08-05T12:10:00.002Z")); + expect(localStorage.getItem("steam-link-pending")).toBeNull(); + } finally { + vi.useRealTimers(); + } + }); + + it("discards a code-entry stash older than the ticket TTL", () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(new Date("2026-08-05T12:00:00Z")); + stashPendingCodeEntry(); + vi.setSystemTime(new Date("2026-08-05T12:10:00.001Z")); + expect(takePendingLink()).toBeNull(); + } finally { + vi.useRealTimers(); + } + }); + + it("still resumes a stash inside the ticket TTL", () => { + vi.useFakeTimers(); + try { + vi.setSystemTime(new Date("2026-08-05T12:00:00Z")); + stashPendingLink("tok123"); + + // Comfortably inside the window: an OAuth round trip through Google + // or Discord takes seconds to a couple of minutes, and must survive. + vi.setSystemTime(new Date("2026-08-05T12:09:59Z")); + expect(takePendingLink()).toEqual({ kind: "token", token: "tok123" }); + } finally { + vi.useRealTimers(); + } + }); + + it("discards a stash with no timestamp rather than guessing its age", () => { + // Written by the build that shipped before this change. Its real age is + // unknowable and the ticket it belongs to is almost certainly dead, so + // treat it as expired rather than resuming something that can only fail. + localStorage.setItem( + "steam-link-pending", + JSON.stringify({ kind: "token", token: "tok123" }), + ); + expect(takePendingLink()).toBeNull(); + expect(localStorage.getItem("steam-link-pending")).toBeNull(); + }); }); describe("resumePendingSteamLink", () => { diff --git a/vite.config.ts b/vite.config.ts index e8c1fc5fc54..b8a118e3239 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -52,6 +52,66 @@ function serveProprietaryDir( }; } +// Dev-only stand-in for nginx's `location = /link` blocks (see nginx.conf). +// +// The desktop app's account-linking gate prints a short URL for the player to +// type by hand when it cannot open their browser for them. In production +// nginx 302s /link to /#steam-link, the client route that shows the code-entry +// form. Without this middleware the dev server falls through to Vite's SPA +// fallback and serves the home page instead -- a 200, so it does not look +// broken, but the printed URL silently would not work locally. +// +// A redirect rather than serving index.html directly, so dev matches +// production exactly and the desktop's siteUrlForAudience can emit one URL +// shape for every environment. +function steamLinkAliasRedirect(): Plugin { + return { + name: "steam-link-alias-redirect", + configureServer(server) { + // Matches on `originalUrl`, not `url`, and that is load-bearing. + // + // Whatever the documented middleware ordering, the measured behaviour + // in this config is that by the time this handler runs `req.url` has + // already been rewritten to "/index.html", while `originalUrl` still + // holds what the browser asked for. Logging both showed a request to + // /link arriving here as url="/index.html", originalUrl="/link". + // Which middleware performs that rewrite was not established, so this + // deliberately does not claim one. + // + // The practical warning: switching this to `req.url` type-checks, + // lints, runs, and silently never matches -- the dev server just keeps + // serving the home page with a 200. Re-verify against a running server + // if you change it, and use a control path (e.g. /linkxyz) to prove a + // 200 is not coming from the SPA fallback. + server.middlewares.use((req, res, next) => { + const requested = (req as { originalUrl?: string }).originalUrl; + if (!requested) return next(); + + // Decode before comparing, because nginx resolves percent-encoded + // bytes before exact `location =` matching but URL.pathname does + // not: "/link%2F" reaches production as /link/ and redirects, and + // would otherwise fall straight through here. The whole point of + // this plugin is that dev and production agree. + let pathname: string; + try { + pathname = decodeURIComponent( + new URL(requested, "http://x").pathname, + ); + } catch { + // Malformed percent-encoding -- not our route; let Vite answer. + return next(); + } + + // Exact matches only, mirroring nginx's `location =`. A prefix match + // would swallow any future /link/* route. + if (pathname !== "/link" && pathname !== "/link/") return next(); + res.writeHead(302, { Location: "/#steam-link" }); + res.end(); + }); + }, + }; +} + // Dev-only stand-in for the nginx random-worker routing (the openfront_workers // upstream). Forwards these prefix-less POSTs to a randomly chosen worker port // so the worker can mint a self-owned id. Runs as direct middleware (before @@ -210,6 +270,7 @@ export default defineConfig(({ mode }) => { ? [ serveProprietaryDir(proprietaryDir, resourcesDir), randomWorkerCreateProxy(devNumWorkers), + steamLinkAliasRedirect(), ] : []), ...(isProduction