Release adaptation packs and let the launcher install them

An adaptation pack is the patch set (exe, GUI, native definitions and
version records) released on its own, so a new game build can be adapted
without a new offline version. It is a zip with a manifest, signed with
Ed25519, published as a GitHub release tagged patches-<YYYY.MM.DD[.N]>.

- packages/patcher/src/patch-pack: manifest and version numbers, zip
  writing and reading with path and size checks, signatures, a check that
  a patch set reads as a whole; tuning/patch-pack.jsonc holds the
  repository and the limits.
- scripts/generate-patch-signing-key.ts writes the public key for the
  repository and the private key outside it; scripts/build-patch-pack.ts
  packs only committed files and signs with PATCH_SIGNING_KEY.
- .github/workflows/patch-pack.yml packs, signs and publishes on a
  patches-* tag or a manual run.
- Launcher main process: find the newest pack release, download, verify,
  unpack into user data and make it active; resource paths use the
  active pack when it is usable (a repository checkout only with
  WTO_USE_PATCH_PACK=1). The pages that show and start this come later.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 16:08:37 +08:00
1 parent 19990fc9de
commit 3e2acc5a17
18 files changed
+1097 -2

No files matched your search

@@ -0,0 +1,116 @@
/**
* Downloaded adaptation packs, under `<user data>/patch-packs/`:
*
* <version>/ one unpacked pack: a patch set (exe/ gui/ native/ versions/) plus manifest.json
* active.json { "version": "<version>" } of the pack the builds use; without it they use
* the patch set that ships with the launcher
*
* A pack is written only after its signature verifies against the public key in
* packages/patcher/keys/ and every entry passed the checks of readPatchPack; it is unpacked into a
* staging folder, read back as a whole patch set, and only then renamed into place and made active.
* Only the active pack is kept.
*/
import { randomBytes } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import {
checkPatchSet,
formatManifest,
isPackVersion,
manifestIncompatibility,
MANIFEST_FILE,
packSigningPublicKey,
parseManifest,
PatchPackError,
patchPackTuning,
readPatchPack,
verifyPatchPack,
type PatchPackManifest,
} from '@wto/patcher';
import { writeJsonAtomic } from '../../util/atomic-json.ts';
export interface DownloadedPack {
readonly root: string;
readonly manifest: PatchPackManifest;
}
function storeFolder(): string {
return join(app.getPath('userData'), 'patch-packs');
}
function activeFile(): string {
return join(storeFolder(), 'active.json');
}
/**
* The active downloaded pack, when there is one this launcher can use. Synchronous, because the
* resource paths are; it reads two small files.
*/
export function activeDownloadedPack(): DownloadedPack | null {
try {
const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown };
if (typeof active.version !== 'string' || !isPackVersion(active.version)) return null;
const root = join(storeFolder(), active.version);
const manifest = parseManifest(readFileSync(join(root, MANIFEST_FILE), 'utf8'));
if (manifest.version !== active.version || manifestIncompatibility(manifest, app.getVersion())) return null;
return { root, manifest };
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[patch-pack] the active pack is unusable:', error);
return null;
}
}
/**
* Verify, unpack and activate a downloaded pack. Throws PatchPackError when the signature, the
* contents or the size is wrong, or when this launcher cannot use the pack.
*/
export async function installPack(version: string, zip: Uint8Array, signature: string): Promise<DownloadedPack> {
const publicKey = packSigningPublicKey();
if (!publicKey) throw new PatchPackError('key', 'this launcher carries no signing key');
if (!verifyPatchPack(zip, signature, publicKey)) throw new PatchPackError('signature', `the signature of pack ${version} does not match`);
const contents = readPatchPack(zip, patchPackTuning().maxUnpackedBytes);
if (contents.manifest.version !== version) {
throw new PatchPackError('contents', `the release says ${version} but the pack says ${contents.manifest.version}`);
}
if (manifestIncompatibility(contents.manifest, app.getVersion())) {
throw new PatchPackError('contents', `pack ${version} needs offline version ${contents.manifest.minAppVersion} or a newer pack format`);
}
const store = storeFolder();
const staging = join(store, `${version}.partial-${randomBytes(4).toString('hex')}`);
try {
for (const file of contents.files) {
const path = join(staging, ...file.path.split('/'));
await mkdir(dirname(path), { recursive: true });
await writeFile(path, file.content);
}
await writeFile(join(staging, MANIFEST_FILE), formatManifest(contents.manifest), 'utf8');
checkPatchSet(staging);
const root = join(store, version);
await rm(root, { recursive: true, force: true });
await rename(staging, root);
await writeJsonAtomic(activeFile(), { version });
await pruneInactive(version);
return { root, manifest: contents.manifest };
} finally {
await rm(staging, { recursive: true, force: true }).catch(() => undefined);
}
}
/** Go back to the patch set that ships with the launcher; the downloaded packs are removed. */
export async function useBundledPatchSet(): Promise<void> {
await rm(activeFile(), { force: true });
await pruneInactive(null);
}
async function pruneInactive(keep: string | null): Promise<void> {
const entries = await readdir(storeFolder(), { withFileTypes: true }).catch(() => []);
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === keep) continue;
await rm(join(storeFolder(), entry.name), { recursive: true, force: true }).catch((error: unknown) => {
console.warn(`[patch-pack] could not remove ${entry.name}:`, error);
});
}
}
@@ -0,0 +1,126 @@
/**
* Adaptation pack updates: which patch set the builds use, whether GitHub 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.
*
* A pack is newer when its version is above the active set's. A bundled set without a version
* (a repository checkout) is older than every pack.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { app } from 'electron';
import {
comparePackVersions,
MANIFEST_FILE,
manifestIncompatibility,
parseManifest,
PatchPackError,
patchPackTuning,
packSigningPublicKey,
recordedGameVersions,
type PatchPackManifest,
} from '@wto/patcher';
import type { ActivePatchSet, PackApplyResult, PackCheck, PackProblem, PackRelease } from '@shared/schemas/patch-pack.ts';
import { bundledResourcePaths, usesDownloadedPacks } from '../resources/resource-paths.ts';
import { activeDownloadedPack, installPack, useBundledPatchSet } from './pack-store.ts';
import { downloadReleaseFile, FeedUnreachableError, newestPackRelease, 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;
export function activePatchSet(): ActivePatchSet {
const pack = usesDownloadedPacks() ? activeDownloadedPack() : null;
if (pack) return { source: 'downloaded', version: pack.manifest.version, gameVersions: [...pack.manifest.gameVersions] };
const root = bundledResourcePaths().patches;
return { source: 'bundled', version: bundledVersion(root), gameVersions: recordedGameVersions(root) };
}
export async function checkPackUpdate(): Promise<PackCheck> {
const active = activePatchSet();
if (!packSigningPublicKey()) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
try {
const found = await newestRelease();
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 };
} catch (error) {
console.warn('[patch-pack] update check failed:', error);
return { status: 'failed', active, latest: null, problem: problemOf(error) };
}
}
/** Download and activate the newest pack, when it is newer than the active set and usable. */
export async function applyPackUpdate(): Promise<PackApplyResult> {
if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' };
try {
const found = await newestRelease();
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`);
return { ok: true, active: activePatchSet() };
} catch (error) {
console.warn('[patch-pack] update failed:', error);
return { ok: false, problem: problemOf(error) };
}
}
/** Stop using downloaded packs. */
export async function revertToBundledPatchSet(): Promise<ActivePatchSet> {
await useBundledPatchSet();
return activePatchSet();
}
interface FoundRelease {
readonly files: PackReleaseFiles;
readonly manifest: PatchPackManifest;
}
async function newestRelease(): Promise<FoundRelease | null> {
const files = await newestPackRelease();
if (!files) return null;
const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES));
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 };
}
function release(found: FoundRelease): PackRelease {
return {
version: found.manifest.version,
gameVersions: [...found.manifest.gameVersions],
minAppVersion: found.manifest.minAppVersion,
publishedAt: found.files.publishedAt,
};
}
function isNewer(candidate: string, active: string | null): boolean {
return active === null || comparePackVersions(candidate, active) > 0;
}
/** The version of a bundled set that carries a manifest (a packaged launcher's), else null. */
function bundledVersion(root: string): string | null {
const path = join(root, MANIFEST_FILE);
if (!existsSync(path)) return null;
try {
return parseManifest(readFileSync(path, 'utf8')).version;
} catch (error) {
console.warn('[patch-pack] the bundled manifest is unreadable:', error);
return null;
}
}
function problemOf(error: unknown): PackProblem {
if (error instanceof FeedUnreachableError) return 'network';
if (error instanceof PatchPackError) {
if (error.problem === 'signature') return 'signature';
if (error.problem === 'size') return 'size';
if (error.problem === 'key') return 'no_signing_key';
}
return 'contents';
}
@@ -0,0 +1,80 @@
/**
* Adaptation pack releases on GitHub: the newest release tagged `patches-<version>` that carries
* all three files (zip, signature, manifest copy), and downloads of those files.
*
* Requests send no account, no cookie and nothing about the player; GitHub sees an anonymous
* request with a generic user agent.
*/
import { net } from 'electron';
import { comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning } from '@wto/patcher';
export interface PackReleaseFiles {
readonly version: string;
readonly publishedAt: string | null;
readonly zipUrl: string;
readonly signatureUrl: string;
readonly manifestUrl: string;
}
/** Thrown when GitHub cannot be reached or answers with an error. */
export class FeedUnreachableError extends Error {
override readonly name = 'FeedUnreachableError';
}
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> {
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.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');
const packs = releases.map(packRelease).filter((release): release is PackReleaseFiles => release !== null);
packs.sort((a, b) => comparePackVersions(b.version, a.version));
return packs[0] ?? null;
}
function packRelease(value: unknown): PackReleaseFiles | null {
if (typeof value !== 'object' || value === null) return null;
const release = value as Record<string, unknown>;
if (release['draft'] === true || release['prerelease'] === true || typeof release['tag_name'] !== 'string') return null;
const version = packVersionOfTag(release['tag_name']);
if (!version || !Array.isArray(release['assets'])) return null;
const urls = new Map<string, string>();
for (const asset of release['assets'] as unknown[]) {
if (typeof asset !== 'object' || asset === null) continue;
const { name, browser_download_url: download } = asset as Record<string, unknown>;
if (typeof name === 'string' && typeof download === 'string' && download.startsWith('https://')) urls.set(name, download);
}
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<Uint8Array> {
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<string, string>, timeoutMs: number): Promise<Response> {
try {
return await net.fetch(url, { credentials: 'omit', headers, signal: AbortSignal.timeout(timeoutMs) });
} catch (error) {
throw new FeedUnreachableError(`${url}: ${(error as Error).message}`);
}
}
@@ -1,9 +1,14 @@
import { join, resolve } from 'node:path';
import { app } from 'electron';
import { activeDownloadedPack } from '../patch-pack/pack-store.ts';
/**
* Where the launcher finds what it ships besides its own code: the patch set (exe, GUI and native
* definitions and version records, @wto/patcher patch-set.ts) and the network hook library. In development they are this repository's folders.
*
* The patch set is the active downloaded adaptation pack when there is a usable one
* (services/patch-pack/), otherwise the bundled one. A repository checkout uses its own patches/
* unless WTO_USE_PATCH_PACK=1 is set, so that edits to patches/ take effect while developing.
*/
export interface ResourcePaths {
/** Root of the patch set. */
@@ -13,6 +18,13 @@ export interface ResourcePaths {
}
export function resourcePaths(): ResourcePaths {
const bundled = bundledResourcePaths();
const pack = usesDownloadedPacks() ? activeDownloadedPack() : null;
return pack ? { ...bundled, patches: pack.root } : bundled;
}
/** The resources that ship with the launcher, ignoring downloaded packs. */
export function bundledResourcePaths(): ResourcePaths {
if (app.isPackaged) {
// The packaged layout is decided with the installer build; nothing ships it yet.
throw new Error('resource paths of a packaged launcher are not defined yet');
@@ -24,3 +36,7 @@ export function resourcePaths(): ResourcePaths {
networkHookLibrary: join(repository, 'build', 'native', 'wto_ws.dll'),
};
}
export function usesDownloadedPacks(): boolean {
return app.isPackaged || process.env['WTO_USE_PATCH_PACK'] === '1';
}
@@ -0,0 +1,56 @@
/**
* What the launcher reports about adaptation packs (main/services/patch-pack/): which patch set
* the builds use, and whether a newer pack is released.
*/
/** The patch set that ships with the launcher, or a downloaded adaptation pack. */
export type PatchSetSource = 'bundled' | 'downloaded';
export interface ActivePatchSet {
readonly source: PatchSetSource;
/** Pack version; null for a bundled set without one (a repository checkout). */
readonly version: string | null;
/** Game versions with a version record in the set. */
readonly gameVersions: readonly string[];
}
export interface PackRelease {
readonly version: string;
readonly gameVersions: readonly string[];
readonly minAppVersion: string;
readonly publishedAt: string | null;
}
export type PackCheckStatus =
/** No release is newer than the active set. */
| 'up_to_date'
/** A newer pack this launcher can use. */
| 'available'
/** A newer pack needs a newer offline version (launcher) first. */
| 'needs_app_update'
/** The check could not be made; see `problem`. */
| 'failed';
export type PackProblem =
/** This build of the launcher carries no signing key, so it accepts no pack. */
| 'no_signing_key'
/** GitHub could not be reached or answered with an error. */
| 'network'
/** The release or the pack is malformed. */
| 'contents'
/** The signature does not match. */
| 'signature'
/** The pack is larger than allowed. */
| 'size';
export interface PackCheck {
readonly status: PackCheckStatus;
readonly active: ActivePatchSet;
/** The newest released pack; null when none is released or the check failed. */
readonly latest: PackRelease | null;
readonly problem: PackProblem | null;
}
export type PackApplyResult =
| { readonly ok: true; readonly active: ActivePatchSet }
| { readonly ok: false; readonly problem: PackProblem | 'needs_app_update' | 'up_to_date' };