Write a self-describing wtoffline/client.json origin marker (copy, hardlink, or in-place) on install, space-saving compaction, and hardlink-detaching updates, and read it with lightweight hardlink nlink sampling when inspecting existing folders. Allow deleting existing folders only when backed by a valid copy/hardlink marker outside Steam and disjoint from all registered source paths, and add an atomic restore-stock-and-remove option that restores the four stock core files and removes only wto_ws.{dll,cfg,log} and wtoffline/.
273 lines
11 KiB
TypeScript
273 lines
11 KiB
TypeScript
import { constants } from 'node:fs';
|
|
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
|
|
import { app } from 'electron';
|
|
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
|
import { AppError } from '@shared/errors.ts';
|
|
import type { ClientOrigin, Copies, InstallRecord } from '@shared/schemas/install.ts';
|
|
import { rawFs } from '../../util/raw-fs.ts';
|
|
import { readClientMarker, type ClientMarker } from '../install/client-marker.ts';
|
|
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord } from '../install/install-record.ts';
|
|
import { requireStockBackupLocation, STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
|
import { gameProcessRunning } from '../launch/launch-controller.ts';
|
|
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
|
import type { Report } from './copy-file-maintenance.ts';
|
|
|
|
const OFFLINE_HOOK_FILES = ['wto_ws.dll', 'wto_ws.cfg', 'wto_ws.log'] as const;
|
|
|
|
export interface RemoveCopyOptions {
|
|
readonly deleteFiles: boolean;
|
|
readonly restoreStock: boolean;
|
|
readonly deleteData: boolean;
|
|
}
|
|
|
|
export function failLocation(reason: string, details: Record<string, unknown>): never {
|
|
console.warn('[copies] maintenance_location:', reason, details);
|
|
throw new AppError('maintenance_location');
|
|
}
|
|
|
|
/**
|
|
* Resolve the effective client origin by preferring a valid on-disk marker while
|
|
* keeping in-place registrations conservatively locked as `in-place`.
|
|
*/
|
|
export function resolveClientOrigin(
|
|
record: InstallRecord,
|
|
diskMarker: ClientMarker | null,
|
|
): ClientOrigin | null {
|
|
if (record.method === 'in-place') return 'in-place';
|
|
if (diskMarker) return diskMarker.origin;
|
|
if (record.method === 'copy') return record.hardlinkedFiles?.length ? 'hardlink' : 'copy';
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Only launcher-created copies or existing folders carrying a valid copy/hardlink marker
|
|
* outside any Steam library and disjoint from every registered copy's sourcePath may be deleted.
|
|
*/
|
|
export function canDeleteCopyFiles(
|
|
record: InstallRecord,
|
|
root: string,
|
|
effectiveOrigin: ClientOrigin | null,
|
|
allCopies: readonly InstallRecord[] = [],
|
|
): boolean {
|
|
if (isInSteamLibrary(record.copyPath) || isInSteamLibrary(root)) return false;
|
|
if (effectiveOrigin !== 'copy' && effectiveOrigin !== 'hardlink') return false;
|
|
const normalizedRoot = resolve(root);
|
|
const normalizedCopyPath = resolve(record.copyPath);
|
|
const sources = record.sourcePath
|
|
? [record.sourcePath, ...allCopies.map((copy) => copy.sourcePath)]
|
|
: allCopies.map((copy) => copy.sourcePath);
|
|
for (const candidate of sources) {
|
|
if (!candidate) continue;
|
|
const source = resolve(candidate);
|
|
if (pathsOverlap(normalizedRoot, source) || pathsOverlap(normalizedCopyPath, source)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** Check that `record` has a safe root and all four original core files readable in wtoffline/stock. */
|
|
export async function canRestoreStock(record: InstallRecord, root: string): Promise<boolean> {
|
|
try {
|
|
const safeRoot = await checkedRoot(record);
|
|
const canonicalRoot = await canonicalCopyPath(root);
|
|
if (relative(safeRoot, canonicalRoot) !== '') return false;
|
|
const backup = await requireStockBackupLocation(safeRoot);
|
|
const fsPromises = rawFs().promises;
|
|
for (const file of Object.values(GAME_FILES)) {
|
|
const stockFile = join(backup, file);
|
|
const info = await fileInfo(stockFile);
|
|
if (!info?.isFile()) return false;
|
|
await fsPromises.access(stockFile, constants.R_OK);
|
|
}
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** Resolve every copy's `sourcePath` through symlinks/junctions for overlap checks. */
|
|
export async function withCanonicalSources(copies: readonly InstallRecord[]): Promise<InstallRecord[]> {
|
|
return Promise.all(copies.map(async (copy) => (
|
|
copy.sourcePath ? { ...copy, sourcePath: await canonicalCopyPath(copy.sourcePath) } : copy
|
|
)));
|
|
}
|
|
|
|
export async function checkedRoot(record: InstallRecord): Promise<string> {
|
|
const root = await safeFolder(record.copyPath, true);
|
|
const backup = await canonicalCopyPath(record.stockBackupPath);
|
|
const expectedBackup = join(root, STOCK_BACKUP_FOLDER);
|
|
if (relative(expectedBackup, backup) !== '') {
|
|
failLocation('stock_backup_outside_copy', { root, expectedBackup, backup, recordedBackup: record.stockBackupPath });
|
|
}
|
|
if (record.sourcePath) {
|
|
const source = await canonicalCopyPath(record.sourcePath);
|
|
if (pathsOverlap(source, root)) {
|
|
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
|
|
}
|
|
}
|
|
return root;
|
|
}
|
|
|
|
export async function safeFolder(path: string, steamAllowed = false): Promise<string> {
|
|
const root = await canonicalCopyPath(path);
|
|
const inSteam = isInSteamLibrary(path) || isInSteamLibrary(root);
|
|
const appPath = await canonicalCopyPath(app.getAppPath());
|
|
const userDataPath = await canonicalCopyPath(app.getPath('userData'));
|
|
if (!isAbsolute(path) || root === parse(root).root || (!steamAllowed && inSteam) ||
|
|
copyPathContains(root, appPath) || copyPathContains(root, userDataPath)) {
|
|
failLocation('unsafe_folder', { path, root, inSteam, steamAllowed, appPath, userDataPath });
|
|
}
|
|
if ((!steamAllowed || !inSteam) && (await fileInfo(path))?.isSymbolicLink()) {
|
|
failLocation('folder_is_symlink', { path, root });
|
|
}
|
|
return root;
|
|
}
|
|
|
|
export async function removeCopy(
|
|
record: InstallRecord,
|
|
options: RemoveCopyOptions,
|
|
signal: AbortSignal,
|
|
report: Report,
|
|
labServerUses: (root: string) => Promise<boolean>,
|
|
): Promise<Copies> {
|
|
const { deleteFiles, restoreStock, deleteData } = options;
|
|
if (deleteFiles && restoreStock) {
|
|
failLocation('delete_files_and_restore_stock_conflict', { id: record.id });
|
|
}
|
|
|
|
const canonicalRoot = await canonicalCopyPath(record.copyPath);
|
|
if (await gameProcessRunning(signal) || await labServerUses(canonicalRoot)) {
|
|
throw new AppError('maintenance_busy');
|
|
}
|
|
signal.throwIfAborted();
|
|
|
|
// Pure list removal touches no files on disk and skips copyPath/stockBackup checks
|
|
// so missing, moved, or damaged client registrations can always be removed safely.
|
|
if (!deleteFiles && !deleteData && !restoreStock) {
|
|
report('applying');
|
|
return removeCopyRecord(record.id);
|
|
}
|
|
|
|
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
|
|
if ((deleteFiles || deleteData) && copyInSteam) {
|
|
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
|
|
method: record.method,
|
|
copyPath: record.copyPath,
|
|
root: canonicalRoot,
|
|
});
|
|
}
|
|
|
|
let root = canonicalRoot;
|
|
if (deleteFiles) {
|
|
const allCopies = (await listCopies()).copies;
|
|
const canonicalCopies = await withCanonicalSources(allCopies);
|
|
const initialOrigin = resolveClientOrigin(record, await readClientMarker(canonicalRoot));
|
|
if (!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, allCopies) ||
|
|
!canDeleteCopyFiles(record, canonicalRoot, initialOrigin, canonicalCopies)) {
|
|
failLocation('delete_files_blocked', { method: record.method, origin: initialOrigin, copyPath: record.copyPath, root: canonicalRoot });
|
|
}
|
|
root = await checkedRoot(record);
|
|
const verifiedOrigin = resolveClientOrigin(record, await readClientMarker(root));
|
|
if (!canDeleteCopyFiles(record, root, verifiedOrigin, allCopies) ||
|
|
!canDeleteCopyFiles(record, root, verifiedOrigin, canonicalCopies)) {
|
|
failLocation('delete_files_blocked', { method: record.method, origin: verifiedOrigin, copyPath: record.copyPath, root });
|
|
}
|
|
} else if (restoreStock) {
|
|
root = await checkedRoot(record);
|
|
if (!(await canRestoreStock(record, root))) {
|
|
failLocation('restore_stock_unavailable', { copyPath: record.copyPath, root, stockBackupPath: record.stockBackupPath });
|
|
}
|
|
}
|
|
|
|
const data = deleteData ? await safeFolder(record.dataPath, false) : await canonicalCopyPath(record.dataPath);
|
|
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
|
|
const stockBackup = await canonicalCopyPath(record.stockBackupPath);
|
|
if (deleteData) {
|
|
const rawRoot = resolve(record.copyPath);
|
|
const overlapsSource = source !== null && pathsOverlap(data, source);
|
|
const containsCopy = deleteFiles
|
|
? relative(data, root) !== '' && copyPathContains(data, root)
|
|
: copyPathContains(data, root) || copyPathContains(data, rawRoot) || copyPathContains(data, stockBackup);
|
|
if (overlapsSource || containsCopy) {
|
|
failLocation('delete_data_overlaps_source_or_copy', { root, data, source, stockBackup, deleteFiles, restoreStock });
|
|
}
|
|
}
|
|
|
|
report('applying');
|
|
const fsPromises = rawFs().promises;
|
|
if (restoreStock) {
|
|
await restoreStockAndCleanOfflineFiles(root, data, deleteData);
|
|
} else if (deleteFiles) {
|
|
if (!deleteData && copyPathContains(root, data)) {
|
|
await removeExcept(root, data);
|
|
} else {
|
|
await fsPromises.rm(root, { recursive: true, force: true });
|
|
}
|
|
}
|
|
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
|
|
await fsPromises.rm(data, { recursive: true, force: true });
|
|
}
|
|
return removeCopyRecord(record.id);
|
|
}
|
|
|
|
/**
|
|
* Atomically restore the four stock core files from `wtoffline/stock`, then remove
|
|
* only launcher-created hook files and the `wtoffline` folder without touching base game files.
|
|
*/
|
|
async function restoreStockAndCleanOfflineFiles(root: string, data: string, deleteData: boolean): Promise<void> {
|
|
const fsPromises = rawFs().promises;
|
|
const backup = await requireStockBackupLocation(root);
|
|
await changeCopyFiles(root, async (incoming) => {
|
|
const files = Object.values(GAME_FILES);
|
|
for (const file of files) {
|
|
const sourceFile = join(backup, file);
|
|
if (!(await fileInfo(sourceFile))?.isFile()) {
|
|
failLocation('stock_backup_source_missing', { root, file, sourceFile });
|
|
}
|
|
const targetFile = join(incoming, file);
|
|
await fsPromises.mkdir(dirname(targetFile), { recursive: true });
|
|
await fsPromises.copyFile(sourceFile, targetFile);
|
|
}
|
|
return { replace: files, remove: [] };
|
|
}, async () => undefined);
|
|
|
|
const exeDir = dirname(GAME_FILES.executable);
|
|
for (const name of OFFLINE_HOOK_FILES) {
|
|
const hookFile = await stagedPath(root, join(exeDir, name));
|
|
const info = await fileInfo(hookFile);
|
|
if (info && !info.isDirectory()) {
|
|
await fsPromises.rm(hookFile, { force: true });
|
|
}
|
|
}
|
|
|
|
const wtofflineFolder = await stagedPath(root, dirname(STOCK_BACKUP_FOLDER));
|
|
const wtofflineInfo = await fileInfo(wtofflineFolder);
|
|
if (wtofflineInfo?.isDirectory()) {
|
|
if (!deleteData && copyPathContains(wtofflineFolder, data)) {
|
|
await removeExcept(wtofflineFolder, data);
|
|
} else {
|
|
await fsPromises.rm(wtofflineFolder, { recursive: true, force: true });
|
|
}
|
|
}
|
|
}
|
|
|
|
function pathsOverlap(left: string, right: string): boolean {
|
|
return copyPathContains(left, right) || copyPathContains(right, left);
|
|
}
|
|
|
|
/** Keep the data folder in place when it was chosen inside this copy. */
|
|
async function removeExcept(folder: string, kept: string): Promise<void> {
|
|
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
|
|
const fsPromises = rawFs().promises;
|
|
for (const entry of await fsPromises.readdir(folder, { withFileTypes: true })) {
|
|
const path = join(folder, entry.name);
|
|
if (copyPathContains(path, kept)) {
|
|
if (!entry.isDirectory()) failLocation('kept_data_ancestor_not_directory', { folder, kept, path });
|
|
await removeExcept(path, kept);
|
|
} else {
|
|
await fsPromises.rm(path, { recursive: true, force: true });
|
|
}
|
|
}
|
|
}
|