fix(updates): scan release channels across pages

Share a bounded release scan across channels and compare tag versions across pages. Report uncertainty when the scan hits its limit without confirming a newer release.

Verified with local release responses covering cross-page versions, truncation, and missing feeds.
This commit is contained in:
N0VAN0M4LY committed 2026-11-30 15:23:18 +08:00
1 parent 5a78b1fdf8
commit 31f4fedafe
11 files changed
+173 -101

No files matched your search

@@ -8,35 +8,18 @@ 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,
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 { FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type LauncherRelease } 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 release: LauncherRelease;
readonly manifest: LauncherReleaseManifest;
}
@@ -48,25 +31,6 @@ 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');
@@ -112,10 +76,9 @@ export function checkAppUpdate(): Promise<AppUpdateCheck> {
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 installedVersion = app.getVersion();
const latest = await newestProjectRelease('launcher', installedVersion);
if (!latest || compareAppVersions(latest.version, installedVersion) <= 0) return { status: 'current' };
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
const [bytes, signature] = await Promise.all([
@@ -132,6 +95,7 @@ export function checkAppUpdate(): Promise<AppUpdateCheck> {
return offerResult(offered, await matchesInstaller(stagedInstaller(), manifest));
} catch (error) {
console.warn('[app-update] checking the release failed:', error);
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
if (error instanceof ManifestSignatureError) return { status: 'failed', problem: 'signature' };
if (error instanceof FeedUnreachableError || (error instanceof Error && error.name === 'TimeoutError')) {
return { status: 'failed', problem: 'network' };
@@ -23,7 +23,7 @@ import {
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';
import { downloadReleaseFile, FeedUnreachableError, newestProjectRelease, ReleasePageLimitError, type PackReleaseFiles } from './release-feed.ts';
/** The manifest copy beside a release is a few hundred bytes. */
const MANIFEST_COPY_MAX_BYTES = 64 * 1024;
@@ -41,7 +41,7 @@ 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();
const found = await newestRelease(active.version);
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 };
@@ -55,7 +55,7 @@ export async function checkPackUpdate(): Promise<PackCheck> {
export async function applyPackUpdate(): Promise<PackApplyResult> {
if (!packSigningPublicKey()) return { ok: false, problem: 'no_signing_key' };
try {
const found = await newestRelease();
const found = await newestRelease(activePatchSet().version);
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();
@@ -81,8 +81,8 @@ interface FoundRelease {
readonly manifest: PatchPackManifest;
}
async function newestRelease(): Promise<FoundRelease | null> {
const files = await newestPackRelease();
async function newestRelease(installedVersion: string | null): Promise<FoundRelease | null> {
const files = await newestProjectRelease('pack', installedVersion);
if (!files) return null;
const text = new TextDecoder().decode(await downloadReleaseFile(files.manifestUrl, MANIFEST_COPY_MAX_BYTES));
const manifest = parseManifest(text);
@@ -116,6 +116,7 @@ function bundledVersion(root: string): string | null {
}
function problemOf(error: unknown): PackProblem {
if (error instanceof ReleasePageLimitError) return 'page_limit';
if (error instanceof FeedUnreachableError) return 'network';
if (error instanceof PatchPackError) {
if (error.problem === 'signature') return 'signature';
@@ -1,12 +1,21 @@
/**
* 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.
* The launcher and adaptation pack channels share GitHub's public Releases list.
* Requests send no account, no cookie and nothing about the player.
*/
import { net } from 'electron';
import { comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning } from '@wto/patcher';
import {
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
} from '@wto/patcher';
import { z } from 'zod';
import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts';
export interface LauncherRelease {
readonly version: string;
readonly notes: string;
readonly installer: URL;
readonly manifest: URL;
readonly signature: URL;
}
export interface PackReleaseFiles {
readonly version: string;
@@ -16,44 +25,132 @@ export interface PackReleaseFiles {
readonly manifestUrl: string;
}
interface ReleaseCandidates {
launcher: LauncherRelease | null;
pack: PackReleaseFiles | null;
}
type ReleaseChannel = keyof ReleaseCandidates;
interface ReleaseListing {
readonly candidates: ReleaseCandidates;
readonly incomplete: Readonly<Partial<Record<ReleaseChannel, string>>>;
readonly pageLimit: number | null;
}
/** Thrown when GitHub cannot be reached or answers with an error. */
export class FeedUnreachableError extends Error {
override readonly name = 'FeedUnreachableError';
}
/** Thrown when the list ends at the configured page limit without finding a newer release. */
export class ReleasePageLimitError extends Error {
override readonly name = 'ReleasePageLimitError';
}
const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'WTOffline-Launcher', 'X-GitHub-Api-Version': '2022-11-28' };
const LauncherReleaseEntry = z.object({
draft: z.literal(false),
prerelease: z.literal(false),
assets: z.array(z.object({ name: z.string() })),
body: z.string().nullable().optional(),
});
let listing: Promise<readonly unknown[]> | null = null;
let listing: Promise<ReleaseListing> | 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; });
/** Share the in-flight scan when the launcher checks both release channels at startup. */
export async function newestProjectRelease<Channel extends ReleaseChannel>(
channel: Channel, installedVersion: string | null,
): Promise<ReleaseCandidates[Channel]> {
listing ??= readProjectReleases().finally(() => { listing = null; });
const { candidates, incomplete, pageLimit } = await listing;
const candidate = candidates[channel];
const compare = channel === 'launcher' ? compareAppVersions : comparePackVersions;
if (candidate && (installedVersion === null || compare(candidate.version, installedVersion) > 0)) return candidate;
if (pageLimit !== null) {
throw new ReleasePageLimitError(`No newer ${channel} release was confirmed within ${pageLimit} pages.`);
}
const partial = incomplete[channel];
if (partial && (!candidate || installedVersion === null || compare(partial, installedVersion) > 0)) {
throw new PatchPackError('contents', `Release ${partial} for the ${channel} channel is missing required files.`);
}
return candidate;
}
async function readProjectReleases(): Promise<readonly unknown[]> {
async function readProjectReleases(): Promise<ReleaseListing> {
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 [];
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 candidates: ReleaseCandidates = { launcher: null, pack: null };
const incomplete: Partial<Record<ReleaseChannel, string>> = {};
const url = `https://api.github.com/repos/${tuning.repository}/releases?per_page=${tuning.releasePageSize}`;
for (let page = 1; page <= tuning.maxReleasePages; page += 1) {
const response = await request(`${url}&page=${page}`, HEADERS, tuning.requestTimeoutMs);
if (!response.ok) throw new FeedUnreachableError(`GitHub answered HTTP ${response.status} for release page ${page}`);
const releases: unknown = await response.json();
if (!Array.isArray(releases)) throw new PatchPackError('contents', 'the release list is not a list');
collectReleases(releases, candidates, incomplete, tuning.repository);
const hasNextPage = /;\s*rel="next"\s*(?:,|$)/i.test(response.headers.get('link') ?? '');
// GitHub does not sort release pages by tag version.
if (!hasNextPage) {
return { candidates, incomplete, pageLimit: null };
}
}
console.info(`[release-feed] More releases exist after the configured limit of ${tuning.maxReleasePages} pages.`);
return { candidates, incomplete, pageLimit: tuning.maxReleasePages };
}
/** 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;
function collectReleases(
entries: readonly unknown[], candidates: ReleaseCandidates, incomplete: Partial<Record<ReleaseChannel, string>>, repository: string,
): void {
for (const entry of entries) {
if (typeof entry !== 'object' || entry === null) continue;
const release = entry as Record<string, unknown>;
const tag = release['tag_name'];
if (typeof tag !== 'string' || release['draft'] === true || release['prerelease'] === true) continue;
if (tag.startsWith('v')) {
const version = AppReleaseVersionSchema.safeParse(tag.slice(1));
if (!version.success) continue;
const launcher = launcherRelease(release, version.data, repository);
if (!launcher) {
const missing = incomplete.launcher;
if (!missing || compareAppVersions(version.data, missing) > 0) incomplete.launcher = version.data;
} else if (!candidates.launcher || compareAppVersions(launcher.version, candidates.launcher.version) > 0) {
candidates.launcher = launcher;
}
continue;
}
const version = packVersionOfTag(tag);
if (!version) continue;
const pack = packRelease(release, version);
if (!pack) {
const missing = incomplete.pack;
if (!missing || comparePackVersions(version, missing) > 0) incomplete.pack = version;
} else if (!candidates.pack || comparePackVersions(pack.version, candidates.pack.version) > 0) {
candidates.pack = pack;
}
}
}
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;
function launcherRelease(entry: Record<string, unknown>, version: string, repository: string): LauncherRelease | null {
const parsed = LauncherReleaseEntry.safeParse(entry);
if (!parsed.success) return null;
const { assets, body } = parsed.data;
const names = launcherReleaseFiles(version);
const present = new Set(assets.map(({ name }) => name));
if (!Object.values(names).every((name) => present.has(name))) return null;
const directory = `https://github.com/${repository}/releases/download/v${version}/`;
return {
version,
notes: body?.trim().slice(0, 1600) ?? '',
installer: new URL(names.installer, directory),
manifest: new URL(names.manifest, directory),
signature: new URL(names.signature, directory),
};
}
function packRelease(release: Record<string, unknown>, version: string): PackReleaseFiles | null {
if (!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;
@@ -552,6 +552,7 @@
"checkFailed": {
"no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.",
"network": "GitHub could not be reached. Try again later.",
"page_limit": "Could not confirm whether a newer adaptation pack is available.",
"contents": "The released adaptation pack is incomplete or malformed.",
"signature": "The adaptation pack's signature is wrong. It was refused.",
"size": "The adaptation pack is larger than allowed. It was refused."
@@ -559,6 +560,7 @@
"applyFailed": {
"no_signing_key": "This launcher has no signing key built in, so it accepts no adaptation pack.",
"network": "The download failed: GitHub could not be reached. Try again later.",
"page_limit": "Could not confirm whether a newer adaptation pack is available.",
"contents": "The adaptation pack is incomplete or malformed. It is not in use.",
"signature": "The adaptation pack's signature is wrong. It was refused and is not in use.",
"size": "The adaptation pack is larger than allowed. It was refused.",
@@ -578,6 +580,7 @@
"installing": "Opening the installer…",
"errors": {
"network": "GitHub Releases could not be reached.",
"page_limit": "Could not confirm whether a newer version is available.",
"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."
@@ -552,6 +552,7 @@
"checkFailed": {
"no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。",
"network": "连不上 GitHub,请稍后再试。",
"page_limit": "无法确认是否有新的适配包。",
"contents": "发布的适配包信息不完整或格式不对。",
"signature": "适配包的签名不对,已拒绝。",
"size": "适配包超出大小上限,已拒绝。"
@@ -559,6 +560,7 @@
"applyFailed": {
"no_signing_key": "这个启动器没有内置签名公钥,不接受适配包。",
"network": "下载失败:连不上 GitHub,请稍后再试。",
"page_limit": "无法确认是否有新的适配包。",
"contents": "适配包内容不完整或格式不对,没有启用。",
"signature": "适配包的签名不对,已拒绝,没有启用。",
"size": "适配包超出大小上限,已拒绝。",
@@ -578,6 +580,7 @@
"installing": "正在打开安装包…",
"errors": {
"network": "暂时无法访问 GitHub 发布页。",
"page_limit": "无法确认是否有新版本。",
"contents": "本体更新的发布信息无效。",
"signature": "本体更新签名校验失败。",
"no_signing_key": "本体更新公钥不可用。"
@@ -24,7 +24,7 @@ const AppUpdateReleaseSchema = z.object({
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
notes: z.string(),
});
const AppUpdateProblemSchema = z.enum(['network', 'contents', 'signature', 'no_signing_key']);
const AppUpdateProblemSchema = z.enum(['network', 'contents', 'signature', 'no_signing_key', 'page_limit']);
export const AppUpdateCheckSchema = z.discriminatedUnion('status', [
z.object({ status: z.literal('current') }),
@@ -39,6 +39,8 @@ export const PackProblemSchema = z.enum([
'no_signing_key',
/** GitHub could not be reached or answered with an error. */
'network',
/** The scan reached the page limit before confirming a newer pack release. */
'page_limit',
/** The release or the pack is malformed. */
'contents',
/** The signature does not match. */
@@ -1,6 +1,6 @@
/** Why an adaptation pack cannot be built, read or used. */
export type PatchPackProblem =
/** tuning/patch-pack.jsonc is invalid. */
/** tuning/release-channels.jsonc is invalid. */
| 'tuning'
/** No signing key, or a key of the wrong kind. */
| 'key'
@@ -1,6 +1,4 @@
/**
* The adaptation pack settings in packages/patcher/tuning/patch-pack.jsonc.
*/
/** Settings shared by the launcher and adaptation pack release checks. */
import { readFileSync } from 'node:fs';
import { parseJsonc } from '@wto/jsonc';
import { PatchPackError } from './patch-pack-error.ts';
@@ -8,13 +6,14 @@ import { PatchPackError } from './patch-pack-error.ts';
export interface PatchPackTuning {
/** `owner/repo` on GitHub. */
readonly repository: string;
readonly releasesPerCheck: number;
readonly releasePageSize: number;
readonly maxReleasePages: number;
readonly maxPackBytes: number;
readonly maxUnpackedBytes: number;
readonly requestTimeoutMs: number;
}
const TUNING_FILE = new URL('../../tuning/patch-pack.jsonc', import.meta.url);
const TUNING_FILE = new URL('../../tuning/release-channels.jsonc', import.meta.url);
let cached: PatchPackTuning | null = null;
@@ -27,9 +26,12 @@ export function patchPackTuning(): PatchPackTuning {
if (typeof repository !== 'string' || !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repository)) {
throw tuningError('"repository" must be "owner/repo"');
}
const releasePageSize = positiveInteger(fields, 'release_page_size');
if (releasePageSize > 100) throw tuningError('"release_page_size" must be at most 100');
cached = {
repository,
releasesPerCheck: positiveInteger(fields, 'releases_per_check'),
releasePageSize,
maxReleasePages: positiveInteger(fields, 'max_release_pages'),
maxPackBytes: positiveInteger(fields, 'max_pack_bytes'),
maxUnpackedBytes: positiveInteger(fields, 'max_unpacked_bytes'),
requestTimeoutMs: positiveInteger(fields, 'request_timeout_ms'),
@@ -39,10 +41,10 @@ export function patchPackTuning(): PatchPackTuning {
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`);
if (typeof value !== 'number' || !Number.isSafeInteger(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}`);
return new PatchPackError('tuning', `tuning/release-channels.jsonc: ${detail}`);
}
-14
View File
@@ -1,14 +0,0 @@
// 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
}
@@ -0,0 +1,14 @@
// GitHub release checks for the launcher and adaptation packs, including the pack size limits.
{
// Both channels share this repository. Launcher tags use `v<version>` and pack tags use `patches-<version>`.
"repository": "N0VAN0M4LY/WT-Offline",
// Entries per request (GitHub allows up to 100) and pages per shared check.
"release_page_size": 30,
"max_release_pages": 5,
// 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
}