From 036a479aabb2cf7f45f151b954c8b380836331ea Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 6 Dec 2026 19:53:45 +0800 Subject: [PATCH] feat(launcher): add map adaptation pack updates --- apps/launcher/src/main/ipc/handlers.ts | 6 + .../main/services/app-update/app-update.ts | 53 +------ .../main/services/launch/launch-controller.ts | 3 + .../main/services/map-nav/map-nav-archive.ts | 65 ++++++++ .../main/services/map-nav/map-nav-store.ts | 89 +++++++++++ .../main/services/map-nav/map-nav-update.ts | 145 ++++++++++++++++++ .../main/services/patch-pack/pack-update.ts | 6 +- .../services/patch-pack/release-assets.ts | 54 ++++++- .../main/services/patch-pack/release-feed.ts | 23 ++- .../src/main/workers/build-protocol.ts | 2 +- .../launcher/src/main/workers/build-worker.ts | 8 +- apps/launcher/src/renderer/src/App.tsx | 3 + .../src/renderer/src/i18n/locales/en.json | 25 ++- .../src/renderer/src/i18n/locales/zh-CN.json | 25 ++- .../renderer/src/pages/about/AboutPage.tsx | 6 +- .../src/pages/about/MapNavPackSection.tsx | 66 ++++++++ .../src/renderer/src/shell/useMapNavPack.ts | 78 ++++++++++ apps/launcher/src/shared/errors.ts | 1 + apps/launcher/src/shared/ipc/channels.ts | 2 + apps/launcher/src/shared/ipc/contract.ts | 18 +++ .../src/shared/schemas/map-nav-pack.ts | 72 +++++++++ scripts/build-windows-installer.ts | 23 +++ scripts/publish-r2-releases.ts | 51 ++++++ tools/navgen/package-maps.mts | 32 ++-- 24 files changed, 770 insertions(+), 86 deletions(-) create mode 100644 apps/launcher/src/main/services/map-nav/map-nav-archive.ts create mode 100644 apps/launcher/src/main/services/map-nav/map-nav-store.ts create mode 100644 apps/launcher/src/main/services/map-nav/map-nav-update.ts create mode 100644 apps/launcher/src/renderer/src/pages/about/MapNavPackSection.tsx create mode 100644 apps/launcher/src/renderer/src/shell/useMapNavPack.ts create mode 100644 apps/launcher/src/shared/schemas/map-nav-pack.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 3e43035..bef02ef 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -16,6 +16,7 @@ import { cancelInstall, checkGameFolder, dataFolderProblem, installGame, install import { canonicalCopyPath, copyFolderMissing, createCopyDraft, hydrateCopiesStatus, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts'; import { readInstalledLab } from '../services/launch/lab-handoff.ts'; import { getLaunchState, launchInProgress, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts'; +import { activeMapNav, applyMapNavUpdate, checkMapNavUpdate, useLocalMapNav } from '../services/map-nav/map-nav-update.ts'; import { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts'; import { applyModPreset, @@ -269,6 +270,11 @@ export function registerIpcHandlers(): void { }); handle('updates:check', () => checkAppUpdate()); + handle('map-nav:active', () => activeMapNav()); + handle('map-nav:check', () => checkMapNavUpdate()); + handle('map-nav:apply', ({ version }) => applyMapNavUpdate(version, (progress) => + broadcast('event:map-nav-progress', progress))); + handle('map-nav:deactivate', () => useLocalMapNav()); handle('updates:download', ({ version }) => downloadAppUpdate(version, (progress) => broadcast('event:app-update-progress', progress))); handle('updates:install', ({ version }) => installAppUpdate(version, () => launchInProgress() || installationInProgress() || maintenanceInProgress() || saveWriteInProgress() || decalImportInProgress())); diff --git a/apps/launcher/src/main/services/app-update/app-update.ts b/apps/launcher/src/main/services/app-update/app-update.ts index 62bc40d..75cac5b 100644 --- a/apps/launcher/src/main/services/app-update/app-update.ts +++ b/apps/launcher/src/main/services/app-update/app-update.ts @@ -1,11 +1,6 @@ import { spawn } from 'node:child_process'; -import { createHash } from 'node:crypto'; import { once } from 'node:events'; -import { createWriteStream } from 'node:fs'; -import { mkdir, rename, unlink } from 'node:fs/promises'; import { dirname, join } from 'node:path'; -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 { AppError } from '@shared/errors.ts'; @@ -19,7 +14,7 @@ import { newestProjectRelease, projectReleaseVersion, ReleasePageLimitError, sameReleaseSource, withReleaseSources, type LauncherRelease, } from '../patch-pack/release-feed.ts'; import { - FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset, + FeedUnreachableError, readReleaseAsset, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, stageReleaseAsset, } from '../patch-pack/release-assets.ts'; import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts'; import { @@ -152,7 +147,7 @@ export function downloadAppUpdate( ? offer.release : await projectReleaseVersion('launcher', version, source); const assetUrl = offer.mode === 'portable' ? release.portable?.archive : release.installer; if (!assetUrl) throw new FeedUnreachableError(`This update source does not have the ${offer.mode} asset for ${version}.`); - await stageArtifact(assetUrl, release.source, offer.manifest, target, report); + await stageReleaseAsset(assetUrl, release.source, offer.manifest, target, report); }, offer.release.source); return offerResult(offer, true); } catch (error) { @@ -162,50 +157,6 @@ export function downloadAppUpdate( }); } -async function stageArtifact( - assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string, - report: (progress: AppUpdateProgress) => void, -): Promise { - const partial = `${target}.partial`; - const deadline = AbortSignal.timeout(30 * 60_000); - let size = 0; - let reportedAt = 0; - const hash = createHash('sha256'); - try { - await mkdir(dirname(target), { recursive: true }); - await unlink(partial).catch((error: NodeJS.ErrnoException) => { - if (error.code !== 'ENOENT') throw error; - }); - const response = await requestReleaseAsset(assetUrl, deadline, source); - const monitor = new Transform({ - transform(chunk: Buffer, _encoding, done) { - size += chunk.length; - if (size > manifest.size) { - done(new Error('The download is larger than the signed release size.')); - return; - } - hash.update(chunk); - if (size === manifest.size || Date.now() - reportedAt >= 200) { - reportedAt = Date.now(); - report({ received: size, total: manifest.size }); - } - done(null, chunk); - }, - }); - await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline }); - if (size !== manifest.size) throw new FeedUnreachableError('The update download is incomplete.'); - if (hash.digest('hex') !== manifest.sha256) throw new Error('The update download does not match the signed release.'); - await rename(partial, target); - } catch (error) { - if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error }); - throw error; - } finally { - await unlink(partial).catch((error: NodeJS.ErrnoException) => { - if (error.code !== 'ENOENT') console.warn('[app-update] removing a partial download failed:', error); - }); - } -} - export function installAppUpdate(version: string, launcherBusy: () => boolean): Promise { return exclusively(async () => { const offer = selectedOffer(version); diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index 4adf9ad..5166c54 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -14,6 +14,7 @@ import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../insta import { findBlockingIncompleteUhqPacks } from '../install/uhq-packages.ts'; import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; +import { selectedMapNavPack } from '../map-nav/map-nav-store.ts'; import { saveBackup } from '../saves/save-archive.ts'; import { buildCopy } from './build-copy.ts'; import { gameProcessRunning } from './game-process.ts'; @@ -222,6 +223,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc signal.throwIfAborted(); update(job, { phase: 'building', port }); const buildStart = Date.now(); + const mapNavFolder = selectedMapNavPack(dataPath)?.folder; let writtenFiles = 0; await buildCopy({ kind: 'build', @@ -231,6 +233,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc port, steamLibraryConfirmed, ...resourcePaths(), + ...(mapNavFolder === undefined ? {} : { mapNavFolder }), ...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}), hookLogging: settings.loggingEnabled, acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), diff --git a/apps/launcher/src/main/services/map-nav/map-nav-archive.ts b/apps/launcher/src/main/services/map-nav/map-nav-archive.ts new file mode 100644 index 0000000..116c3dc --- /dev/null +++ b/apps/launcher/src/main/services/map-nav/map-nav-archive.ts @@ -0,0 +1,65 @@ +import { execFile } from 'node:child_process'; +import { readFile, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; +import { PatchPackError } from '@wto/patcher'; +import { MapNavManifestSchema, type MapNavManifest } from '@shared/schemas/map-nav-pack.ts'; +import { installerDigest } from '../app-update/installer-integrity.ts'; +import { RELEASE_MANIFEST_MAX_BYTES } from '../patch-pack/release-assets.ts'; + +const execute = promisify(execFile); + +/** Compare the exact maps written by the installer with the signed release manifest. */ +export async function verifyMapNavFolder(folder: string, manifest: MapNavManifest): Promise { + const stored = MapNavManifestSchema.parse(JSON.parse(await readFile(join(folder, 'manifest.json'), 'utf8'))); + if (JSON.stringify(stored) !== JSON.stringify(MapNavManifestSchema.parse(manifest))) { + throw new PatchPackError('contents', 'The map pack manifest does not match the signed release.'); + } + for (const entry of manifest.maps) { + const digest = await installerDigest(join(folder, 'maps', entry.level + '.wtonav'), entry.size); + if (digest.size !== entry.size || digest.sha256 !== entry.sha256) { + throw new PatchPackError('contents', 'The map file does not match the signed release: ' + entry.level); + } + } +} + +/** The ZIP is already verified. Extract only the exact file names and sizes the manifest promises. */ +export async function extractMapNavArchive(zip: string, staging: string, manifest: MapNavManifest): Promise { + const folder = join(staging, 'map-nav'); + const index = join(staging, 'expected-maps.json'); + const script = join(staging, 'extract-maps.ps1'); + const expected = manifest.maps.map(({ level, size }) => ({ name: 'map-nav/maps/' + level + '.wtonav', size })); + await writeFile(index, JSON.stringify(expected)); + await writeFile(script, '\uFEFF' + EXTRACTION_SCRIPT.join('\r\n'), 'utf8'); + await execute('powershell.exe', [ + '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, + zip, staging, index, String(RELEASE_MANIFEST_MAX_BYTES), + ], { windowsHide: true, timeout: 180_000 }); + await verifyMapNavFolder(folder, manifest); + return folder; +} + +const EXTRACTION_SCRIPT = [ + 'param([string]$ZipPath, [string]$Root, [string]$IndexPath, [long]$ManifestLimit)', + "$ErrorActionPreference = 'Stop'", + 'Add-Type -AssemblyName System.IO.Compression.FileSystem', + '$expected = [System.Collections.Generic.Dictionary[string,long]]::new([StringComparer]::Ordinal)', + 'foreach ($item in (Get-Content -LiteralPath $IndexPath -Raw -Encoding UTF8 | ConvertFrom-Json)) { $expected.Add($item.name, $item.size) }', + '$seenManifest = $false', + '$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)', + 'try {', + ' [System.IO.Directory]::CreateDirectory((Join-Path $Root "map-nav/maps")) | Out-Null', + ' foreach ($entry in $zip.Entries) {', + ' $name = $entry.FullName', + ' if ($entry.Length -eq 0 -and ($name -ceq "map-nav/" -or $name -ceq "map-nav/maps/")) { continue }', + ' if (!$seenManifest -and $name -ceq "map-nav/manifest.json" -and $entry.Length -le $ManifestLimit) {', + ' $seenManifest = $true', + ' } else {', + ' if (!$expected.ContainsKey($name) -or $entry.Length -ne $expected[$name]) { throw "Unexpected map pack entry: $name" }', + ' [void]$expected.Remove($name)', + ' }', + ' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $Root $name), $false)', + ' }', + ' if (!$seenManifest -or $expected.Count -gt 0) { throw "The map pack is incomplete." }', + '} finally { $zip.Dispose() }', +]; diff --git a/apps/launcher/src/main/services/map-nav/map-nav-store.ts b/apps/launcher/src/main/services/map-nav/map-nav-store.ts new file mode 100644 index 0000000..0a3c5e8 --- /dev/null +++ b/apps/launcher/src/main/services/map-nav/map-nav-store.ts @@ -0,0 +1,89 @@ +import { readFileSync, readdirSync } from 'node:fs'; +import { mkdir, rename, rm } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { app } from 'electron'; +import { compareAppVersions } from '@wto/patcher'; +import { + MAP_NAV_FORMAT, MapNavManifestSchema, MapNavVersionSchema, type ActiveMapNav, type MapNavManifest, +} from '@shared/schemas/map-nav-pack.ts'; +import { writeJsonAtomic } from '../../util/atomic-json.ts'; +import { bundledResourcePaths } from '../resources/resource-paths.ts'; + +interface MapNavPack { + readonly folder: string; + readonly info: NonNullable; +} + +export function mapNavStoreFolder(): string { + return join(app.getPath('userData'), 'map-nav'); +} + +function activeFile(): string { + return join(mapNavStoreFolder(), 'active.json'); +} + +export function needsMapNavLauncherUpdate(manifest: MapNavManifest): boolean { + return manifest.format !== MAP_NAV_FORMAT || compareAppVersions(app.getVersion(), manifest.minAppVersion) < 0; +} + +function readManifest(folder: string): MapNavManifest | null { + try { + return MapNavManifestSchema.parse(JSON.parse(readFileSync(join(dirname(folder), 'manifest.json'), 'utf8'))); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] could not read the pack manifest:', error); + return null; + } +} + +function foundPack(folder: string, source: NonNullable['source']): MapNavPack | null { + let maps: string[]; + try { + maps = readdirSync(folder, { withFileTypes: true }) + .filter((file) => (file.isFile() || file.isSymbolicLink()) && file.name.endsWith('.wtonav')) + .map((file) => file.name); + } catch (error) { + if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) { + console.warn('[map-nav] could not read the maps folder:', error); + } + return null; + } + if (maps.length === 0) return null; + const manifest = readManifest(folder); + if (manifest && needsMapNavLauncherUpdate(manifest)) return null; + return { + folder, + info: { source, version: manifest?.version ?? null, gameVersions: manifest?.gameVersions ?? [], mapCount: maps.length }, + }; +} + +function downloadedPack(): MapNavPack | null { + try { + const active = JSON.parse(readFileSync(activeFile(), 'utf8')) as { version?: unknown }; + const version = MapNavVersionSchema.parse(active.version); + const pack = foundPack(join(mapNavStoreFolder(), version, 'maps'), 'downloaded'); + return pack?.info.version === version ? pack : null; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') console.warn('[map-nav] the active pack is unusable:', error); + return null; + } +} + +export function selectedMapNavPack(dataPath: string | null): MapNavPack | null { + return downloadedPack() ?? + (dataPath ? foundPack(join(dataPath, 'map-nav', 'maps'), 'local') : null) ?? + foundPack(bundledResourcePaths().bundledMapNavFolder, 'bundled'); +} + +/** Commit a verified map directory, then switch the pointer used by new launches. */ +export async function activateMapNavPack(version: string, stagedFolder?: string): Promise { + const store = mapNavStoreFolder(); + if (stagedFolder !== undefined) { + await mkdir(store, { recursive: true }); + await rename(stagedFolder, join(store, version)); + } + await writeJsonAtomic(activeFile(), { version }); +} + +export async function deactivateMapNavPack(): Promise { + await rm(activeFile(), { force: true }); +} diff --git a/apps/launcher/src/main/services/map-nav/map-nav-update.ts b/apps/launcher/src/main/services/map-nav/map-nav-update.ts new file mode 100644 index 0000000..ce9b57e --- /dev/null +++ b/apps/launcher/src/main/services/map-nav/map-nav-update.ts @@ -0,0 +1,145 @@ +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(update: () => Promise): Promise { + if (updating) throw new AppError('map_nav_update_busy'); + updating = true; + try { + return await update(); + } finally { + updating = false; + } +} + +export async function activeMapNav(): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + return duringMapNavUpdate(async () => { + await deactivateMapNavPack(); + return activeMapNav(); + }); +} diff --git a/apps/launcher/src/main/services/patch-pack/pack-update.ts b/apps/launcher/src/main/services/patch-pack/pack-update.ts index f856c91..b9314d1 100644 --- a/apps/launcher/src/main/services/patch-pack/pack-update.ts +++ b/apps/launcher/src/main/services/patch-pack/pack-update.ts @@ -42,7 +42,7 @@ export async function checkPackUpdate(): Promise { 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) }; + return { status: 'failed', active, latest: null, problem: packUpdateProblem(error) }; } } @@ -69,7 +69,7 @@ export async function applyPackUpdate(version: string): Promise return { ok: true, active: activePatchSet() }; } catch (error) { console.warn('[patch-pack] update failed:', error); - return { ok: false, problem: problemOf(error) }; + return { ok: false, problem: packUpdateProblem(error) }; } } @@ -110,7 +110,7 @@ function isNewer(candidate: string, active: string | null): boolean { return active === null || comparePackVersions(candidate, active) > 0; } -function problemOf(error: unknown): PackProblem { +export function packUpdateProblem(error: unknown): PackProblem { if (error instanceof ReleasePageLimitError) return 'page_limit'; if (error instanceof FeedUnreachableError) return 'network'; if (error instanceof PatchPackError) { diff --git a/apps/launcher/src/main/services/patch-pack/release-assets.ts b/apps/launcher/src/main/services/patch-pack/release-assets.ts index 49f1a94..4357ddd 100644 --- a/apps/launcher/src/main/services/patch-pack/release-assets.ts +++ b/apps/launcher/src/main/services/patch-pack/release-assets.ts @@ -1,4 +1,9 @@ -import type { Readable } from 'node:stream'; +import { createHash } from 'node:crypto'; +import { createWriteStream } from 'node:fs'; +import { mkdir, rename, unlink } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { Transform, type Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; import { net, type IncomingMessage } from 'electron'; import { PatchPackError } from '@wto/patcher'; import type { ReleaseSource } from './release-feed.ts'; @@ -85,3 +90,50 @@ export async function readReleaseAsset( } return Buffer.concat(chunks); } + +/** Stream a large, signed asset to disk and install the file only after its size and hash match. */ +export async function stageReleaseAsset( + url: URL, source: ReleaseSource, file: { readonly size: number; readonly sha256: string }, target: string, + report: (progress: { received: number; total: number }) => void, +): Promise { + const partial = target + '.partial'; + const deadline = AbortSignal.timeout(30 * 60_000); + const hash = createHash('sha256'); + let received = 0; + let reportedAt = 0; + try { + await mkdir(dirname(target), { recursive: true }); + await removePartial(partial); + const response = await requestReleaseAsset(url, deadline, source); + const monitor = new Transform({ + transform(chunk: Buffer, _encoding, done) { + received += chunk.length; + if (received > file.size) { + done(new PatchPackError('size', 'The download is larger than its signed size.')); + return; + } + hash.update(chunk); + if (received === file.size || Date.now() - reportedAt >= 200) { + reportedAt = Date.now(); + report({ received, total: file.size }); + } + done(null, chunk); + }, + }); + await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline }); + if (received !== file.size) throw new FeedUnreachableError('The update download is incomplete.'); + if (hash.digest('hex') !== file.sha256) throw new PatchPackError('signature', 'The download does not match the signed release.'); + await rename(partial, target); + } catch (error) { + if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error }); + throw error; + } finally { + await removePartial(partial).catch((error: unknown) => console.warn('[release-assets] removing a partial download failed:', error)); + } +} + +async function removePartial(path: string): Promise { + await unlink(path).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw error; + }); +} diff --git a/apps/launcher/src/main/services/patch-pack/release-feed.ts b/apps/launcher/src/main/services/patch-pack/release-feed.ts index 47b2753..ff3092c 100644 --- a/apps/launcher/src/main/services/patch-pack/release-feed.ts +++ b/apps/launcher/src/main/services/patch-pack/release-feed.ts @@ -8,6 +8,7 @@ import { } from '@wto/patcher'; import { z } from 'zod'; import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts'; +import { MAP_NAV_TAG_PREFIX, MapNavVersionSchema, mapNavReleaseFiles } from '@shared/schemas/map-nav-pack.ts'; import { releaseRepositoryUrl } from '@shared/update-source.ts'; import { getSettings } from '../config/settings-store.ts'; import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts'; @@ -45,6 +46,7 @@ export interface PackReleaseFiles { interface ReleaseByChannel { launcher: LauncherRelease; pack: PackReleaseFiles; + mapNav: PackReleaseFiles; } type ReleaseChannel = keyof ReleaseByChannel; @@ -170,7 +172,7 @@ export async function projectReleaseVersion( async function readProjectReleases(source: ReleaseSource): Promise { const tuning = patchPackTuning(); - const versions: ReleaseVersions = { launcher: new Map(), pack: new Map() }; + const versions: ReleaseVersions = { launcher: new Map(), pack: new Map(), mapNav: new Map() }; const incomplete: Partial> = {}; const url = new URL(source.feed); url.searchParams.set('per_page', String(tuning.releasePageSize)); @@ -222,11 +224,16 @@ function collectReleases( continue; } - const version = packVersionOfTag(tag); + const mapNav = tag.startsWith(MAP_NAV_TAG_PREFIX); + const channel = mapNav ? 'mapNav' : 'pack'; + const version = mapNav ? MapNavVersionSchema.safeParse(tag.slice(MAP_NAV_TAG_PREFIX.length)).data : packVersionOfTag(tag); if (!version) continue; - const pack = packRelease(release, version, tag, source); - if (pack) versions.pack.set(pack.version, pack); - else if (!incomplete.pack || comparePackVersions(version, incomplete.pack) > 0) incomplete.pack = version; + const pack = packRelease(release, version, tag, source, mapNav ? mapNavReleaseFiles(version) : packFileNames(version)); + if (pack) versions[channel].set(pack.version, pack); + else { + const partial = incomplete[channel]; + if (!partial || comparePackVersions(version, partial) > 0) incomplete[channel] = version; + } } } @@ -274,10 +281,12 @@ function launcherRelease(entry: Record, version: string, source }; } -function packRelease(release: Record, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null { +function packRelease( + release: Record, version: string, tag: string, source: ReleaseSource, + names: ReturnType, +): PackReleaseFiles | null { if (!Array.isArray(release['assets'])) return null; const urls = assetUrls(release['assets'], tag, source); - const names = packFileNames(version); const zipUrl = urls.get(names.zip); const signatureUrl = urls.get(names.signature); const manifestUrl = urls.get(names.manifest); diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index ba27d7c..19ba8bb 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -10,7 +10,7 @@ export interface BuildRequest { readonly patches: string; readonly networkHookLibrary: string; readonly groundAiScripts: string; - readonly bundledMapNavFolder: string; + readonly mapNavFolder?: string; readonly decalCache?: string; readonly hookLogging: boolean; readonly acceptedUnavailable: readonly string[]; diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index 900c8cc..9ac4506 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -1,5 +1,5 @@ -import { readFileSync, realpathSync, statSync } from 'node:fs'; -import { join, relative } from 'node:path'; +import { readFileSync, realpathSync } from 'node:fs'; +import { relative } from 'node:path'; import type { MessageEvent } from 'electron'; import { discoverMods, touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods'; import { @@ -95,8 +95,6 @@ function build(request: BuildRequest): void { const extraStockPacks = optionalPacksInBuild.length > 0 ? prepareOptionalStockPacks(request.copyPath, request.stockPath, optionalPacksInBuild) : undefined; - const mapNavFolder = [join(request.dataPath, 'map-nav', 'maps'), request.bundledMapNavFolder] - .find((folder) => statSync(folder, { throwIfNoEntry: false })?.isDirectory()); const result = buildGameCopy({ stock: readStockGameFiles(request.stockPath), @@ -107,7 +105,7 @@ function build(request: BuildRequest): void { placeholderDecals: decalCache === undefined, ...(decalIndexFiles ? { decalIndexFiles } : {}), hookLogging: request.hookLogging, - ...(mapNavFolder === undefined ? {} : { mapNavFolder }), + ...(request.mapNavFolder === undefined ? {} : { mapNavFolder: request.mapNavFolder }), ...(enabledMods.length > 0 ? { mods: enabledMods } : {}), ...(extraStockPacks ? { extraStockPacks } : {}), groundAi: { scriptsFolder: request.groundAiScripts, config: groundAiConfig }, diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index 50a4c90..46349d6 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -38,6 +38,7 @@ import { SubNav } from './shell/SubNav.tsx'; import { TitleBar } from './shell/TitleBar.tsx'; import { useBackgrounds } from './shell/useBackgrounds.ts'; import { useAppUpdate } from './shell/useAppUpdate.ts'; +import { useMapNavPack } from './shell/useMapNavPack.ts'; import { usePatchPack } from './shell/usePatchPack.ts'; import { useErrorMessage } from './useErrorMessage.ts'; @@ -69,6 +70,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { const [route, setRoute] = useState(START_ROUTE); // The setting as the window opened: turning it on later does not check right away. const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report); + const mapNavPack = useMapNavPack(initialSettings.checkPatchPacksOnStart, report); const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report); const maintenance = useCopyMaintenance(report); const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions; @@ -159,6 +161,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { launcherVersion={info.version} supportedVersions={supported} patchPack={patchPack} + mapNavPack={mapNavPack} appUpdate={appUpdate} loggingEnabled={settings.loggingEnabled} onError={report} diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index b36eafe..94a656c 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -940,11 +940,11 @@ "appUpdates": "Launcher updates", "appUpdatesToggle": "Check for launcher updates at start", "patchPacks": "Adaptation pack updates", - "patchPacksHint": "After a game update, patches for the new version are released as an adaptation pack.", + "patchPacksHint": "Checks for new client patches and ground AI map packs.", "updateMirror": "Update mirror repository", "updateMirrorHint": "Enter an HTTPS mirror with a GitHub-compatible releases list. It is used if the primary source is unreachable. Leave blank to disable it.", "updateMirrorInvalid": "Enter a valid HTTPS repository address or leave the field blank.", - "patchPacksToggle": "Check for a new adaptation pack at start", + "patchPacksToggle": "Check for adaptation pack updates at start", "windowClose": "When closing the window", "windowQuit": "Quit launcher", "windowTray": "Minimize to system tray", @@ -1065,6 +1065,26 @@ "up_to_date": "Up to date: there is no adaptation pack to download." } }, + "mapNav": { + "title": "Map adaptation packs", + "hint": "The selected navigation and cover data takes effect the next time you start the game.", + "missing": "No map pack installed", + "source": { + "bundled": "Included with the launcher", + "downloaded": "Downloaded map pack", + "local": "Local map pack" + }, + "mapCount_one": "{{count}} map", + "mapCount_other": "{{count}} maps", + "deactivate": "Stop using downloaded pack", + "downloading": "Downloading map pack…", + "installing": "Verifying and activating map pack…", + "upToDate": "Up to date (latest map pack {{version}}).", + "noneReleased": "No map pack has been released yet.", + "available_one": "Map pack {{version}} is available · {{count}} map · {{size}}.", + "available_other": "Map pack {{version}} is available · {{count}} maps · {{size}}.", + "compatible": "Baked for game versions {{versions}}." + }, "update": { "title": "Launcher update", "check": "Launcher version check", @@ -1227,6 +1247,7 @@ "errors": { "app_update_unavailable": "There is no launcher update available to install.", "app_update_busy": "A launcher update operation is already in progress.", + "map_nav_update_busy": "A map pack update is already in progress.", "app_update_launcher_busy": "Close the game and local server and finish any client or save operations before updating.", "app_update_download_failed": "The launcher installer could not be downloaded and verified. See the launcher log.", "app_update_installer_invalid": "The installer failed verification. Download it again.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 17f8e77..18ce4df 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -940,11 +940,11 @@ "appUpdates": "启动器本体更新", "appUpdatesToggle": "启动时检查本体更新", "patchPacks": "适配包更新", - "patchPacksHint": "游戏更新后,新版本的补丁会以适配包的形式发布。", + "patchPacksHint": "检查客户端补丁和陆战 AI 地图适配包的更新。", "updateMirror": "备用更新仓库", "updateMirrorHint": "填写支持 GitHub Releases 格式的 HTTPS 镜像地址。主源连接失败时使用,留空关闭。", "updateMirrorInvalid": "请输入有效的 HTTPS 仓库地址,或留空。", - "patchPacksToggle": "启动时检查有没有新的适配包", + "patchPacksToggle": "启动时检查适配包更新", "windowClose": "关闭窗口时", "windowQuit": "退出启动器", "windowTray": "最小化到系统托盘", @@ -1065,6 +1065,26 @@ "up_to_date": "已是最新,没有需要下载的适配包。" } }, + "mapNav": { + "title": "地图适配包", + "hint": "所选的导航和掩体数据将在下次启动游戏时生效。", + "missing": "未安装地图适配包", + "source": { + "bundled": "启动器自带", + "downloaded": "已下载的地图包", + "local": "本地地图包" + }, + "mapCount_one": "{{count}} 张地图", + "mapCount_other": "{{count}} 张地图", + "deactivate": "停用已下载的地图包", + "downloading": "正在下载地图适配包…", + "installing": "正在校验并启用地图适配包…", + "upToDate": "已是最新(最新的地图包是 {{version}})。", + "noneReleased": "还没有发布地图适配包。", + "available_one": "地图包 {{version}} 可用 · {{count}} 张地图 · {{size}}。", + "available_other": "地图包 {{version}} 可用 · {{count}} 张地图 · {{size}}。", + "compatible": "生成时使用的游戏版本为 {{versions}}。" + }, "update": { "title": "本体更新", "check": "检查本体版本", @@ -1227,6 +1247,7 @@ "errors": { "app_update_unavailable": "当前没有可安装的本体更新。", "app_update_busy": "本体更新操作正在进行。", + "map_nav_update_busy": "地图适配包更新正在进行。", "app_update_launcher_busy": "请在游戏退出、服务器关闭及客户端和存档操作完成后安装更新。", "app_update_download_failed": "无法下载并验证本体安装包。请查看启动器日志。", "app_update_installer_invalid": "安装包校验失败。请重新下载。", diff --git a/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx b/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx index eacc6fb..9035985 100644 --- a/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx +++ b/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx @@ -6,6 +6,8 @@ import { ipcInvoke } from '../../ipc.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import { AppUpdateSection } from './AppUpdateSection.tsx'; import type { PatchPackState } from '../../shell/usePatchPack.ts'; +import type { MapNavPackState } from '../../shell/useMapNavPack.ts'; +import { MapNavPackSection } from './MapNavPackSection.tsx'; const HOMEPAGE_URL = 'https://wto-project.net'; const DISCORD_INVITE_URL = 'https://discord.gg/P566xWNpEs'; @@ -14,13 +16,14 @@ interface AboutPageProps { readonly launcherVersion: string; readonly supportedVersions: readonly string[]; readonly patchPack: PatchPackState; + readonly mapNavPack: MapNavPackState; readonly appUpdate: AppUpdateState; readonly loggingEnabled: boolean; readonly onError: (error: unknown) => void; } /** The launcher's version, the game versions it supports, updates, community links, log export, and the project statement. */ -export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) { +export function AboutPage({ launcherVersion, supportedVersions, patchPack, mapNavPack, appUpdate, loggingEnabled, onError }: AboutPageProps) { const { t } = useTranslation(); return ( @@ -36,6 +39,7 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp
+
diff --git a/apps/launcher/src/renderer/src/pages/about/MapNavPackSection.tsx b/apps/launcher/src/renderer/src/pages/about/MapNavPackSection.tsx new file mode 100644 index 0000000..7c8df91 --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/about/MapNavPackSection.tsx @@ -0,0 +1,66 @@ +import { useTranslation } from 'react-i18next'; +import { Notice } from '../../components/Notice.tsx'; +import { ProgressBar } from '../../components/ProgressBar.tsx'; +import { formatBytes } from '../../format.ts'; +import type { MapNavPackState } from '../../shell/useMapNavPack.ts'; + +export function MapNavPackSection({ state }: { readonly state: MapNavPackState }) { + const { t } = useTranslation(); + const { active, busy, check, progress } = state; + const latest = check?.latest; + return ( +
+
+

{t('about.mapNav.title')}

+
+ + {active?.source === 'downloaded' && ( + + )} +
+
+

+ {t('about.pack.current')} + {' · '} + {active === undefined ? '…' : active === null ? t('about.mapNav.missing') : [ + t('about.mapNav.source.' + active.source), active.version, + t('about.mapNav.mapCount', { count: active.mapCount }), + ].filter(Boolean).join(' · ')} +

+

{t('about.mapNav.hint')}

+ {busy === 'applying' && ( +
+

+ {t(progress?.total && progress.received >= progress.total ? 'about.mapNav.installing' : 'about.mapNav.downloading')} +

+ +
+ )} + {state.failure &&

{t('about.pack.applyFailed.' + state.failure)}

} + {busy !== 'checking' && check?.status === 'failed' && ( +

{t('about.pack.checkFailed.' + (check.problem ?? 'contents'))}

+ )} + {busy !== 'checking' && check?.status === 'up_to_date' && ( +

{latest ? t('about.mapNav.upToDate', { version: latest.version }) : t('about.mapNav.noneReleased')}

+ )} + {busy !== 'checking' && check?.status === 'needs_app_update' && latest && ( +

{t('about.pack.needsAppUpdate', { version: latest.version, app: latest.minAppVersion })}

+ )} + {busy !== 'checking' && check?.status === 'available' && latest && ( + +

{t('about.mapNav.available', { version: latest.version, count: latest.mapCount, size: formatBytes(latest.size) })}

+

{t('about.mapNav.compatible', { versions: latest.gameVersions.join(', ') })}

+ {busy !== 'applying' && ( + + )} +
+ )} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/shell/useMapNavPack.ts b/apps/launcher/src/renderer/src/shell/useMapNavPack.ts new file mode 100644 index 0000000..3abedc6 --- /dev/null +++ b/apps/launcher/src/renderer/src/shell/useMapNavPack.ts @@ -0,0 +1,78 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import type { AppUpdateProgress } from '@shared/schemas/app-update.ts'; +import type { ActiveMapNav, MapNavCheck } from '@shared/schemas/map-nav-pack.ts'; +import { ipcInvoke, ipcOn } from '../ipc.ts'; +import type { PackFailure } from './usePatchPack.ts'; + +export function useMapNavPack(checkOnStart: boolean, onError: (error: unknown) => void) { + const [active, setActive] = useState(); + const [check, setCheck] = useState(null); + const [busy, setBusy] = useState<'checking' | 'applying' | 'deactivating' | null>(null); + const [progress, setProgress] = useState(null); + const [failure, setFailure] = useState(null); + const startChecked = useRef(false); + + useEffect(() => { + const refresh = (): void => { ipcInvoke('map-nav:active').then(setActive).catch(onError); }; + refresh(); + window.addEventListener('focus', refresh); + const disposeCopies = ipcOn('event:copies-changed', refresh); + const disposeProgress = ipcOn('event:map-nav-progress', setProgress); + return () => { + window.removeEventListener('focus', refresh); + disposeCopies(); + disposeProgress(); + }; + }, [onError]); + + const checkNow = useCallback((): void => { + setBusy('checking'); + setFailure(null); + ipcInvoke('map-nav:check') + .then((result) => { + setCheck(result); + setActive(result.active); + }) + .catch(onError) + .finally(() => setBusy(null)); + }, [onError]); + + useEffect(() => { + if (!checkOnStart || startChecked.current) return; + startChecked.current = true; + checkNow(); + }, [checkOnStart, checkNow]); + + function apply(version: string): void { + setBusy('applying'); + setProgress(null); + setFailure(null); + ipcInvoke('map-nav:apply', { version }) + .then((result) => { + if (!result.ok) { + setFailure(result.problem); + return; + } + setActive(result.active); + setCheck((previous) => previous ? { ...previous, status: 'up_to_date', active: result.active } : null); + }) + .catch(onError) + .finally(() => setBusy(null)); + } + + function deactivate(): void { + setBusy('deactivating'); + setFailure(null); + ipcInvoke('map-nav:deactivate') + .then((result) => { + setActive(result); + setCheck(null); + }) + .catch(onError) + .finally(() => setBusy(null)); + } + + return { active, check, busy, progress, failure, checkNow, apply, deactivate }; +} + +export type MapNavPackState = ReturnType; diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index d83a34e..3aa179d 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -14,6 +14,7 @@ export const APP_ERROR_CODES = [ 'internal_error', 'app_update_unavailable', 'app_update_busy', + 'map_nav_update_busy', 'app_update_launcher_busy', 'app_update_download_failed', 'app_update_installer_invalid', diff --git a/apps/launcher/src/shared/ipc/channels.ts b/apps/launcher/src/shared/ipc/channels.ts index 20beb28..8adb1b4 100644 --- a/apps/launcher/src/shared/ipc/channels.ts +++ b/apps/launcher/src/shared/ipc/channels.ts @@ -28,6 +28,8 @@ export const IPC_CHANNEL_PREFIXES = [ 'settings:', /** Adaptation packs: the active patch set, update checks, installing a newer pack. */ 'patches:', + /** Map navigation pack status and updates. */ + 'map-nav:', /** Checking, downloading and installing a launcher release. */ 'updates:', /** The launcher window itself (it draws its own title bar). */ diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 52d3682..84f6936 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -16,6 +16,7 @@ import { TargetFolderInspectionSchema, } from '../schemas/install.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; +import { ActiveMapNavSchema, MapNavApplyResultSchema, MapNavCheckSchema, MapNavVersionSchema } from '../schemas/map-nav-pack.ts'; import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; import { ModsStateViewSchema } from '../schemas/mods.ts'; import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from '../schemas/patch-pack.ts'; @@ -367,6 +368,22 @@ export const ipcContract = { input: z.void(), output: ActivePatchSetSchema, }, + 'map-nav:active': { + input: z.void(), + output: ActiveMapNavSchema, + }, + 'map-nav:check': { + input: z.void(), + output: MapNavCheckSchema, + }, + 'map-nav:apply': { + input: z.object({ version: MapNavVersionSchema }), + output: MapNavApplyResultSchema, + }, + 'map-nav:deactivate': { + input: z.void(), + output: ActiveMapNavSchema, + }, 'updates:check': { input: z.void(), output: AppUpdateCheckSchema, @@ -393,6 +410,7 @@ export const ipcEvents = { 'event:settings-changed': SettingsSchema, 'event:install-progress': InstallProgressSchema, 'event:app-update-progress': AppUpdateProgressSchema, + 'event:map-nav-progress': AppUpdateProgressSchema, 'event:launch-state': LaunchStateSchema, 'event:copies-changed': CopiesSchema, 'event:copy-maintenance': MaintenanceProgressSchema.nullable(), diff --git a/apps/launcher/src/shared/schemas/map-nav-pack.ts b/apps/launcher/src/shared/schemas/map-nav-pack.ts new file mode 100644 index 0000000..b4bd699 --- /dev/null +++ b/apps/launcher/src/shared/schemas/map-nav-pack.ts @@ -0,0 +1,72 @@ +import { z } from 'zod'; +import { AppReleaseVersionSchema, MAX_INSTALLER_BYTES } from './app-update.ts'; +import { ActivePatchSetSchema, PackApplyResultSchema, PackCheckSchema, PackReleaseSchema } from './patch-pack.ts'; + +export const MAP_NAV_TAG_PREFIX = 'map-nav-'; +export const MAP_NAV_FORMAT = 1; +export const MapNavVersionSchema = z.string().regex(/^\d{4}\.\d{2}\.\d{2}(\.[1-9]\d*)?$/); + +export function mapNavReleaseFiles(version: string): { zip: string; signature: string; manifest: string } { + const name = 'wtoffline-map-nav-' + MapNavVersionSchema.parse(version); + return { zip: name + '.zip', signature: name + '.zip.sig', manifest: name + '.manifest.json' }; +} + +const Sha256 = z.string().regex(/^[0-9a-f]{64}$/); +const FileSize = z.number().int().positive().max(MAX_INSTALLER_BYTES); +const MapEntry = z.object({ + level: z.string().regex(/^(?!(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$)[a-z0-9_]+$/), + everSha1: z.string().regex(/^[0-9a-f]{40}$/), + size: FileSize, + sha256: Sha256, + covers: z.number().int().nonnegative(), +}); + +export const MapNavManifestSchema = z.object({ + format: z.number().int().positive(), + version: MapNavVersionSchema, + minAppVersion: AppReleaseVersionSchema, + gameVersions: z.array(z.string().regex(/^\d+\.\d+\.\d+\.\d+$/)).min(1), + createdAt: z.iso.datetime(), + maps: z.array(MapEntry).min(1).refine((maps) => + new Set(maps.map(({ level }) => level)).size === maps.length && + maps.reduce((size, entry) => size + entry.size, 0) <= MAX_INSTALLER_BYTES * 2), +}); + +export const MapNavReleaseManifestSchema = MapNavManifestSchema.extend({ + archive: z.object({ size: FileSize, sha256: Sha256 }), +}); + +/** The signature covers a release manifest with the size and SHA-256 of the ZIP. */ +export function mapNavSignaturePayload(manifest: Uint8Array): Uint8Array { + const domain = new TextEncoder().encode('WTOffline map navigation release v1\n'); + const bytes = new Uint8Array(domain.length + manifest.length); + bytes.set(domain); + bytes.set(manifest, domain.length); + return bytes; +} + +export const ActiveMapNavSchema = ActivePatchSetSchema.extend({ + source: z.enum(['bundled', 'downloaded', 'local']), + mapCount: z.number().int().nonnegative(), +}).nullable(); + +export const MapNavReleaseSchema = PackReleaseSchema.extend({ + mapCount: z.number().int().positive(), + size: FileSize, +}); + +export const MapNavCheckSchema = PackCheckSchema.extend({ + active: ActiveMapNavSchema, + latest: MapNavReleaseSchema.nullable(), +}); + +export const MapNavApplyResultSchema = z.discriminatedUnion('ok', [ + z.object({ ok: z.literal(true), active: ActiveMapNavSchema }), + PackApplyResultSchema.options[1], +]); + +export type MapNavManifest = z.output; +export type MapNavReleaseManifest = z.output; +export type ActiveMapNav = z.output; +export type MapNavCheck = z.output; +export type MapNavApplyResult = z.output; diff --git a/scripts/build-windows-installer.ts b/scripts/build-windows-installer.ts index f318533..f631ea3 100644 --- a/scripts/build-windows-installer.ts +++ b/scripts/build-windows-installer.ts @@ -3,7 +3,9 @@ import { cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } import { tmpdir } from 'node:os'; import { dirname, join, relative, resolve, sep } from 'node:path'; import { Arch, build, Platform } from 'electron-builder'; +import { installerDigest } from '../apps/launcher/src/main/services/app-update/installer-integrity.ts'; import { launcherReleaseFiles, portableLauncherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts'; +import { MapNavManifestSchema } from '../apps/launcher/src/shared/schemas/map-nav-pack.ts'; import { formatManifest, MANIFEST_FILE, PATCH_PACK_FORMAT, recordedGameVersions } from '../packages/patcher/src/index.ts'; const repository = resolve(import.meta.dirname, '..'); @@ -72,6 +74,7 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis await cp(join(native, 'wto_ws.dll'), join(resources, 'native', 'wto_ws.dll')); await cp(join(repository, 'mod-dev-docs', 'templates'), join(resources, 'mod-templates'), { recursive: true }); await cp(join(repository, 'game-ai', 'ground'), join(resources, 'game-ai', 'ground'), { recursive: true }); + await stageMapNavBundle(resources); for (const folder of ['exe', 'gui', 'native', 'versions']) { await cp(join(repository, 'patches', folder), join(resources, 'patches', folder), { recursive: true }); } @@ -91,6 +94,26 @@ async function stageInstaller(stage: string, manifest: LauncherManifest): Promis } } +async function stageMapNavBundle(resources: string): Promise { + const source = join(buildFolder, 'map-nav'); + const text = await readFile(join(source, 'manifest.json'), 'utf8').catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return null; + throw error; + }); + if (!text) return; + const manifest = MapNavManifestSchema.parse(JSON.parse(text)); + const destination = join(resources, 'map-nav'); + await mkdir(join(destination, 'maps'), { recursive: true }); + for (const { level, size, sha256 } of manifest.maps) { + const filename = level + '.wtonav'; + const target = join(destination, 'maps', filename); + await cp(join(source, 'maps', filename), target, { dereference: true }); + const digest = await installerDigest(target, size); + if (digest.size !== size || digest.sha256 !== sha256) throw new Error('The bundled map file does not match its manifest: ' + filename); + } + await writeFile(join(destination, 'manifest.json'), text, 'utf8'); +} + async function cleanInstallerOutput(version: string): Promise { await mkdir(buildFolder, { recursive: true }); if (relative(buildFolder, await realpath(buildFolder)) !== '') throw new Error('The build directory is redirected.'); diff --git a/scripts/publish-r2-releases.ts b/scripts/publish-r2-releases.ts index 9a2aedb..63c7292 100644 --- a/scripts/publish-r2-releases.ts +++ b/scripts/publish-r2-releases.ts @@ -9,6 +9,7 @@ * Options: * --add-launcher Stage signed installer (and optional portable zip) from a build folder * --add-pack Stage signed adaptation pack(s) from a folder or a specific .zip file + * --add-map-nav Stage a signed map navigation archive * --notes Release notes Markdown for --add-launcher (defaults to .github/release-notes/v.md) * --remove-tag Remove a tag from the release feed * --out Local staging directory (default: build/r2-dist) @@ -50,6 +51,9 @@ import { portableLauncherReleaseFiles, PortableReleaseManifest, } from '../apps/launcher/src/shared/schemas/app-update.ts'; +import { + MAP_NAV_TAG_PREFIX, MapNavVersionSchema, MapNavReleaseManifestSchema, mapNavReleaseFiles, mapNavSignaturePayload, +} from '../apps/launcher/src/shared/schemas/map-nav-pack.ts'; import { renderDownloadPage, type ReleaseAssetEntry, type ReleaseEntry } from './r2/download-page.ts'; import { R2Client, sha256 } from './r2/sigv4.ts'; @@ -68,6 +72,7 @@ async function main(): Promise { options: { 'add-launcher': { type: 'string', multiple: true }, 'add-pack': { type: 'string', multiple: true }, + 'add-map-nav': { type: 'string', multiple: true }, notes: { type: 'string' }, 'remove-tag': { type: 'string', multiple: true }, out: { type: 'string', default: DEFAULT_OUT }, @@ -127,6 +132,12 @@ async function main(): Promise { } } + for (const target of values['add-map-nav'] ?? []) { + const entry = await stageMapNavRelease(resolve(target), filesRoot, publicUrl, publicKey); + byTag.set(entry.tag_name, entry); + console.info('Staged map pack ' + entry.tag_name); + } + for (const tag of values['remove-tag'] ?? []) { if (byTag.delete(tag)) console.info(`Removed ${tag} from release list.`); } @@ -292,6 +303,45 @@ async function stageAdaptationPacks( return staged; } +async function stageMapNavRelease( + zipPath: string, filesRoot: string, publicUrl: string, publicKey: string, +): Promise { + const version = MapNavVersionSchema.parse(/^wtoffline-map-nav-(.+)\.zip$/.exec(basename(zipPath))?.[1]); + const files = mapNavReleaseFiles(version); + const directory = dirname(zipPath); + const signature = join(directory, files.signature); + const manifestFile = join(directory, files.manifest); + const [bytes, signatureText] = await Promise.all([readFile(manifestFile), readFile(signature, 'utf8')]); + if (!verifyEd25519(mapNavSignaturePayload(bytes), signatureText, publicKey)) { + throw new Error('Signature verification failed for ' + files.zip); + } + const manifest = MapNavReleaseManifestSchema.parse(JSON.parse(bytes.toString('utf8'))); + if (manifest.version !== version) throw new Error('The map pack manifest version does not match its file name.'); + const digest = await installerDigest(zipPath, manifest.archive.size); + if (digest.size !== manifest.archive.size || digest.sha256 !== manifest.archive.sha256) { + throw new Error('The map archive does not match the signed manifest.'); + } + const tag = MAP_NAV_TAG_PREFIX + version; + const destination = join(filesRoot, tag); + await mkdir(destination, { recursive: true }); + const assets = [ + await copyAsset(zipPath, destination, tag, publicUrl, digest.sha256), + await copyAsset(signature, destination, tag, publicUrl), + await copyAsset(manifestFile, destination, tag, publicUrl), + ]; + return { + tag_name: tag, + name: 'Map Adaptation Pack ' + version, + draft: false, + prerelease: true, + published_at: manifest.createdAt, + body: 'Maps: ' + manifest.maps.length + '\nGame versions: ' + manifest.gameVersions.join(', ') + '\n', + game_versions: manifest.gameVersions, + min_app_version: manifest.minAppVersion, + assets, + }; +} + async function copyAsset( sourcePath: string, targetDir: string, @@ -455,6 +505,7 @@ function printUsage(): void { '', ' --add-launcher Stage signed installer/portable release from a build folder', ' --add-pack Stage signed adaptation pack(s) from a folder or .zip file', + ' --add-map-nav Stage a signed map navigation archive', ' --notes Release notes Markdown file for --add-launcher', ' --remove-tag Remove a tag from the release feed', ' --out Local staging directory (default: build/r2-dist)', diff --git a/tools/navgen/package-maps.mts b/tools/navgen/package-maps.mts index 8d383a2..36223fe 100644 --- a/tools/navgen/package-maps.mts +++ b/tools/navgen/package-maps.mts @@ -12,6 +12,10 @@ import { mkdir, mkdtemp, readFile, readdir, rename, writeFile } from 'node:fs/pr import { join, resolve } from 'node:path'; import { parseArgs } from 'node:util'; import { isPackVersion, packSigningPublicKey, signEd25519, verifyEd25519 } from '@wto/patcher'; +import { installerDigest } from '../../apps/launcher/src/main/services/app-update/installer-integrity.ts'; +import { + MAP_NAV_FORMAT, MapNavManifestSchema, MapNavReleaseManifestSchema, mapNavReleaseFiles, mapNavSignaturePayload, +} from '../../apps/launcher/src/shared/schemas/map-nav-pack.ts'; import { readNavPack } from '../../packages/ground-sim/src/map/wtonav.ts'; const { values } = parseArgs({ @@ -61,31 +65,33 @@ async function main(): Promise { } const app = JSON.parse(await readFile(new URL('../../apps/launcher/package.json', import.meta.url), 'utf8')) as { version: string }; - const manifest = JSON.stringify({ - format: 1, + const manifest = MapNavManifestSchema.parse({ + format: MAP_NAV_FORMAT, version, minAppVersion: app.version, gameVersions: [gameVersion], createdAt: new Date().toISOString(), maps: entries, - }, null, 2) + '\n'; - await writeFile(join(pack, 'manifest.json'), manifest); - const stem = 'wtoffline-map-nav-' + version; - const archive = join(staging, stem + '.zip'); + }); + await writeFile(join(pack, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n'); + const files = mapNavReleaseFiles(version); + const archive = join(staging, files.zip); execFileSync('tar', ['-a', '-c', '-f', archive, '-C', staging, 'map-nav'], { stdio: 'inherit', windowsHide: true }); + const releaseManifest = MapNavReleaseManifestSchema.parse({ ...manifest, archive: await installerDigest(archive) }); + const bytes = Buffer.from(JSON.stringify(releaseManifest, null, 2) + '\n', 'utf8'); if (privateKey) { - const bytes = await readFile(archive); - const signature = signEd25519(bytes, privateKey); + const payload = mapNavSignaturePayload(bytes); + const signature = signEd25519(payload, privateKey); const publicKey = packSigningPublicKey(); - if (!publicKey || !verifyEd25519(bytes, signature, publicKey)) { - throw new Error('The map archive signature did not verify against the project public key.'); + if (!publicKey || !verifyEd25519(payload, signature, publicKey)) { + throw new Error('The map release signature did not verify against the project public key.'); } - await writeFile(join(staging, stem + '.zip.sig'), signature); + await writeFile(join(staging, files.signature), signature); } - await writeFile(join(staging, stem + '.manifest.json'), manifest); + await writeFile(join(staging, files.manifest), bytes); const release = join(output, version); await rename(staging, release); - console.log('Packaged ' + entries.length + ' maps in ' + join(release, stem + '.zip')); + console.log('Packaged ' + entries.length + ' maps in ' + join(release, files.zip)); console.log('Unpacked maps: ' + join(release, 'map-nav')); }