Files
WT-Offline/apps/launcher/src/main/services/map-nav/map-nav-update.ts
T

146 lines
6.5 KiB
TypeScript

import { lstat, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { app } from 'electron';
import {
comparePackVersions, packSigningPublicKey, PatchPackError, patchPackTuning, verifyEd25519,
} from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { AppUpdateProgress } from '@shared/schemas/app-update.ts';
import {
MapNavReleaseManifestSchema, mapNavSignaturePayload, type ActiveMapNav, type MapNavApplyResult,
type MapNavCheck, type MapNavReleaseManifest,
} from '@shared/schemas/map-nav-pack.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { packUpdateProblem } from '../patch-pack/pack-update.ts';
import {
readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset,
} from '../patch-pack/release-assets.ts';
import {
newestProjectRelease, projectReleaseVersion, withReleaseSources, type PackReleaseFiles,
} from '../patch-pack/release-feed.ts';
import { extractMapNavArchive, verifyMapNavFolder } from './map-nav-archive.ts';
import {
activateMapNavPack, deactivateMapNavPack, mapNavStoreFolder, needsMapNavLauncherUpdate, selectedMapNavPack,
} from './map-nav-store.ts';
let updating = false;
async function duringMapNavUpdate<T>(update: () => Promise<T>): Promise<T> {
if (updating) throw new AppError('map_nav_update_busy');
updating = true;
try {
return await update();
} finally {
updating = false;
}
}
export async function activeMapNav(): Promise<ActiveMapNav> {
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const useLab = !app.isPackaged && settings.developerMode;
const dataPath = (useLab ? settings.labDataPath : null) ?? record?.dataPath ?? null;
return selectedMapNavPack(dataPath)?.info ?? null;
}
function isNewer(version: string, active: ActiveMapNav): boolean {
return !active?.version || comparePackVersions(version, active.version) > 0;
}
async function signedManifest(files: PackReleaseFiles, key: string): Promise<MapNavReleaseManifest> {
const signal = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
const [bytes, signature] = await Promise.all([
readReleaseAsset(files.manifestUrl, RELEASE_MANIFEST_MAX_BYTES, signal, files.source),
readReleaseAsset(files.signatureUrl, RELEASE_SIGNATURE_MAX_BYTES, signal, files.source),
]);
const decoder = new TextDecoder('utf-8', { fatal: true });
if (!verifyEd25519(mapNavSignaturePayload(bytes), decoder.decode(signature), key)) {
throw new PatchPackError('signature', 'The map pack manifest signature does not match.');
}
const manifest = MapNavReleaseManifestSchema.parse(JSON.parse(decoder.decode(bytes)));
if (manifest.version !== files.version) throw new PatchPackError('contents', 'The signed map pack version does not match the release.');
return manifest;
}
export async function checkMapNavUpdate(): Promise<MapNavCheck> {
const active = await activeMapNav();
const key = packSigningPublicKey();
if (!key) return { status: 'failed', active, latest: null, problem: 'no_signing_key' };
try {
const offer = await withReleaseSources(async (source) => {
const files = await newestProjectRelease('mapNav', active?.version ?? null, source);
return files ? { files, manifest: await signedManifest(files, key) } : null;
});
if (!offer) return { status: 'up_to_date', active, latest: null, problem: null };
const { files, manifest } = offer;
const latest = {
version: manifest.version, gameVersions: manifest.gameVersions, minAppVersion: manifest.minAppVersion,
publishedAt: files.publishedAt, mapCount: manifest.maps.length, size: manifest.archive.size,
};
const status = !isNewer(manifest.version, active) ? 'up_to_date'
: needsMapNavLauncherUpdate(manifest) ? 'needs_app_update' : 'available';
return { status, active, latest, problem: null };
} catch (error) {
console.warn('[map-nav] update check failed:', error);
return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) };
}
}
async function installMapNav(
files: PackReleaseFiles, manifest: MapNavReleaseManifest, report: (progress: AppUpdateProgress) => void,
): Promise<void> {
const root = mapNavStoreFolder();
const installed = join(root, manifest.version);
const existing = await lstat(installed).catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
return null;
});
if (existing) {
if (!existing.isDirectory()) throw new PatchPackError('contents', 'The destination for this map pack is not a directory.');
await verifyMapNavFolder(installed, manifest);
await activateMapNavPack(manifest.version);
return;
}
await mkdir(root, { recursive: true });
const staging = await mkdtemp(join(await realpath(root), '.map-nav-install-'));
try {
const zip = join(staging, 'maps.zip');
await stageReleaseAsset(files.zipUrl, files.source, manifest.archive, zip, report);
const folder = await extractMapNavArchive(zip, staging, manifest);
await activateMapNavPack(manifest.version, folder);
} finally {
await rm(staging, { recursive: true, force: true }).catch((error: unknown) =>
console.warn('[map-nav] could not remove the installation staging directory:', error));
}
}
export function applyMapNavUpdate(version: string, report: (progress: AppUpdateProgress) => void): Promise<MapNavApplyResult> {
return duringMapNavUpdate(async () => {
const key = packSigningPublicKey();
if (!key) return { ok: false, problem: 'no_signing_key' };
if (!isNewer(version, await activeMapNav())) return { ok: false, problem: 'up_to_date' };
try {
const installed = await withReleaseSources(async (source) => {
const files = await projectReleaseVersion('mapNav', version, source);
const manifest = await signedManifest(files, key);
if (needsMapNavLauncherUpdate(manifest)) return false;
await installMapNav(files, manifest, report);
return true;
});
if (!installed) return { ok: false, problem: 'needs_app_update' };
return { ok: true, active: await activeMapNav() };
} catch (error) {
console.warn('[map-nav] update failed:', error);
return { ok: false, problem: packUpdateProblem(error) };
}
});
}
export function useLocalMapNav(): Promise<ActiveMapNav> {
return duringMapNavUpdate(async () => {
await deactivateMapNavPack();
return activeMapNav();
});
}