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

+2 -1
View File
@@ -10,6 +10,7 @@
"@wto/blk": "*",
"@wto/exepatch": "*",
"@wto/jsonc": "*",
"@wto/vromfs": "*"
"@wto/vromfs": "*",
"fflate": "^0.8.2"
}
}
+28
View File
@@ -28,6 +28,34 @@ export { redirectNetworkConfig, type NetworkRedirectReport } from './network/red
export { loadNativeModules, type NativeModule, type NativeSite, type NativeSiteVariant } from './native/native-definition.ts';
export { resolveNativeModules, type NativeResolution } from './native/native-resolve.ts';
export { patchFeatures, type PatchFeature } from './patch-features.ts';
export { checkPatchSet, type PatchSetSummary } from './patch-pack/check-patch-set.ts';
export {
compareAppVersions,
comparePackVersions,
formatManifest,
isPackVersion,
manifestIncompatibility,
MANIFEST_FILE,
packFileNames,
packVersionOfTag,
parseManifest,
PATCH_PACK_FORMAT,
PATCH_PACK_TAG_PREFIX,
type ManifestIncompatibility,
type PatchPackFileNames,
type PatchPackManifest,
} from './patch-pack/manifest.ts';
export { packGameVersions, readPatchPack, writePatchPack, type PatchPackContents, type PatchPackFile } from './patch-pack/pack-archive.ts';
export { PatchPackError, type PatchPackProblem } from './patch-pack/patch-pack-error.ts';
export { patchPackTuning, type PatchPackTuning } from './patch-pack/patch-pack-tuning.ts';
export {
generateSigningKeys,
packSigningPublicKey,
signPatchPack,
SIGNING_PUBLIC_KEY_FILE,
verifyPatchPack,
type SigningKeyPair,
} from './patch-pack/signature.ts';
export { patchSetFolders, type PatchSetFolders } from './patch-set.ts';
export { offlinePackBundleGuids } from './store/offline-bundles.ts';
export {
@@ -0,0 +1,33 @@
/**
* Check that a patch set folder (patch-set.ts) reads as a whole: every exe, GUI and native
* definition and every version record parses. Run on the repository's patches/ before packing
* and on a downloaded pack before the launcher switches to it, so that a malformed file shows up
* there and not in the middle of a build.
*/
import { loadPatches } from '@wto/exepatch';
import { loadGuiPatches } from '../gui-patch-definition.ts';
import { loadNativeModules } from '../native/native-definition.ts';
import { patchSetFolders } from '../patch-set.ts';
import { loadVersionRecords } from '../version-record.ts';
import { PatchPackError } from './patch-pack-error.ts';
export interface PatchSetSummary {
readonly exePatches: number;
readonly guiPatches: number;
readonly nativeModules: number;
readonly gameVersions: readonly string[];
}
export function checkPatchSet(root: string): PatchSetSummary {
const folders = patchSetFolders(root);
try {
return {
exePatches: loadPatches(folders.exe).length,
guiPatches: loadGuiPatches(folders.gui).length,
nativeModules: loadNativeModules(folders.native).length,
gameVersions: loadVersionRecords(folders.versions).map((record) => record.gameVersion),
};
} catch (error) {
throw new PatchPackError('contents', `the patch set does not read: ${(error as Error).message}`);
}
}
+145
View File
@@ -0,0 +1,145 @@
/**
* The manifest of an adaptation pack (`manifest.json` at the root of the zip), and the version
* numbers it carries.
*
* An adaptation pack is a patch set (patch-set.ts) released on its own, so that a new game build
* can be adapted without a new release of the offline version. It is published as a GitHub
* release tagged `patches-<pack version>` with two files: the zip and its Ed25519 signature
* (signature.ts).
*
* format layout of the pack; a launcher uses only formats it knows
* version pack version, `YYYY.MM.DD` or `YYYY.MM.DD.N` for a second pack on a day
* min_app_version the oldest offline version (launcher version) whose patch engine reads it
* game_versions the game builds with a version record in the pack
* created_at when the pack was built (ISO 8601)
*/
import { PatchPackError } from './patch-pack-error.ts';
/** The pack layout this code writes and reads. */
export const PATCH_PACK_FORMAT = 1;
export const PATCH_PACK_TAG_PREFIX = 'patches-';
export const MANIFEST_FILE = 'manifest.json';
export interface PatchPackManifest {
readonly format: number;
readonly version: string;
readonly minAppVersion: string;
readonly gameVersions: readonly string[];
readonly createdAt: string;
}
export interface PatchPackFileNames {
readonly zip: string;
readonly signature: string;
/**
* A copy of the manifest beside the zip, so a launcher can tell what a release holds before it
* downloads the zip. It is not signed and only informs; the manifest inside the signed zip is
* the one that counts.
*/
readonly manifest: string;
}
export function packFileNames(version: string): PatchPackFileNames {
const base = `wtoffline-patches-${version}`;
return { zip: `${base}.zip`, signature: `${base}.zip.sig`, manifest: `${base}.manifest.json` };
}
/** The pack version of a release tag, or null when the tag is not a pack's. */
export function packVersionOfTag(tag: string): string | null {
if (!tag.startsWith(PATCH_PACK_TAG_PREFIX)) return null;
const version = tag.slice(PATCH_PACK_TAG_PREFIX.length);
return isPackVersion(version) ? version : null;
}
export function isPackVersion(text: string): boolean {
return /^\d{4}\.\d{2}\.\d{2}(\.[1-9]\d*)?$/.test(text);
}
/** Negative when a is older than b. Both must be pack versions. */
export function comparePackVersions(a: string, b: string): number {
return compareNumberLists(packVersionParts(a), packVersionParts(b));
}
function packVersionParts(version: string): number[] {
const parts = version.split('.').map(Number);
// `2026.11.29` is the first pack of the day, the same as `2026.11.29.1` would be.
if (parts.length === 3) parts.push(1);
return parts;
}
/** Negative when a is older than b. Versions are `x.y.z`, a pre-release suffix is ignored. */
export function compareAppVersions(a: string, b: string): number {
return compareNumberLists(appVersionParts(a), appVersionParts(b));
}
export function isAppVersion(text: string): boolean {
return /^\d+\.\d+\.\d+([-+].*)?$/.test(text);
}
function appVersionParts(version: string): number[] {
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
if (!match) throw new PatchPackError('contents', `not a version number: ${version}`);
return [Number(match[1]), Number(match[2]), Number(match[3])];
}
function compareNumberLists(a: readonly number[], b: readonly number[]): number {
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const difference = (a[i] ?? 0) - (b[i] ?? 0);
if (difference !== 0) return difference;
}
return 0;
}
/** Why this launcher cannot use a pack, or null when it can. */
export type ManifestIncompatibility = 'format' | 'app_version';
export function manifestIncompatibility(manifest: PatchPackManifest, appVersion: string): ManifestIncompatibility | null {
if (manifest.format > PATCH_PACK_FORMAT) return 'format';
if (compareAppVersions(appVersion, manifest.minAppVersion) < 0) return 'app_version';
return null;
}
export function formatManifest(manifest: PatchPackManifest): string {
const json = {
format: manifest.format,
version: manifest.version,
min_app_version: manifest.minAppVersion,
game_versions: manifest.gameVersions,
created_at: manifest.createdAt,
};
return `${JSON.stringify(json, null, 2)}\n`;
}
export function parseManifest(text: string): PatchPackManifest {
let value: unknown;
try {
value = JSON.parse(text);
} catch {
throw manifestError('not valid JSON');
}
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw manifestError('not an object');
const fields = value as Record<string, unknown>;
const format = fields['format'];
if (typeof format !== 'number' || !Number.isInteger(format) || format < 1) throw manifestError('"format" must be a positive integer');
const version = stringField(fields, 'version');
if (!isPackVersion(version)) throw manifestError(`"version" is not a pack version: ${version}`);
const minAppVersion = stringField(fields, 'min_app_version');
if (!isAppVersion(minAppVersion)) throw manifestError(`"min_app_version" is not a version number: ${minAppVersion}`);
const gameVersions = fields['game_versions'];
if (!Array.isArray(gameVersions) || !gameVersions.every((entry) => typeof entry === 'string' && /^\d+(\.\d+){3}$/.test(entry))) {
throw manifestError('"game_versions" must list game versions such as "2.61.0.37"');
}
const createdAt = stringField(fields, 'created_at');
if (Number.isNaN(Date.parse(createdAt))) throw manifestError('"created_at" is not a date');
return { format, version, minAppVersion, gameVersions: [...gameVersions] as string[], createdAt };
}
function stringField(fields: Record<string, unknown>, key: string): string {
const value = fields[key];
if (typeof value !== 'string' || value.length === 0) throw manifestError(`"${key}" must be a string`);
return value;
}
function manifestError(detail: string): PatchPackError {
return new PatchPackError('contents', `${MANIFEST_FILE}: ${detail}`);
}
@@ -0,0 +1,90 @@
/**
* Write and read the zip of an adaptation pack: `manifest.json` plus the patch set folders
* (patch-set.ts) with their files at the same relative paths.
*
* Reading checks every entry before anything is written to disk: only paths inside the four
* patch set folders, no `..`, no absolute paths, and size limits on what is unpacked.
*/
import { strFromU8, strToU8, unzipSync, zipSync, type Zippable } from 'fflate';
import { formatManifest, MANIFEST_FILE, parseManifest, type PatchPackManifest } from './manifest.ts';
import { PatchPackError } from './patch-pack-error.ts';
export interface PatchPackFile {
/** Relative to the patch set root, with `/` separators, e.g. `versions/2.61.0.43.jsonc`. */
readonly path: string;
readonly content: Uint8Array;
}
export interface PatchPackContents {
readonly manifest: PatchPackManifest;
readonly files: readonly PatchPackFile[];
}
const ENTRY_PATH = /^(exe|gui|native|versions)\/[A-Za-z0-9._\-/]+$/;
const RECORD_PATH = /^versions\/(\d+(?:\.\d+){3})\.jsonc$/;
/** The game versions that have a version record among the files, sorted. */
export function packGameVersions(files: readonly PatchPackFile[]): string[] {
return files
.map((file) => RECORD_PATH.exec(file.path)?.[1])
.filter((version): version is string => version !== undefined)
.sort();
}
export function writePatchPack(contents: PatchPackContents): Uint8Array {
checkContents(contents);
const entries: Zippable = { [MANIFEST_FILE]: strToU8(formatManifest(contents.manifest)) };
for (const file of contents.files) entries[file.path] = file.content;
return zipSync(entries, { level: 9 });
}
export function readPatchPack(zip: Uint8Array, maxUnpackedBytes: number): PatchPackContents {
let declared = 0;
let entries: Record<string, Uint8Array>;
try {
entries = unzipSync(zip, {
filter: (entry) => {
declared += entry.originalSize;
if (declared > maxUnpackedBytes) throw new PatchPackError('size', `the pack unpacks to more than ${maxUnpackedBytes} bytes`);
return true;
},
});
} catch (error) {
if (error instanceof PatchPackError) throw error;
throw new PatchPackError('contents', `the pack is not a readable zip: ${(error as Error).message}`);
}
const unpacked = Object.values(entries).reduce((sum, content) => sum + content.length, 0);
if (unpacked > maxUnpackedBytes) throw new PatchPackError('size', `the pack unpacks to more than ${maxUnpackedBytes} bytes`);
const manifestBytes = entries[MANIFEST_FILE];
if (!manifestBytes) throw new PatchPackError('contents', `the pack has no ${MANIFEST_FILE}`);
const manifest = parseManifest(strFromU8(manifestBytes));
const files: PatchPackFile[] = [];
for (const [path, content] of Object.entries(entries)) {
if (path === MANIFEST_FILE || path.endsWith('/')) continue;
files.push({ path, content });
}
const contents = { manifest, files };
checkContents(contents);
return contents;
}
function checkContents(contents: PatchPackContents): void {
const seen = new Set<string>();
for (const file of contents.files) {
if (!isAllowedPath(file.path)) throw new PatchPackError('contents', `file not allowed in a pack: ${file.path}`);
const key = file.path.toLowerCase();
if (seen.has(key)) throw new PatchPackError('contents', `file listed twice: ${file.path}`);
seen.add(key);
}
const recorded = packGameVersions(contents.files);
const listed = [...contents.manifest.gameVersions].sort();
if (recorded.join() !== listed.join()) {
throw new PatchPackError('contents', `game_versions (${listed.join(', ')}) does not match the version records (${recorded.join(', ')})`);
}
}
function isAllowedPath(path: string): boolean {
if (!ENTRY_PATH.test(path)) return false;
return path.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..');
}
@@ -0,0 +1,22 @@
/** Why an adaptation pack cannot be built, read or used. */
export type PatchPackProblem =
/** tuning/patch-pack.jsonc is invalid. */
| 'tuning'
/** No signing key, or a key of the wrong kind. */
| 'key'
/** The signature does not match the pack. */
| 'signature'
/** The zip, its manifest or a file in it is malformed or not allowed. */
| 'contents'
/** The pack is larger than the limits allow. */
| 'size';
export class PatchPackError extends Error {
readonly problem: PatchPackProblem;
constructor(problem: PatchPackProblem, message: string) {
super(message);
this.name = 'PatchPackError';
this.problem = problem;
}
}
@@ -0,0 +1,48 @@
/**
* The adaptation pack settings in packages/patcher/tuning/patch-pack.jsonc.
*/
import { readFileSync } from 'node:fs';
import { parseJsonc } from '@wto/jsonc';
import { PatchPackError } from './patch-pack-error.ts';
export interface PatchPackTuning {
/** `owner/repo` on GitHub. */
readonly repository: string;
readonly releasesPerCheck: number;
readonly maxPackBytes: number;
readonly maxUnpackedBytes: number;
readonly requestTimeoutMs: number;
}
const TUNING_FILE = new URL('../../tuning/patch-pack.jsonc', import.meta.url);
let cached: PatchPackTuning | null = null;
export function patchPackTuning(): PatchPackTuning {
if (cached) return cached;
const value = parseJsonc(readFileSync(TUNING_FILE, 'utf8'));
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw tuningError('the file is not an object');
const fields = value as Record<string, unknown>;
const repository = fields['repository'];
if (typeof repository !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repository)) {
throw tuningError('"repository" must be "owner/repo"');
}
cached = {
repository,
releasesPerCheck: positiveInteger(fields, 'releases_per_check'),
maxPackBytes: positiveInteger(fields, 'max_pack_bytes'),
maxUnpackedBytes: positiveInteger(fields, 'max_unpacked_bytes'),
requestTimeoutMs: positiveInteger(fields, 'request_timeout_ms'),
};
return cached;
}
function positiveInteger(fields: Record<string, unknown>, key: string): number {
const value = fields[key];
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) throw tuningError(`"${key}" must be a positive integer`);
return value;
}
function tuningError(detail: string): PatchPackError {
return new PatchPackError('tuning', `tuning/patch-pack.jsonc: ${detail}`);
}
@@ -0,0 +1,56 @@
/**
* Ed25519 signatures of adaptation packs.
*
* 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
* key is committed at packages/patcher/keys/patch-pack-signing.pub.pem; the launcher accepts a
* downloaded pack only when its signature verifies against it. The signature covers the zip bytes
* as downloaded, and the `.sig` file holds it in base64.
*/
import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify, type KeyObject } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { PatchPackError } from './patch-pack-error.ts';
export const SIGNING_PUBLIC_KEY_FILE = fileURLToPath(new URL('../../keys/patch-pack-signing.pub.pem', import.meta.url));
export interface SigningKeyPair {
readonly publicKeyPem: string;
readonly privateKeyPem: string;
}
export function generateSigningKeys(): SigningKeyPair {
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
return {
publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }).toString(),
privateKeyPem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
};
}
/** The committed public key, or null when no key has been generated yet. */
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 {
const key = ed25519Key(() => createPrivateKey(privateKeyPem), 'private');
return `${sign(null, zip, key).toString('base64')}\n`;
}
export function verifyPatchPack(zip: 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);
}
function ed25519Key(read: () => KeyObject, kind: 'private' | 'public'): KeyObject {
let key: KeyObject;
try {
key = read();
} catch (error) {
throw new PatchPackError('key', `the ${kind} signing key is not readable: ${(error as Error).message}`);
}
if (key.asymmetricKeyType !== 'ed25519') throw new PatchPackError('key', `the ${kind} signing key is not an Ed25519 key`);
return key;
}
+14
View File
@@ -0,0 +1,14 @@
// Adaptation packs (packages/patcher/src/patch-pack/): where the launcher looks for them and the
// limits it applies to what it downloads.
{
// GitHub repository whose Releases carry the packs (tags `patches-<version>`).
"repository": "N0VAN0M4LY/WT-Offline",
// How many of the newest releases one check reads; packs are found among them.
"releases_per_check": 30,
// Largest pack (zip) the launcher downloads, and the most its files may add up to unpacked.
// The whole patch set is about 0.2 MB today.
"max_pack_bytes": 16777216,
"max_unpacked_bytes": 67108864,
// A request to GitHub that takes longer is given up.
"request_timeout_ms": 20000
}