feat(patch-pack): publish signed adaptation packs and install them locally

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 597df6b4f5
commit f5c5377d44
18 files changed
+1097 -2

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
# Release an adaptation pack (packages/patcher/src/patch-pack/): pack and sign patches/ and publish
# it as a GitHub release tagged patches-<version>, where the launcher looks for it.
#
# Start it either way:
# - push a tag: git tag patches-2026.11.29 && git push origin patches-2026.11.29
# - from the Actions page (Run workflow), giving the version; the tag is created on the chosen
# branch's latest commit.
# The signing key comes from the repository secret PATCH_SIGNING_KEY
# (scripts/generate-patch-signing-key.ts).
name: Adaptation pack
on:
push:
tags: ['patches-*']
workflow_dispatch:
inputs:
version:
description: 'Pack version, YYYY.MM.DD or YYYY.MM.DD.N'
required: true
type: string
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
env:
# Packing needs no Electron binary.
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || '' }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci
- name: Pack and sign
env:
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
run: |
if [ -n "$VERSION" ]; then
node scripts/build-patch-pack.ts --version "$VERSION" --out dist
else
# The version comes from the pushed tag (GITHUB_REF_NAME).
node scripts/build-patch-pack.ts --out dist
fi
- name: Publish the release
env:
GH_TOKEN: ${{ github.token }}
run: |
manifest=$(ls dist/*.manifest.json)
field() { node -e "const m=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=m[process.argv[2]];process.stdout.write(Array.isArray(v)?v.join(', '):String(v))" "$manifest" "$1"; }
version=$(field version)
printf 'Adaptation pack %s.\n\nChecked game versions: %s\nNeeds offline version %s or newer.\n' \
"$version" "$(field game_versions)" "$(field min_app_version)" > dist/notes.md
gh release create "patches-$version" \
"dist/wtoffline-patches-$version.zip" \
"dist/wtoffline-patches-$version.zip.sig" \
"dist/wtoffline-patches-$version.manifest.json" \
--title "Adaptation pack $version" \
--notes-file dist/notes.md \
--target "$GITHUB_SHA"
@@ -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' };
+3 -1
View File
@@ -5,6 +5,7 @@
"packages": {
"": {
"name": "wto",
"license": "AGPL-3.0-or-later",
"workspaces": [
"apps/*",
"packages/*"
@@ -2743,7 +2744,8 @@
"@wto/blk": "*",
"@wto/exepatch": "*",
"@wto/jsonc": "*",
"@wto/vromfs": "*"
"@wto/vromfs": "*",
"fflate": "^0.8.2"
}
},
"packages/vromfs": {
+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
}
+131
View File
@@ -0,0 +1,131 @@
/**
* Build and sign an adaptation pack from this repository's patches/ (packages/patcher/src/patch-pack/).
*
* node scripts/build-patch-pack.ts --version <YYYY.MM.DD[.N]> [--out <folder>] [--min-app-version <x.y.z>] [--unsigned]
*
* The private key comes from the environment variable PATCH_SIGNING_KEY (PEM text), as the release
* workflow .github/workflows/patch-pack.yml passes it from the GitHub secret of the same name.
* --unsigned writes the zip without a signature, for a look at the contents only: the launcher
* refuses an unsigned pack. In GitHub Actions --version defaults to the pushed tag
* (`patches-<version>`).
*
* Only committed files go into a pack: the script refuses when patches/ has uncommitted changes or
* untracked files, so a version record is released only after it was committed (it is committed
* once the build was played in the game, docs/architecture.md 5.2). --min-app-version defaults to
* the launcher version in apps/launcher/package.json, the oldest launcher whose patch engine is
* known to read this pack.
*
* Writes <out>/wtoffline-patches-<version>.zip, the .zip.sig and the .manifest.json next to it.
*/
import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import {
checkPatchSet,
formatManifest,
isPackVersion,
packFileNames,
packGameVersions,
packSigningPublicKey,
packVersionOfTag,
PATCH_PACK_FORMAT,
signPatchPack,
verifyPatchPack,
writePatchPack,
type PatchPackFile,
type PatchPackManifest,
} from '@wto/patcher';
const REPOSITORY = fileURLToPath(new URL('..', import.meta.url));
const PATCHES = join(REPOSITORY, 'patches');
const PACKED_FOLDERS = ['patches/exe', 'patches/gui', 'patches/native', 'patches/versions'];
const USAGE = 'usage: build-patch-pack.ts --version <YYYY.MM.DD[.N]> [--out <folder>] [--min-app-version <x.y.z>] [--unsigned]';
function main(): number {
const { values } = parseArgs({
options: {
version: { type: 'string' },
out: { type: 'string', default: join(REPOSITORY, 'build', 'patch-packs') },
'min-app-version': { type: 'string' },
unsigned: { type: 'boolean', default: false },
},
});
const version = values.version ?? tagVersion();
if (!version || !isPackVersion(version)) {
console.error(version ? `not a pack version: ${version}` : USAGE);
return 2;
}
const privateKey = process.env['PATCH_SIGNING_KEY'];
if (!values.unsigned && !privateKey) {
console.error('PATCH_SIGNING_KEY is not set; pass --unsigned for a pack to look at only');
return 2;
}
const uncommitted = git(['status', '--porcelain', '--untracked-files=all', '--', ...PACKED_FOLDERS]).trim();
if (uncommitted) {
console.error(`patches/ has uncommitted changes; commit them first:\n${uncommitted}`);
return 1;
}
const summary = checkPatchSet(PATCHES);
const files = committedFiles();
const manifest: PatchPackManifest = {
format: PATCH_PACK_FORMAT,
version,
minAppVersion: values['min-app-version'] ?? launcherVersion(),
gameVersions: packGameVersions(files),
createdAt: new Date().toISOString(),
};
const zip = writePatchPack({ manifest, files });
const names = packFileNames(version);
mkdirSync(values.out, { recursive: true });
writeFileSync(join(values.out, names.zip), zip);
writeFileSync(join(values.out, names.manifest), formatManifest(manifest));
if (privateKey && !values.unsigned) {
const signature = signPatchPack(zip, privateKey);
const publicKey = packSigningPublicKey();
if (!publicKey) {
console.error('no committed public key (packages/patcher/keys/); run scripts/generate-patch-signing-key.ts first');
return 1;
}
if (!verifyPatchPack(zip, signature, publicKey)) {
console.error('the signature does not verify against the committed public key: PATCH_SIGNING_KEY is not its private key');
return 1;
}
writeFileSync(join(values.out, names.signature), signature);
}
console.log(`pack ${version} (format ${manifest.format}, launcher ${manifest.minAppVersion} or newer)`);
console.log(` ${summary.exePatches} exe patch(es), ${summary.guiPatches} GUI patch(es), ${summary.nativeModules} native module(s)`);
console.log(` game versions: ${manifest.gameVersions.join(', ') || 'none'}`);
console.log(` ${files.length} file(s), ${zip.length} bytes zipped${values.unsigned ? ', NOT signed' : ', signed'}`);
console.log(`wrote ${join(values.out, names.zip)}`);
return 0;
}
/** In GitHub Actions, the version of the pushed `patches-*` tag. */
function tagVersion(): string | undefined {
const ref = process.env['GITHUB_REF_NAME'];
return ref ? (packVersionOfTag(ref) ?? undefined) : undefined;
}
function committedFiles(): PatchPackFile[] {
return git(['ls-files', '-z', '--', ...PACKED_FOLDERS])
.split('\0')
.filter((path) => path.length > 0)
.map((path) => ({ path: path.slice('patches/'.length), content: readFileSync(join(REPOSITORY, path)) }));
}
function launcherVersion(): string {
const manifest = JSON.parse(readFileSync(join(REPOSITORY, 'apps', 'launcher', 'package.json'), 'utf8')) as { version?: unknown };
if (typeof manifest.version !== 'string') throw new Error('apps/launcher/package.json has no version');
return manifest.version;
}
function git(args: readonly string[]): string {
return execFileSync('git', args, { cwd: REPOSITORY, encoding: 'utf8' });
}
process.exitCode = main();
+63
View File
@@ -0,0 +1,63 @@
/**
* One-time developer script: create the Ed25519 key pair that signs adaptation packs
* (packages/patcher/src/patch-pack/signature.ts).
*
* node scripts/generate-patch-signing-key.ts --private-out <file outside the repository> [--replace]
*
* The public key is written to packages/patcher/keys/patch-pack-signing.pub.pem, to be committed;
* launchers built from then on accept only packs signed by the matching private key. The private
* key is written to --private-out, which must lie outside the repository. Put its contents into
* the GitHub secret PATCH_SIGNING_KEY, keep a backup (for example in a password manager), then
* delete the file. Replacing an existing key (--replace) makes every launcher released before
* the change refuse packs signed with the new key.
*/
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { generateSigningKeys, SIGNING_PUBLIC_KEY_FILE } from '@wto/patcher';
const REPOSITORY = fileURLToPath(new URL('..', import.meta.url));
const USAGE = 'usage: generate-patch-signing-key.ts --private-out <file outside the repository> [--replace]';
function main(): number {
const { values } = parseArgs({ options: { 'private-out': { type: 'string' }, replace: { type: 'boolean', default: false } } });
const privateOut = values['private-out'];
if (!privateOut) {
console.error(USAGE);
return 2;
}
const privatePath = resolve(privateOut);
// On another drive `relative` gives an absolute path.
const fromRepository = relative(REPOSITORY, privatePath);
if (!fromRepository.startsWith('..') && !isAbsolute(fromRepository)) {
console.error(`refusing to write the private key inside the repository: ${privatePath}`);
return 2;
}
if (existsSync(privatePath)) {
console.error(`refusing to overwrite ${privatePath}`);
return 2;
}
if (existsSync(SIGNING_PUBLIC_KEY_FILE) && !values.replace) {
console.error(`a public key already exists at ${SIGNING_PUBLIC_KEY_FILE}; pass --replace to make a new pair`);
return 2;
}
const keys = generateSigningKeys();
mkdirSync(dirname(privatePath), { recursive: true });
writeFileSync(privatePath, keys.privateKeyPem, { mode: 0o600, flag: 'wx' });
mkdirSync(dirname(SIGNING_PUBLIC_KEY_FILE), { recursive: true });
writeFileSync(SIGNING_PUBLIC_KEY_FILE, keys.publicKeyPem);
console.log(`public key: ${SIGNING_PUBLIC_KEY_FILE} (commit this file)`);
console.log(`private key: ${privatePath}`);
console.log('');
console.log('Next:');
console.log(' 1. GitHub repository > Settings > Secrets and variables > Actions > New repository secret,');
console.log(' name PATCH_SIGNING_KEY, value: the whole contents of the private key file.');
console.log(' 2. Keep a backup of the private key outside this computer (for example a password manager).');
console.log(' 3. Delete the private key file.');
return 0;
}
process.exitCode = main();