From a6dd5727ef586436780c6a0bcf998dbd95d65224 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:38:21 +0000 Subject: [PATCH 1/3] fix: show why the short-lived key is missing in game list sync errors Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01PJPA3xKZgDNFKY4QCS6rNX --- src/main/services/gameService.ts | 10 +++++++--- src/main/services/keyService.ts | 12 ++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/services/gameService.ts b/src/main/services/gameService.ts index 332e733..31e5858 100644 --- a/src/main/services/gameService.ts +++ b/src/main/services/gameService.ts @@ -8,7 +8,7 @@ import dependencyService from './dependencyService' import mirrorService from './mirrorService' import settingsService from './settingsService' import { getApiKey, redactApiKey as redactKey } from './apiKey' -import { getMirrorApiKey, invalidateMirrorApiKey } from './keyService' +import { getMirrorApiKey, invalidateMirrorApiKey, keyStatusHint } from './keyService' import { GameInfo, ServiceStatus, GamesAPI, BlacklistEntry } from '@shared/types' import metaStoreService from './metaStoreService' import EventEmitter from 'events' @@ -557,12 +557,16 @@ class GameService extends EventEmitter implements GamesAPI { // execa rejects on non-zero exit, so translate the failure here const result = await rcloneProcess.catch((e: { exitCode?: number; stderr?: string }) => { if (/\b403\b|forbidden/i.test(String(e?.stderr ?? e))) invalidateMirrorApiKey() - throw new Error(friendlyRcloneError(e?.exitCode, String(e?.stderr ?? e), !!publicApiKey)) + throw new Error( + friendlyRcloneError(e?.exitCode, String(e?.stderr ?? e), !!publicApiKey) + keyStatusHint() + ) }) if (result.exitCode !== 0) { console.error(`Rclone failed with exit code ${result.exitCode}: ${result.stderr}`) - throw new Error(friendlyRcloneError(result.exitCode, result.stderr, !!publicApiKey)) + throw new Error( + friendlyRcloneError(result.exitCode, result.stderr, !!publicApiKey) + keyStatusHint() + ) } console.log('Download complete') diff --git a/src/main/services/keyService.ts b/src/main/services/keyService.ts index 22151b4..0d9b97c 100644 --- a/src/main/services/keyService.ts +++ b/src/main/services/keyService.ts @@ -41,6 +41,8 @@ let installId: string | null = null // After a hard failure (403/429/network) don't hammer the endpoint: requests // are rate limited per address. Fall back to the legacy key for a while. let backoffUntilMs = 0 +// Why the last key request did not produce a key (shown in sync errors). +let lastKeyProblem = '' function clientId(): string { return decodeApiKey(process.env.VRSRC_CLIENT_ID_ENC ?? '') @@ -117,6 +119,7 @@ async function requestKey(baseUri: string): Promise { const data = (await res.json()) as KeyResponse if (!data.apiKey || typeof data.apiKey !== 'string') throw new Error('no apiKey in response') + lastKeyProblem = '' addRedactedSecret(data.apiKey) const refreshAt = data.refreshAfter ? Date.parse(data.refreshAfter) : NaN cached = { @@ -143,6 +146,7 @@ export async function getMirrorApiKey(baseUri: string): Promise { if (!inflight) { inflight = requestKey(baseUri) .catch((err) => { + lastKeyProblem = err instanceof Error ? err.message : String(err) console.warn( '[KeyService] Key request failed, using legacy key:', err instanceof Error ? err.message : String(err) @@ -156,6 +160,14 @@ export async function getMirrorApiKey(baseUri: string): Promise { return inflight } +/** Short diagnostic for error messages: why no short-lived key is in use. Empty when one is. */ +export function keyStatusHint(): string { + if (!hasKeyCredentials()) { + return ' [This build has no key-service credentials (VRSRC_CLIENT_ID / VRSRC_BUILD_SECRET).]' + } + return lastKeyProblem ? ` [Key request failed: ${lastKeyProblem}.]` : '' +} + /** Call after a 403 so the next getMirrorApiKey() fetches a fresh key. */ export function invalidateMirrorApiKey(): void { cached = null From 2936d36659e2b2be41b2f4af837b9352038736bf Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:44:26 +0000 Subject: [PATCH 2/3] fix: send key request over raw HTTP/2 with rclone User-Agent Electron's net.fetch did not get past the mirror edge (generic 403 page, no JSON reason), so every build fell back to the legacy key. Also keep the backoff when a download 403 invalidates the cached key. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01PJPA3xKZgDNFKY4QCS6rNX --- src/main/services/keyService.ts | 76 +++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 13 deletions(-) diff --git a/src/main/services/keyService.ts b/src/main/services/keyService.ts index 0d9b97c..71b2234 100644 --- a/src/main/services/keyService.ts +++ b/src/main/services/keyService.ts @@ -1,4 +1,5 @@ -import { app, net } from 'electron' +import { app } from 'electron' +import { connect } from 'http2' import { join } from 'path' import { randomBytes } from 'crypto' import { promises as fs } from 'fs' @@ -83,18 +84,64 @@ function keyUrl(baseUri: string): string { return baseUri.replace(/\/+$/, '') + '/key' } +/** + * POST JSON over HTTP/2 with an exact User-Agent. Electron's net.fetch does not + * reliably send a custom User-Agent, and the mirror's edge answers any request + * without the rclone UA or HTTP/2 with a generic 403 page before the key is even + * looked at (that is what the first release hit), so we speak HTTP/2 directly. + */ +function postJson(url: string, body: string): Promise<{ status: number; text: string }> { + return new Promise((resolve, reject) => { + const u = new URL(url) + const session = connect(u.origin) + const fail = (err: Error): void => { + session.destroy() + reject(err) + } + const timer = setTimeout(() => fail(new Error('timeout')), KEY_TIMEOUT_MS) + session.on('error', (e) => { + clearTimeout(timer) + fail(e) + }) + const req = session.request({ + ':method': 'POST', + ':path': u.pathname + u.search, + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(body), + 'user-agent': KEY_USER_AGENT + }) + let status = 0 + let text = '' + req.setEncoding('utf8') + req.on('response', (h) => { + status = Number(h[':status'] ?? 0) + }) + req.on('data', (d: string) => { + text += d + }) + req.on('end', () => { + clearTimeout(timer) + session.close() + resolve({ status, text }) + }) + req.on('error', (e) => { + clearTimeout(timer) + fail(e) + }) + req.end(body) + }) +} + async function requestKey(baseUri: string): Promise { - const res = await net.fetch(keyUrl(baseUri), { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'User-Agent': KEY_USER_AGENT }, - body: JSON.stringify({ + const res = await postJson( + keyUrl(baseUri), + JSON.stringify({ client_id: clientId(), build_secret: buildSecret(), install_id: await getInstallId(), app_version: app.getVersion() - }), - signal: AbortSignal.timeout(KEY_TIMEOUT_MS) - }) + }) + ) if (res.status === 503) { // key_pending: the server is still minting one. Short pause, then fall back. @@ -105,18 +152,18 @@ async function requestKey(baseUri: string): Promise { backoffUntilMs = Date.now() + 5 * 60_000 throw new Error('rate limited') } - if (!res.ok) { + if (res.status < 200 || res.status >= 300) { let reason = '' try { - reason = ((await res.json()) as { reason?: string }).reason ?? '' + reason = (JSON.parse(res.text) as { reason?: string }).reason ?? '' } catch { - // body wasn't JSON + // body wasn't JSON (e.g. an edge block page) } backoffUntilMs = Date.now() + 10 * 60_000 throw new Error(`HTTP ${res.status}${reason ? ` (${reason})` : ''}`) } - const data = (await res.json()) as KeyResponse + const data = JSON.parse(res.text) as KeyResponse if (!data.apiKey || typeof data.apiKey !== 'string') throw new Error('no apiKey in response') lastKeyProblem = '' @@ -147,6 +194,8 @@ export async function getMirrorApiKey(baseUri: string): Promise { inflight = requestKey(baseUri) .catch((err) => { lastKeyProblem = err instanceof Error ? err.message : String(err) + // Network-level failure (no status to set a backoff from): wait a bit too. + if (Date.now() >= backoffUntilMs) backoffUntilMs = Date.now() + 2 * 60_000 console.warn( '[KeyService] Key request failed, using legacy key:', err instanceof Error ? err.message : String(err) @@ -170,6 +219,7 @@ export function keyStatusHint(): string { /** Call after a 403 so the next getMirrorApiKey() fetches a fresh key. */ export function invalidateMirrorApiKey(): void { + // Keep any backoff: a 403 from the download side must not make us hammer + // the (rate limited) key endpoint when the key request itself is failing. cached = null - backoffUntilMs = 0 } From a76e43d0efd753e98f07085d80a6584541e58164 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 20:47:59 +0000 Subject: [PATCH 3/3] chore: add scripts/test-key.mjs to verify build credentials against /key Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01PJPA3xKZgDNFKY4QCS6rNX --- scripts/test-key.mjs | 68 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 scripts/test-key.mjs diff --git a/scripts/test-key.mjs b/scripts/test-key.mjs new file mode 100644 index 0000000..978c31d --- /dev/null +++ b/scripts/test-key.mjs @@ -0,0 +1,68 @@ +// Checks a client ID + build secret against the mirror's /key endpoint, the same +// way the app does (raw HTTP/2, rclone User-Agent). Works on Windows/macOS/Linux. +// +// node scripts/test-key.mjs (asks for the values) +// node scripts/test-key.mjs [base-url] +// +// The key itself is never printed in full. +import { connect } from 'node:http2' +import { createInterface } from 'node:readline/promises' + +let [clientId, secret, base] = process.argv.slice(2) +if (!clientId || !secret) { + const rl = createInterface({ input: process.stdin, output: process.stdout }) + clientId = clientId || (await rl.question('Client ID: ')).trim() + secret = secret || (await rl.question('Build secret: ')).trim() + rl.close() +} +base = (base || 'https://go.srcdl1.xyz').replace(/\/+$/, '') + +const body = JSON.stringify({ client_id: clientId, build_secret: secret, app_version: 'test' }) +const url = new URL(base + '/key') +const session = connect(url.origin) +session.on('error', (e) => { + console.log('Connection error:', e.message) + process.exit(1) +}) +const req = session.request({ + ':method': 'POST', + ':path': url.pathname, + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(body), + 'user-agent': 'rclone/v1.70' +}) +let status = 0 +let text = '' +req.setEncoding('utf8') +req.on('response', (h) => (status = Number(h[':status']))) +req.on('data', (d) => (text += d)) +req.on('end', () => { + session.close() + let json = {} + try { + json = JSON.parse(text) + } catch { + // not JSON + } + if (status === 200 && json.apiKey) { + console.log('OK: the server issued a key.') + console.log(' key (masked):', json.apiKey.slice(0, 4) + '...' + json.apiKey.slice(-2)) + console.log(' refreshAfter:', json.refreshAfter) + console.log(' expiresAt: ', json.expiresAt) + console.log('Your client ID and secret are good. If the app still fails, the problem is in the build.') + } else { + console.log(`FAILED: HTTP ${status}${json.reason ? ' reason=' + json.reason : ''}`) + if (json.reason === 'invalid') console.log('Wrong client ID or build secret (check for typos or stray spaces).') + else if (json.reason === 'retired') console.log('That build secret was retired. Create a new one.') + else if (json.reason === 'suspended') console.log('The application is suspended by the operator.') + else if (status === 503) console.log('key_pending: try again in a minute.') + else if (status === 429) console.log('Rate limited: wait a few minutes.') + else console.log('Blocked before the key was checked (no JSON reason).') + process.exit(1) + } +}) +req.on('error', (e) => { + console.log('Request error:', e.message) + process.exit(1) +}) +req.end(body)