Files
WT-Offline/apps/launcher/src/main/services/app-update/app-update.ts
T
N0VAN0M4LY 152be6af0e feat(launcher): add configurable update mirror
Let a saved HTTPS repository serve as the fallback for launcher and adaptation pack releases. Retry downloads for the selected version and validate against the project signing key. Verified type checks, the launcher build, and a simulated primary outage.
2026-12-01 20:04:29 +08:00

203 lines
8.5 KiB
TypeScript

import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import { once } from 'node:events';
import { createWriteStream } from 'node:fs';
import { mkdir, rename, unlink } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { app } from 'electron';
import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519 } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import {
LauncherReleaseManifest,
type AppUpdateCheck, type AppUpdateProgress,
} from '@shared/schemas/app-update.ts';
import { gameProcessRunning } from '../launch/game-process.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 {
readonly release: LauncherRelease;
readonly manifest: LauncherReleaseManifest;
}
class ManifestSignatureError extends Error {}
let offered: OfferedUpdate | null = null;
let updating = false;
export function appUpdatesSupported(): boolean {
return app.isPackaged && process.platform === 'win32' && process.arch === 'x64';
}
async function exclusively<T>(action: () => Promise<T>): Promise<T> {
if (!appUpdatesSupported()) throw new AppError('app_update_unavailable');
if (updating) throw new AppError('app_update_busy');
updating = true;
try {
return await action();
} finally {
updating = false;
}
}
function stagedInstaller(): string {
return join(app.getPath('userData'), 'launcher-updates', 'installer.exe');
}
async function matchesInstaller(path: string, manifest: LauncherReleaseManifest): Promise<boolean> {
try {
const digest = await installerDigest(path, manifest.size);
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
} catch {
return false;
}
}
function offerResult(offer: OfferedUpdate, ready: boolean): AppUpdateCheck {
return {
status: 'available',
release: { version: offer.manifest.version, size: offer.manifest.size, notes: offer.release.notes },
ready,
};
}
function selectedOffer(version: string): OfferedUpdate {
if (!offered || version !== offered.manifest.version || compareAppVersions(version, app.getVersion()) <= 0) {
throw new AppError('app_update_unavailable');
}
return offered;
}
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
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<AppUpdateCheck> {
return exclusively(async () => {
offered = null;
try {
const key = packSigningPublicKey();
if (!key) return { status: 'failed', problem: 'no_signing_key' };
const installedVersion = app.getVersion();
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' };
if (error instanceof ManifestSignatureError) return { status: 'failed', problem: 'signature' };
if (error instanceof FeedUnreachableError || (error instanceof Error && error.name === 'TimeoutError')) {
return { status: 'failed', problem: 'network' };
}
if (error instanceof PatchPackError && error.problem === 'key') return { status: 'failed', problem: 'no_signing_key' };
return { status: 'failed', problem: 'contents' };
}
});
}
export function downloadAppUpdate(
version: string, report: (progress: AppUpdateProgress) => void,
): Promise<AppUpdateCheck> {
return exclusively(async () => {
const offer = selectedOffer(version);
const target = stagedInstaller();
if (await matchesInstaller(target, offer.manifest)) return offerResult(offer, true);
try {
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');
}
});
}
async function stageInstaller(
release: LauncherRelease, manifest: LauncherReleaseManifest, target: string,
report: (progress: AppUpdateProgress) => void,
): Promise<void> {
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<void> {
return exclusively(async () => {
const offer = selectedOffer(version);
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
const path = stagedInstaller();
if (!await matchesInstaller(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
const signal = AbortSignal.timeout(5000);
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
try {
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
await once(installer, 'spawn');
installer.unref();
app.quit();
} catch (error) {
console.warn('[app-update] starting the installer failed:', error);
throw new AppError('app_update_install_failed');
}
});
}