feat(launcher): support signed in-place updates for portable builds
This commit is contained in:
1 parent
e284ea7ed6
commit
82ec1c47ff
8 files changed
+477
-46
No files matched your search
@@ -1,8 +1,8 @@
|
||||
# Build, sign, and publish a Windows installer of the WTOffline Launcher as a GitHub release
|
||||
# tagged v<version>. The launcher's update check reads v<version> releases and expects the three
|
||||
# signed files (installer, manifest, signature); a release missing any of them breaks the check
|
||||
# for already-installed launchers. The workflow also attaches an unsigned portable zip of the
|
||||
# unpacked app for manual download.
|
||||
# for already-installed launchers. The workflow also packages and signs the portable zip with its
|
||||
# own manifest and signature so portable installations can update in place.
|
||||
#
|
||||
# Start it either way:
|
||||
# - push a tag: git tag v0.1.0 && git push origin v0.1.0
|
||||
@@ -68,14 +68,9 @@ jobs:
|
||||
npm run typecheck
|
||||
npm run typecheck --workspace "@wto/launcher"
|
||||
|
||||
- name: Build and package the Windows installer
|
||||
- name: Build and package the Windows installer and portable archive
|
||||
run: npm --workspace "@wto/launcher" run package:win
|
||||
|
||||
- name: Package the portable archive
|
||||
shell: pwsh
|
||||
run: |
|
||||
Compress-Archive -Path "build/windows-installer/win-unpacked/*" -DestinationPath "build/windows-installer/wtoffline-launcher-$env:VERSION-win-x64-portable.zip" -Force
|
||||
|
||||
- name: Sign the release
|
||||
env:
|
||||
PATCH_SIGNING_KEY: ${{ secrets.PATCH_SIGNING_KEY }}
|
||||
@@ -94,6 +89,8 @@ jobs:
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64.manifest.json.sig" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.zip" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json" \
|
||||
"build/windows-installer/wtoffline-launcher-$VERSION-win-x64-portable.manifest.json.sig" \
|
||||
"${flags[@]}" \
|
||||
--title "WTOffline Launcher $VERSION" \
|
||||
--notes-file ".github/release-notes/v$VERSION.md" \
|
||||
|
||||
@@ -11,6 +11,7 @@ import { compareAppVersions, packSigningPublicKey, PatchPackError, patchPackTuni
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import {
|
||||
LauncherReleaseManifest,
|
||||
PortableReleaseManifest,
|
||||
type AppUpdateCheck, type AppUpdateProgress,
|
||||
} from '@shared/schemas/app-update.ts';
|
||||
import { gameProcessRunning } from '../launch/game-process.ts';
|
||||
@@ -20,11 +21,15 @@ import {
|
||||
import {
|
||||
FeedUnreachableError, readReleaseAsset, releaseAssetChunks, RELEASE_MANIFEST_MAX_BYTES, RELEASE_SIGNATURE_MAX_BYTES, requestReleaseAsset,
|
||||
} from '../patch-pack/release-assets.ts';
|
||||
import { installerDigest, launcherSignaturePayload } from './installer-integrity.ts';
|
||||
import { installerDigest, launcherSignaturePayload, portableSignaturePayload } from './installer-integrity.ts';
|
||||
import { isPortableLauncher, launchPortableUpdater, preparePortableInstall } from './portable-update.ts';
|
||||
|
||||
type UpdateMode = 'installer' | 'portable';
|
||||
|
||||
interface OfferedUpdate {
|
||||
readonly mode: UpdateMode;
|
||||
readonly release: LauncherRelease;
|
||||
readonly manifest: LauncherReleaseManifest;
|
||||
readonly manifest: LauncherReleaseManifest | PortableReleaseManifest;
|
||||
}
|
||||
|
||||
class ManifestSignatureError extends Error {}
|
||||
@@ -46,11 +51,15 @@ async function exclusively<T>(action: () => Promise<T>): Promise<T> {
|
||||
}
|
||||
}
|
||||
|
||||
function stagedInstaller(): string {
|
||||
return join(app.getPath('userData'), 'launcher-updates', 'installer.exe');
|
||||
function updatesRoot(): string {
|
||||
return join(app.getPath('userData'), 'launcher-updates');
|
||||
}
|
||||
|
||||
async function matchesInstaller(path: string, manifest: LauncherReleaseManifest): Promise<boolean> {
|
||||
function stagedArtifact(mode: UpdateMode): string {
|
||||
return join(updatesRoot(), mode === 'portable' ? 'portable.zip' : 'installer.exe');
|
||||
}
|
||||
|
||||
async function matchesArtifact(path: string, manifest: LauncherReleaseManifest | PortableReleaseManifest): Promise<boolean> {
|
||||
try {
|
||||
const digest = await installerDigest(path, manifest.size);
|
||||
return digest.size === manifest.size && digest.sha256 === manifest.sha256;
|
||||
@@ -76,6 +85,18 @@ function selectedOffer(version: string): OfferedUpdate {
|
||||
|
||||
async function signedOffer(release: LauncherRelease, key: string): Promise<OfferedUpdate> {
|
||||
const deadline = AbortSignal.timeout(patchPackTuning().requestTimeoutMs);
|
||||
if (isPortableLauncher(app.isPackaged) && release.portable) {
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readReleaseAsset(release.portable.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||
readReleaseAsset(release.portable.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||
]);
|
||||
if (!verifyEd25519(portableSignaturePayload(bytes), new TextDecoder().decode(signature), key)) {
|
||||
throw new ManifestSignatureError('The portable release manifest signature does not match.');
|
||||
}
|
||||
const manifest = PortableReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== release.version) throw new Error('The signed portable manifest version does not match the release tag.');
|
||||
return { mode: 'portable', release, manifest };
|
||||
}
|
||||
const [bytes, signature] = await Promise.all([
|
||||
readReleaseAsset(release.manifest, RELEASE_MANIFEST_MAX_BYTES, deadline, release.source),
|
||||
readReleaseAsset(release.signature, RELEASE_SIGNATURE_MAX_BYTES, deadline, release.source),
|
||||
@@ -85,7 +106,7 @@ async function signedOffer(release: LauncherRelease, key: string): Promise<Offer
|
||||
}
|
||||
const manifest = LauncherReleaseManifest.parse(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
||||
if (manifest.version !== release.version) throw new Error('The signed manifest version does not match the release tag.');
|
||||
return { release, manifest };
|
||||
return { mode: 'installer', release, manifest };
|
||||
}
|
||||
|
||||
export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||
@@ -102,7 +123,7 @@ export function checkAppUpdate(): Promise<AppUpdateCheck> {
|
||||
});
|
||||
if (!offer) return { status: 'current' };
|
||||
offered = offer;
|
||||
return offerResult(offer, await matchesInstaller(stagedInstaller(), offer.manifest));
|
||||
return offerResult(offer, await matchesArtifact(stagedArtifact(offer.mode), offer.manifest));
|
||||
} catch (error) {
|
||||
console.warn('[app-update] checking the release failed:', error);
|
||||
if (error instanceof ReleasePageLimitError) return { status: 'failed', problem: 'page_limit' };
|
||||
@@ -121,24 +142,26 @@ export function downloadAppUpdate(
|
||||
): Promise<AppUpdateCheck> {
|
||||
return exclusively(async () => {
|
||||
const offer = selectedOffer(version);
|
||||
const target = stagedInstaller();
|
||||
if (await matchesInstaller(target, offer.manifest)) return offerResult(offer, true);
|
||||
const target = stagedArtifact(offer.mode);
|
||||
if (await matchesArtifact(target, offer.manifest)) return offerResult(offer, true);
|
||||
try {
|
||||
await withReleaseSources(async (source) => {
|
||||
const release = sameReleaseSource(source, offer.release.source)
|
||||
? offer.release : await projectReleaseVersion('launcher', version, source);
|
||||
await stageInstaller(release, offer.manifest, target, report);
|
||||
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);
|
||||
}, offer.release.source);
|
||||
return offerResult(offer, true);
|
||||
} catch (error) {
|
||||
console.warn('[app-update] preparing the installer failed:', error);
|
||||
console.warn('[app-update] preparing the update asset failed:', error);
|
||||
throw new AppError('app_update_download_failed');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stageInstaller(
|
||||
release: LauncherRelease, manifest: LauncherReleaseManifest, target: string,
|
||||
async function stageArtifact(
|
||||
assetUrl: URL, source: LauncherRelease['source'], manifest: LauncherReleaseManifest | PortableReleaseManifest, target: string,
|
||||
report: (progress: AppUpdateProgress) => void,
|
||||
): Promise<void> {
|
||||
const partial = `${target}.partial`;
|
||||
@@ -151,12 +174,12 @@ async function stageInstaller(
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
});
|
||||
const response = await requestReleaseAsset(release.installer, deadline, release.source);
|
||||
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 installer size.'));
|
||||
done(new Error('The download is larger than the signed release size.'));
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
@@ -168,11 +191,11 @@ async function stageInstaller(
|
||||
},
|
||||
});
|
||||
await pipeline(releaseAssetChunks(response), monitor, createWriteStream(partial, { flags: 'wx' }), { signal: deadline });
|
||||
if (size !== manifest.size) throw new FeedUnreachableError('The installer download is incomplete.');
|
||||
if (hash.digest('hex') !== manifest.sha256) throw new Error('The installer download does not match the signed release.');
|
||||
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 installer download timed out.', { cause: error });
|
||||
if (deadline.aborted) throw new FeedUnreachableError('The update download timed out.', { cause: error });
|
||||
throw error;
|
||||
} finally {
|
||||
await unlink(partial).catch((error: NodeJS.ErrnoException) => {
|
||||
@@ -185,17 +208,23 @@ export function installAppUpdate(version: string, launcherBusy: () => boolean):
|
||||
return exclusively(async () => {
|
||||
const offer = selectedOffer(version);
|
||||
if (launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||
const path = stagedInstaller();
|
||||
if (!await matchesInstaller(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
||||
const path = stagedArtifact(offer.mode);
|
||||
if (!await matchesArtifact(path, offer.manifest)) throw new AppError('app_update_installer_invalid');
|
||||
const signal = AbortSignal.timeout(5000);
|
||||
if (await gameProcessRunning(signal) || launcherBusy()) throw new AppError('app_update_launcher_busy');
|
||||
try {
|
||||
if (offer.mode === 'portable') {
|
||||
const prepared = await preparePortableInstall(path, offer.manifest.version, updatesRoot());
|
||||
launchPortableUpdater(prepared);
|
||||
app.quit();
|
||||
return;
|
||||
}
|
||||
const installer = spawn(path, [], { cwd: dirname(path), detached: true, stdio: 'ignore', shell: false });
|
||||
await once(installer, 'spawn');
|
||||
installer.unref();
|
||||
app.quit();
|
||||
} catch (error) {
|
||||
console.warn('[app-update] starting the installer failed:', error);
|
||||
console.warn('[app-update] starting the update failed:', error);
|
||||
throw new AppError('app_update_install_failed');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,11 +3,16 @@ import { createReadStream } from 'node:fs';
|
||||
import { MAX_INSTALLER_BYTES } from '../../../shared/schemas/app-update.ts';
|
||||
|
||||
const SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher release v1\n', 'utf8');
|
||||
const PORTABLE_SIGNATURE_DOMAIN = Buffer.from('WTOffline launcher portable release v1\n', 'utf8');
|
||||
|
||||
export function launcherSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export function portableSignaturePayload(manifest: Uint8Array): Uint8Array {
|
||||
return Buffer.concat([PORTABLE_SIGNATURE_DOMAIN, manifest]);
|
||||
}
|
||||
|
||||
export async function installerDigest(path: string, limit = MAX_INSTALLER_BYTES): Promise<{ size: number; sha256: string }> {
|
||||
const hash = createHash('sha256');
|
||||
let size = 0;
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* In-place updater for portable (unpacked ZIP) launcher builds on Windows.
|
||||
*
|
||||
* Extraction and path validation happen while the launcher is still running so a bad archive or
|
||||
* read-only folder fails cleanly before quitting. Once staged, a detached PowerShell helper waits
|
||||
* for this process to exit, overwrites only files listed in the new portable inventory, removes
|
||||
* only obsolete files listed in the previous portable inventory (never touching unrelated user
|
||||
* files in the same folder), and restarts the updated executable.
|
||||
*/
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { z } from 'zod';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
export const PORTABLE_MARKER_FILE = 'portable-mode';
|
||||
export const PORTABLE_FILES_MANIFEST = 'portable-files.json';
|
||||
const LAUNCHER_EXECUTABLE = 'WTOffline Launcher.exe';
|
||||
const UNINSTALLER_EXECUTABLE = 'Uninstall WTOffline Launcher.exe';
|
||||
|
||||
const PortableInventorySchema = z.object({
|
||||
format: z.literal(1),
|
||||
version: z.string().min(1),
|
||||
files: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
|
||||
export interface PreparedPortableUpdate {
|
||||
readonly scriptPath: string;
|
||||
readonly planPath: string;
|
||||
readonly stagingDir: string;
|
||||
}
|
||||
|
||||
export interface PortableUpdatePlan {
|
||||
readonly pid: number;
|
||||
readonly installDir: string;
|
||||
readonly stagingDir: string;
|
||||
readonly archivePath: string;
|
||||
readonly logPath: string;
|
||||
readonly executable: string;
|
||||
readonly newFiles: readonly string[];
|
||||
readonly staleFiles: readonly string[];
|
||||
}
|
||||
|
||||
export function isPortableLauncher(isPackaged: boolean): boolean {
|
||||
if (!isPackaged || process.platform !== 'win32') return false;
|
||||
if (existsSync(join(process.resourcesPath, PORTABLE_MARKER_FILE))) return true;
|
||||
return !existsSync(join(dirname(process.execPath), UNINSTALLER_EXECUTABLE));
|
||||
}
|
||||
|
||||
/** Validate a POSIX-style relative path from a portable inventory against traversal or drive prefixes. */
|
||||
export function isSafePortableRelativePath(entry: string): boolean {
|
||||
if (!entry || entry.includes('\\') || entry.includes(':') || entry.startsWith('/')) return false;
|
||||
if (/[\0-\x1f]/.test(entry)) return false;
|
||||
const parts = entry.split('/');
|
||||
return parts.every((part) => part.length > 0 && part !== '.' && part !== '..');
|
||||
}
|
||||
|
||||
function resolveInside(root: string, relPosix: string): string {
|
||||
if (!isSafePortableRelativePath(relPosix)) throw new Error(`Unsafe portable path: ${relPosix}`);
|
||||
const target = resolve(root, ...relPosix.split('/'));
|
||||
const rel = relative(root, target);
|
||||
if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
|
||||
throw new Error(`Portable path escapes root: ${relPosix}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
async function readPortableInventory(resourcesDir: string): Promise<readonly string[] | null> {
|
||||
try {
|
||||
const raw = await readFile(join(resourcesDir, PORTABLE_FILES_MANIFEST), 'utf8');
|
||||
const parsed = PortableInventorySchema.parse(JSON.parse(raw));
|
||||
return parsed.files.filter(isSafePortableRelativePath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function assertWritableFolder(folder: string): Promise<void> {
|
||||
const probe = join(folder, `.wto-update-probe-${randomUUID()}.tmp`);
|
||||
await writeFile(probe, '', { flag: 'wx' });
|
||||
await rm(probe, { force: true });
|
||||
}
|
||||
|
||||
async function extractPortableArchive(zipPath: string, stagingDir: string, updatesRoot: string): Promise<void> {
|
||||
const extractScriptPath = join(updatesRoot, `extract-portable-${randomUUID()}.ps1`);
|
||||
const script = [
|
||||
'param([string]$ZipPath, [string]$DestDir)',
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'Add-Type -AssemblyName System.IO.Compression.FileSystem',
|
||||
'$destFull = [System.IO.Path]::GetFullPath($DestDir)',
|
||||
'if (-not $destFull.EndsWith([System.IO.Path]::DirectorySeparatorChar)) { $destFull += [System.IO.Path]::DirectorySeparatorChar }',
|
||||
'$zip = [System.IO.Compression.ZipFile]::OpenRead($ZipPath)',
|
||||
'try {',
|
||||
' foreach ($entry in $zip.Entries) {',
|
||||
' $name = $entry.FullName',
|
||||
' if ([string]::IsNullOrEmpty($name) -or $name.EndsWith("/") -or $name.EndsWith("\\")) { continue }',
|
||||
' if ($name.Contains("..") -or $name.StartsWith("/") -or $name.StartsWith("\\") -or $name.Contains(":")) {',
|
||||
' throw "Unsafe zip entry: $name"',
|
||||
' }',
|
||||
' $target = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($destFull, $name))',
|
||||
' if (-not $target.StartsWith($destFull, [System.StringComparison]::OrdinalIgnoreCase)) {',
|
||||
' throw "Zip entry escapes destination: $name"',
|
||||
' }',
|
||||
' $parent = [System.IO.Path]::GetDirectoryName($target)',
|
||||
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||
' [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $true)',
|
||||
' }',
|
||||
'} finally {',
|
||||
' $zip.Dispose()',
|
||||
'}',
|
||||
].join('\r\n');
|
||||
// UTF-8 BOM ensures Windows PowerShell 5.1 decodes non-ASCII paths properly.
|
||||
await writeFile(extractScriptPath, `\uFEFF${script}\r\n`, 'utf8');
|
||||
try {
|
||||
await execute('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', extractScriptPath, zipPath, stagingDir,
|
||||
], { windowsHide: true, timeout: 180_000 });
|
||||
} finally {
|
||||
await rm(extractScriptPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function buildPortableApplyScript(): string {
|
||||
return [
|
||||
'param([string]$PlanPath)',
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'$utf8 = New-Object System.Text.UTF8Encoding($false)',
|
||||
'$plan = [System.IO.File]::ReadAllText($PlanPath, $utf8) | ConvertFrom-Json',
|
||||
'function Write-Log([string]$msg) {',
|
||||
' try {',
|
||||
' $line = "$(Get-Date -Format o) $msg`r`n"',
|
||||
' [System.IO.File]::AppendAllText($plan.logPath, $line, $utf8)',
|
||||
' } catch {}',
|
||||
'}',
|
||||
'try {',
|
||||
' Write-Log "Starting portable update in $($plan.installDir) (waiting for pid $($plan.pid))"',
|
||||
' $deadline = (Get-Date).AddSeconds(30)',
|
||||
' while ((Get-Date) -lt $deadline) {',
|
||||
' if (-not (Get-Process -Id $plan.pid -ErrorAction SilentlyContinue)) { break }',
|
||||
' Start-Sleep -Milliseconds 200',
|
||||
' }',
|
||||
' Start-Sleep -Milliseconds 400',
|
||||
' foreach ($rel in $plan.newFiles) {',
|
||||
' $winRel = $rel -replace "/", "\\"',
|
||||
' $src = [System.IO.Path]::Combine($plan.stagingDir, $winRel)',
|
||||
' $dst = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||
' $parent = [System.IO.Path]::GetDirectoryName($dst)',
|
||||
' if ($parent) { [System.IO.Directory]::CreateDirectory($parent) | Out-Null }',
|
||||
' $copied = $false',
|
||||
' for ($attempt = 1; $attempt -le 20; $attempt++) {',
|
||||
' try {',
|
||||
' if ([System.IO.File]::Exists($dst)) { [System.IO.File]::SetAttributes($dst, [System.IO.FileAttributes]::Normal) }',
|
||||
' [System.IO.File]::Copy($src, $dst, $true)',
|
||||
' $copied = $true',
|
||||
' break',
|
||||
' } catch {',
|
||||
' if ($attempt -eq 20) { throw }',
|
||||
' Start-Sleep -Milliseconds 300',
|
||||
' }',
|
||||
' }',
|
||||
' if (-not $copied) { throw "Failed to copy $rel" }',
|
||||
' }',
|
||||
' $installRoot = [System.IO.Path]::GetFullPath($plan.installDir).TrimEnd("\\")',
|
||||
' foreach ($rel in $plan.staleFiles) {',
|
||||
' $winRel = $rel -replace "/", "\\"',
|
||||
' $old = [System.IO.Path]::Combine($plan.installDir, $winRel)',
|
||||
' if ([System.IO.File]::Exists($old)) {',
|
||||
' try {',
|
||||
' [System.IO.File]::SetAttributes($old, [System.IO.FileAttributes]::Normal)',
|
||||
' [System.IO.File]::Delete($old)',
|
||||
' } catch { Write-Log "Could not remove stale file ${rel}: $_" }',
|
||||
' }',
|
||||
' $dir = [System.IO.Path]::GetDirectoryName($old)',
|
||||
' while ($dir -and ($dir.TrimEnd("\\") -ne $installRoot)) {',
|
||||
' if (-not [System.IO.Directory]::Exists($dir)) { break }',
|
||||
' $entries = [System.IO.Directory]::GetFileSystemEntries($dir)',
|
||||
' if ($entries.Length -gt 0) { break }',
|
||||
' try { [System.IO.Directory]::Delete($dir) } catch { break }',
|
||||
' $dir = [System.IO.Path]::GetDirectoryName($dir)',
|
||||
' }',
|
||||
' }',
|
||||
' Write-Log "Replaced $($plan.newFiles.Count) files and cleaned $($plan.staleFiles.Count) obsolete files."',
|
||||
' if ($plan.stagingDir -and [System.IO.Directory]::Exists($plan.stagingDir)) {',
|
||||
' try { Remove-Item -LiteralPath $plan.stagingDir -Recurse -Force } catch {}',
|
||||
' }',
|
||||
' if ($plan.archivePath -and [System.IO.File]::Exists($plan.archivePath)) {',
|
||||
' try { Remove-Item -LiteralPath $plan.archivePath -Force } catch {}',
|
||||
' }',
|
||||
' if ([System.IO.File]::Exists($PlanPath)) {',
|
||||
' try { Remove-Item -LiteralPath $PlanPath -Force } catch {}',
|
||||
' }',
|
||||
' $exe = [System.IO.Path]::Combine($plan.installDir, $plan.executable)',
|
||||
' if ([System.IO.File]::Exists($exe)) {',
|
||||
' Start-Process -FilePath $exe -WorkingDirectory $plan.installDir',
|
||||
' Write-Log "Relaunched $exe"',
|
||||
' }',
|
||||
'} catch {',
|
||||
' Write-Log "Portable update failed: $_"',
|
||||
' exit 1',
|
||||
'}',
|
||||
].join('\r\n');
|
||||
}
|
||||
|
||||
export async function preparePortableInstall(
|
||||
archivePath: string,
|
||||
expectedVersion: string,
|
||||
updatesRoot: string,
|
||||
installDir = dirname(process.execPath),
|
||||
resourcesDir = process.resourcesPath,
|
||||
parentPid = process.pid,
|
||||
): Promise<PreparedPortableUpdate> {
|
||||
await assertWritableFolder(installDir);
|
||||
await mkdir(updatesRoot, { recursive: true });
|
||||
const stagingDir = join(updatesRoot, `portable-staging-${randomUUID()}`);
|
||||
await mkdir(stagingDir, { recursive: true });
|
||||
try {
|
||||
await extractPortableArchive(archivePath, stagingDir, updatesRoot);
|
||||
|
||||
const stagedInventoryRaw = await readFile(join(stagingDir, 'resources', PORTABLE_FILES_MANIFEST), 'utf8');
|
||||
const stagedInventory = PortableInventorySchema.parse(JSON.parse(stagedInventoryRaw));
|
||||
if (stagedInventory.version !== expectedVersion) {
|
||||
throw new Error(`Portable archive inventory version ${stagedInventory.version} does not match ${expectedVersion}.`);
|
||||
}
|
||||
const newFiles = stagedInventory.files;
|
||||
const newSet = new Set(newFiles);
|
||||
const requiredEntries = [
|
||||
LAUNCHER_EXECUTABLE,
|
||||
`resources/${PORTABLE_MARKER_FILE}`,
|
||||
`resources/${PORTABLE_FILES_MANIFEST}`,
|
||||
];
|
||||
for (const required of requiredEntries) {
|
||||
if (!newSet.has(required)) throw new Error(`Portable archive inventory is missing ${required}.`);
|
||||
}
|
||||
for (const rel of newFiles) {
|
||||
const stagedPath = resolveInside(stagingDir, rel);
|
||||
const stats = await lstat(stagedPath);
|
||||
if (!stats.isFile()) throw new Error(`Staged portable entry is not a file: ${rel}`);
|
||||
}
|
||||
|
||||
const oldFiles = await readPortableInventory(resourcesDir);
|
||||
const staleFiles = oldFiles
|
||||
? oldFiles.filter((rel) => !newSet.has(rel) && isSafePortableRelativePath(rel))
|
||||
: [];
|
||||
|
||||
const planPath = join(updatesRoot, `portable-plan-${randomUUID()}.json`);
|
||||
const scriptPath = join(updatesRoot, 'apply-portable-update.ps1');
|
||||
const plan: PortableUpdatePlan = {
|
||||
pid: parentPid,
|
||||
installDir: resolve(installDir),
|
||||
stagingDir,
|
||||
archivePath,
|
||||
logPath: join(updatesRoot, 'portable-update.log'),
|
||||
executable: LAUNCHER_EXECUTABLE,
|
||||
newFiles,
|
||||
staleFiles,
|
||||
};
|
||||
await writeFile(planPath, `${JSON.stringify(plan, null, 2)}\n`, 'utf8');
|
||||
await writeFile(scriptPath, `\uFEFF${buildPortableApplyScript()}\r\n`, 'utf8');
|
||||
return { scriptPath, planPath, stagingDir };
|
||||
} catch (error) {
|
||||
await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function launchPortableUpdater(prepared: PreparedPortableUpdate): void {
|
||||
const child = spawn('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass',
|
||||
'-File', prepared.scriptPath, prepared.planPath,
|
||||
], {
|
||||
cwd: dirname(prepared.scriptPath),
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
});
|
||||
child.unref();
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
compareAppVersions, comparePackVersions, packFileNames, packVersionOfTag, PatchPackError, patchPackTuning,
|
||||
} from '@wto/patcher';
|
||||
import { z } from 'zod';
|
||||
import { AppReleaseVersionSchema, launcherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||
import { AppReleaseVersionSchema, launcherReleaseFiles, portableLauncherReleaseFiles } from '@shared/schemas/app-update.ts';
|
||||
import { releaseRepositoryUrl } from '@shared/update-source.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { FeedUnreachableError, UPDATE_USER_AGENT } from './release-assets.ts';
|
||||
@@ -17,6 +17,12 @@ export interface ReleaseSource {
|
||||
readonly githubDownloads: URL | null;
|
||||
}
|
||||
|
||||
export interface PortableReleaseAssets {
|
||||
readonly archive: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
}
|
||||
|
||||
export interface LauncherRelease {
|
||||
readonly source: ReleaseSource;
|
||||
readonly version: string;
|
||||
@@ -24,6 +30,7 @@ export interface LauncherRelease {
|
||||
readonly installer: URL;
|
||||
readonly manifest: URL;
|
||||
readonly signature: URL;
|
||||
readonly portable?: PortableReleaseAssets;
|
||||
}
|
||||
|
||||
export interface PackReleaseFiles {
|
||||
@@ -226,12 +233,27 @@ function launcherRelease(entry: Record<string, unknown>, version: string, source
|
||||
if (!parsed.success) return null;
|
||||
const { assets, body } = parsed.data;
|
||||
const names = launcherReleaseFiles(version);
|
||||
const portableNames = portableLauncherReleaseFiles(version);
|
||||
const urls = assetUrls(assets, `v${version}`, source);
|
||||
const installer = urls.get(names.installer);
|
||||
const manifest = urls.get(names.manifest);
|
||||
const signature = urls.get(names.signature);
|
||||
if (!installer || !manifest || !signature) return null;
|
||||
return { source, version, notes: body?.trim().slice(0, 1600) ?? '', installer, manifest, signature };
|
||||
const portableArchive = urls.get(portableNames.archive);
|
||||
const portableManifest = urls.get(portableNames.manifest);
|
||||
const portableSignature = urls.get(portableNames.signature);
|
||||
const portable = portableArchive && portableManifest && portableSignature
|
||||
? { archive: portableArchive, manifest: portableManifest, signature: portableSignature }
|
||||
: undefined;
|
||||
return {
|
||||
source,
|
||||
version,
|
||||
notes: body?.trim().slice(0, 1600) ?? '',
|
||||
installer,
|
||||
manifest,
|
||||
signature,
|
||||
...(portable ? { portable } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function packRelease(release: Record<string, unknown>, version: string, tag: string, source: ReleaseSource): PackReleaseFiles | null {
|
||||
|
||||
@@ -9,6 +9,11 @@ export function launcherReleaseFiles(version: string) {
|
||||
return { installer: `${base}.exe`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export function portableLauncherReleaseFiles(version: string) {
|
||||
const base = `wtoffline-launcher-${AppReleaseVersionSchema.parse(version)}-win-x64-portable`;
|
||||
return { archive: `${base}.zip`, manifest: `${base}.manifest.json`, signature: `${base}.manifest.json.sig` };
|
||||
}
|
||||
|
||||
export const LauncherReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-release'),
|
||||
format: z.literal(1),
|
||||
@@ -19,6 +24,16 @@ export const LauncherReleaseManifest = z.strictObject({
|
||||
});
|
||||
export type LauncherReleaseManifest = z.output<typeof LauncherReleaseManifest>;
|
||||
|
||||
export const PortableReleaseManifest = z.strictObject({
|
||||
kind: z.literal('wto-launcher-portable-release'),
|
||||
format: z.literal(1),
|
||||
version: AppReleaseVersionSchema,
|
||||
platform: z.literal('win32-x64'),
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
});
|
||||
export type PortableReleaseManifest = z.output<typeof PortableReleaseManifest>;
|
||||
|
||||
const AppUpdateReleaseSchema = z.object({
|
||||
version: AppReleaseVersionSchema,
|
||||
size: z.number().int().positive().max(MAX_INSTALLER_BYTES),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { cp, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, relative, resolve, sep } from 'node:path';
|
||||
import { Arch, build, Platform } from 'electron-builder';
|
||||
import { launcherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
import { launcherReleaseFiles, portableLauncherReleaseFiles } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
import { formatManifest, MANIFEST_FILE, PATCH_PACK_FORMAT, recordedGameVersions } from '../packages/patcher/src/index.ts';
|
||||
|
||||
const repository = resolve(import.meta.dirname, '..');
|
||||
@@ -97,9 +97,13 @@ async function cleanInstallerOutput(version: string): Promise<void> {
|
||||
if (relative(output, root) !== '') throw new Error('The installer output directory is redirected.');
|
||||
|
||||
const { installer, manifest, signature } = launcherReleaseFiles(version);
|
||||
const portable = `wtoffline-launcher-${version}-win-x64-portable.zip`;
|
||||
const portable = portableLauncherReleaseFiles(version);
|
||||
const legacy = `WTOffline Launcher Setup ${version}.exe`;
|
||||
const names = [installer, installer + '.blockmap', portable, legacy, legacy + '.blockmap', manifest, signature, 'win-unpacked'];
|
||||
const names = [
|
||||
installer, installer + '.blockmap',
|
||||
portable.archive, portable.manifest, portable.signature,
|
||||
legacy, legacy + '.blockmap', manifest, signature, 'win-unpacked',
|
||||
];
|
||||
const artifacts = [];
|
||||
for (const name of names) {
|
||||
const path = join(root, name);
|
||||
@@ -161,17 +165,55 @@ async function main(): Promise<void> {
|
||||
},
|
||||
});
|
||||
for (const artifact of artifacts) console.info(artifact);
|
||||
const portable = join(output, `wtoffline-launcher-${manifest.version}-win-x64-portable.zip`);
|
||||
const unpackedGlob = join(output, 'win-unpacked', '*');
|
||||
execFileSync('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-Command',
|
||||
`Compress-Archive -Path "${unpackedGlob}" -DestinationPath "${portable}" -Force`,
|
||||
], { cwd: repository, stdio: 'inherit', windowsHide: true });
|
||||
console.info(portable);
|
||||
const portablePath = await packagePortableArchive(output, manifest.version);
|
||||
console.info(portablePath);
|
||||
} finally {
|
||||
const actual = await realpath(stage);
|
||||
if (actual === stage && dirname(actual) === temp) await rm(stage, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function listRelativeFiles(root: string): Promise<string[]> {
|
||||
const files: string[] = [];
|
||||
const pending = [root];
|
||||
while (pending.length) {
|
||||
const folder = pending.pop()!;
|
||||
for (const entry of await readdir(folder, { withFileTypes: true })) {
|
||||
const fullPath = join(folder, entry.name);
|
||||
if (entry.isDirectory()) pending.push(fullPath);
|
||||
else if (entry.isFile()) files.push(relative(root, fullPath).split(sep).join('/'));
|
||||
}
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Package win-unpacked into the portable archive with a portable marker and an inventory of
|
||||
* launcher-owned files so portable in-place updates only replace launcher files and never remove
|
||||
* unrelated user files in the extraction folder.
|
||||
*/
|
||||
async function packagePortableArchive(outputFolder: string, version: string): Promise<string> {
|
||||
const unpacked = join(outputFolder, 'win-unpacked');
|
||||
const resources = join(unpacked, 'resources');
|
||||
const markerPath = join(resources, 'portable-mode');
|
||||
const inventoryPath = join(resources, 'portable-files.json');
|
||||
const portable = join(outputFolder, portableLauncherReleaseFiles(version).archive);
|
||||
try {
|
||||
await writeFile(markerPath, 'portable\n', 'utf8');
|
||||
await writeFile(inventoryPath, '', 'utf8');
|
||||
const ownedFiles = await listRelativeFiles(unpacked);
|
||||
await writeFile(inventoryPath, `${JSON.stringify({ format: 1, version, files: ownedFiles }, null, 2)}\n`, 'utf8');
|
||||
const unpackedGlob = join(unpacked, '*').replaceAll("'", "''");
|
||||
const destination = portable.replaceAll("'", "''");
|
||||
execFileSync('powershell.exe', [
|
||||
'-NoProfile', '-NonInteractive', '-Command',
|
||||
`Compress-Archive -Path '${unpackedGlob}' -DestinationPath '${destination}' -Force`,
|
||||
], { cwd: repository, stdio: 'inherit', windowsHide: true });
|
||||
return portable;
|
||||
} finally {
|
||||
await rm(markerPath, { force: true }).catch(() => undefined);
|
||||
await rm(inventoryPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -1,15 +1,21 @@
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { access, readFile, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { packSigningPublicKey, signEd25519, verifyEd25519 } from '@wto/patcher';
|
||||
import { installerDigest, launcherSignaturePayload } from '../apps/launcher/src/main/services/app-update/installer-integrity.ts';
|
||||
import { launcherReleaseFiles, LauncherReleaseManifest } from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
import {
|
||||
installerDigest, launcherSignaturePayload, portableSignaturePayload,
|
||||
} from '../apps/launcher/src/main/services/app-update/installer-integrity.ts';
|
||||
import {
|
||||
launcherReleaseFiles, LauncherReleaseManifest,
|
||||
portableLauncherReleaseFiles, PortableReleaseManifest,
|
||||
} from '../apps/launcher/src/shared/schemas/app-update.ts';
|
||||
|
||||
const repository = resolve(import.meta.dirname, '..');
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { version } = JSON.parse(await readFile(join(repository, 'apps', 'launcher', 'package.json'), 'utf8')) as { version: string };
|
||||
const files = launcherReleaseFiles(version);
|
||||
const installer = join(repository, 'build', 'windows-installer', files.installer);
|
||||
const outputFolder = join(repository, 'build', 'windows-installer');
|
||||
const installer = join(outputFolder, files.installer);
|
||||
const privateKey = process.env['PATCH_SIGNING_KEY'];
|
||||
const publicKey = packSigningPublicKey();
|
||||
if (!privateKey || !publicKey) throw new Error('The project signing key pair is required.');
|
||||
@@ -29,6 +35,38 @@ async function main(): Promise<void> {
|
||||
await writeFile(join(folder, files.manifest), bytes);
|
||||
await writeFile(join(folder, files.signature), signature, 'utf8');
|
||||
for (const file of Object.values(files)) console.info(join(folder, file));
|
||||
|
||||
// Sign the portable archive with a separate manifest so older launchers whose installer manifest
|
||||
// schema is strict keep validating releases without error.
|
||||
const portableFiles = portableLauncherReleaseFiles(version);
|
||||
const portableArchive = join(folder, portableFiles.archive);
|
||||
if (await fileExists(portableArchive)) {
|
||||
const portableManifest = PortableReleaseManifest.parse({
|
||||
kind: 'wto-launcher-portable-release',
|
||||
format: 1,
|
||||
platform: 'win32-x64',
|
||||
version,
|
||||
...await installerDigest(portableArchive),
|
||||
});
|
||||
const portableBytes = Buffer.from(JSON.stringify(portableManifest, null, 2) + '\n', 'utf8');
|
||||
const portablePayload = portableSignaturePayload(portableBytes);
|
||||
const portableSig = signEd25519(portablePayload, privateKey);
|
||||
if (!verifyEd25519(portablePayload, portableSig, publicKey)) {
|
||||
throw new Error('The portable release key does not match the bundled public key.');
|
||||
}
|
||||
await writeFile(join(folder, portableFiles.manifest), portableBytes);
|
||||
await writeFile(join(folder, portableFiles.signature), portableSig, 'utf8');
|
||||
for (const file of Object.values(portableFiles)) console.info(join(folder, file));
|
||||
}
|
||||
}
|
||||
|
||||
async function fileExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
Reference in new issue
Block a user