diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 93f29ee..288a64d 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -176,10 +176,10 @@ export function registerIpcHandlers(): void { handle('patches:active', () => activePatchSet()); handle('patches:check', () => checkPackUpdate()); - handle('patches:apply', async () => { + handle('patches:apply', async ({ version }) => { // A build reads the patch set while it runs; switch only between builds. if (maintenanceInProgress()) throw new AppError('maintenance_busy'); - const result = await applyPackUpdate(); + const result = await applyPackUpdate(version); if (result.ok) broadcast('event:patch-set-changed', result.active); return result; }); diff --git a/apps/launcher/src/main/services/app-update/app-update.ts b/apps/launcher/src/main/services/app-update/app-update.ts index 401fab8..2263613 100644 --- a/apps/launcher/src/main/services/app-update/app-update.ts +++ b/apps/launcher/src/main/services/app-update/app-update.ts @@ -14,8 +14,12 @@ import { type AppUpdateCheck, type AppUpdateProgress, } from '@shared/schemas/app-update.ts'; import { gameProcessRunning } from '../launch/game-process.ts'; -import { FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type LauncherRelease } from '../patch-pack/release-feed.ts'; -import { readGithubAsset, requestGithubAsset } from './github-assets.ts'; +import { + newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease, +} from '../patch-pack/release-feed.ts'; +import { + FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset, +} from '../patch-pack/release-assets.ts'; import { installerDigest, launcherSignaturePayload } from './installer-integrity.ts'; interface OfferedUpdate { @@ -70,6 +74,20 @@ function selectedOffer(version: string): OfferedUpdate { return offered; } +async function signedOffer(release: LauncherRelease, key: string): Promise { + const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs); + const [bytes, signature] = await Promise.all([ + readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source), + readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source), + ]); + if (!verifyEd25519(launcherSignaturePayload(bytes), new TextDecoder().decode(signature), key)) { + throw new ManifestSignatureError('The release manifest signature does not match.'); + } + const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))); + if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.'); + return { release, manifest }; +} + export function checkAppUpdate(): Promise { return exclusively(async () => { offered = null; @@ -77,22 +95,14 @@ export function checkAppUpdate(): Promise { const key = packSigningPublicKey(); if (!key) return { status: 'failed', problem: 'no_signing_key' }; const installedVersion = app.getVersion(); - const latest = await newestProjectRelease('launcher', installedVersion); - if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return { status: 'current' }; - - const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs); - const [bytes, signature] = await Promise.all([ - readGithubAsset(latest.manifest, 64 * 1024, deadline), - readGithubAsset(latest.signature, 1024, deadline), - ]); - if (!verifyEd25519(launcherSignaturePayload(bytes), new TextDecoder().decode(signature), key)) { - throw new ManifestSignatureError('The release manifest signature does not match.'); - } - const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))); - if (manifest.version !== latest.version) throw new Error('The signed manifest version does not match the release tag.'); - - offered = { release: latest, manifest }; - return offerResult(offered, await matchesInstaller(stagedInstaller(), manifest)); + const offer = await withReleaseSources(async (source) => { + const latest = await newestProjectRelease('launcher', installedVersion, source); + if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return null; + return signedOffer(latest, key); + }); + if (!offer) return { status: 'current' }; + offered = offer; + return offerResult(offer, await matchesInstaller(stagedInstaller(), offer.manifest)); } catch (error) { console.warn('[app-update] checking the release failed:', error); if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' }; @@ -111,52 +121,66 @@ export function downloadAppUpdate( ): Promise { return exclusively(async () => { const offer = selectedOffer(version); - const { manifest } = offer; const target = stagedInstaller(); - if (await matchesInstaller(target, manifest)) return offerResult(offer, true); - const partial = `${target}.partial`; - const deadline = AbortSignal.timeout(30 * 60_000); - let size = 0; - let reportedAt = 0; - const hash = createHash('sha256'); + if (await matchesInstaller(target, offer.manifest)) return offerResult(offer, true); try { - await mkdir(dirname(target), { recursive: true }); - await unlink(partial).catch((error: NodeJS.ErrnoException) => { - if (error.code !== 'ENOENT') throw error; - }); - const response = await requestGithubAsset(offer.release.installer, deadline); - const monitor = new Transform({ - transform(chunk: Buffer, _encoding, done) { - size += chunk.length; - if (size > manifest.size) { - done(new Error('The download is larger than the signed installer size.')); - return; - } - hash.update(chunk); - if (size === manifest.size || Date.now() - reportedAt >= 200) { - reportedAt = Date.now(); - report({ received: size, total: manifest.size }); - } - done(null, chunk); - }, - }); - await pipeline(response, monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline }); - if (size !== manifest.size || hash.digest('hex') !== manifest.sha256) { - throw new Error('The installer download does not match the signed release.'); - } - await rename(partial, target); + await withReleaseSources(async (source) => { + const release = sameReleaseSource(source, offer.release.source) + ? offer.release : await projectReleaseVersion('launcher', version, source); + await stageInstaller(release, offer.manifest, target, report); + }, offer.release.source); return offerResult(offer, true); } catch (error) { console.warn('[app-update] preparing the installer failed:', error); throw new AppError('app_update_download_failed'); - } finally { - await unlink(partial).catch((error: NodeJS.ErrnoException) => { - if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error); - }); } }); } +async function stageInstaller( + release: LauncherRelease, manifest: LauncherReleaseManifest, target: string, + report: (progress: AppUpdateProgress) => void, +): Promise { + const partial = `${target}.partial`; + const deadline = AbortSignal.timeout(30 * 60_000); + let size = 0; + let reportedAt = 0; + const hash = createHash('sha256'); + try { + await mkdir(dirname(target), { recursive: true }); + await unlink(partial).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); + const response = await requestReleaseAsset(release.installer, deadline, release.source); + const monitor = new Transform({ + transform(chunk: Buffer, _encoding, done) { + size += chunk.length; + if (size > manifest.size) { + done(new Error('The download is larger than the signed installer size.')); + return; + } + hash.update(chunk); + if (size === manifest.size || Date.now() - reportedAt >= 200) { + reportedAt = Date.now(); + report({ received: size, total: manifest.size }); + } + done(null, chunk); + }, + }); + await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline }); + if (size !== manifest.size) throw new FeedUnreachableError('The installer download is incomplete.'); + if (hash.digest('hex') !== manifest.sha256) throw new Error('The installer download does not match the signed release.'); + await rename(partial, target); + } catch (error) { + if (deadline.aborted) throw new FeedUnreachableError('The installer download timed out.', { cause: error }); + throw error; + } finally { + await unlink(partial).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error); + }); + } +} + export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise { return exclusively(async () => { const offer = selectedOffer(version); diff --git a/apps/launcher/src/main/services/app-update/github-assets.ts b/apps/launcher/src/main/services/app-update/github-assets.ts deleted file mode 100644 index 6aa6e82..0000000 --- a/apps/launcher/src/main/services/app-update/github-assets.ts +++ /dev/null @@ -1,71 +0,0 @@ -import type { Readable } from 'node:stream'; -import { net, type IncomingMessage } from 'electron'; -import { FeedUnreachableError } from '../patch-pack/release-feed.ts'; - -const ASSET_HOSTS = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']); - -function isGithubAsset(value: string): boolean { - try { - const url = new URL(value); - return url.protocol === 'https:' && ASSET_HOSTS.has(url.hostname) && !url.port && !url.username && !url.password; - } catch { - return false; - } -} - -/** Request only GitHub assets, including every redirect, without sending session credentials. */ -export async function requestGithubAsset(url: URL, signal: AbortSignal): Promise { - signal.throwIfAborted(); - if (!isGithubAsset(url.href)) throw new FeedUnreachableError('The release asset is outside GitHub.'); - return new Promise((resolve, reject) => { - const request = net.request({ url: url.href, credentials: 'omit', redirect: 'manual' }); - request.setHeader('User-Agent', 'WTOffline-Launcher'); - const abort = (): void => { - cleanup(); - reject(signal.reason); - request.abort(); - }; - const cleanup = (): void => signal.removeEventListener('abort', abort); - signal.addEventListener('abort', abort, { once: true }); - - request.once('error', (error) => { - cleanup(); - reject(new FeedUnreachableError(error.message)); - }); - request.on('redirect', (_status, _method, destination) => { - if (isGithubAsset(destination)) request.followRedirect(); - else { - cleanup(); - reject(new FeedUnreachableError('The release asset redirected outside GitHub.')); - request.abort(); - } - }); - request.once('response', (response) => { - if (response.statusCode !== 200) { - cleanup(); - reject(new FeedUnreachableError(`GitHub answered HTTP ${response.statusCode} for a release asset.`)); - request.abort(); - return; - } - // The request's writable side can close before the response arrives. - const stream = response as IncomingMessage & Readable; - stream.once('end', cleanup); - stream.once('close', cleanup); - resolve(stream); - }); - request.end(); - }); -} - -export async function readGithubAsset(url: URL, limit: number, signal: AbortSignal): Promise { - const response = await requestGithubAsset(url, signal); - const chunks: Buffer[] = []; - let size = 0; - for await (const chunk of response) { - const bytes = chunk as Buffer; - size += bytes.length; - if (size > limit) throw new Error('Release metadata is larger than expected.'); - chunks.push(bytes); - } - return Buffer.concat(chunks); -} diff --git a/apps/launcher/src/main/services/patch-pack/pack-update.ts b/apps/launcher/src/main/services/patch-pack/pack-update.ts index 472ad6f..f856c91 100644 --- a/apps/launcher/src/main/services/patch-pack/pack-update.ts +++ b/apps/launcher/src/main/services/patch-pack/pack-update.ts @@ -1,5 +1,5 @@ /** - * Adaptation pack updates: which patch set the builds use, whether GitHub has a newer pack, and + * Adaptation pack updates: which patch set the builds use, whether a source has a newer pack, and * installing it. The launcher checks at start (when the setting allows) and from the About page; * a pack is installed only when the player confirms. * @@ -20,12 +20,10 @@ import { import type { ActivePatchSet, PackApplyResult, PackCheck, PackProblem, PackRelease } from '@shared/schemas/patch-pack.ts'; import { bundledResourcePaths, usesDownloadedPacks } from '../resources/resource-paths.ts'; import { activeDownloadedPack, bundledPatchVersion, installPack, useBundledPatchSet } from './pack-store.ts'; -import { downloadReleaseFile, FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type PackReleaseFiles } from './release-feed.ts'; - -/** The manifest copy beside a release is a few hundred bytes. */ -const MANIFEST_COPY_MAX_BYTES = 64 * 1024; -/** A signature file is 89 bytes. */ -const SIGNATURE_MAX_BYTES = 1024; +import { + newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, withReleaseSources, type PackReleaseFiles, type ReleaseSource, +} from './release-feed.ts'; +import { FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES } from './release-assets.ts'; export function activePatchSet(): ActivePatchSet { const root = bundledResourcePaths().patches; @@ -38,7 +36,7 @@ export async function checkPackUpdate(): Promise { const active = activePatchSet(); if (!packSigningPublicKey()) return { status: 'failed', active, latest: null, problem: 'no_signing_key' }; try { - const found = await newestRelease(active.version); + const found = await withReleaseSources((source) => newestRelease(active.version, source)); if (!found || !isNewer(found.manifest.version, active.version)) return { status: 'up_to_date', active, latest: found ? release(found) : null, problem: null }; const status = manifestIncompatibility(found.manifest, app.getVersion()) ? 'needs_app_update' : 'available'; return { status, active, latest: release(found), problem: null }; @@ -48,18 +46,26 @@ export async function checkPackUpdate(): Promise { } } -/** Download and activate the newest pack, when it is newer than the active set and usable. */ -export async function applyPackUpdate(): Promise { +/** Download and activate the selected pack when it is newer than the active set and usable. */ +export async function applyPackUpdate(version: string): Promise { if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' }; + if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' }; try { - const found = await newestRelease(activePatchSet().version); - if (!found || !isNewer(found.manifest.version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' }; - if (manifestIncompatibility(found.manifest, app.getVersion())) return { ok: false, problem: 'needs_app_update' }; - const tuning = patchPackTuning(); - const zip = await downloadReleaseFile(found.files.zipUrl, tuning.maxPackBytes); - const signature = new TextDecoder().decode(await downloadReleaseFile(found.files.signatureUrl, SIGNATURE_MAX_BYTES)); - await installPack(found.files.version, zip, signature); - console.info(`[patch-pack] pack ${found.files.version} installed and active`); + const downloaded = await withReleaseSources(async (source) => { + const files = await projectReleaseVersion('pack', version, source); + const manifest = await readPackManifest(files); + if (manifestIncompatibility(manifest, app.getVersion())) return null; + const tuning = patchPackTuning(); + const zip = await readReleaseAsset(files.zipUrl, tuning.maxPackBytes, AbortSignal.timeout(tuning.requestTimeoutMs), source); + const signature = new TextDecoder().decode(await readReleaseAsset( + files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, AbortSignal.timeout(tuning.requestTimeoutMs), source, + )); + return { zip, signature }; + }); + if (!downloaded) return { ok: false, problem: 'needs_app_update' }; + if (!isNewer(version, activePatchSet().version)) return { ok: false, problem: 'up_to_date' }; + await installPack(version, downloaded.zip, downloaded.signature); + console.info(`[patch-pack] pack ${version} installed and active`); return { ok: true, active: activePatchSet() }; } catch (error) { console.warn('[patch-pack] update failed:', error); @@ -78,13 +84,17 @@ interface FoundRelease { readonly manifest: PatchPackManifest; } -async function newestRelease(installedVersion: string | null): Promise { - const files = await newestProjectRelease('pack', installedVersion); - if (!files) return null; - const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES)); +async function newestRelease(installedVersion: string | null, source: ReleaseSource): Promise { + const files = await newestProjectRelease('pack', installedVersion, source); + return files ? { files, manifest: await readPackManifest(files) } : null; +} + +async function readPackManifest(files: PackReleaseFiles): Promise { + const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs); + const text = new TextDecoder().decode(await readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, deadline, files.source)); const manifest = parseManifest(text); if (manifest.version !== files.version) throw new PatchPackError('contents', `release ${files.version} carries the manifest of ${manifest.version}`); - return { files, manifest }; + return manifest; } function release(found: FoundRelease): PackRelease { diff --git a/apps/launcher/src/main/services/patch-pack/release-assets.ts b/apps/launcher/src/main/services/patch-pack/release-assets.ts new file mode 100644 index 0000000..49f1a94 --- /dev/null +++ b/apps/launcher/src/main/services/patch-pack/release-assets.ts @@ -0,0 +1,87 @@ +import type { Readable } from 'node:stream'; +import { net, type IncomingMessage } from 'electron'; +import { PatchPackError } from '@wto/patcher'; +import type { ReleaseSource } from './release-feed.ts'; + +const GITHUB_ASSET_HOSTS = new Set(['github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']); +export const UPDATE_USER_AGENT = 'WTOffline-Launcher'; +export const RELEASE_MANIFEST_MAX_BYTES = 64 * 1024; +export const RELEASE_SIGNATURE_MAX_BYTES = 1024; + +export class FeedUnreachableError extends Error { + override readonly name = 'FeedUnreachableError'; +} + +function isReleaseAsset(value: string, source: ReleaseSource): boolean { + try { + const url = new URL(value); + if (url.protocol !== 'https:' || url.username || url.password) return false; + return !source.githubDownloads || (!url.port && GITHUB_ASSET_HOSTS.has(url.hostname)); + } catch { + return false; + } +} + +/** Download over HTTPS, including redirects, without sending session credentials. */ +export function requestReleaseAsset( + url: URL, signal: AbortSignal, source: ReleaseSource, +): Promise { + if (signal.aborted) return Promise.reject(new FeedUnreachableError('The release download timed out.')); + if (!isReleaseAsset(url.href, source)) { + return Promise.reject(new FeedUnreachableError('The release asset URL is not allowed.')); + } + return new Promise((resolve, reject) => { + const request = net.request({ url: url.href, credentials: 'omit', redirect: 'manual' }); + request.setHeader('User-Agent', UPDATE_USER_AGENT); + const cleanup = (): void => signal.removeEventListener('abort', abort); + const fail = (error: FeedUnreachableError): void => { + cleanup(); + reject(error); + request.abort(); + }; + const abort = (): void => fail(new FeedUnreachableError('The release download timed out.')); + signal.addEventListener('abort', abort, { once: true }); + + request.once('error', (error) => { + cleanup(); + reject(new FeedUnreachableError('The release asset could not be downloaded.', { cause: error })); + }); + request.on('redirect', (_status, _method, destination) => { + if (isReleaseAsset(destination, source)) request.followRedirect(); + else fail(new FeedUnreachableError('The release asset redirected to a disallowed URL.')); + }); + request.once('response', (response) => { + if (response.statusCode !== 200) { + fail(new FeedUnreachableError(`The update source answered HTTP ${response.statusCode} for a release asset.`)); + return; + } + const stream = response as IncomingMessage & Readable; + stream.once('end', cleanup); + stream.once('close', cleanup); + resolve(stream); + }); + request.end(); + }); +} + +export async function* releaseAssetChunks(response: Readable): AsyncGenerator { + try { + for await (const chunk of response) yield chunk as Buffer; + } catch (error) { + throw new FeedUnreachableError('The release asset download was interrupted.', { cause: error }); + } +} + +export async function readReleaseAsset( + url: URL, limit: number, signal: AbortSignal, source: ReleaseSource, +): Promise { + const response = await requestReleaseAsset(url, signal, source); + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of releaseAssetChunks(response)) { + size += chunk.length; + if (size > limit) throw new PatchPackError('size', 'the release asset is larger than expected'); + chunks.push(chunk); + } + return Buffer.concat(chunks); +} diff --git a/apps/launcher/src/main/services/patch-pack/release-feed.ts b/apps/launcher/src/main/services/patch-pack/release-feed.ts index acd309c..b004df6 100644 --- a/apps/launcher/src/main/services/patch-pack/release-feed.ts +++ b/apps/launcher/src/main/services/patch-pack/release-feed.ts @@ -1,6 +1,6 @@ /** - * The launcher and adaptation pack channels share GitHub's public Releases list. - * Requests send no account, no cookie and nothing about the player. + * The launcher and adaptation pack channels share an anonymous, GitHub-compatible release list. + * The project repository is tried first, with an optional player-configured fallback. */ import { net } from 'electron'; import { @@ -8,8 +8,17 @@ import { } from '@wto/patcher'; import { z } from 'zod'; import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts'; +import { releaseRepositoryUrl } from '@shared/update-source.ts'; +import { getSettings } from '../config/settings-store.ts'; +import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts'; + +export interface ReleaseSource { + readonly feed: URL; + readonly githubDownloads: URL | null; +} export interface LauncherRelease { + readonly source: ReleaseSource; readonly version: string; readonly notes: string; readonly installer: URL; @@ -18,54 +27,102 @@ export interface LauncherRelease { } export interface PackReleaseFiles { + readonly source: ReleaseSource; readonly version: string; readonly publishedAt: string | null; - readonly zipUrl: string; - readonly signatureUrl: string; - readonly manifestUrl: string; + readonly zipUrl: URL; + readonly signatureUrl: URL; + readonly manifestUrl: URL; } -interface ReleaseCandidates { - launcher: LauncherRelease | null; - pack: PackReleaseFiles | null; +interface ReleaseByChannel { + launcher: LauncherRelease; + pack: PackReleaseFiles; } -type ReleaseChannel = keyof ReleaseCandidates; +type ReleaseChannel = keyof ReleaseByChannel; +type ReleaseVersions = { [Channel in ReleaseChannel]: Map }; interface ReleaseListing { - readonly candidates: ReleaseCandidates; + readonly versions: ReleaseVersions; readonly incomplete: Readonly>>; readonly pageLimit: number | null; } -/** Thrown when GitHub cannot be reached or answers with an error. */ -export class FeedUnreachableError extends Error { - override readonly name = 'FeedUnreachableError'; -} - /** Thrown when the list ends at the configured page limit without finding a newer release. */ export class ReleasePageLimitError extends Error { override readonly name = 'ReleasePageLimitError'; } -const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' }; +const GITHUB_HEADERS = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; +const ReleaseAsset = z.object({ name: z.string(), browser_download_url: z.string().optional() }); const LauncherReleaseEntry = z.object({ draft: z.literal(false), prerelease: z.literal(false), - assets: z.array(z.object({ name: z.string() })), + assets: z.array(ReleaseAsset), body: z.string().nullable().optional(), }); -let listing: Promise | null = null; +const listings = new Map>(); + +function releaseSource(repository: URL): ReleaseSource { + const githubPath = repository.origin === 'https://github.com' ? repository.pathname + : repository.origin === 'https://api.github.com' + ? /^\/repos(\/[\w.-]+\/[\w.-]+)(?:\/releases)?$/.exec(repository.pathname)?.[1] + : null; + if (githubPath) { + return { + feed: new URL(`https://api.github.com/repos${githubPath}/releases`), + githubDownloads: new URL(`https://github.com${githubPath}/releases/download/`), + }; + } + const feed = new URL(repository); + if (!feed.pathname.endsWith('/releases')) feed.pathname = `${feed.pathname.replace(/\/$/, '')}/releases`; + return { feed, githubDownloads: null }; +} + +export function sameReleaseSource(a: ReleaseSource, b: ReleaseSource): boolean { + return a.githubDownloads && b.githubDownloads + ? a.feed.href.toLowerCase() === b.feed.href.toLowerCase() + : a.feed.href === b.feed.href; +} + +/** Keep a check or download on its preferred source until that source becomes unavailable. */ +export async function withReleaseSources( + read: (source: ReleaseSource) => Promise, preferred?: ReleaseSource, +): Promise { + const primary = releaseSource(new URL(`https://github.com/${patchPackTuning().repository}`)); + const repository = releaseRepositoryUrl((await getSettings()).updateMirrorUrl); + const mirror = repository ? releaseSource(repository) : null; + if (!mirror || sameReleaseSource(primary, mirror)) return read(primary); + const [first, second] = preferred && sameReleaseSource(preferred, mirror) ? [mirror, primary] : [primary, mirror]; + try { + return await read(first); + } catch (error) { + if (!(error instanceof FeedUnreachableError || error instanceof ReleasePageLimitError)) throw error; + console.info(`[release-feed] ${first.feed.hostname} was unavailable, trying ${second.feed.hostname}.`); + return read(second); + } +} + +function listingFor(source: ReleaseSource): Promise { + const key = source.feed.href; + const existing = listings.get(key); + if (existing) return existing; + const pending = readProjectReleases(source).finally(() => { listings.delete(key); }); + listings.set(key, pending); + return pending; +} -/** Share the in-flight scan when the launcher checks both release channels at startup. */ export async function newestProjectRelease( - channel: Channel, installedVersion: string | null, -): Promise { - listing ??= readProjectReleases().finally(() => { listing = null; }); - const { candidates, incomplete, pageLimit } = await listing; - const candidate = candidates[channel]; + channel: Channel, installedVersion: string | null, source: ReleaseSource, +): Promise { + const { versions, incomplete, pageLimit } = await listingFor(source); const compare = channel === 'launcher' ? compareAppVersions : comparePackVersions; + let candidate: ReleaseByChannel[Channel] | null = null; + for (const release of versions[channel].values()) { + if (!candidate || compare(release.version, candidate.version) > 0) candidate = release; + } if (candidate && (installedVersion === null || compare(candidate.version, installedVersion) > 0)) return candidate; if (pageLimit !== null) { throw new ReleasePageLimitError(`No newer ${channel} release was confirmed within ${pageLimit} pages.`); @@ -77,29 +134,52 @@ export async function newestProjectRelease( return candidate; } -async function readProjectReleases(): Promise { +/** The fallback must supply the same release the player selected. */ +export async function projectReleaseVersion( + channel: Channel, version: string, source: ReleaseSource, +): Promise { + const release = (await listingFor(source)).versions[channel].get(version); + if (!release) throw new FeedUnreachableError(`This update source does not have the files for ${version}.`); + return release; +} + +async function readProjectReleases(source: ReleaseSource): Promise { const tuning = patchPackTuning(); - const candidates: ReleaseCandidates = { launcher: null, pack: null }; + const versions: ReleaseVersions = { launcher: new Map(), pack: new Map() }; const incomplete: Partial> = {}; - const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasePageSize}`; + const url = new URL(source.feed); + url.searchParams.set('per_page', String(tuning.releasePageSize)); + const headers = { + Accept: 'application/json', 'User-Agent': UPDATE_USER_AGENT, + ...(source.githubDownloads ? GITHUB_HEADERS : {}), + }; for (let page = 1; page <= tuning.maxReleasePages; page += 1) { - const response = await request(`${url}&page=${page}`, HEADERS, tuning.requestTimeoutMs); - if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for release page ${page}`); - const releases: unknown = await response.json(); - if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list'); - collectReleases(releases, candidates, incomplete, tuning.repository); - const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? ''); + url.searchParams.set('page', String(page)); + const result = await requestReleasePage(url, headers, tuning.requestTimeoutMs); + collectReleases(result.releases, versions, incomplete, source); // GitHub does not sort release pages by tag version. - if (!hasNextPage) { - return { candidates, incomplete, pageLimit: null }; - } + if (!result.hasNextPage) return { versions, incomplete, pageLimit: null }; } console.info(`[release-feed] More releases exist after the configured limit of ${tuning.maxReleasePages} pages.`); - return { candidates, incomplete, pageLimit: tuning.maxReleasePages }; + return { versions, incomplete, pageLimit: tuning.maxReleasePages }; +} + +async function requestReleasePage(url: URL, headers: Record, timeoutMs: number) { + try { + const response = await net.fetch(url.href, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) }); + if (!response.ok) throw new FeedUnreachableError(`The update source answered HTTP ${response.status} for a release page.`); + const releases: unknown = await response.json(); + if (!Array.isArray(releases)) throw new FeedUnreachableError('The update source did not return a release list.'); + const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? ''); + return { releases: releases as readonly unknown[], hasNextPage }; + } catch (error) { + if (error instanceof FeedUnreachableError) throw error; + throw new FeedUnreachableError('The update source could not be read.', { cause: error }); + } } function collectReleases( - entries: readonly unknown[], candidates: ReleaseCandidates, incomplete: Partial>, repository: string, + entries: readonly unknown[], versions: ReleaseVersions, incomplete: Partial>, source: ReleaseSource, ): void { for (const entry of entries) { if (typeof entry !== 'object' || entry === null) continue; @@ -111,78 +191,57 @@ function collectReleases( if (release['prerelease'] === true) continue; const version = AppReleaseVersionSchema.safeParse(tag.slice(1)); if (!version.success) continue; - const launcher = launcherRelease(release, version.data, repository); - if (!launcher) { - const missing = incomplete.launcher; - if (!missing || compareAppVersions(version.data, missing) > 0) incomplete.launcher = version.data; - } else if (!candidates.launcher || compareAppVersions(launcher.version, candidates.launcher.version) > 0) { - candidates.launcher = launcher; - } + const launcher = launcherRelease(release, version.data, source); + if (launcher) versions.launcher.set(launcher.version, launcher); + else if (!incomplete.launcher || compareAppVersions(version.data, incomplete.launcher) > 0) incomplete.launcher = version.data; continue; } const version = packVersionOfTag(tag); if (!version) continue; - const pack = packRelease(release, version); - if (!pack) { - const missing = incomplete.pack; - if (!missing || comparePackVersions(version, missing) > 0) incomplete.pack = version; - } else if (!candidates.pack || comparePackVersions(pack.version, candidates.pack.version) > 0) { - candidates.pack = pack; - } + const pack = packRelease(release, version, tag, source); + if (pack) versions.pack.set(pack.version, pack); + else if (!incomplete.pack || comparePackVersions(version, incomplete.pack) > 0) incomplete.pack = version; } } -function launcherRelease(entry: Record, version: string, repository: string): LauncherRelease | null { +function assetUrls(assets: readonly unknown[], tag: string, source: ReleaseSource): Map { + const urls = new Map(); + for (const asset of assets) { + const parsed = ReleaseAsset.safeParse(asset); + if (!parsed.success) continue; + const { name, browser_download_url: download } = parsed.data; + if (source.githubDownloads) { + urls.set(name, new URL(`${tag}/${encodeURIComponent(name)}`, source.githubDownloads)); + continue; + } + const url = download ? URL.parse(download, source.feed.href) : null; + if (url?.protocol === 'https:' && !url.username && !url.password) urls.set(name, url); + } + return urls; +} + +function launcherRelease(entry: Record, version: string, source: ReleaseSource): LauncherRelease | null { const parsed = LauncherReleaseEntry.safeParse(entry); if (!parsed.success) return null; const { assets, body } = parsed.data; const names = launcherReleaseFiles(version); - const present = new Set(assets.map(({ name }) => name)); - if (!Object.values(names).every((name) => present.has(name))) return null; - const directory = `https://github.com/${repository}/releases/download/v${version}/`; - return { - version, - notes: body?.trim().slice(0, 1600) ?? '', - installer: new URL(names.installer, directory), - manifest: new URL(names.manifest, directory), - signature: new URL(names.signature, directory), - }; + const urls = assetUrls(assets, `v${version}`, source); + const installer = urls.get(names.installer); + const manifest = urls.get(names.manifest); + const signature = urls.get(names.signature); + if (!installer || !manifest || !signature) return null; + return { source, version, notes: body?.trim().slice(0, 1600) ?? '', installer, manifest, signature }; } -function packRelease(release: Record, version: string): PackReleaseFiles | null { +function packRelease(release: Record, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null { if (!Array.isArray(release['assets'])) return null; - const urls = new Map(); - for (const asset of release['assets'] as unknown[]) { - if (typeof asset !== 'object' || asset === null) continue; - const { name, browser_download_url: download } = asset as Record; - if (typeof name === 'string' && typeof download === 'string' && download.startsWith('https://')) urls.set(name, download); - } + const urls = assetUrls(release['assets'], tag, source); const names = packFileNames(version); const zipUrl = urls.get(names.zip); const signatureUrl = urls.get(names.signature); const manifestUrl = urls.get(names.manifest); if (!zipUrl || !signatureUrl || !manifestUrl) return null; const publishedAt = typeof release['published_at'] === 'string' ? release['published_at'] : null; - return { version, publishedAt, zipUrl, signatureUrl, manifestUrl }; -} - -/** Download a release file, refusing anything larger than `maxBytes`. */ -export async function downloadReleaseFile(url: string, maxBytes: number): Promise { - const tuning = patchPackTuning(); - const response = await request(url, { 'User-Agent': HEADERS['User-Agent'] }, tuning.requestTimeoutMs); - if (!response.ok) throw new FeedUnreachableError(`HTTP ${response.status} for ${url}`); - const declared = Number(response.headers.get('content-length') ?? '0'); - if (declared > maxBytes) throw new PatchPackError('size', `${url} is ${declared} bytes, more than ${maxBytes}`); - const content = new Uint8Array(await response.arrayBuffer()); - if (content.length > maxBytes) throw new PatchPackError('size', `${url} is more than ${maxBytes} bytes`); - return content; -} - -async function request(url: string, headers: Record, timeoutMs: number): Promise { - try { - return await net.fetch(url, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) }); - } catch (error) { - throw new FeedUnreachableError(`${url}: ${(error as Error).message}`); - } + return { source, version, publishedAt, zipUrl, signatureUrl, manifestUrl }; } diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 9541596..38acdab 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -490,6 +490,9 @@ "appUpdatesToggle": "Check for launcher updates at start", "patchPacks": "Adaptation pack updates", "patchPacksHint": "After a game update, the patches for the new version are released on GitHub as an adaptation pack.", + "updateMirror": "Update mirror repository", + "updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.", + "updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.", "patchPacksToggle": "Check for a new adaptation pack at start", "windowClose": "When closing the window", "windowQuit": "Quit launcher", @@ -572,7 +575,7 @@ "downloaded": "Adaptation pack {{version}}", "useBundled": "Go back to the included patches", "check": "Check for updates", - "checkHint": "Looks for a new adaptation pack on GitHub.", + "checkHint": "Checks for a new adaptation pack.", "checkButton": "Check", "checking": "Checking…", "applying": "Downloading and verifying the adaptation pack…", @@ -584,7 +587,7 @@ "needsAppUpdate": "Adaptation pack {{version}} needs offline version {{app}} or newer. Update the offline version first.", "checkFailed": { "no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.", - "network": "GitHub could not be reached. Try again later.", + "network": "The update source could not be reached. Try again later.", "page_limit": "Could not confirm whether a newer adaptation pack is available.", "contents": "The released adaptation pack is incomplete or malformed.", "signature": "The adaptation pack's signature is wrong. It was refused.", @@ -592,7 +595,7 @@ }, "applyFailed": { "no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.", - "network": "The download failed: GitHub could not be reached. Try again later.", + "network": "Could not reach the update source to download the adaptation pack. Try again later.", "page_limit": "Could not confirm whether a newer adaptation pack is available.", "contents": "The adaptation pack is incomplete or malformed. It is not in use.", "signature": "The adaptation pack's signature is wrong. It was refused and is not in use.", @@ -612,7 +615,7 @@ "install": "Quit and install", "installing": "Opening the installer…", "errors": { - "network": "GitHub Releases could not be reached.", + "network": "The update source could not be reached.", "page_limit": "Could not confirm whether a newer version is available.", "contents": "The launcher release information is invalid.", "signature": "The launcher update signature could not be verified.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index fc670a3..d9f984e 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -490,6 +490,9 @@ "appUpdatesToggle": "启动时检查本体更新", "patchPacks": "适配包更新", "patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。", + "updateMirror": "备用更新仓库", + "updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。", + "updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。", "patchPacksToggle": "启动时检查有没有新的适配包", "windowClose": "关闭窗口时", "windowQuit": "退出启动器", @@ -572,7 +575,7 @@ "downloaded": "适配包 {{version}}", "useBundled": "改回启动器自带", "check": "检查更新", - "checkHint": "在 GitHub 上查找新的适配包。", + "checkHint": "检查是否有新的适配包。", "checkButton": "检查", "checking": "正在检查…", "applying": "正在下载并校验适配包…", @@ -584,7 +587,7 @@ "needsAppUpdate": "适配包 {{version}} 需要离线版 {{app}} 或更新的版本,请先更新离线版。", "checkFailed": { "no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。", - "network": "连不上 GitHub,请稍后再试。", + "network": "无法连接更新源,请稍后再试。", "page_limit": "无法确认是否有新的适配包。", "contents": "发布的适配包信息不完整或格式不对。", "signature": "适配包的签名不对,已拒绝。", @@ -592,7 +595,7 @@ }, "applyFailed": { "no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。", - "network": "下载失败:连不上 GitHub,请稍后再试。", + "network": "无法连接更新源来下载适配包,请稍后再试。", "page_limit": "无法确认是否有新的适配包。", "contents": "适配包内容不完整或格式不对,没有启用。", "signature": "适配包的签名不对,已拒绝,没有启用。", @@ -612,7 +615,7 @@ "install": "退出并安装", "installing": "正在打开安装包…", "errors": { - "network": "暂时无法访问 GitHub 发布页。", + "network": "暂时无法访问更新源。", "page_limit": "无法确认是否有新版本。", "contents": "本体更新的发布信息无效。", "signature": "本体更新签名校验失败。", diff --git a/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx index 80b7ec3..746ea76 100644 --- a/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx +++ b/apps/launcher/src/renderer/src/pages/settings/GeneralSettings.tsx @@ -1,6 +1,6 @@ import { useTranslation } from 'react-i18next'; import { BACKGROUND_RANDOM, type BackgroundPicture } from '@shared/schemas/background.ts'; -import type { Settings } from '@shared/schemas/settings.ts'; +import { UpdateMirrorUrlSchema, type Settings } from '@shared/schemas/settings.ts'; import { Row } from '../../components/Row.tsx'; import { Sheet } from '../../components/Sheet.tsx'; import { ipcInvoke } from '../../ipc.ts'; @@ -71,6 +71,32 @@ export function GeneralSettings({ settings, appUpdatesSupported, pictures, onErr {t('settings.patchPacksToggle')} + + event.currentTarget.setCustomValidity('')} + onKeyDown={(event) => { + if (event.key === 'Enter') event.currentTarget.blur(); + }} + onBlur={(event) => { + const input = event.currentTarget; + const parsed = UpdateMirrorUrlSchema.safeParse(input.value); + if (!parsed.success) { + input.setCustomValidity(t('settings.updateMirrorInvalid')); + input.reportValidity(); + return; + } + if (parsed.data !== settings.updateMirrorUrl) update({ updateMirrorUrl: parsed.data }); + }} + /> +

{t('background.title')}

{t('background.hint')}

{pictures.length === 0 ? ( diff --git a/apps/launcher/src/renderer/src/shell/usePatchPack.ts b/apps/launcher/src/renderer/src/shell/usePatchPack.ts index 4579f4b..01f4de7 100644 --- a/apps/launcher/src/renderer/src/shell/usePatchPack.ts +++ b/apps/launcher/src/renderer/src/shell/usePatchPack.ts @@ -52,9 +52,11 @@ export function usePatchPack(checkOnStart: boolean, onError: (error: unknown) => }, [checkOnStart, checkNow]); const apply = useCallback((): void => { + const version = check?.status === 'available' ? check.latest?.version : undefined; + if (!version) return; setBusy('applying'); setApplyFailure(null); - ipcInvoke('patches:apply') + ipcInvoke('patches:apply', { version }) .then((result) => { if (!result.ok) { setApplyFailure(result.problem); @@ -65,7 +67,7 @@ export function usePatchPack(checkOnStart: boolean, onError: (error: unknown) => }) .catch(onError) .finally(() => setBusy(null)); - }, [onError]); + }, [check, onError]); const useBundled = useCallback((): void => { setBusy('reverting'); diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 1f78ebf..2d526a1 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -16,7 +16,7 @@ import { } from '../schemas/install.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; -import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema } from '../schemas/patch-pack.ts'; +import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts'; import { AccountEditsSchema, SaveAvatarChoicesSchema, SaveAvatarIdSchema, ResearchBranchSchema, ResearchOperationSchema, SaveResearchSchema, OfficialImportOptionsSchema, OfficialPreviewSchema, OnlineDataSourceSchema, SaveOfficialRequestSchema, CurrencyEditsSchema, SaveBackupNameSchema, SaveBackupSchema, SaveDetailsSchema, SaveKeysSchema, SaveListSchema, SaveRegistrationSchema, SaveTransferSchema } from '../schemas/saves.ts'; import { TuningPatchSchema, TuningViewSchema } from '../schemas/tuning.ts'; import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts'; @@ -282,13 +282,13 @@ export const ipcContract = { output: ActivePatchSetSchema, }, 'patches:check': { - /** Asks GitHub for the newest adaptation pack. */ + /** Checks for a newer adaptation pack. */ input: z.void(), output: PackCheckSchema, }, 'patches:apply': { - /** Downloads, verifies and activates the newest pack; the window asks the player first. */ - input: z.void(), + /** Downloads, verifies and activates the pack version selected by the player. */ + input: z.object({ version: PackReleaseSchema.shape.version }), output: PackApplyResultSchema, }, 'patches:useBundled': { diff --git a/apps/launcher/src/shared/schemas/settings.ts b/apps/launcher/src/shared/schemas/settings.ts index 300ac93..fb44043 100644 --- a/apps/launcher/src/shared/schemas/settings.ts +++ b/apps/launcher/src/shared/schemas/settings.ts @@ -1,6 +1,7 @@ import { z } from 'zod'; import { LANGUAGE_CHOICES } from '../languages.ts'; import { parseLaunchArguments } from '../launch-arguments.ts'; +import { releaseRepositoryUrl } from '../update-source.ts'; import { BACKGROUND_RANDOM, BackgroundChoiceSchema } from './background.ts'; const LanguageChoiceSchema = z.enum(LANGUAGE_CHOICES); @@ -11,6 +12,7 @@ const PortModeSchema = z.enum(['auto', 'fixed']); const PortSchema = z.number().int().min(1).max(65535); export const LAUNCH_ARGUMENTS_LIMIT = 4000; const LaunchArgumentsSchema = z.string().max(LAUNCH_ARGUMENTS_LIMIT).refine((value) => parseLaunchArguments(value) !== null); +export const UpdateMirrorUrlSchema = z.string().trim().refine((value) => value === '' || releaseRepositoryUrl(value) !== null); /** The launcher's own settings (not the game's, not the local service's tuning). */ export const SettingsSchema = z.object({ @@ -19,9 +21,10 @@ export const SettingsSchema = z.object({ background: BackgroundChoiceSchema.default(BACKGROUND_RANDOM), /** Fetch wallpapers from the game website's public gallery. */ officialWallpapers: z.boolean().default(true), - /** Ask GitHub for a newer adaptation pack when the launcher starts. */ + /** Check for a newer adaptation pack when the launcher starts. */ checkPatchPacksOnStart: z.boolean().default(true), checkLauncherUpdatesOnStart: z.boolean().default(true), + updateMirrorUrl: UpdateMirrorUrlSchema.default(''), windowClose: WindowCloseSchema.default('quit'), afterGameStarts: AfterGameStartsSchema.default('minimize'), autoSaveBackups: z.boolean().default(true), @@ -43,6 +46,7 @@ export const SettingsPatchSchema = z.object({ officialWallpapers: z.boolean().optional(), checkPatchPacksOnStart: z.boolean().optional(), checkLauncherUpdatesOnStart: z.boolean().optional(), + updateMirrorUrl: UpdateMirrorUrlSchema.optional(), windowClose: WindowCloseSchema.optional(), afterGameStarts: AfterGameStartsSchema.optional(), autoSaveBackups: z.boolean().optional(), diff --git a/apps/launcher/src/shared/update-source.ts b/apps/launcher/src/shared/update-source.ts new file mode 100644 index 0000000..dfa6d48 --- /dev/null +++ b/apps/launcher/src/shared/update-source.ts @@ -0,0 +1,12 @@ +/** Parse a repository URL that can be used with the release update protocol. */ +export function releaseRepositoryUrl(value: string): URL | null { + try { + const url = new URL(value); + if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) return null; + url.pathname = url.pathname.replace(/\/+$/, '').replace(/\.git$/, '') || '/'; + if (url.origin === 'https://github.com' && !/^\/[\w.-]+\/[\w.-]+$/.test(url.pathname)) return null; + return url; + } catch { + return null; + } +}