Files
WT-Offline/apps/launcher/src/main/services/copies/copy-maintenance.ts
T
N0VAN0M4LY 9e6e13895e fix(launcher): separate client removal from deleting disk files
Split deleteFiles from deleteData in copy maintenance requests with safe false defaults. Block disk deletion for non-copy (in-place/existing) and Steam-library clients on both main and renderer sides, and allow pure list removal to bypass stockBackup/root checks so missing or damaged client entries can always be removed.
2026-12-04 19:55:05 +08:00

275 lines
11 KiB
TypeScript

import { readdir, rm } from 'node:fs/promises';
import { isAbsolute, join, parse, relative, resolve } from 'node:path';
import { app } from 'electron';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { installationInProgress } from '../install/install-game.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 { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import { readSource, setCopySource } from './copy-source.ts';
let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
export function maintenanceInProgress(): boolean {
return current !== null;
}
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort();
}
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),
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
};
}
export async function maintainCopy(
request: MaintenanceRequest,
publish: (progress: MaintenanceProgress | null) => void,
): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const initial: MaintenanceProgress = {
id: request.id,
operation: request.operation,
phase: 'checking',
doneBytes: 0,
totalBytes: 0,
};
const job = {
stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
};
current = job;
const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
if (phase === 'applying') job.interruptible = false;
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
job.progress = next;
publish(next);
};
try {
report('checking');
return await performMaintenance(request, signal, report);
} catch (error) {
if (signal.aborted) throw new AppError('maintenance_cancelled');
if (error instanceof AppError) throw error;
console.error('[copies] maintenance failed:', request.operation, error);
throw new AppError('maintenance_failed');
} finally {
current = null;
publish(null);
}
}
/** Only launcher-created copies outside any Steam library may have their game folder deleted on disk. */
export function canDeleteCopyFiles(record: InstallRecord, root: string): boolean {
return record.method === 'copy' && !isInSteamLibrary(record.copyPath) && !isInSteamLibrary(root);
}
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request;
const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
if (operation === 'delete') {
return remove(record, request.deleteFiles === true, request.deleteData === true, signal, report);
}
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' && 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) !== '') {
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
}
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);
}
}
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;
}
function failLocation(reason: string, details: Record<string, unknown>): never {
console.warn('[copies] maintenance_location:', reason, details);
throw new AppError('maintenance_location');
}
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 (copyPathContains(source, root) || copyPathContains(root, source)) {
failLocation('copy_overlaps_source', { root, source, sourcePath: record.sourcePath });
}
}
return root;
}
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;
}
async function labServerUses(root: string): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab || relative(lab.copyPath, root) !== '') return false;
return localServerReady(lab.port);
}
async function recordCheck(record: InstallRecord, folder: string): Promise<Copies> {
const check = await checkPatches(folder, record.dataPath);
return updateCopyRecord(record.id, (copy) => ({
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
}));
}
async function remove(
record: InstallRecord,
deleteFiles: boolean,
deleteData: boolean,
signal: AbortSignal,
report: Report,
): Promise<Copies> {
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) {
report('applying');
return removeCopyRecord(record.id);
}
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(canonicalRoot);
if (copyInSteam) {
failLocation(deleteFiles ? 'delete_files_blocked_in_steam' : 'delete_data_blocked_in_steam', {
method: record.method,
copyPath: record.copyPath,
root: canonicalRoot,
});
}
if (deleteFiles && !canDeleteCopyFiles(record, canonicalRoot)) {
failLocation('delete_files_blocked_for_method', {
method: record.method,
copyPath: record.copyPath,
root: canonicalRoot,
});
}
const root = deleteFiles ? await checkedRoot(record) : canonicalRoot;
if (deleteFiles && !canDeleteCopyFiles(record, root)) {
failLocation('delete_files_blocked', { method: record.method, copyPath: record.copyPath, root });
}
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 && (copyPathContains(data, source) || copyPathContains(source, data));
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 });
}
}
report('applying');
if (deleteFiles) {
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await rm(root, { recursive: true, force: true });
}
}
if (deleteData && (!deleteFiles || !copyPathContains(root, data))) {
await rm(data, { recursive: true, force: true });
}
return removeCopyRecord(record.id);
}
/** 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;
for (const entry of await 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 rm(path, { recursive: true, force: true });
}
}
}