feat(updates): verify and install launcher releases
Check the versioned release channel, verify the signed manifest and installer digest, and open the installer only after confirmation. Verified type checks, the Windows package, and an upgrade handoff from a local release fixture, including tampering and interrupted downloads.
This commit is contained in:
1 parent
31b38518f8
commit
746b74c564
24 files changed
+638
-28
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { app, BrowserWindow, dialog, shell } from 'electron';
|
||||
import { patchFeatures, recordedGameVersions } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdate } from '../services/app-update/app-update.ts';
|
||||
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
|
||||
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
|
||||
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
|
||||
@@ -27,6 +28,7 @@ export function registerIpcHandlers(): void {
|
||||
version: app.getVersion(),
|
||||
electron: process.versions.electron,
|
||||
development: !app.isPackaged,
|
||||
appUpdatesSupported: appUpdatesSupported(),
|
||||
systemLocale: app.getLocale(),
|
||||
userDataPath: app.getPath('userData'),
|
||||
supportedGameVersions: recordedGameVersions(resources.patches),
|
||||
@@ -167,6 +169,11 @@ export function registerIpcHandlers(): void {
|
||||
return active;
|
||||
});
|
||||
|
||||
handle('updates:check', () => checkAppUpdate());
|
||||
handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress)));
|
||||
handle('updates:install', ({ version }) => installAppUpdate(version, () =>
|
||||
launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress()));
|
||||
|
||||
handle('settings:get', () => getSettings());
|
||||
handle('settings:update', async (patch) => {
|
||||
const settings = await updateSettings(patch);
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
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 { z } from 'zod';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import {
|
||||
AppReleaseVersionSchema, launcherReleaseFiles, LauncherReleaseManifest,
|
||||
type AppUpdateCheck, type AppUpdateProgress,
|
||||
} from '@shared/schemas/app-update.ts';
|
||||
import { gameProcessRunning } from '../launch/game-process.ts';
|
||||
import { FeedUnreachableError, listProjectReleases } from '../patch-pack/release-feed.ts';
|
||||
import { readGithubAsset, requestGithubAsset } from './github-assets.ts';
|
||||
import { installerDigest, launcherSignaturePayload } from './installer-integrity.ts';
|
||||
|
||||
const ReleaseEntry = z.object({
|
||||
tag_name: z.string().startsWith('v'),
|
||||
draft: z.literal(false),
|
||||
prerelease: z.literal(false),
|
||||
assets: z.array(z.object({ name: z.string() })),
|
||||
body: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
interface Release {
|
||||
readonly version: string;
|
||||
readonly notes: string;
|
||||
readonly installer: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
}
|
||||
|
||||
interface OfferedUpdate {
|
||||
readonly release: Release;
|
||||
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';
|
||||
}
|
||||
|
||||
function releaseFromEntry(entry: unknown): Release | null {
|
||||
const parsed = ReleaseEntry.safeParse(entry);
|
||||
if (!parsed.success) return null;
|
||||
const { tag_name: tag, assets, body } = parsed.data;
|
||||
const version = AppReleaseVersionSchema.safeParse(tag.slice(1));
|
||||
if (!version.success) return null;
|
||||
const names = launcherReleaseFiles(version.data);
|
||||
const present = new Set(assets.map(({ name }) => name));
|
||||
if (!Object.values(names).every((name) => present.has(name))) return null;
|
||||
const directory = `https://github.com/${patchPackTuning().repository}/releases/download/${tag}/`;
|
||||
return {
|
||||
version: version.data,
|
||||
notes: body?.trim().slice(0, 1600) ?? '',
|
||||
installer: new URL(names.installer, directory),
|
||||
manifest: new URL(names.manifest, directory),
|
||||
signature: new URL(names.signature, directory),
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||
return exclusively(async () => {
|
||||
offered = null;
|
||||
try {
|
||||
const key = packSigningPublicKey();
|
||||
if (!key) return { status: 'failed', problem: 'no_signing_key' };
|
||||
const candidates = (await listProjectReleases()).map(releaseFromEntry).filter((entry) => entry !== null);
|
||||
candidates.sort((a, b) => compareAppVersions(b.version, a.version));
|
||||
const latest = candidates[0];
|
||||
if (!latest || compareAppVersions(latest.version, app.getVersion()) <= 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));
|
||||
} catch (error) {
|
||||
console.warn('[app-update] checking the release failed:', error);
|
||||
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 { 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');
|
||||
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);
|
||||
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);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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<IncomingMessage & Readable> {
|
||||
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<Uint8Array> {
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
|
||||
|
||||
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
|
||||
|
||||
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
|
||||
const hash = createHash('sha256');
|
||||
let size = 0;
|
||||
for await (const chunk of createReadStream(path)) {
|
||||
size += (chunk as Buffer).length;
|
||||
if (size > limit) throw new Error('The installer is larger than expected.');
|
||||
hash.update(chunk as Buffer);
|
||||
}
|
||||
return { size, sha256: hash.digest('hex') };
|
||||
}
|
||||
@@ -23,17 +23,27 @@ export class FeedUnreachableError extends Error {
|
||||
|
||||
const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
|
||||
/** The newest complete pack release, or null when none is released (or the repository is not public yet). */
|
||||
export async function newestPackRelease(): Promise<PackReleaseFiles | null> {
|
||||
let listing: Promise<readonly unknown[]> | null = null;
|
||||
|
||||
/** Share the in-flight request when the launcher checks both release channels at startup. */
|
||||
export function listProjectReleases(): Promise<readonly unknown[]> {
|
||||
return listing ??= readProjectReleases().finally(() => { listing = null; });
|
||||
}
|
||||
|
||||
async function readProjectReleases(): Promise<readonly unknown[]> {
|
||||
const tuning = patchPackTuning();
|
||||
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasesPerCheck}`;
|
||||
const response = await request(url, HEADERS, tuning.requestTimeoutMs);
|
||||
if (response.status === 404) return null;
|
||||
if (response.status === 404) return [];
|
||||
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for the release list`);
|
||||
const releases = (await response.json()) as unknown;
|
||||
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
|
||||
return releases;
|
||||
}
|
||||
|
||||
const packs = releases.map(packRelease).filter((release): release is PackReleaseFiles => release !== null);
|
||||
/** The newest complete pack release, or null when none is released. */
|
||||
export async function newestPackRelease(): Promise<PackReleaseFiles | null> {
|
||||
const packs = (await listProjectReleases()).map(packRelease).filter((release): release is PackReleaseFiles => release !== null);
|
||||
packs.sort((a, b) => comparePackVersions(b.version, a.version));
|
||||
return packs[0] ?? null;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ import { COPY_SECTIONS, navigate, SAVE_SECTIONS, SETTINGS_SECTIONS, START_ROUTE,
|
||||
import { SubNav } from './shell/SubNav.tsx';
|
||||
import { TitleBar } from './shell/TitleBar.tsx';
|
||||
import { useBackgrounds } from './shell/useBackgrounds.ts';
|
||||
import { useAppUpdate } from './shell/useAppUpdate.ts';
|
||||
import { usePatchPack } from './shell/usePatchPack.ts';
|
||||
import { useErrorMessage } from './useErrorMessage.ts';
|
||||
|
||||
@@ -64,6 +65,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
const [route, setRoute] = useState<Route>(START_ROUTE);
|
||||
// The setting as the window opened: turning it on later does not check right away.
|
||||
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
|
||||
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
|
||||
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
|
||||
|
||||
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
|
||||
@@ -120,11 +122,11 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
bar: home,
|
||||
};
|
||||
case 'about':
|
||||
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} />, bar: home };
|
||||
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} appUpdate={appUpdate} />, bar: home };
|
||||
case 'settings': {
|
||||
const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev');
|
||||
const content = {
|
||||
general: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
|
||||
general: <GeneralSettings settings={settings} appUpdatesSupported={info.appUpdatesSupported} pictures={backgrounds.pictures} onError={report} />,
|
||||
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
|
||||
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
|
||||
dev: <DeveloperSettings settings={settings} onError={report} />,
|
||||
@@ -195,7 +197,8 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
|
||||
gameVersion={record?.gameVersion ?? null}
|
||||
copyName={record?.name ?? null}
|
||||
packUpdate={patchPack.check?.status === 'available' ? (patchPack.check.latest?.version ?? null) : null}
|
||||
onOpenPackUpdate={() => go({ page: 'about' })}
|
||||
appUpdate={appUpdate.check?.status === 'available' ? appUpdate.check.release.version : null}
|
||||
onOpenUpdates={() => go({ page: 'about' })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
"launcher": "Launcher {{version}}",
|
||||
"game": "{{name}} · Game {{version}}",
|
||||
"notInstalled": "Not installed",
|
||||
"packUpdate": "Adaptation pack {{version}} available · Update ›"
|
||||
"packUpdate": "Adaptation pack {{version}} available · Update ›",
|
||||
"appUpdate": "Launcher {{version}} available · Update ›"
|
||||
},
|
||||
"home": {
|
||||
"kicker": "Local server · AI battles",
|
||||
@@ -440,6 +441,8 @@
|
||||
"dev": "Developer",
|
||||
"diag": "Diagnostics"
|
||||
},
|
||||
"appUpdates": "Launcher updates",
|
||||
"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.",
|
||||
"patchPacksToggle": "Check for a new adaptation pack at start",
|
||||
@@ -551,6 +554,23 @@
|
||||
"up_to_date": "Up to date: there is no adaptation pack to download."
|
||||
}
|
||||
},
|
||||
"update": {
|
||||
"title": "Launcher update",
|
||||
"check": "Launcher version check",
|
||||
"checking": "Checking…",
|
||||
"current": "The launcher is up to date.",
|
||||
"available": "Version {{version}} is available. Installer size {{size}}.",
|
||||
"downloading": "Downloading the installer…",
|
||||
"download": "Download update",
|
||||
"install": "Quit and install",
|
||||
"installing": "Opening the installer…",
|
||||
"errors": {
|
||||
"network": "GitHub Releases could not be reached.",
|
||||
"contents": "The launcher release information is invalid.",
|
||||
"signature": "The launcher update signature could not be verified.",
|
||||
"no_signing_key": "The launcher update verification key is unavailable."
|
||||
}
|
||||
},
|
||||
"statement": "Project information",
|
||||
"statementBody": "WTOffline is a noncommercial hobby project independent of Gaijin. Running it requires your own War Thunder base game files."
|
||||
},
|
||||
@@ -588,6 +608,12 @@
|
||||
"L-Battle awards": "Battle awards"
|
||||
},
|
||||
"errors": {
|
||||
"app_update_unavailable": "There is no launcher update available to install.",
|
||||
"app_update_busy": "A launcher update operation is already in progress.",
|
||||
"app_update_launcher_busy": "Close the game and local server and finish any copy or save operations before updating.",
|
||||
"app_update_download_failed": "The launcher installer could not be downloaded and verified. See the launcher log.",
|
||||
"app_update_installer_invalid": "The installer failed verification. Download it again.",
|
||||
"app_update_install_failed": "The launcher installer could not be opened. See the launcher log.",
|
||||
"internal_error": "An internal launcher error occurred.",
|
||||
"logs_folder_open_failed": "The launcher log folder could not be opened.",
|
||||
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
"launcher": "启动器 {{version}}",
|
||||
"game": "{{name}} · 游戏 {{version}}",
|
||||
"notInstalled": "未安装",
|
||||
"packUpdate": "适配包 {{version}} 可用 · 更新 ›"
|
||||
"packUpdate": "适配包 {{version}} 可用 · 更新 ›",
|
||||
"appUpdate": "本体 {{version}} 可用 · 更新 ›"
|
||||
},
|
||||
"home": {
|
||||
"kicker": "本地服务器 · AI 对局",
|
||||
@@ -440,6 +441,8 @@
|
||||
"dev": "开发者",
|
||||
"diag": "诊断"
|
||||
},
|
||||
"appUpdates": "启动器本体更新",
|
||||
"appUpdatesToggle": "启动时检查本体更新",
|
||||
"patchPacks": "适配包更新",
|
||||
"patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布在 GitHub 上。",
|
||||
"patchPacksToggle": "启动时检查有没有新的适配包",
|
||||
@@ -551,6 +554,23 @@
|
||||
"up_to_date": "已是最新,没有需要下载的适配包。"
|
||||
}
|
||||
},
|
||||
"update": {
|
||||
"title": "本体更新",
|
||||
"check": "检查本体版本",
|
||||
"checking": "正在检查…",
|
||||
"current": "当前已是最新版本。",
|
||||
"available": "版本 {{version}} 可用,安装包 {{size}}。",
|
||||
"downloading": "正在下载安装包…",
|
||||
"download": "下载更新",
|
||||
"install": "退出并安装",
|
||||
"installing": "正在打开安装包…",
|
||||
"errors": {
|
||||
"network": "暂时无法访问 GitHub 发布页。",
|
||||
"contents": "本体更新的发布信息无效。",
|
||||
"signature": "本体更新签名校验失败。",
|
||||
"no_signing_key": "本体更新公钥不可用。"
|
||||
}
|
||||
},
|
||||
"statement": "项目信息",
|
||||
"statementBody": "WTOffline 是一个独立于 Gaijin 的非商业兴趣项目。运行需要自备战争雷霆游戏本体文件。"
|
||||
},
|
||||
@@ -588,6 +608,12 @@
|
||||
"L-Battle awards": "战斗嘉奖"
|
||||
},
|
||||
"errors": {
|
||||
"app_update_unavailable": "当前没有可安装的本体更新。",
|
||||
"app_update_busy": "本体更新操作正在进行。",
|
||||
"app_update_launcher_busy": "请在游戏退出、服务器关闭及副本和存档操作完成后安装更新。",
|
||||
"app_update_download_failed": "无法下载并验证本体安装包。请查看启动器日志。",
|
||||
"app_update_installer_invalid": "安装包校验失败。请重新下载。",
|
||||
"app_update_install_failed": "无法打开本体安装包。请查看启动器日志。",
|
||||
"internal_error": "启动器内部错误。",
|
||||
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
|
||||
"diagnostics_export_failed": "无法保存诊断信息。",
|
||||
|
||||
@@ -2,16 +2,19 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { Sheet } from '../../components/Sheet.tsx';
|
||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||
import { AppUpdateSection } from './AppUpdateSection.tsx';
|
||||
import type { PatchPackState } from '../../shell/usePatchPack.ts';
|
||||
|
||||
interface AboutPageProps {
|
||||
readonly launcherVersion: string;
|
||||
readonly supportedVersions: readonly string[];
|
||||
readonly patchPack: PatchPackState;
|
||||
readonly appUpdate: AppUpdateState;
|
||||
}
|
||||
|
||||
/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */
|
||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack }: AboutPageProps) {
|
||||
export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate }: AboutPageProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Sheet title={t('nav.about')}>
|
||||
@@ -23,6 +26,7 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack }: Abo
|
||||
{t('about.supported', { versions: supportedVersions.join(', ') })}
|
||||
</div>
|
||||
</div>
|
||||
<AppUpdateSection state={appUpdate} />
|
||||
<PatchPackSection state={patchPack} />
|
||||
<h3 className="section-title section-title-spaced">{t('about.statement')}</h3>
|
||||
<p className="lead">{t('about.statementBody')}</p>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Notice } from '../../components/Notice.tsx';
|
||||
import { ProgressBar } from '../../components/ProgressBar.tsx';
|
||||
import { Row } from '../../components/Row.tsx';
|
||||
import { formatBytes } from '../../format.ts';
|
||||
import type { AppUpdateState } from '../../shell/useAppUpdate.ts';
|
||||
|
||||
export function AppUpdateSection({ state }: { readonly state: AppUpdateState }) {
|
||||
const { t } = useTranslation();
|
||||
if (!state.supported) return null;
|
||||
const { check, busy, progress } = state;
|
||||
return (
|
||||
<>
|
||||
<h3 className="section-title">{t('about.update.title')}</h3>
|
||||
<Row label={t('about.update.check')}>
|
||||
<button type="button" className="button" disabled={busy !== null} onClick={state.checkNow}>
|
||||
{t(busy === 'checking' ? 'about.update.checking' : 'about.pack.checkButton')}
|
||||
</button>
|
||||
</Row>
|
||||
{check?.status === 'current' && busy !== 'checking' && <Notice tone="info"><p>{t('about.update.current')}</p></Notice>}
|
||||
{check?.status === 'failed' && busy !== 'checking' && <Notice tone="error"><p>{t(`about.update.errors.${check.problem}`)}</p></Notice>}
|
||||
{check?.status === 'available' && busy !== 'checking' && (
|
||||
<Notice tone="info">
|
||||
<p>{t('about.update.available', { version: check.release.version, size: formatBytes(check.release.size) })}</p>
|
||||
{check.release.notes && <p className="small update-notes">{check.release.notes}</p>}
|
||||
{busy === 'downloading' ? (
|
||||
<>
|
||||
<p>{t('about.update.downloading')}</p>
|
||||
<ProgressBar value={progress?.received ?? 0} max={progress?.total ?? null} />
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="button button-primary"
|
||||
disabled={busy !== null}
|
||||
onClick={() => {
|
||||
if (check.ready) state.install(check.release.version);
|
||||
else state.download(check.release.version);
|
||||
}}
|
||||
>
|
||||
{t(busy === 'installing' ? 'about.update.installing' : check.ready ? 'about.update.install' : 'about.update.download')}
|
||||
</button>
|
||||
)}
|
||||
</Notice>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -9,12 +9,13 @@ import { LanguageMenu } from '../../shell/LanguageMenu.tsx';
|
||||
|
||||
interface GeneralSettingsProps {
|
||||
readonly settings: Settings;
|
||||
readonly appUpdatesSupported: boolean;
|
||||
readonly pictures: readonly BackgroundPicture[];
|
||||
readonly onError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** General launcher settings: language and background picture. */
|
||||
export function GeneralSettings({ settings, pictures, onError }: GeneralSettingsProps) {
|
||||
export function GeneralSettings({ settings, appUpdatesSupported, pictures, onError }: GeneralSettingsProps) {
|
||||
const { t } = useTranslation();
|
||||
const update = (patch: Partial<Settings>): void => {
|
||||
ipcInvoke('settings:update', patch).catch(onError);
|
||||
@@ -56,6 +57,14 @@ export function GeneralSettings({ settings, pictures, onError }: GeneralSettings
|
||||
{t('background.officialToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
{appUpdatesSupported && (
|
||||
<Row label={t('settings.appUpdates')}>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={settings.checkLauncherUpdatesOnStart} onChange={(event) => update({ checkLauncherUpdatesOnStart: event.target.checked })} />
|
||||
{t('settings.appUpdatesToggle')}
|
||||
</label>
|
||||
</Row>
|
||||
)}
|
||||
<Row label={t('settings.patchPacks')} hint={t('settings.patchPacksHint')}>
|
||||
<label className="check check-inline">
|
||||
<input type="checkbox" checked={settings.checkPatchPacksOnStart} onChange={(event) => update({ checkPatchPacksOnStart: event.target.checked })} />
|
||||
|
||||
@@ -7,21 +7,31 @@ interface FooterProps {
|
||||
readonly copyName: string | null;
|
||||
/** A newer adaptation pack that this launcher can use, or null. */
|
||||
readonly packUpdate: string | null;
|
||||
readonly onOpenPackUpdate: () => void;
|
||||
readonly appUpdate: string | null;
|
||||
readonly onOpenUpdates: () => void;
|
||||
}
|
||||
|
||||
/** Launcher and game versions along the bottom edge; on the right, an available adaptation pack. */
|
||||
export function Footer({ launcherVersion, gameVersion, copyName, packUpdate, onOpenPackUpdate }: FooterProps) {
|
||||
/** Launcher and game versions along the bottom edge; on the right, available updates. */
|
||||
export function Footer({ launcherVersion, gameVersion, copyName, packUpdate, appUpdate, onOpenUpdates }: FooterProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<footer className="footer">
|
||||
<span>{t('footer.launcher', { version: launcherVersion })}</span>
|
||||
<span className="footer-separator">|</span>
|
||||
<span className="footer-copy">{copyName ? t('footer.game', { name: copyName, version: gameVersion ?? t('source.versionUnknown') }) : t('footer.notInstalled')}</span>
|
||||
{packUpdate && (
|
||||
<button type="button" className="footer-update" onClick={onOpenPackUpdate}>
|
||||
{t('footer.packUpdate', { version: packUpdate })}
|
||||
</button>
|
||||
{(appUpdate || packUpdate) && (
|
||||
<div className="footer-updates">
|
||||
{appUpdate && (
|
||||
<button type="button" className="footer-update" onClick={onOpenUpdates}>
|
||||
{t('footer.appUpdate', { version: appUpdate })}
|
||||
</button>
|
||||
)}
|
||||
{packUpdate && (
|
||||
<button type="button" className="footer-update" onClick={onOpenUpdates}>
|
||||
{t('footer.packUpdate', { version: packUpdate })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</footer>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { AppUpdateCheck, AppUpdateProgress } from '@shared/schemas/app-update.ts';
|
||||
import { AppIpcError, ipcInvoke, ipcOn } from '../ipc.ts';
|
||||
|
||||
export function useAppUpdate(supported: boolean, checkOnStart: boolean, onError: (error: unknown) => void) {
|
||||
const [check, setCheck] = useState<AppUpdateCheck | null>(null);
|
||||
const [progress, setProgress] = useState<AppUpdateProgress | null>(null);
|
||||
const [busy, setBusy] = useState<'checking' | 'downloading' | 'installing' | null>(null);
|
||||
const started = useRef(false);
|
||||
|
||||
useEffect(() => ipcOn('event:app-update-progress', setProgress), []);
|
||||
|
||||
const checkNow = useCallback(() => {
|
||||
setBusy('checking');
|
||||
ipcInvoke('updates:check').then(setCheck).catch(onError).finally(() => setBusy(null));
|
||||
}, [onError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!supported || !checkOnStart || started.current) return;
|
||||
started.current = true;
|
||||
checkNow();
|
||||
}, [supported, checkOnStart, checkNow]);
|
||||
|
||||
const download = (version: string): void => {
|
||||
setProgress(null);
|
||||
setBusy('downloading');
|
||||
ipcInvoke('updates:download', { version }).then(setCheck).catch(onError).finally(() => setBusy(null));
|
||||
};
|
||||
|
||||
const install = (version: string): void => {
|
||||
setBusy('installing');
|
||||
ipcInvoke('updates:install', { version }).catch((error: unknown) => {
|
||||
if (error instanceof AppIpcError && error.code === 'app_update_installer_invalid') {
|
||||
setCheck((previous) => previous?.status === 'available' ? { ...previous, ready: false } : previous);
|
||||
}
|
||||
onError(error);
|
||||
}).finally(() => setBusy(null));
|
||||
};
|
||||
|
||||
return { supported, check, progress, busy, checkNow, download, install };
|
||||
}
|
||||
|
||||
export type AppUpdateState = ReturnType<typeof useAppUpdate>;
|
||||
@@ -312,6 +312,11 @@
|
||||
}
|
||||
|
||||
/* ===== About ===== */
|
||||
.update-notes {
|
||||
white-space: pre-line;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.about-head {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
|
||||
@@ -550,10 +550,15 @@
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* An available adaptation pack, at the right end. */
|
||||
.footer-update {
|
||||
/* Available updates at the right end. */
|
||||
.footer-updates {
|
||||
margin-left: auto;
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.footer-update {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
|
||||
@@ -12,6 +12,12 @@
|
||||
export const APP_ERROR_CODES = [
|
||||
/** A bug of ours: a handler returned something its contract does not allow. */
|
||||
'internal_error',
|
||||
'app_update_unavailable',
|
||||
'app_update_busy',
|
||||
'app_update_launcher_busy',
|
||||
'app_update_download_failed',
|
||||
'app_update_installer_invalid',
|
||||
'app_update_install_failed',
|
||||
/** The launcher's own settings file could not be written. */
|
||||
'settings_write_failed',
|
||||
'logs_folder_open_failed',
|
||||
|
||||
@@ -24,6 +24,8 @@ export const IPC_CHANNEL_PREFIXES = [
|
||||
'settings:',
|
||||
/** Adaptation packs: the active patch set, update checks, installing a newer pack. */
|
||||
'patches:',
|
||||
/** Checking, downloading and installing a launcher release. */
|
||||
'updates:',
|
||||
/** The launcher window itself (it draws its own title bar). */
|
||||
'window:',
|
||||
] as const;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import { AppReleaseVersionSchema, AppUpdateCheckSchema, AppUpdateProgressSchema } from '../schemas/app-update.ts';
|
||||
import { BackgroundPictureSchema } from '../schemas/background.ts';
|
||||
import {
|
||||
CopiesSchema,
|
||||
@@ -34,6 +35,7 @@ export const ipcContract = {
|
||||
version: z.string(),
|
||||
electron: z.string(),
|
||||
development: z.boolean(),
|
||||
appUpdatesSupported: z.boolean(),
|
||||
/** The operating system's preferred language, as Electron reports it (e.g. "zh-CN"). */
|
||||
systemLocale: z.string(),
|
||||
userDataPath: z.string(),
|
||||
@@ -270,6 +272,18 @@ export const ipcContract = {
|
||||
input: z.void(),
|
||||
output: ActivePatchSetSchema,
|
||||
},
|
||||
'updates:check': {
|
||||
input: z.void(),
|
||||
output: AppUpdateCheckSchema,
|
||||
},
|
||||
'updates:download': {
|
||||
input: z.object({ version: AppReleaseVersionSchema }),
|
||||
output: AppUpdateCheckSchema,
|
||||
},
|
||||
'updates:install': {
|
||||
input: z.object({ version: AppReleaseVersionSchema }),
|
||||
output: z.void(),
|
||||
},
|
||||
'window:minimize': {
|
||||
input: z.void(),
|
||||
output: z.void(),
|
||||
@@ -283,6 +297,7 @@ export const ipcContract = {
|
||||
export const ipcEvents = {
|
||||
'event:settings-changed': SettingsSchema,
|
||||
'event:install-progress': InstallProgressSchema,
|
||||
'event:app-update-progress': AppUpdateProgressSchema,
|
||||
'event:launch-state': LaunchStateSchema,
|
||||
'event:copies-changed': CopiesSchema,
|
||||
'event:copy-maintenance': MaintenanceProgressSchema,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const STABLE_VERSION = /^(0|[1-9][0-9]{0,4})\.(0|[1-9][0-9]{0,4})\.(0|[1-9][0-9]{0,4})$/;
|
||||
export const AppReleaseVersionSchema = z.string().regex(STABLE_VERSION);
|
||||
export const MAX_INSTALLER_BYTES = 2 ** 31 - 1;
|
||||
|
||||
export function launcherReleaseFiles(version: string) {
|
||||
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64`;
|
||||
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export const LauncherReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-release'),
|
||||
format: z.literal(1),
|
||||
version: AppReleaseVersionSchema,
|
||||
platform: z.literal('win32-x64'),
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
|
||||
|
||||
const AppUpdateReleaseSchema = z.object({
|
||||
version: AppReleaseVersionSchema,
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
notes: z.string(),
|
||||
});
|
||||
const AppUpdateProblemSchema = z.enum(['network', 'contents', 'signature', 'no_signing_key']);
|
||||
|
||||
export const AppUpdateCheckSchema = z.discriminatedUnion('status', [
|
||||
z.object({ status: z.literal('current') }),
|
||||
z.object({ status: z.literal('available'), release: AppUpdateReleaseSchema, ready: z.boolean() }),
|
||||
z.object({ status: z.literal('failed'), problem: AppUpdateProblemSchema }),
|
||||
]);
|
||||
export type AppUpdateCheck = z.output<typeof AppUpdateCheckSchema>;
|
||||
|
||||
export const AppUpdateProgressSchema = z.object({
|
||||
received: z.number().int().nonnegative(),
|
||||
total: z.number().int().positive(),
|
||||
});
|
||||
export type AppUpdateProgress = z.output<typeof AppUpdateProgressSchema>;
|
||||
@@ -21,6 +21,7 @@ export const SettingsSchema = z.object({
|
||||
officialWallpapers: z.boolean().default(true),
|
||||
/** Ask GitHub for a newer adaptation pack when the launcher starts. */
|
||||
checkPatchPacksOnStart: z.boolean().default(true),
|
||||
checkLauncherUpdatesOnStart: z.boolean().default(true),
|
||||
windowClose: WindowCloseSchema.default('quit'),
|
||||
afterGameStarts: AfterGameStartsSchema.default('minimize'),
|
||||
autoSaveBackups: z.boolean().default(true),
|
||||
@@ -41,6 +42,7 @@ export const SettingsPatchSchema = z.object({
|
||||
background: BackgroundChoiceSchema.optional(),
|
||||
officialWallpapers: z.boolean().optional(),
|
||||
checkPatchPacksOnStart: z.boolean().optional(),
|
||||
checkLauncherUpdatesOnStart: z.boolean().optional(),
|
||||
windowClose: WindowCloseSchema.optional(),
|
||||
afterGameStarts: AfterGameStartsSchema.optional(),
|
||||
autoSaveBackups: z.boolean().optional(),
|
||||
|
||||
@@ -51,8 +51,10 @@ export { patchPackTuning, type PatchPackTuning } from './patch-pack/patch-pack-t
|
||||
export {
|
||||
generateSigningKeys,
|
||||
packSigningPublicKey,
|
||||
signEd25519,
|
||||
signPatchPack,
|
||||
SIGNING_PUBLIC_KEY_FILE,
|
||||
verifyEd25519,
|
||||
verifyPatchPack,
|
||||
type SigningKeyPair,
|
||||
} from './patch-pack/signature.ts';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Ed25519 signatures of adaptation packs.
|
||||
* Ed25519 signatures for project releases.
|
||||
*
|
||||
* The private key never enters the repository: the release workflow reads it from the GitHub
|
||||
* secret PATCH_SIGNING_KEY, and the developer keeps a backup outside the repository. The public
|
||||
@@ -32,18 +32,20 @@ export function packSigningPublicKey(): string | null {
|
||||
return existsSync(SIGNING_PUBLIC_KEY_FILE) ? readFileSync(SIGNING_PUBLIC_KEY_FILE, 'utf8') : null;
|
||||
}
|
||||
|
||||
export function signPatchPack(zip: Uint8Array, privateKeyPem: string): string {
|
||||
export function signEd25519(bytes: Uint8Array, privateKeyPem: string): string {
|
||||
const key = ed25519Key(() => createPrivateKey(privateKeyPem), 'private');
|
||||
return `${sign(null, zip, key).toString('base64')}\n`;
|
||||
return `${sign(null, bytes, key).toString('base64')}\n`;
|
||||
}
|
||||
|
||||
export function verifyPatchPack(zip: Uint8Array, signatureText: string, publicKeyPem: string): boolean {
|
||||
export function verifyEd25519(bytes: Uint8Array, signatureText: string, publicKeyPem: string): boolean {
|
||||
const key = ed25519Key(() => createPublicKey(publicKeyPem), 'public');
|
||||
const signature = Buffer.from(signatureText.trim(), 'base64');
|
||||
if (signature.length !== 64) return false;
|
||||
return verify(null, zip, key, signature);
|
||||
return verify(null, bytes, key, signature);
|
||||
}
|
||||
|
||||
export { signEd25519 as signPatchPack, verifyEd25519 as verifyPatchPack };
|
||||
|
||||
function ed25519Key(read: () => KeyObject, kind: 'private' | 'public'): KeyObject {
|
||||
let key: KeyObject;
|
||||
try {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { cp, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/p
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { Arch, build, Platform } from 'electron-builder';
|
||||
import { launcherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
|
||||
const repository = resolve(import.meta.dirname, '..');
|
||||
const launcher = join(repository, 'apps', 'launcher');
|
||||
@@ -46,9 +47,10 @@ async function stageWorkspacePackage(folder: string, resources: string, runtimeM
|
||||
await writeFile(join(bridge, 'index.js'), 'export * from ' + JSON.stringify(entry) + ';\n');
|
||||
}
|
||||
|
||||
async function stageInstaller(stage: string): Promise<void> {
|
||||
async function stageInstaller(stage: string): Promise<string> {
|
||||
const manifest = JSON.parse(await readFile(join(launcher, 'package.json'), 'utf8')) as LauncherManifest;
|
||||
const { productName, version, description, main, type } = manifest;
|
||||
const artifactName = launcherReleaseFiles(version).installer;
|
||||
await writeFile(join(stage, 'package.json'), JSON.stringify({
|
||||
name: 'wtoffline-launcher', productName, version, description, main, type, license: 'AGPL-3.0-or-later',
|
||||
}));
|
||||
@@ -66,6 +68,7 @@ async function stageInstaller(stage: string): Promise<void> {
|
||||
for (const name of ['fflate', 'zod']) {
|
||||
await cp(join(modules, name), join(runtimeModules, name), { recursive: true });
|
||||
}
|
||||
return artifactName;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
@@ -75,7 +78,7 @@ async function main(): Promise<void> {
|
||||
try {
|
||||
const electron = join(modules, 'electron');
|
||||
const { version: electronVersion } = JSON.parse(await readFile(join(electron, 'package.json'), 'utf8')) as { version: string };
|
||||
await stageInstaller(stage);
|
||||
const artifactName = await stageInstaller(stage);
|
||||
const artifacts = await build({
|
||||
projectDir: stage,
|
||||
targets: Platform.WINDOWS.createTarget('nsis', Arch.x64),
|
||||
@@ -92,7 +95,10 @@ async function main(): Promise<void> {
|
||||
{ from: 'installer-resources', to: '.', filter: ['**/*'] },
|
||||
{ from: 'installer-modules', to: 'node_modules', filter: ['**/*'] },
|
||||
],
|
||||
win: { signExecutable: false },
|
||||
win: {
|
||||
artifactName,
|
||||
signExecutable: false,
|
||||
},
|
||||
nsis: { oneClick: false, perMachine: false, allowToChangeInstallationDirectory: true, runAfterFinish: false },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { packSigningPublicKey, signEd25519, verifyEd25519 } from '@wto/patcher';
|
||||
import { installerDigest, launcherSignaturePayload } from '../apps/launcher/src/main/services/app-update/installer-integrity.ts';
|
||||
import { launcherReleaseFiles, LauncherReleaseManifest } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
|
||||
const repository = resolve(import.meta.dirname, '..');
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { version } = JSON.parse(await readFile(join(repository, 'apps', 'launcher', 'package.json'), 'utf8')) as { version: string };
|
||||
const files = launcherReleaseFiles(version);
|
||||
const installer = join(repository, 'build', 'windows-installer', files.installer);
|
||||
const privateKey = process.env['PATCH_SIGNING_KEY'];
|
||||
const publicKey = packSigningPublicKey();
|
||||
if (!privateKey || !publicKey) throw new Error('The project signing key pair is required.');
|
||||
const manifest = LauncherReleaseManifest.parse({
|
||||
kind: 'wto-launcher-release',
|
||||
format: 1,
|
||||
platform: 'win32-x64',
|
||||
version,
|
||||
...await installerDigest(installer),
|
||||
});
|
||||
const bytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n', 'utf8');
|
||||
const payload = launcherSignaturePayload(bytes);
|
||||
const signature = signEd25519(payload, privateKey);
|
||||
if (!verifyEd25519(payload, signature, publicKey)) throw new Error('The release key does not match the bundled public key.');
|
||||
|
||||
const folder = dirname(installer);
|
||||
await writeFile(join(folder, files.manifest), bytes);
|
||||
await writeFile(join(folder, files.signature), signature, 'utf8');
|
||||
for (const file of Object.values(files)) console.info(join(folder, file));
|
||||
}
|
||||
|
||||
await main();
|
||||
Reference in new issue
Block a user