Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions scripts/test-key.mjs
Original file line number Diff line number Diff line change
@@ -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 <client-id> <secret> [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.')

Check warning on line 52 in scripts/test-key.mjs

View workflow job for this annotation

GitHub Actions / Lint

Replace `'Your·client·ID·and·secret·are·good.·If·the·app·still·fails,·the·problem·is·in·the·build.'` with `⏎······'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).')

Check warning on line 55 in scripts/test-key.mjs

View workflow job for this annotation

GitHub Actions / Lint

Insert `⏎·····`
else if (json.reason === 'retired') console.log('That build secret was retired. Create a new one.')

Check warning on line 56 in scripts/test-key.mjs

View workflow job for this annotation

GitHub Actions / Lint

Insert `⏎·····`
else if (json.reason === 'suspended') console.log('The application is suspended by the operator.')

Check warning on line 57 in scripts/test-key.mjs

View workflow job for this annotation

GitHub Actions / Lint

Insert `⏎·····`
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)
10 changes: 7 additions & 3 deletions src/main/services/gameService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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')
Expand Down
88 changes: 75 additions & 13 deletions src/main/services/keyService.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -41,6 +42,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 ?? '')
Expand Down Expand Up @@ -81,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<string> {
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.
Expand All @@ -103,20 +152,21 @@ async function requestKey(baseUri: string): Promise<string> {
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 = ''
addRedactedSecret(data.apiKey)
const refreshAt = data.refreshAfter ? Date.parse(data.refreshAfter) : NaN
cached = {
Expand All @@ -143,6 +193,9 @@ export async function getMirrorApiKey(baseUri: string): Promise<string> {
if (!inflight) {
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)
Expand All @@ -156,8 +209,17 @@ export async function getMirrorApiKey(baseUri: string): Promise<string> {
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 {
// 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
}
Loading