fix(copies): honor confirmed Steam locations

Bind confirmation to the selected copy and data paths throughout installation, launch, and maintenance. Validate redirected runtime data paths and recheck original files before refreshing an in-place backup.

Verified by type checking and build. The acceptance checklist covers directory links and Steam confirmation.
This commit is contained in:
N0VAN0M4LY committed 2026-11-30 15:23:17 +08:00
1 parent 84158f719d
commit 5a78b1fdf8
28 files changed
+813 -459

No files matched your search

+6 -2
View File
@@ -1,5 +1,5 @@
import { app, BrowserWindow, dialog, shell } from 'electron';
import { patchFeatures, recordedGameVersions } from '@wto/patcher';
import { isInSteamLibrary, patchFeatures, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdate } from '../services/app-update/app-update.ts';
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
@@ -12,7 +12,7 @@ import { inspectGameFolder, requireFolder } from '../services/game-folder/inspec
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { changeDecalSource, decalImportInProgress } from '../services/install/decals.ts';
import { cancelInstall, checkGameFolder, installGame, installationInProgress } from '../services/install/install-game.ts';
import { createCopyDraft, listCopies, readInstallRecord, renameCopy, setCurrentCopy } from '../services/install/install-record.ts';
import { canonicalCopyPath, createCopyDraft, 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 { activePatchSet, applyPackUpdate, checkPackUpdate, revertToBundledPatchSet } from '../services/patch-pack/pack-update.ts';
@@ -64,6 +64,10 @@ export function registerIpcHandlers(): void {
handle('install:prepareCopy', () => createCopyDraft());
handle('install:inspectGameFolder', ({ path }) => inspectGameFolder(path));
handle('install:inspectTargetFolder', ({ path, stockPath }) => inspectTargetFolder(path, stockPath));
handle('install:inspectDataFolder', async ({ path }) => {
const resolved = await canonicalCopyPath(path);
return { path: resolved, inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved) };
});
handle('install:measureFolder', async ({ path, version }) => {
await requireFolder(path);
try {
@@ -0,0 +1,208 @@
import type { BigIntStats } from 'node:fs';
import { copyFile, lstat, mkdir } from 'node:fs/promises';
import { dirname, join, normalize } from 'node:path';
import { compareVersions, GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
export type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
export async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
export function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
}
export async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
return changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
applying();
return { replace: files, remove: [] };
}, listCopies);
}
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const game = await readSource(record);
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
const dataPath = await canonicalCopyPath(record.dataPath);
const plan = await planCopy(game.path);
const inventory = plan.files.map((entry) => entry.relativePath);
const found = new Set(inventory.map(key));
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
const copy = await planChangedFiles(game.path, root, dataPath, plan, linkedPaths, signal);
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted();
return changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes);
let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('copying', doneBytes, copy.totalBytes);
}
});
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
signal.throwIfAborted();
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
}
await verifySourceFiles(game.path, plan, signal);
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return { replace: [...copy.files.map(({ relativePath }) => relativePath), ...stockFiles], remove };
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(linked.length ? { hardlinkedFiles: [] } : {}),
})));
}
async function planChangedFiles(
source: string, root: string, dataPath: string, plan: CopyPlan, linked: ReadonlySet<string>, signal: AbortSignal,
): Promise<CopyPlan> {
const changed: CopyPlan['files'][number][] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const old = await fileInfo(target);
if (linked.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(join(source, file.relativePath), signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
return {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
};
}
async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSignal): Promise<void> {
for (const file of plan.files) {
signal.throwIfAborted();
const info = await fileInfo(join(source, file.relativePath));
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
throw new AppError('maintenance_source_changed');
}
}
}
export async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
return record.method === 'copy' && source.version === record.gameVersion &&
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
}
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const source = await readSource(record);
if (!source || !await convertibleCopy(record, source, root) ||
(await inspectGameFolder(root)).version !== source.version) {
throw new AppError('hardlink_unavailable');
}
const plan = await planCopy(source.path);
const candidates = plan.files.flatMap(({ relativePath, bytes }) => {
const evidence = hardlinkResource(source.version, relativePath, bytes);
return evidence ? [{ relativePath, evidence }] : [];
});
const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
return changeCopyFiles(root, async (incoming) => {
const replacements: string[] = [];
const unchanged = new Map<string, BigIntStats>();
let checked = 0;
let matches = 0;
let lastReport = 0;
report('checking', 0, total);
for (const { relativePath, evidence } of candidates) {
const target = await scopedInstallFile(dataPath, root, relativePath);
const original = join(source.path, relativePath);
const copyStamp = await verifyHardlinkResource(target, evidence, signal);
const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null;
if (copyStamp && sourceStamp) {
if (!sameResource(copyStamp, sourceStamp)) {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp);
unchanged.set(target, copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
}
linked.set(key(relativePath), relativePath);
matches += 1;
}
checked += evidence.bytes;
if (checked === total || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('checking', checked, total);
}
}
if (!matches) throw new AppError('hardlink_no_match');
await verifyStagedLinks(record, source.version, unchanged, signal);
signal.throwIfAborted();
report('applying', total, total);
return { replace: replacements, remove: [] };
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
}
async function verifyStagedLinks(
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
): Promise<void> {
signal.throwIfAborted();
if ((await readSource(record))?.version !== version) throw new AppError('hardlink_file_changed');
for (const [path, stamp] of unchanged) {
signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
}
function key(path: string): string {
const name = normalize(path);
return process.platform === 'win32' ? name.toLowerCase() : name;
}
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
const target = await stagedPath(root, name);
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
copyPathContains(dataPath, target)) {
throw new AppError('maintenance_location');
}
return target;
}
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
await mkdir(dirname(target), { recursive: true });
const source = join(folder, file);
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
await copyFile(source, target);
}
@@ -1,23 +1,19 @@
import type { BigIntStats } from 'node:fs';
import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path';
import { readdir, rm } from 'node:fs/promises';
import { isAbsolute, join, parse, relative } from 'node:path';
import { app } from 'electron';
import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts';
import { installationInProgress } from '../install/install-game.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, type Report } from './copy-file-maintenance.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null;
@@ -32,10 +28,15 @@ export function cancelMaintenance(): void {
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
const record = await requireCopy(id);
const source = await readSource(record);
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
return {
sourceVersion: source?.version ?? null,
updateAvailable: isNewer(source, record.gameVersion),
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
};
}
@@ -50,31 +51,14 @@ export async function maintainCopy(
};
current = job;
const signal = job.stop.signal;
const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => {
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
if (phase === 'applying') job.interruptible = false;
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
};
report('checking');
try {
const record = await requireCopy(request.id);
const root = await checkedRoot(record);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
switch (request.operation) {
case 'check':
return await recordCheck(record, record.stockBackupPath);
case 'repair':
return await repair(record, root, () => report('applying'));
case 'update':
return await updateFromSource(record, root, signal, report);
case 'compact':
return await compactCopy(record, root, signal, report);
case 'delete':
report('applying');
return await remove(record, root, request.deleteData);
}
report('checking');
return await performMaintenance(request, signal, report);
} catch (error) {
if (signal.aborted) throw new AppError('maintenance_cancelled');
if (error instanceof AppError) throw error;
@@ -85,29 +69,51 @@ export async function maintainCopy(
}
}
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request;
const record = await requireCopy(id);
const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath);
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
if (operation !== 'confirm-steam' && operation !== 'delete' && needsConfirmation) {
throw new AppError('launch_steam_confirmation_required');
}
switch (operation) {
case 'confirm-steam':
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
throw new AppError('maintenance_location');
}
if (!needsConfirmation) return listCopies();
return updateCopyRecord(id, (copy) => ({
...copy, steamLibraryConfirmation: { copyPath: root, dataPath },
}));
case 'check':
return recordCheck(record, record.stockBackupPath);
case 'repair':
return repair(record, root, () => report('applying'));
case 'update':
return updateFromSource(record, root, signal, report);
case 'compact':
return compactCopy(record, root, signal, report);
case 'delete':
report('applying');
return remove(record, root, request.deleteData);
}
}
async function requireCopy(id: string): Promise<InstallRecord> {
const record = (await listCopies()).copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
return record;
}
async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
}
async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath);
const root = await safeFolder(record.copyPath, true);
const backup = await canonicalCopyPath(record.stockBackupPath);
if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location');
if (record.sourcePath) {
@@ -117,14 +123,15 @@ async function checkedRoot(record: InstallRecord): Promise<string> {
return root;
}
async function safeFolder(path: string): Promise<string> {
async function safeFolder(path: string, steamAllowed = false): Promise<string> {
const root = await canonicalCopyPath(path);
if (!isAbsolute(path) || root === parse(root).root || isInSteamLibrary(root) ||
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
copyPathContains(root, await canonicalCopyPath(app.getAppPath())) ||
copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) {
throw new AppError('maintenance_location');
}
if ((await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
return root;
}
@@ -141,169 +148,12 @@ async function recordCheck(record: InstallRecord, folder: string): Promise<Copie
}));
}
async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
return changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
applying();
return { replace: files, remove: [] };
}, listCopies);
}
type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const game = await readSource(record);
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
const dataPath = await canonicalCopyPath(record.dataPath);
const plan = await planCopy(game.path);
const inventory = plan.files.map((entry) => entry.relativePath);
const found = new Set(inventory.map(key));
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
const changed: CopyPlan['files'][number][] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const old = await fileInfo(target);
if (linkedPaths.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(join(game.path, file.relativePath), signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted();
const copy: CopyPlan = {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
};
return changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes);
let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('copying', doneBytes, copy.totalBytes);
}
});
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
signal.throwIfAborted();
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
}
for (const file of plan.files) {
signal.throwIfAborted();
const info = await fileInfo(join(game.path, file.relativePath));
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
throw new AppError('maintenance_source_changed');
}
}
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return { replace: [...changed.map(({ relativePath }) => relativePath), ...stockFiles], remove };
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(linked.length ? { hardlinkedFiles: [] } : {}),
})));
}
function key(path: string): string {
const name = normalize(path);
return process.platform === 'win32' ? name.toLowerCase() : name;
}
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
const target = await stagedPath(root, name);
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
copyPathContains(dataPath, target)) {
throw new AppError('maintenance_location');
}
return target;
}
async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
return record.method === 'copy' && source.version === record.gameVersion &&
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
}
async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const source = await readSource(record);
if (!source || !await convertibleCopy(record, source, root) ||
(await inspectGameFolder(root)).version !== source.version) {
throw new AppError('hardlink_unavailable');
}
const plan = await planCopy(source.path);
const candidates = plan.files.flatMap(({ relativePath, bytes }) => {
const evidence = hardlinkResource(source.version, relativePath, bytes);
return evidence ? [{ relativePath, evidence }] : [];
});
const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
return changeCopyFiles(root, async (incoming) => {
const replacements: string[] = [];
const unchanged = new Map<string, BigIntStats>();
let checked = 0;
let matches = 0;
let lastReport = 0;
report('checking', 0, total);
for (const { relativePath, evidence } of candidates) {
const target = await scopedInstallFile(dataPath, root, relativePath);
const original = join(source.path, relativePath);
const copyStamp = await verifyHardlinkResource(target, evidence, signal);
const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null;
if (copyStamp && sourceStamp) {
if (!sameResource(copyStamp, sourceStamp)) {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp);
unchanged.set(target, copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
}
linked.set(key(relativePath), relativePath);
matches += 1;
}
checked += evidence.bytes;
if (checked === total || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('checking', checked, total);
}
}
if (!matches) throw new AppError('hardlink_no_match');
signal.throwIfAborted();
if ((await readSource(record))?.version !== source.version) throw new AppError('hardlink_file_changed');
for (const [path, stamp] of unchanged) {
signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
signal.throwIfAborted();
report('applying', total, total);
return { replace: replacements, remove: [] };
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
}
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
await mkdir(dirname(target), { recursive: true });
const source = join(folder, file);
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
await copyFile(source, target);
}
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) {
if (deleteData) throw new AppError('maintenance_location');
return removeCopyRecord(record.id);
}
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
@@ -1,4 +1,4 @@
import { access, readFile, stat } from 'node:fs/promises';
import { access, readFile, realpath, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { executableVersion, GAME_FILES, isInSteamLibrary, recordedGameVersions } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
@@ -11,18 +11,20 @@ import { resourcePaths } from '../resources/resource-paths.ts';
*/
export async function inspectGameFolder(path: string): Promise<GameFolderInspection> {
await requireFolder(path);
const resolved = await realpath(path);
const required = Object.values(GAME_FILES);
const missingFiles: string[] = [];
for (const file of required) {
if (!(await exists(join(path, file)))) missingFiles.push(file);
if (!(await exists(join(resolved, file)))) missingFiles.push(file);
}
const resources = resourcePaths();
return {
path,
resolvedPath: resolved,
missingFiles,
version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(path, GAME_FILES.executable)),
version: missingFiles.includes(GAME_FILES.executable) ? null : await readVersion(join(resolved, GAME_FILES.executable)),
verifiedVersions: recordedGameVersions(resources.patches),
inSteamLibrary: isInSteamLibrary(path),
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(resolved),
};
}
@@ -1,19 +1,20 @@
import { readdir, realpath, stat, statfs } from 'node:fs/promises';
import { readdir, stat, statfs } from 'node:fs/promises';
import { dirname, relative, resolve, isAbsolute } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import type { TargetFolderInspection } from '@shared/schemas/install.ts';
import { canonicalCopyPath } from '../install/install-record.ts';
/**
* Look at the folder the player chose for the game copy (install by copying): it must be new or
* empty, must not overlap the stock installation, and the drive must have room. Only reads.
*/
export async function inspectTargetFolder(path: string, stockPath: string): Promise<TargetFolderInspection> {
const target = await canonical(path);
const stock = await canonical(stockPath);
const [target, stock] = await Promise.all([canonicalCopyPath(path), canonicalCopyPath(stockPath)]);
return {
path,
resolvedPath: target,
problem: await targetProblem(target, stock),
inSteamLibrary: isInSteamLibrary(target),
inSteamLibrary: isInSteamLibrary(path) || isInSteamLibrary(target),
freeBytes: await freeBytes(target),
sameDriveAsStock: await sameVolume(target, stock),
};
@@ -65,15 +66,3 @@ export async function freeBytes(path: string): Promise<number | null> {
}
}
}
/** The real path of the nearest existing part, with the rest appended as given. */
async function canonical(path: string): Promise<string> {
const absolute = resolve(path);
try {
return await realpath(absolute);
} catch {
const parent = dirname(absolute);
if (parent === absolute) return absolute;
return resolve(await canonical(parent), relative(parent, absolute));
}
}
@@ -17,7 +17,7 @@ import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
* own missions. The offline copy does not take the online game's data (working rules 18); the
* game creates these folders again when it needs them.
*/
const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
export const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
interface CopyEntry {
readonly relativePath: string;
@@ -0,0 +1,18 @@
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { AppError } from '@shared/errors.ts';
/** A data tree must keep the server's saves, logs and caches inside the selected folder. */
export async function requireUnredirectedData(root: string): Promise<void> {
const folders = [root];
for (let folder = folders.pop(); folder !== undefined; folder = folders.pop()) {
const entries = await readdir(folder, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {
if (folder === root && error.code === 'ENOENT') return [];
throw error;
});
for (const entry of entries) {
if (entry.isSymbolicLink()) throw new AppError('launch_location');
if (entry.isDirectory()) folders.push(join(folder, entry.name));
}
}
}
@@ -4,7 +4,7 @@ import { dirname, isAbsolute, join, relative } from 'node:path';
import { isInSteamLibrary, playerDecalCacheProblem } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies } from '@shared/schemas/install.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from './install-record.ts';
import { canonicalCopyPath, copyPathContains, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from './install-record.ts';
const CACHE_FOLDER = 'decal-cache';
let changing = false;
@@ -17,11 +17,12 @@ export function decalCachePath(dataPath: string, cacheId: string): string {
return join(dataPath, CACHE_FOLDER, cacheId);
}
async function cacheRoot(dataPath: string): Promise<string> {
async function cacheRoot(dataPath: string, steamDataConfirmed: boolean): Promise<string> {
if (!isAbsolute(dataPath)) throw new AppError('decal_import_failed');
const data = await canonicalCopyPath(dataPath);
const root = join(data, CACHE_FOLDER);
if (isInSteamLibrary(data) || relative(root, await canonicalCopyPath(root)) !== '') {
if ((isInSteamLibrary(data) && (!steamDataConfirmed || relative(dataPath, data) !== '')) ||
relative(root, await canonicalCopyPath(root)) !== '') {
throw new AppError('decal_import_failed');
}
return root;
@@ -29,13 +30,13 @@ async function cacheRoot(dataPath: string): Promise<string> {
/** Import the selected cache as its own snapshot so a later build can use the copy's data alone. */
export async function importDecalCache(
dataPath: string, sourcePath: string, signal?: AbortSignal,
dataPath: string, sourcePath: string, signal?: AbortSignal, steamDataConfirmed = false,
): Promise<string> {
if (!isAbsolute(sourcePath)) throw new AppError('decal_source_invalid');
const source = await realpath(sourcePath).catch(() => null);
if (!source || playerDecalCacheProblem(source)) throw new AppError('decal_source_invalid');
const root = await cacheRoot(dataPath);
const root = await cacheRoot(dataPath, steamDataConfirmed);
if (copyPathContains(source, root) || copyPathContains(root, source)) {
throw new AppError('decal_source_invalid');
}
@@ -58,16 +59,16 @@ export async function importDecalCache(
if (playerDecalCacheProblem(target)) throw new AppError('decal_source_invalid');
return id;
} catch (error) {
await discardDecalCache(dataPath, id);
await discardDecalCache(dataPath, id, steamDataConfirmed);
if (signal?.aborted || error instanceof AppError) throw error;
console.error('[decals] could not import the cache:', error);
throw new AppError('decal_import_failed');
}
}
export async function discardDecalCache(dataPath: string, id: string): Promise<void> {
export async function discardDecalCache(dataPath: string, id: string, steamDataConfirmed = false): Promise<void> {
try {
const root = await cacheRoot(dataPath);
const root = await cacheRoot(dataPath, steamDataConfirmed);
const target = decalCachePath(dataPath, id);
const actual = await realpath(target).catch(() => null);
if (actual && relative(root, dirname(actual)) === '' && relative(join(root, id), actual) === '') {
@@ -84,7 +85,10 @@ export async function changeDecalSource(id: string, source: string | null): Prom
try {
const record = (await listCopies()).copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
const cacheId = source === null ? undefined : await importDecalCache(record.dataPath, source);
const [copyPath, dataPath] = await Promise.all([canonicalCopyPath(record.copyPath), canonicalCopyPath(record.dataPath)]);
if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required');
const dataInSteam = isInSteamLibrary(dataPath);
const cacheId = source === null ? undefined : await importDecalCache(dataPath, source, undefined, dataInSteam);
let copies: Copies;
try {
copies = await updateCopyRecord(id, (current) => {
@@ -92,10 +96,10 @@ export async function changeDecalSource(id: string, source: string | null): Prom
return cacheId === undefined ? other : { ...other, decalCacheId: cacheId };
});
} catch (error) {
if (cacheId) await discardDecalCache(record.dataPath, cacheId);
if (cacheId) await discardDecalCache(dataPath, cacheId, dataInSteam);
throw error;
}
if (record.decalCacheId) await discardDecalCache(record.dataPath, record.decalCacheId);
if (record.decalCacheId) await discardDecalCache(dataPath, record.decalCacheId, dataInSteam);
return copies;
} finally {
changing = false;
@@ -1,17 +1,18 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { isAbsolute, join, relative } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
import { requireUnredirectedData } from './data-location.ts';
import { discardDecalCache, importDecalCache } from './decals.ts';
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts';
/**
* Install the offline version: check the patches against the player's game,
@@ -55,55 +56,22 @@ export function cancelInstall(): boolean {
return true;
}
/**
* The stock files a check of `gameFolder` starts from: its backup folder when it already has one
* (a folder installed before, whose own files may be patched), otherwise its own files.
*/
export async function stockFolderOf(gameFolder: string): Promise<string> {
const backup = stockBackupPath(gameFolder);
try {
await access(backup);
return backup;
} catch {
return gameFolder;
}
}
/** Which patches fit the game in `gameFolder`, for the window to show before installing. */
export async function checkGameFolder(gameFolder: string, dataPath: string): Promise<PatchCheck> {
await requireGameFolder(gameFolder);
return checkPatches(await stockFolderOf(gameFolder), dataPath);
const { resolvedPath, version } = await requireGameFolder(gameFolder);
const stock = await installStockSource(resolvedPath, version);
const data = await canonicalCopyPath(dataPath);
await requireUnredirectedData(data);
return checkPatches(stock.path, data);
}
async function install(request: InstallRequest, signal: AbortSignal, report: (progress: InstallProgress) => void): Promise<InstallRecord> {
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
const game = await requireGameFolder(gameFolder);
const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
await requireAvailableCopy(request.id, copyPath, request.dataPath);
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
if (useHardLinks) {
if (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version)) throw new AppError('hardlink_unavailable');
if (copyPathContains(await canonicalCopyPath(gameFolder), await canonicalCopyPath(request.dataPath))) {
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
}
}
const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary;
if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed');
if (request.decalSourcePath) {
const dataPath = await canonicalCopyPath(request.dataPath);
if (isInSteamLibrary(dataPath) ||
(request.method === 'copy' && copyPathContains(await canonicalCopyPath(gameFolder), dataPath))) {
throw new AppError('decal_import_failed');
}
}
const { version, requestedCopyPath, copyPath, dataPath, sourcePath, target, useHardLinks, copyInSteam, dataInSteam } =
await inspectInstallation(request);
report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
await mkdir(request.dataPath, { recursive: true });
const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath);
const stock = await installStockSource(sourcePath, version);
await mkdir(dataPath, { recursive: true });
const check = await checkPatches(stock.path, dataPath);
const essential = check.unavailable.filter((patch) => patch.essential);
if (essential.length) throw new AppError('essential_patches_unavailable', { patches: essential.map((patch) => patch.patchId).join(', ') });
if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted');
@@ -112,26 +80,29 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
let decalCacheId: string | undefined;
if (request.decalSourcePath) {
report({ phase: 'importing-decals', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
decalCacheId = await importDecalCache(request.dataPath, request.decalSourcePath, signal);
decalCacheId = await importDecalCache(dataPath, request.decalSourcePath, signal, dataInSteam);
}
try {
const copied = request.method === 'copy'
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, useHardLinks ? game.version : null, signal, report)
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks ? version : null, signal, report)
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = await backUpStockFiles(copyPath);
const stockBackup = request.method === 'in-place' && stock.refresh
? await refreshStockBackup(copyPath)
: await backUpStockFiles(copyPath);
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = {
id: request.id,
name: request.name,
sourcePath: request.method === 'copy' ? request.sourcePath : null,
sourcePath: request.method === 'copy' ? sourcePath : null,
method: request.method,
copyPath,
copyPath: requestedCopyPath,
dataPath: request.dataPath,
...(copyInSteam || dataInSteam ? { steamLibraryConfirmation: { copyPath, dataPath } } : {}),
stockBackupPath: stockBackup,
gameVersion: game.version,
gameVersion: version,
unavailablePatches: check.unavailable,
installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(),
@@ -141,11 +112,42 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
await writeInstallRecord(record);
return record;
} catch (error) {
if (decalCacheId) await discardDecalCache(request.dataPath, decalCacheId);
if (decalCacheId) await discardDecalCache(dataPath, decalCacheId, dataInSteam);
throw error;
}
}
async function inspectInstallation(request: InstallRequest) {
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
const game = await requireGameFolder(gameFolder);
const requestedCopyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
const [copyPath, dataPath, sourcePath] = await Promise.all([
canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder),
]);
await requireAvailableCopy(request.id, copyPath, dataPath);
if (!isAbsolute(request.dataPath) || copyPathContains(stockBackupPath(copyPath), dataPath) ||
(request.method === 'copy' && copyPathContains(sourcePath, dataPath))) {
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
}
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
if (useHardLinks && (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version))) {
throw new AppError('hardlink_unavailable');
}
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(request.dataPath) || isInSteamLibrary(dataPath);
const { confirmedSteamCopyPath, confirmedSteamDataPath } = request;
const copyConfirmed = confirmedSteamCopyPath !== undefined && relative(copyPath, confirmedSteamCopyPath) === '';
const dataConfirmed = confirmedSteamDataPath !== undefined && relative(dataPath, confirmedSteamDataPath) === '';
if ((copyInSteam && !copyConfirmed) || (dataInSteam && !dataConfirmed)) {
throw new AppError('steam_library_not_confirmed');
}
await Promise.all([requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]);
return { version: game.version, requestedCopyPath, copyPath, dataPath, sourcePath, target, useHardLinks, copyInSteam, dataInSteam };
}
async function copyGame(
source: string,
target: string,
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import { realpath } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { app } from 'electron';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { CopiesSchema, type Copies, type InstallRecord } from '@shared/schemas/install.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
@@ -106,6 +107,12 @@ export function copyPathContains(parent: string, child: string): boolean {
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
}
export function steamLibraryNeedsConfirmation(record: InstallRecord, copyPath: string, dataPath: string): boolean {
if (![record.copyPath, record.dataPath, copyPath, dataPath].some(isInSteamLibrary)) return false;
const confirmed = record.steamLibraryConfirmation;
return !confirmed || relative(confirmed.copyPath, copyPath) !== '' || relative(confirmed.dataPath, dataPath) !== '';
}
function overlaps(left: string, right: string): boolean {
return copyPathContains(left, right) || copyPathContains(right, left);
}
@@ -1,7 +1,10 @@
import { constants } from 'node:fs';
import { access, copyFile, mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { GAME_FILES } from '@wto/patcher';
import { access, copyFile, mkdir, readFile } from 'node:fs/promises';
import { dirname, join, relative } from 'node:path';
import { executableVersion, GAME_FILES } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import { changeCopyFiles } from '../copies/change-copy-files.ts';
import { canonicalCopyPath } from './install-record.ts';
/**
* The stock files every build starts from, kept inside the game copy: the three data packs and
@@ -15,12 +18,21 @@ export function stockBackupPath(copyFolder: string): string {
return join(copyFolder, STOCK_BACKUP_FOLDER);
}
export async function requireStockBackupLocation(copyFolder: string): Promise<string> {
const backup = stockBackupPath(await canonicalCopyPath(copyFolder));
for (const file of Object.values(GAME_FILES)) {
const path = join(backup, file);
if (relative(path, await canonicalCopyPath(path)) !== '') throw new AppError('launch_location');
}
return backup;
}
/**
* Copies each stock file from the copy into the backup folder, unless the backup already has it:
* a backed-up file is never replaced, because the copy's own file may be a patched one by then.
*/
export async function backUpStockFiles(copyFolder: string): Promise<string> {
const backup = stockBackupPath(copyFolder);
const backup = await requireStockBackupLocation(copyFolder);
for (const file of Object.values(GAME_FILES)) {
const kept = join(backup, file);
if (await exists(kept)) continue;
@@ -30,6 +42,27 @@ export async function backUpStockFiles(copyFolder: string): Promise<string> {
return backup;
}
/** A new game version must pass the patch checks before replacing an existing stock backup. */
export async function installStockSource(copyFolder: string, version: string | null) {
const backup = await requireStockBackupLocation(copyFolder);
if (!await exists(join(backup, GAME_FILES.executable))) return { path: copyFolder, refresh: await exists(backup) };
const backedUpVersion = executableVersion(await readFile(join(backup, GAME_FILES.executable)));
return version !== null && backedUpVersion !== version ? { path: copyFolder, refresh: true } : { path: backup, refresh: false };
}
export async function refreshStockBackup(copyFolder: string): Promise<string> {
const backup = await requireStockBackupLocation(copyFolder);
return await changeCopyFiles(copyFolder, async (incoming) => {
const replace = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
const target = join(incoming, STOCK_BACKUP_FOLDER, file);
await mkdir(dirname(target), { recursive: true });
await copyFile(join(copyFolder, file), target);
}
return { replace, remove: [] };
}, async () => backup);
}
async function exists(path: string): Promise<boolean> {
try {
await access(path);
@@ -5,15 +5,17 @@ import { app, BrowserWindow, shell } from 'electron';
import { AccountStore, LOOPBACK } from '@wto/server';
import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { GameExit, LaunchState } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts';
import { copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
import { gameProcessRunning } from './game-process.ts';
import { readInstalledLab, runLab } from './lab-handoff.ts';
import { readInstalledLab, runLab, type Lab } from './lab-handoff.ts';
import { localServerStatusUrl } from './local-server.ts';
import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts';
@@ -104,61 +106,10 @@ async function launch(job: LaunchJob): Promise<void> {
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
if (!record) throw new AppError('launch_no_copy');
job.copyId = record.id;
const useLab = !app.isPackaged && settings.developerMode;
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
const currentVersion = await readVersion(record.copyPath, signal);
if (!currentVersion || currentVersion !== record.gameVersion) {
update(job, { phase: 'version-changed', actualVersion: currentVersion });
return;
}
const lab = useLab ? await readInstalledLab() : null;
const { copyPath, stockPath, dataPath } = lab ? {
copyPath: lab.copyPath,
stockPath: settings.labStockPath ?? record.stockBackupPath,
dataPath: settings.labDataPath ?? record.dataPath,
} : await ordinaryLaunchPaths(record);
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
}
if (isInSteamLibrary(dataPath) || copyPathContains(stockPath, dataPath)) {
throw new AppError('launch_copy_in_steam');
}
const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0);
if (requestedPort) update(job, { phase: 'checking', port: requestedPort });
const [copyVersion, stockVersion, games] = await Promise.all([
lab ? readVersion(copyPath, signal) : currentVersion,
readVersion(stockPath, signal),
gameProcessRunning(signal),
]);
signal.throwIfAborted();
if (!copyVersion || copyVersion !== stockVersion) {
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (games) throw new AppError('launch_game_running');
const port = await selectPort(requestedPort);
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
}
}
signal.throwIfAborted();
update(job, { phase: 'building', port });
await buildCopy({
kind: 'build',
stockPath,
copyPath,
dataPath,
port,
...resourcePaths(),
...(record.decalCacheId ? { decalCache: decalCachePath(record.dataPath, record.decalCacheId) } : {}),
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
}, signal, (filesWritten, filesTotal, file) => {
if (!signal.aborted) update(job, {
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
});
});
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port } = plan;
await buildForLaunch(job, record, plan, settings.autoSaveBackups);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
if (signal.aborted) return;
@@ -176,6 +127,85 @@ async function launch(job: LaunchJob): Promise<void> {
update(job, { phase: 'game-exited', gameExit });
}
interface LaunchPlan {
readonly lab: Lab | null;
readonly copyPath: string;
readonly stockPath: string;
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
}
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
const signal = job.stop.signal;
const useLab = !app.isPackaged && settings.developerMode;
if (useLab && (isInSteamLibrary(record.copyPath) || isInSteamLibrary(await canonicalCopyPath(record.copyPath)))) {
throw new AppError('launch_copy_in_steam');
}
const currentVersion = await readVersion(record.copyPath, signal);
if (!currentVersion || currentVersion !== record.gameVersion) {
update(job, { phase: 'version-changed', actualVersion: currentVersion });
return null;
}
const lab = useLab ? await readInstalledLab() : null;
const { copyPath, stockPath, dataPath, steamLibraryConfirmed } = lab ? {
copyPath: lab.copyPath,
stockPath: settings.labStockPath ?? record.stockBackupPath,
dataPath: settings.labDataPath ?? record.dataPath,
steamLibraryConfirmed: false,
} : await ordinaryLaunchPaths(record);
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
}
if (lab && (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath) || isInSteamLibrary(await canonicalCopyPath(dataPath)))) {
throw new AppError('launch_copy_in_steam');
}
if (copyPathContains(stockPath, dataPath)) throw new AppError('launch_location');
const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0);
if (requestedPort) update(job, { phase: 'checking', port: requestedPort });
const [copyVersion, stockVersion, games] = await Promise.all([
lab ? readVersion(copyPath, signal) : currentVersion,
readVersion(stockPath, signal),
gameProcessRunning(signal),
]);
signal.throwIfAborted();
if (!copyVersion || copyVersion !== stockVersion) {
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (games) throw new AppError('launch_game_running');
const port = await selectPort(requestedPort);
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan;
if (autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
}
}
signal.throwIfAborted();
update(job, { phase: 'building', port });
await buildCopy({
kind: 'build',
stockPath,
copyPath,
dataPath,
port,
steamLibraryConfirmed,
...resourcePaths(),
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
}, signal, (filesWritten, filesTotal, file) => {
if (!signal.aborted) update(job, {
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
});
});
}
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
try {
return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal }));
@@ -6,8 +6,10 @@ import { parseLaunchArguments } from '@shared/launch-arguments.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { GameExit } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { requireUnredirectedData } from '../install/data-location.ts';
import { PLAYER_DATA_FOLDERS } from '../install/copy-game.ts';
import { canonicalCopyPath, copyPathContains, steamLibraryNeedsConfirmation } from '../install/install-record.ts';
import { requireStockBackupLocation, stockBackupPath } from '../install/stock-backup.ts';
import { runGameProcess } from './game-process.ts';
import { startLocalServer } from './local-server.ts';
@@ -17,16 +19,25 @@ export async function ordinaryLaunchPaths(record: InstallRecord) {
const [copyPath, stockPath, dataPath] = await Promise.all([
canonicalCopyPath(record.copyPath), canonicalCopyPath(record.stockBackupPath), canonicalCopyPath(record.dataPath),
]);
const executable = await canonicalCopyPath(join(copyPath, GAME_FILES.executable));
const source = record.sourcePath;
if (relative(copyPath, stockPath).toLowerCase() !== STOCK_BACKUP_FOLDER.toLowerCase() ||
relative(copyPath, executable).toLowerCase() !== GAME_FILES.executable.toLowerCase() ||
const source = record.sourcePath === null ? null : await canonicalCopyPath(record.sourcePath);
if (relative(stockBackupPath(copyPath), stockPath) !== '' ||
copyPathContains(stockPath, dataPath) ||
(source !== null && [copyPath, dataPath].some((path) => copyPathContains(source, path)))) {
throw new AppError('launch_location');
}
if (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath)) throw new AppError('launch_copy_in_steam');
return { copyPath: copyPath, stockPath: stockPath, dataPath: dataPath };
await Promise.all([requireUnredirectedGamePaths(copyPath), requireStockBackupLocation(copyPath), requireUnredirectedData(dataPath)]);
if (steamLibraryNeedsConfirmation(record, copyPath, dataPath)) throw new AppError('launch_steam_confirmation_required');
return { copyPath, stockPath, dataPath, steamLibraryConfirmed: isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath) };
}
/** The game and build write to these copy-relative locations. */
async function requireUnredirectedGamePaths(copyPath: string): Promise<void> {
const paths = ['config.blk', join('cache', 'content'), ...PLAYER_DATA_FOLDERS, ...Object.values(GAME_FILES)];
const checks = await Promise.all(paths.map(async (name) => {
const intended = join(copyPath, name);
return relative(intended, await canonicalCopyPath(intended)) === '';
}));
if (checks.includes(false)) throw new AppError('launch_location');
}
type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-running';
@@ -5,6 +5,7 @@ export interface BuildRequest {
readonly stockPath: string;
readonly copyPath: string;
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
readonly patches: string;
readonly networkHookLibrary: string;
+15 -4
View File
@@ -5,7 +5,16 @@ import { assertWritableCopy, buildGameCopy, copyPlayerDecalCache, playerDecalCac
import { multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[]; readonly decalCache: string | undefined } | null = null;
let prepared: {
readonly request: BuildRequest;
readonly files: readonly GameCopyFile[];
readonly decalCache: string | undefined;
} | null = null;
function checkBuildLocation({ stockPath, copyPath, steamLibraryConfirmed }: BuildRequest): void {
if (relative(copyPath, realpathSync(copyPath)) !== '') throw new Error('The copy path changed during the build.');
assertWritableCopy(stockPath, copyPath, { steamLibraryConfirmed });
}
function send(reply: BuildReply): void {
process.parentPort.postMessage(reply);
@@ -23,7 +32,7 @@ function importedDecals(path: string | undefined): string | undefined {
}
function build(request: BuildRequest): void {
assertWritableCopy(request.stockPath, request.copyPath);
checkBuildLocation(request);
const decalCache = importedDecals(request.decalCache);
const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath),
@@ -40,7 +49,7 @@ function build(request: BuildRequest): void {
send({ kind: 'failed', error: 'launch_build_unavailable' });
return;
}
prepared = { copyPath: request.copyPath, files: result.files, decalCache };
prepared = { request, files: result.files, decalCache };
send({ kind: 'prepared', total: prepared.files.length });
}
@@ -52,8 +61,10 @@ process.parentPort.on('message', (event: MessageEvent) => {
return;
}
if (!prepared) throw new Error('No build is ready to write.');
const { copyPath, files, decalCache } = prepared;
const { request, files, decalCache } = prepared;
prepared = null;
checkBuildLocation(request);
const { copyPath } = request;
if (decalCache) copyPlayerDecalCache(decalCache, copyPath);
for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]);