From e2ac4fa744d90098cfc0ad38e1b3e4225001d1d0 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:40:49 +0800 Subject: [PATCH] fix(launcher): use original-fs for copy and guard nested launcher folders Electron patches node:fs to treat any .asar file on disk as a virtual archive directory. When a player's War Thunder source directory contains an .asar file (for example from a leftover portable launcher folder previously unpacked inside the game folder), createReadStream fails with ENOENT and aborts full-copy installation. Changes: - Add rawFs() helper using Electron's original-fs (with node:fs fallback) and use it across copy-game.ts and change-copy-files.ts for directory scans, streaming copies, timestamp preservation, rollback and cleanup. - Preserve the first non-cancellation worker error in copyPlannedFiles so sibling AbortError rejections do not mask the real filesystem or hardlink error. - Skip nested subfolders containing WTOffline Launcher.exe during planCopy, and reject copy installation upfront with launcher_inside_source when the packaged launcher itself runs from inside the selected source game directory (with en and zh-CN messages). Verification: - Root and launcher typecheck passed. - Launcher electron-vite build passed. - en.json and zh-CN.json key parity check passed (720 keys). - Verified in Electron that patched node:fs reproduces ENOENT on default_app.asar while original-fs copies and cleans it up cleanly. - Packaged installer end-to-end verification pending. --- .../main/services/copies/change-copy-files.ts | 22 +++++---- .../src/main/services/install/copy-game.ts | 47 ++++++++++++++----- .../src/main/services/install/install-game.ts | 7 +++ apps/launcher/src/main/util/raw-fs.ts | 23 +++++++++ .../src/renderer/src/i18n/locales/en.json | 1 + .../src/renderer/src/i18n/locales/zh-CN.json | 1 + apps/launcher/src/shared/errors.ts | 2 + 7 files changed, 80 insertions(+), 23 deletions(-) create mode 100644 apps/launcher/src/main/util/raw-fs.ts diff --git a/apps/launcher/src/main/services/copies/change-copy-files.ts b/apps/launcher/src/main/services/copies/change-copy-files.ts index 195c1f0..3fd1127 100644 --- a/apps/launcher/src/main/services/copies/change-copy-files.ts +++ b/apps/launcher/src/main/services/copies/change-copy-files.ts @@ -1,10 +1,11 @@ -import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises'; import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'; +import { rawFs } from '../../util/raw-fs.ts'; import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts'; export async function fileInfo(path: string) { + const fsPromises = rawFs().promises; try { - return await lstat(path); + return await fsPromises.lstat(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; return null; @@ -28,7 +29,8 @@ export async function changeCopyFiles( prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>, recordChange: () => Promise, ): Promise { - const work = await mkdtemp(join(dirname(root), '.wto-copy-')); + const fsPromises = rawFs().promises; + const work = await fsPromises.mkdtemp(join(dirname(root), '.wto-copy-')); const incoming = join(work, 'new'); const backups = join(work, 'old'); const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = []; @@ -44,14 +46,14 @@ export async function changeCopyFiles( const entry = { target, saved: null as string | null, replaced: false }; if (old) { const saved = join(backups, path); - await mkdir(dirname(saved), { recursive: true }); - await rename(target, saved); + await fsPromises.mkdir(dirname(saved), { recursive: true }); + await fsPromises.rename(target, saved); entry.saved = saved; } changes.push(entry); if (add) { - await mkdir(dirname(target), { recursive: true }); - await rename(join(incoming, path), target); + await fsPromises.mkdir(dirname(target), { recursive: true }); + await fsPromises.rename(join(incoming, path), target); entry.replaced = true; } } @@ -60,8 +62,8 @@ export async function changeCopyFiles( } catch (error) { for (const { target, saved, replaced } of changes.reverse()) { try { - if (replaced) await rm(target, { force: true }); - if (saved) await rename(saved, target); + if (replaced) await fsPromises.rm(target, { force: true }); + if (saved) await fsPromises.rename(saved, target); } catch (rollbackError) { keepBackups = true; console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError); @@ -70,7 +72,7 @@ export async function changeCopyFiles( throw error; } finally { if (!keepBackups && relative(dirname(root), dirname(work)) === '') { - await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error)); + await fsPromises.rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error)); } } } diff --git a/apps/launcher/src/main/services/install/copy-game.ts b/apps/launcher/src/main/services/install/copy-game.ts index 1fbafd7..7075573 100644 --- a/apps/launcher/src/main/services/install/copy-game.ts +++ b/apps/launcher/src/main/services/install/copy-game.ts @@ -1,9 +1,9 @@ -import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs'; -import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises'; +import type { BigIntStats, Dirent } from 'node:fs'; import { join, relative } from 'node:path'; import { Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { AppError } from '@shared/errors.ts'; +import { rawFs } from '../../util/raw-fs.ts'; import { linkVerifiedResource, sameResource } from './hardlink-files.ts'; /** @@ -40,6 +40,11 @@ const SKIPPED_SOURCE_FOLDERS = new Set([ 'warthundercdk', 'wtoffline', ]); +const LAUNCHER_EXECUTABLE_LOWER = 'wtoffline launcher.exe'; + +function isLauncherFolder(entries: readonly Dirent[]): boolean { + return entries.some((entry) => entry.isFile() && entry.name.toLowerCase() === LAUNCHER_EXECUTABLE_LOWER); +} interface CopyEntry { readonly relativePath: string; @@ -60,20 +65,26 @@ export interface CopyProgress { /** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */ export async function planCopy(source: string): Promise { + const fsPromises = rawFs().promises; const files: CopyEntry[] = []; const folders: string[] = []; let totalBytes = 0; const pending = [source]; while (pending.length) { const folder = pending.pop()!; - for (const entry of await readdir(folder, { withFileTypes: true })) { + const entries = await fsPromises.readdir(folder, { withFileTypes: true }); + if (folder !== source) { + // Skip any WTOffline Launcher folder that was previously extracted inside the game directory. + if (isLauncherFolder(entries)) continue; + folders.push(relative(source, folder)); + } + for (const entry of entries) { const path = join(folder, entry.name); if (folder === source && SKIPPED_SOURCE_FOLDERS.has(entry.name.toLowerCase())) continue; if (entry.isDirectory()) { - folders.push(relative(source, path)); pending.push(path); } else if (entry.isFile()) { - const { size, mtimeMs } = await lstat(path); + const { size, mtimeMs } = await fsPromises.lstat(path); files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs }); totalBytes += size; } @@ -98,8 +109,10 @@ export async function copyPlannedFiles( onProgress: (progress: CopyProgress) => void, hardlinks?: ReadonlyMap, ): Promise { - await mkdir(target, { recursive: true }); - for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true }); + const fs = rawFs(); + const fsPromises = fs.promises; + await fsPromises.mkdir(target, { recursive: true }); + for (const folder of plan.folders) await fsPromises.mkdir(join(target, folder), { recursive: true }); const linkedTargets = hardlinks ? new Map() : undefined; let next = 0; let doneBytes = 0; @@ -115,6 +128,8 @@ export async function copyPlannedFiles( // caller cleaning up after an error never races a copy still writing. const stop = new AbortController(); const stopSignal = AbortSignal.any([signal, stop.signal]); + let firstError: unknown = null; + let hasError = false; const copyNext = async (): Promise => { try { while (next < plan.files.length) { @@ -129,30 +144,35 @@ export async function copyPlannedFiles( doneBytes += file.bytes; } else { await pipeline( - createReadStream(from), + fs.createReadStream(from), countBytes(), // 'wx': fail instead of overwriting a file that is already there. - createWriteStream(to, { flags: 'wx' }), + fs.createWriteStream(to, { flags: 'wx' }), { signal: stopSignal }, ); const modified = new Date(file.modifiedAt); - await utimes(to, modified, modified); + await fsPromises.utimes(to, modified, modified); } doneFiles += 1; onProgress({ doneBytes, doneFiles }); } } catch (error) { + if (!hasError && !stop.signal.aborted && !signal.aborted) { + hasError = true; + firstError = error; + } stop.abort(error); throw error; } }; const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext)); + if (hasError) throw firstError; const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected'); if (failed) throw failed.reason; if (linkedTargets) { for (const [path, stamp] of linkedTargets) { signal.throwIfAborted(); - if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed'); + if (!sameResource(stamp, await fsPromises.lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed'); } } } @@ -162,9 +182,10 @@ export async function copyPlannedFiles( * when the copy started, so everything in it came from the copy. */ export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise { + const fsPromises = rawFs().promises; if (!targetExisted) { - await rm(target, { recursive: true, force: true }); + await fsPromises.rm(target, { recursive: true, force: true }); return; } - for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true }); + for (const entry of await fsPromises.readdir(target)) await fsPromises.rm(join(target, entry), { recursive: true, force: true }); } diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index fb3ef22..ea86232 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -1,6 +1,7 @@ import type { BigIntStats } from 'node:fs'; import { access, mkdir } from 'node:fs/promises'; import { dirname, isAbsolute, join, relative } from 'node:path'; +import { app } from 'electron'; import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import type { DataFolderProblem, InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts'; @@ -140,6 +141,12 @@ async function inspectInstallation(request: InstallRequest) { const [copyPath, dataPath, sourcePath] = await Promise.all([ canonicalCopyPath(requestedCopyPath), canonicalCopyPath(request.dataPath), canonicalCopyPath(gameFolder), ]); + if (request.method === 'copy' && app.isPackaged) { + const launcherDir = await canonicalCopyPath(dirname(process.execPath)); + if (copyPathContains(sourcePath, launcherDir)) { + throw new AppError('launcher_inside_source'); + } + } await requireAvailableCopy(request.id, copyPath, dataPath); const dataProblem = dataFolderProblem( dataPath, diff --git a/apps/launcher/src/main/util/raw-fs.ts b/apps/launcher/src/main/util/raw-fs.ts new file mode 100644 index 0000000..63654ee --- /dev/null +++ b/apps/launcher/src/main/util/raw-fs.ts @@ -0,0 +1,23 @@ +import * as nodeFs from 'node:fs'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); + +let cached: typeof nodeFs | null = null; + +/** + * Return Node's unpatched fs module inside Electron. + * + * Electron patches `node:fs` to treat any `.asar` file anywhere on disk as a virtual archive + * directory, which breaks streaming reads, stats and recursive cleanup when copying or managing + * player folders that happen to contain an `.asar` file. Falls back to `node:fs` outside Electron. + */ +export function rawFs(): typeof nodeFs { + if (cached) return cached; + try { + cached = require('original-fs') as typeof nodeFs; + } catch { + cached = nodeFs; + } + return cached; +} diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index c49b9d4..e5662a9 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -854,6 +854,7 @@ "essential_patches_unavailable": "Patches required by the offline edition do not apply to this game version. Installation is not possible: {{patches}}", "missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.", "patch_check_failed": "An error occurred while checking patches.", + "launcher_inside_source": "WTOffline Launcher is currently inside the selected War Thunder folder. Move the launcher to a separate folder outside the game directory, then retry.", "copy_failed": "Copying the game files failed. The copied files have been deleted.", "hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.", "hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 4f2677e..17ced17 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -854,6 +854,7 @@ "essential_patches_unavailable": "此游戏版本缺少离线版运行所必需的补丁,无法安装:{{patches}}", "missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。", "patch_check_failed": "检查补丁时出错。", + "launcher_inside_source": "启动器当前位于所选的战争雷霆游戏目录内。请先把启动器移动到游戏目录之外的独立文件夹,然后再试。", "copy_failed": "复制游戏文件失败,已复制的文件已删除。", "hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。", "hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。", diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 672eba6..ad0d2f0 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -94,6 +94,8 @@ export const APP_ERROR_CODES = [ 'missing_features_not_accepted', /** Working out which patches fit failed; the details are in the log. */ 'patch_check_failed', + /** The packaged launcher itself sits inside the selected stock War Thunder folder. */ + 'launcher_inside_source', /** Copying the game failed; what was copied has been removed. */ 'copy_failed', 'hardlink_unavailable',