From f798714f8df81fe972e866c8e88c6768576400c0 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Sat, 29 Aug 2026 16:55:07 +0300 Subject: [PATCH 01/15] chore(build): enforce lint, type-check and dist invariants in build and CI Add verify-dist.mjs (node --check on bundles, dev-only payload guard). Wire lint into build.ps1 and type-check both web and bridge in pnpm build. Drop noImplicitAny override and switch bridge to Bundler resolution. Run CI on pull_request and push to master. --- .github/workflows/build.yml | 3 + AGENTS.md | 13 ++++- build.ps1 | 64 ++++++++------------- web-panel/bridge/tsconfig.json | 10 +++- web-panel/package.json | 4 +- web-panel/pnpm-lock.yaml | 10 ++++ web-panel/scripts/verify-dist.mjs | 94 +++++++++++++++++++++++++++++++ 7 files changed, 153 insertions(+), 45 deletions(-) create mode 100644 web-panel/scripts/verify-dist.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 796047a5..e6cb57f1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,6 +2,9 @@ name: Build executable on: workflow_dispatch: + pull_request: + push: + branches: [master] jobs: build: diff --git a/AGENTS.md b/AGENTS.md index bd3fab1d..167fcb09 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,18 @@ This repository patches the Wand Electron app from a .NET Framework WPF desktop - The websocket `hello` snapshot must still send cached `installed_apps` and `game_status` even when no trainer snapshot is active yet; do not reintroduce a handshake path that returns early after `trainer_changed`. - Remote Play/Stop uses the websocket `remote_command` message. The bridge forwards it over `wand-remote-command` / `wand-remote-command-response`, and `installed-apps-sync.js` resolves Wand's trainer API + trainer service to launch a trainer for a `gameId` or end the current trainer. - Remote Play must construct Wand's real trainer launch request class (`69482.vO`) before calling `trainerService.launch(...)`. Passing a plain object launches the game process but breaks Wand's `getMetadata(vO)`-based trainer state, causing missing status, disappearing play/close buttons, and stuck loading behavior. -- Pro activation is a C# asar patch (`EPatchType.ActivatePro`, independent of the remote panel / bridge). It rewrites three account-returning service methods to inject `subscription:{period:"yearly",state:"active"}` into the response before it reaches the store: `getUserAccount` and `setAccountWandBrandExperience` (Resolver-style, service field via `` placeholder) and `setAccountLanguage` (`BuildSetAccountLanguagePatch` PatchFactory — captures the real param names + the original `post("/v3/account/language",{...})` expr and wraps `.then`). A fourth patch (`setAccountReducer`) rewrites the `ACTION_SET_ACCOUNT` store reducer so any account write (periodic `refreshAccount`, push/profile updates, etc.) keeps Pro even when it bypasses those API methods. Pro is `am(account) = !!account.subscription` (flags/512 are irrelevant). `setAccountLanguage` is the one the original two patches missed, which is why Pro dropped on language change. If a future Wand build changes these method bodies, re-derive the regexes against the live `app-*.bundle.js` (do NOT trust `.source/new` — it is a different version). +- Pro activation is a C# asar patch (`EPatchType.ActivatePro`, independent of the remote panel / bridge). It wraps the returned promise of three account-returning service methods so `subscription:{period:"yearly",state:"active"}` is injected before the response reaches the store: `getUserAccount`, `setAccountWandBrandExperience` and `setAccountLanguage`. A fourth patch (`setAccountReducer`) rewrites the `ACTION_SET_ACCOUNT` store reducer so any account write (periodic `refreshAccount`, push/profile updates, etc.) keeps Pro even when it bypasses those API methods. Pro is `am(account) = !!account.subscription` (flags/512 are irrelevant). `setAccountLanguage` is the one the original two patches missed, which is why Pro dropped on language change. `setAccountWandBrandExperience` does not exist on every build, so it is declared optional through `CapabilityHints`. + +## Patch Engine + +- Patches are located structurally, not by shape. A patch anchors on something Wand does not rename between builds — an API endpoint, an IPC channel name, a public method name — and then walks the delimiter structure (`Core/Js/JsCursor.cs`) to the edit site. Identifiers that do change (`#Xe`, `l.vO`, the numeric Remote source) are read out of the located region, never baked into a pattern. A rebuild that only reminifies therefore needs no change here. +- Never write a regex that spans a whole method body or matches across a bundle. Scope patterns to a located `JsFunction` via `Resolve`, where they run against a few hundred characters instead of megabytes. +- A patch is one `PatchEntry` in `Core/EnhancerConfig.cs` with a `Locate` delegate returning the edits to splice. Return `null` when the anchor is absent from this file — that means "not my file", not "failure". Throw only when the anchor IS present but the surrounding structure is unrecognisable; that is a genuinely unsupported build and must fail loudly. +- Injected JavaScript lives in `WandEnhancer/Patches/*.js` and is embedded as `patches/.js`. Load it with `PatchPayload.Load(name, "key", value, ...)`, which fills `${key}` placeholders in one pass. Do not put payload JS back into C# string literals. +- Multiple edits from one patch are applied highest-offset-first, so their positions stay valid. Keep them non-overlapping. +- A patch that only exists on some builds sets `CapabilityHints`: absent capability logs a skip, a detected-but-unpatchable capability still fails the run. +- When a build really does restructure something, add a fallback branch inside that patch's `Locate` rather than a version table — old shapes keep working because the old branch is still there. +- Verify against real bundles, minified and prettified, before shipping: locating must succeed on both and the patched files must pass `node --check`. ## ASAR Patch Pipeline diff --git a/build.ps1 b/build.ps1 index 6aab6db4..b4a8865c 100644 --- a/build.ps1 +++ b/build.ps1 @@ -7,9 +7,6 @@ $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path $webPanelDir = Join-Path $repoRoot 'web-panel' -$nativeBuildRoot = Join-Path $repoRoot '.tmp/cmake' -$asarFusesSourceDir = Join-Path $repoRoot 'tools/asar-fuses-bypass' -$asarFusesBuildDir = Join-Path $nativeBuildRoot 'asar-fuses-bypass' $solutionPath = Join-Path $repoRoot 'Wand-Enhancer.sln' function Resolve-CommandPath { @@ -48,23 +45,6 @@ function Resolve-MSBuildPath { return $msbuildPath } -function Resolve-DumpBinPath { - param([string]$VisualStudioPath) - - $versionFile = Join-Path $VisualStudioPath 'VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt' - if (-not (Test-Path $versionFile)) { - throw "MSVC tools version file not found: $versionFile" - } - - $toolsVersion = (Get-Content $versionFile -Raw).Trim() - $dumpBinPath = Join-Path $VisualStudioPath "VC\Tools\MSVC\$toolsVersion\bin\Hostx64\x64\dumpbin.exe" - if (-not (Test-Path $dumpBinPath)) { - throw "dumpbin.exe not found: $dumpBinPath" - } - - return $dumpBinPath -} - function Invoke-Step { param( [string]$Label, @@ -78,35 +58,39 @@ function Invoke-Step { } } -$cmake = Resolve-CommandPath 'cmake' +function Resolve-TargetFrameworkRoot { + # Some environments do not register the v4.8 targeting pack for MSBuild to find on its own. + # Point at it explicitly when present; skip on CI where default resolution already works. + $root = Join-Path ${env:ProgramFiles(x86)} 'Reference Assemblies\Microsoft\Framework' + $frameworkList = Join-Path $root '.NETFramework\v4.8\RedistList\FrameworkList.xml' + if (Test-Path $frameworkList) { + return $root + } + + return $null +} + $pnpm = Resolve-CommandPath 'pnpm' $visualStudio = Resolve-VisualStudioPath $msbuild = Resolve-MSBuildPath $visualStudio -$dumpBin = Resolve-DumpBinPath $visualStudio +$targetFrameworkRoot = Resolve-TargetFrameworkRoot -Invoke-Step 'Install web-panel dependencies' { - & $pnpm --dir $webPanelDir install --frozen-lockfile -} - -Invoke-Step 'Build web-panel' { - & $pnpm --dir $webPanelDir run build +$buildArgs = @('/m', "/p:Configuration=$Configuration", '/p:Platform=Any CPU') +if ($targetFrameworkRoot) { + $buildArgs += "/p:TargetFrameworkRootPath=$targetFrameworkRoot" } -Invoke-Step 'Configure asar-fuses-bypass' { - Remove-Item Env:CMAKE_GENERATOR -ErrorAction SilentlyContinue - & $cmake -S $asarFusesSourceDir -B $asarFusesBuildDir -A x64 +Invoke-Step 'Install web-panel dependencies' { + & $pnpm --dir $webPanelDir install --frozen-lockfile } -Invoke-Step 'Build asar-fuses-bypass' { - & $cmake --build $asarFusesBuildDir --config $Configuration +Invoke-Step 'Lint web-panel' { + & $pnpm --dir $webPanelDir run lint } -Invoke-Step 'Verify native runtime dependencies' { - $nativeDll = Join-Path $asarFusesBuildDir "$Configuration\version.dll" - $dependencies = & $dumpBin /dependents $nativeDll - if ($dependencies -match '(?im)^\s*(VCRUNTIME|MSVCP|api-ms-win-crt-)[^\s]*\.dll\s*$') { - throw 'version.dll depends on the dynamic Visual C++ runtime.' - } +# Runs type-check (web + bridge), Vite, the bridge bundle, then the dist invariant check. +Invoke-Step 'Build web-panel' { + & $pnpm --dir $webPanelDir run build } Invoke-Step 'Restore NuGet packages' { @@ -114,7 +98,7 @@ Invoke-Step 'Restore NuGet packages' { } Invoke-Step 'Build solution' { - & $msbuild $solutionPath /m /p:Configuration=$Configuration '/p:Platform=Any CPU' /t:Build + & $msbuild $solutionPath @buildArgs /t:Build } Write-Host '' diff --git a/web-panel/bridge/tsconfig.json b/web-panel/bridge/tsconfig.json index 49a3a50f..9e8a23be 100644 --- a/web-panel/bridge/tsconfig.json +++ b/web-panel/bridge/tsconfig.json @@ -2,9 +2,13 @@ "extends": "../tsconfig.json", "compilerOptions": { "lib": ["ES2022"], - "module": "NodeNext", - "moduleResolution": "NodeNext", - "noImplicitAny": false, + // Bundled by esbuild (bridge/build.mjs), not resolved by Node's ESM loader, so + // type-check under the same model the bundler uses. + "module": "ESNext", + "moduleResolution": "Bundler", + // The injected renderer scripts are plain .js by design; tests import them directly. + "allowJs": true, + "checkJs": false, "types": ["node"] }, "include": ["src"] diff --git a/web-panel/package.json b/web-panel/package.json index 6c3df9d1..14875807 100644 --- a/web-panel/package.json +++ b/web-panel/package.json @@ -7,8 +7,9 @@ "scripts": { "dev": "vite", "dev:host": "vite --host 0.0.0.0", - "build": "tsc --noEmit && vite build && pnpm run build:bridge", + "build": "pnpm run typecheck && vite build && pnpm run build:bridge && pnpm run verify:dist", "build:bridge": "node ./bridge/build.mjs", + "verify:dist": "node ./scripts/verify-dist.mjs", "lint": "eslint src protocol bridge/src --max-warnings=0", "typecheck:web": "tsc --noEmit", "typecheck:bridge": "tsc -p bridge/tsconfig.json --noEmit", @@ -37,6 +38,7 @@ "@types/node": "^24.12.0", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", + "@types/ws": "^8.18.1", "@vitejs/plugin-react": "^5.2.0", "esbuild": "0.27.7", "eslint": "^9.39.4", diff --git a/web-panel/pnpm-lock.yaml b/web-panel/pnpm-lock.yaml index c15c9823..49f5c569 100644 --- a/web-panel/pnpm-lock.yaml +++ b/web-panel/pnpm-lock.yaml @@ -51,6 +51,9 @@ importers: '@types/react-dom': specifier: ^19.2.3 version: 19.2.3(@types/react@19.2.14) + '@types/ws': + specifier: ^8.18.1 + version: 8.18.1 '@vitejs/plugin-react': specifier: ^5.2.0 version: 5.2.0(vite@7.3.2(@types/node@24.12.2)(jiti@2.6.1)(lightningcss@1.32.0)) @@ -995,6 +998,9 @@ packages: '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + '@types/yargs-parser@21.0.3': resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} @@ -3133,6 +3139,10 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/ws@8.18.1': + dependencies: + '@types/node': 24.12.2 + '@types/yargs-parser@21.0.3': {} '@types/yargs@17.0.35': diff --git a/web-panel/scripts/verify-dist.mjs b/web-panel/scripts/verify-dist.mjs new file mode 100644 index 00000000..5cb1fbbf --- /dev/null +++ b/web-panel/scripts/verify-dist.mjs @@ -0,0 +1,94 @@ +#!/usr/bin/env node +// Enforces the dist invariants AGENTS.md previously only stated in prose: +// the bundles must parse, and no dev-only payload may ship to users. +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const distDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist'); + +const REQUIRED_FILES = [ + 'bridge.cjs', + 'index.html', + path.join('renderer-scripts', 'remote-popup-cleanup.js'), +]; + +const FORBIDDEN_SUBSTRINGS = [ + 'mock-instance', + 'Mock Adventure', + 'Debug session', + 'mock=1', + 'demo-session', + 'vite.svg', + 'tailwind-merge', + 'class-variance-authority', +]; + +const failures = []; + +if (!fs.existsSync(distDir)) { + fail(`dist/ not found at ${distDir} - run the build first`); +} + +for (const relative of REQUIRED_FILES) { + if (!fs.existsSync(path.join(distDir, relative))) { + failures.push(`missing required artifact: ${relative}`); + } +} + +for (const file of collectFiles(distDir)) { + const relative = path.relative(distDir, file); + + if (file.endsWith('.js') || file.endsWith('.cjs')) { + try { + execFileSync(process.execPath, ['--check', file], { stdio: 'pipe' }); + } catch (error) { + failures.push(`syntax error in ${relative}: ${firstLine(error)}`); + } + } + + if (!isTextArtifact(file)) { + continue; + } + + const content = fs.readFileSync(file, 'utf8'); + for (const needle of FORBIDDEN_SUBSTRINGS) { + if (content.includes(needle)) { + failures.push(`dev-only payload "${needle}" found in ${relative}`); + } + } +} + +if (failures.length > 0) { + fail(`dist verification failed:\n - ${failures.join('\n - ')}`); +} + +console.log('dist verified: bundles parse, no dev-only payload.'); + +function collectFiles(dir) { + const found = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + found.push(...collectFiles(full)); + } else if (entry.isFile()) { + found.push(full); + } + } + return found; +} + +function isTextArtifact(file) { + return ['.js', '.cjs', '.mjs', '.css', '.html', '.json'].includes(path.extname(file)); +} + +function firstLine(error) { + const output = String(error.stderr || error.message || ''); + return output.split('\n').find((line) => line.trim().length > 0) ?? 'unknown error'; +} + +function fail(message) { + console.error(message); + process.exit(1); +} From 20956c3228f9fe5bc0bf36d14b35dbdbcc391b58 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Sat, 29 Aug 2026 16:55:55 +0300 Subject: [PATCH 02/15] fix(asar): correct archive tree lookups and fail loudly on unreadable input InsertFile resolved the grandparent node instead of the parent. Reads no longer create phantom directories in the header. Bound symlink traversal and skip reparse points when crawling. Locked or unreadable files now abort packing instead of being dropped. Read headers and integrity blocks with a full-read loop. Assert the header keeps its size before overwriting the placeholder. Validate Pickle buffer sizes, payload overflow and negative lengths. Check CreateSymbolicLink and external tool exit codes. Drop unused Pickle accessors, TransformedFile and FilesystemFilesAndLinks.Links. --- AsarSharp/AsarCreator.cs | 18 +-- AsarSharp/AsarExtractor.cs | 17 +-- AsarSharp/AsarFileSystem/Disk.cs | 81 +++++-------- AsarSharp/AsarFileSystem/FileSystem.cs | 55 ++++++--- AsarSharp/AsarFileSystem/FileSystemCrawler.cs | 15 +-- AsarSharp/Integrity/IntegrityHelper.cs | 5 +- AsarSharp/PickleTools/Pickle.cs | 113 +++--------------- AsarSharp/PickleTools/PickleIterator.cs | 25 +--- AsarSharp/Utils/Extensions.cs | 79 +++++++----- 9 files changed, 163 insertions(+), 245 deletions(-) diff --git a/AsarSharp/AsarCreator.cs b/AsarSharp/AsarCreator.cs index 9b1276f7..804f69fc 100644 --- a/AsarSharp/AsarCreator.cs +++ b/AsarSharp/AsarCreator.cs @@ -73,22 +73,26 @@ private void HandleFile(Filesystem filesystem, string filename, List + /// Matches the directory path (relative to the archive root) against the unpack regex. + /// + private bool ShouldUnpackPath(string relativeParentPath) { - return _options?.Unpack?.IsMatch(relativePath) == true; + return _options?.Unpack?.IsMatch(relativeParentPath) == true; } private void InsertsDone(Filesystem filesystem, List files) { - Directory.CreateDirectory( - Path.GetDirectoryName(_destPath) - ?? throw new InvalidOperationException()); + string dir = Path.GetDirectoryName(_destPath); + if (!string.IsNullOrEmpty(dir)) + Directory.CreateDirectory(dir); + Disk.WriteFileSystem(_destPath, filesystem, - new Disk.FilesystemFilesAndLinks { Files = files, Links = null }, _metadata); + new Disk.FilesystemFilesAndLinks { Files = files }, _metadata); } } } diff --git a/AsarSharp/AsarExtractor.cs b/AsarSharp/AsarExtractor.cs index 96aca5dc..29ba9d9a 100644 --- a/AsarSharp/AsarExtractor.cs +++ b/AsarSharp/AsarExtractor.cs @@ -159,13 +159,6 @@ private static void ExtractLink(string dest, string fullPath, string destFilenam FilesystemEntry file, HashSet dirCache) { var linkSrcPath = Extensions.GetDirectoryName(Path.Combine(dest, file.Link)); - var linkDestPath = Extensions.GetDirectoryName(destFilename); - var relativeLinkPath = Extensions.GetRelativePath(linkDestPath, linkSrcPath); - - try { File.Delete(destFilename); } - catch { /* ignore — failing to remove an existing link is non-fatal */ } - - var linkTo = Path.Combine(relativeLinkPath, Path.GetFileName(file.Link)); if (!Extensions.IsPathInside(dest, linkSrcPath)) { @@ -173,6 +166,12 @@ private static void ExtractLink(string dest, string fullPath, string destFilenam $"{fullPath}: file \"{file.Link}\" links out of the package to \"{linkSrcPath}\""); } + try { File.Delete(destFilename); } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) + { + // Nothing to replace, or the old entry is locked; the copy below reports the real failure. + } + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var targetPath = Path.Combine(linkSrcPath, Path.GetFileName(file.Link)); @@ -189,8 +188,10 @@ private static void ExtractLink(string dest, string fullPath, string destFilenam } else { + var linkDestPath = Extensions.GetDirectoryName(destFilename); + var relativeLinkPath = Extensions.GetRelativePath(linkDestPath, linkSrcPath); EnsureParentDir(destFilename, dirCache); - Extensions.CreateSymbolicLink(linkTo, destFilename); + Extensions.CreateSymbolicLink(Path.Combine(relativeLinkPath, Path.GetFileName(file.Link)), destFilename); } } } diff --git a/AsarSharp/AsarFileSystem/Disk.cs b/AsarSharp/AsarFileSystem/Disk.cs index d83e11a9..509fc5ee 100644 --- a/AsarSharp/AsarFileSystem/Disk.cs +++ b/AsarSharp/AsarFileSystem/Disk.cs @@ -12,8 +12,6 @@ namespace AsarSharp.AsarFileSystem public static class Disk { private const int StreamBufferSize = 1024 * 1024; - private static readonly ConcurrentDictionary _filesystemCache = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); public class ArchiveHeader { @@ -25,7 +23,6 @@ public class ArchiveHeader public class FilesystemFilesAndLinks { public List Files { get; set; } = new List(); - public List Links { get; set; } = new List(); } public class BasicFileInfo @@ -42,14 +39,14 @@ public static ArchiveHeader ReadArchiveHeaderSync(string archivePath) 65536, FileOptions.SequentialScan)) { byte[] sizeBuf = new byte[8]; - if (fs.Read(sizeBuf, 0, 8) != 8) + if (fs.ReadFull(sizeBuf, 0, 8) != 8) throw new Exception("Unable to read header size"); var sizePickle = Pickle.CreateFromBuffer(sizeBuf); var size = sizePickle.CreateIterator().ReadUInt32(); var headerBuf = new byte[size]; - if (fs.Read(headerBuf, 0, (int)size) != size) + if (fs.ReadFull(headerBuf, 0, (int)size) != size) throw new Exception("Unable to read header"); var headerPickle = Pickle.CreateFromBuffer(headerBuf); @@ -65,62 +62,28 @@ public static ArchiveHeader ReadArchiveHeaderSync(string archivePath) } } + /// + /// Reads the header fresh every time: an archive is repacked in place during a patch run, + /// so a cached header would hand out stale offsets on the next read of the same path. + /// public static Filesystem ReadFilesystemSync(string archivePath) { - return _filesystemCache.GetOrAdd(archivePath, key => - { - var header = ReadArchiveHeaderSync(key); - var filesystem = new Filesystem(key); - filesystem.SetHeader(header.Header, header.HeaderSize); - return filesystem; - }); - } - - public static byte[] ReadFileSync(Filesystem filesystem, string filename, FilesystemEntry info) - { - if (!info.IsFile || !info.Size.HasValue) - throw new ArgumentException("Entry is not a file", nameof(info)); - - long size = info.Size.Value; - byte[] buffer = new byte[size]; - - if (size <= 0) return buffer; - - if (info.Unpacked == true) - { - string filePath = Path.Combine($"{filesystem.GetRootPath()}.unpacked", filename); - return File.ReadAllBytes(filePath); - } - - using (var fs = new FileStream(filesystem.GetRootPath(), FileMode.Open, FileAccess.Read, - FileShare.Read, 65536, FileOptions.RandomAccess)) - { - long offset = 8 + filesystem.GetHeaderSize() + long.Parse(info.Offset); - fs.Position = offset; - int bytesRead = fs.Read(buffer, 0, (int)size); - if (bytesRead != size) - throw new Exception($"Failed to read entire file, got {bytesRead} bytes instead of {size}"); - } - - return buffer; + var header = ReadArchiveHeaderSync(archivePath); + var filesystem = new Filesystem(archivePath); + filesystem.SetHeader(header.Header, header.HeaderSize); + return filesystem; } #endregion - public static bool UncacheFilesystem(string archivePath) - { - return _filesystemCache.TryRemove(archivePath, out _); - } - - public static void UncacheAll() - { - _filesystemCache.Clear(); - } - public static void CopyFile(string dest, string rootPath, string filename) { - if (dest == null || rootPath == null || filename == null) - throw new ArgumentNullException(); + if (dest == null) + throw new ArgumentNullException(nameof(dest)); + if (rootPath == null) + throw new ArgumentNullException(nameof(rootPath)); + if (filename == null) + throw new ArgumentNullException(nameof(filename)); string normalizedDestRoot = Path.GetFullPath(dest) .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); @@ -192,6 +155,18 @@ public static void WriteFileSystem(string dest, Filesystem fileSystem, var patchedSizePickle = Pickle.CreateEmpty(); patchedSizePickle.WriteUInt32((uint)patchedPickle.GetTotalSize()); + // The rewrite lands on top of the placeholder header, so it must be exactly as + // long. Placeholder hashes are the same width as real ones, so this holds unless + // a file changed size between crawl and write - which would silently shred the + // payload that follows. + if (patchedPickle.GetTotalSize() != headerPickle.GetTotalSize() || + patchedSizePickle.GetTotalSize() != sizePickleSize) + { + throw new InvalidOperationException( + "ASAR header changed size while packing (a source file was modified mid-build). " + + "Aborting rather than writing a corrupt archive."); + } + fs.Position = 0; patchedSizePickle.WriteTo(fs); patchedPickle.WriteTo(fs); diff --git a/AsarSharp/AsarFileSystem/FileSystem.cs b/AsarSharp/AsarFileSystem/FileSystem.cs index e577c4ed..0410245e 100644 --- a/AsarSharp/AsarFileSystem/FileSystem.cs +++ b/AsarSharp/AsarFileSystem/FileSystem.cs @@ -33,7 +33,7 @@ public void SetHeader(FilesystemEntry header, int headerSize) _headerSize = headerSize; } - public FilesystemEntry SearchNodeFromDirectory(string p) + public FilesystemEntry SearchNodeFromDirectory(string p, bool create = true) { FilesystemEntry json = _header; @@ -59,12 +59,31 @@ public FilesystemEntry SearchNodeFromDirectory(string p) string seg = p.Substring(start, segLen); if (!json.IsDirectory) - throw new Exception($"Unexpected directory state while traversing: {p}"); + { + if (create) + throw new Exception($"Unexpected directory state while traversing: {p}"); + return null; + } + + if (json.Files == null) + { + if (create) + json.Files = new Dictionary(StringComparer.Ordinal); + else + return null; + } if (!json.Files.TryGetValue(seg, out var child)) { - child = new FilesystemEntry { Files = new Dictionary(StringComparer.Ordinal) }; - json.Files[seg] = child; + if (create) + { + child = new FilesystemEntry { Files = new Dictionary(StringComparer.Ordinal) }; + json.Files[seg] = child; + } + else + { + return null; + } } json = child; start = end + 1; @@ -81,7 +100,7 @@ public FilesystemEntry SearchNodeFromDirectory(string p) string name = Path.GetFileName(rel); string dir = Extensions.GetDirectoryName(rel); - var parent = SearchNodeFromDirectory(dir); + var parent = SearchNodeFromDirectory(dir, true); if (parent.Files == null) parent.Files = new Dictionary(StringComparer.Ordinal); @@ -111,18 +130,23 @@ void FillFilesFromMetadata(string basePath, FilesystemEntry metadata) } } - public FilesystemEntry GetNode(string p, bool followLinks = true) + public FilesystemEntry GetNode(string p, bool followLinks = true, int linkDepth = 0) { + if (linkDepth > 40) + throw new Exception($"Symlink loop detected at {p}"); + p = p.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar); - FilesystemEntry node = SearchNodeFromDirectory(Extensions.GetDirectoryName(p)); + FilesystemEntry node = SearchNodeFromDirectory(Extensions.GetDirectoryName(p), false); + if (node == null) + return null; string name = Path.GetFileName(p); if (node.IsLink && followLinks) - return GetNode(Path.Combine(node.Link, name)); + return GetNode(Path.Combine(node.Link, name), followLinks, linkDepth + 1); if (!string.IsNullOrEmpty(name)) { - if (node.IsDirectory && node.Files.TryGetValue(name, out var entry)) + if (node.IsDirectory && node.Files != null && node.Files.TryGetValue(name, out var entry)) return entry; return null; } @@ -130,16 +154,17 @@ public FilesystemEntry GetNode(string p, bool followLinks = true) return node; } - public FilesystemEntry GetFile(string p, bool followLinks = true) + public FilesystemEntry GetFile(string p, bool followLinks = true, int linkDepth = 0) { - FilesystemEntry info = GetNode(p, followLinks); + if (linkDepth > 40) + throw new Exception($"Symlink loop detected at {p}"); + + FilesystemEntry info = GetNode(p, followLinks, linkDepth); if (info == null) throw new Exception($"\"{p}\" was not found in this archive"); - if (info.IsLink && followLinks) return GetFile(info.Link, followLinks); + if (info.IsLink && followLinks) return GetFile(info.Link, followLinks, linkDepth + 1); return info; } - public static string ReadLink(string path) => throw new NotImplementedException(); - #region Writing public FilesystemEntry SearchNodeFromPath(string p) @@ -159,7 +184,7 @@ public void InsertDirectory(string p, bool unpack) public void InsertFile(string path, bool shouldUnpack, CrawledFileType file, IntegrityHelper.FileIntegrity precomputedIntegrity = null) { - var (dirNode, _) = SearchNodeFromPathWithParent(Path.GetDirectoryName(path) ?? path); + var (dirNode, _) = SearchNodeFromPathWithParent(path); var node = SearchNodeFromPath(path); long size; diff --git a/AsarSharp/AsarFileSystem/FileSystemCrawler.cs b/AsarSharp/AsarFileSystem/FileSystemCrawler.cs index a4ee35ef..6bf5ea9b 100644 --- a/AsarSharp/AsarFileSystem/FileSystemCrawler.cs +++ b/AsarSharp/AsarFileSystem/FileSystemCrawler.cs @@ -9,13 +9,6 @@ public class CrawledFileType { public FileType Type { get; set; } public FileSystemInfo Stat { get; set; } - public TransformedFile Transformed { get; set; } - } - - public class TransformedFile - { - public string Path { get; set; } - public FileSystemInfo Stat { get; set; } } public enum FileType @@ -36,7 +29,7 @@ public static CrawledFileType DetermineFileType(string filename) } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { - return null; + throw new IOException($"Failed to read attributes for '{filename}'", ex); } bool isDirectory = (attributes & FileAttributes.Directory) == FileAttributes.Directory; @@ -59,7 +52,6 @@ public static (List filenames, Dictionary metad foreach (var fullPath in CrawlIterative(dir)) { var type = DetermineFileType(fullPath); - if (type == null) continue; metadata[fullPath] = type; if (type.Type == FileType.Link) links.Add(fullPath); filenames.Add(fullPath); @@ -77,7 +69,8 @@ public static (List filenames, Dictionary metad { if (string.Equals(filename, link, StringComparison.OrdinalIgnoreCase)) continue; - if (filename.StartsWith(link, StringComparison.OrdinalIgnoreCase)) + // Require a separator after the prefix so "…/foobar" does not match link "…/foo". + if (filename.StartsWith(link + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) { string rel = Extensions.GetRelativePath(link, fileDir); if (!rel.StartsWith("..", StringComparison.Ordinal)) @@ -120,7 +113,7 @@ public static List CrawlIterative(string dir) foreach (var entry in entries) { result.Add(entry.FullName); - if (entry is DirectoryInfo subDir) + if (entry is DirectoryInfo subDir && (subDir.Attributes & FileAttributes.ReparsePoint) == 0) stack.Push(subDir); } } diff --git a/AsarSharp/Integrity/IntegrityHelper.cs b/AsarSharp/Integrity/IntegrityHelper.cs index f6c5302d..fb765824 100644 --- a/AsarSharp/Integrity/IntegrityHelper.cs +++ b/AsarSharp/Integrity/IntegrityHelper.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Security.Cryptography; +using AsarSharp.Utils; using Newtonsoft.Json; namespace AsarSharp.Integrity @@ -60,7 +61,9 @@ public static FileIntegrity GetFileIntegrity(string path, byte[] reusableBuffer var blockHashes = new List(estimatedBlockCount); int bytesRead; - while ((bytesRead = fileStream.Read(reusableBuffer, 0, reusableBuffer.Length)) > 0) + // ReadFull, not Read: a short read would hash a partial block and produce + // integrity blocks Electron rejects. + while ((bytesRead = fileStream.ReadFull(reusableBuffer, 0, reusableBuffer.Length)) > 0) { blockHashes.Add(ToLowerHex(blockHash.ComputeHash(reusableBuffer, 0, bytesRead))); fileHash.AppendData(reusableBuffer, 0, bytesRead); diff --git a/AsarSharp/PickleTools/Pickle.cs b/AsarSharp/PickleTools/Pickle.cs index c192a8fc..b02e72a9 100644 --- a/AsarSharp/PickleTools/Pickle.cs +++ b/AsarSharp/PickleTools/Pickle.cs @@ -28,16 +28,18 @@ private Pickle(byte[] buffer = null) { if (buffer != null) { + if (buffer.Length < SIZE_UINT32) + throw new ArgumentException("Buffer is too small.", nameof(buffer)); + _header = buffer; - _headerSize = buffer.Length - GetPayloadSize(); + int payloadSize = GetPayloadSize(); + if (payloadSize > buffer.Length) + throw new ArgumentException("Payload size exceeds buffer length.", nameof(buffer)); + + _headerSize = buffer.Length - payloadSize; _capacityAfterHeader = CAPACITY_READ_ONLY; _writeOffset = 0; - if (_headerSize > buffer.Length) - { - _headerSize = 0; - } - if (_headerSize != AlignInt(_headerSize, SIZE_UINT32)) { _headerSize = 0; @@ -86,7 +88,7 @@ public void WriteTo(Stream stream) } - public bool WriteBool(bool value) => WriteInt(value ? 1 : 0); + public bool WriteInt(int value) { @@ -121,74 +123,7 @@ public bool WriteUInt32(uint value) return true; } - public bool WriteInt64(long value) - { - const int dataLength = SIZE_INT64; - int newSize = _writeOffset + dataLength; - - if (newSize > _capacityAfterHeader) - { - Resize(Math.Max((int)_capacityAfterHeader * 2, newSize)); - } - - WriteInt64LE(value, _headerSize + _writeOffset); - SetPayloadSize(newSize); - _writeOffset = newSize; - return true; - } - - - public bool WriteUInt64(ulong value) - { - const int dataLength = SIZE_UINT64; - int newSize = _writeOffset + dataLength; - - if (newSize > _capacityAfterHeader) - { - Resize(Math.Max((int)_capacityAfterHeader * 2, newSize)); - } - - WriteUInt64LE(value, _headerSize + _writeOffset); - SetPayloadSize(newSize); - _writeOffset = newSize; - return true; - } - - public bool WriteFloat(float value) - { - const int dataLength = SIZE_FLOAT; - int newSize = _writeOffset + dataLength; - - if (newSize > _capacityAfterHeader) - { - Resize(Math.Max((int)_capacityAfterHeader * 2, newSize)); - } - - int bits = BitConverter.ToInt32(BitConverter.GetBytes(value), 0); - WriteInt32LE(bits, _headerSize + _writeOffset); - - SetPayloadSize(newSize); - _writeOffset = newSize; - return true; - } - - public bool WriteDouble(double value) - { - const int dataLength = SIZE_DOUBLE; - int newSize = _writeOffset + dataLength; - if (newSize > _capacityAfterHeader) - { - Resize(Math.Max((int)_capacityAfterHeader * 2, newSize)); - } - - long bits = BitConverter.DoubleToInt64Bits(value); - WriteInt64LE(bits, _headerSize + _writeOffset); - - SetPayloadSize(newSize); - _writeOffset = newSize; - return true; - } public bool WriteString(string value) { @@ -226,7 +161,13 @@ public void SetPayloadSize(int payloadSize) WriteUInt32LE((uint)payloadSize, 0); } - public int GetPayloadSize() => (int)ReadUInt32LE(0); + public int GetPayloadSize() + { + uint size = ReadUInt32LE(0); + if (size > int.MaxValue) + throw new InvalidOperationException("Payload size exceeds maximum allowed (2GB)."); + return (int)size; + } private void Resize(int newCapacity) { @@ -275,29 +216,7 @@ private void WriteUInt32LE(uint value, int offset) _header[offset + 3] = (byte)(value >> 24); } - private void WriteInt64LE(long value, int offset) - { - _header[offset] = (byte)value; - _header[offset + 1] = (byte)(value >> 8); - _header[offset + 2] = (byte)(value >> 16); - _header[offset + 3] = (byte)(value >> 24); - _header[offset + 4] = (byte)(value >> 32); - _header[offset + 5] = (byte)(value >> 40); - _header[offset + 6] = (byte)(value >> 48); - _header[offset + 7] = (byte)(value >> 56); - } - private void WriteUInt64LE(ulong value, int offset) - { - _header[offset] = (byte)value; - _header[offset + 1] = (byte)(value >> 8); - _header[offset + 2] = (byte)(value >> 16); - _header[offset + 3] = (byte)(value >> 24); - _header[offset + 4] = (byte)(value >> 32); - _header[offset + 5] = (byte)(value >> 40); - _header[offset + 6] = (byte)(value >> 48); - _header[offset + 7] = (byte)(value >> 56); - } #endregion diff --git a/AsarSharp/PickleTools/PickleIterator.cs b/AsarSharp/PickleTools/PickleIterator.cs index 11d069a5..95647e78 100644 --- a/AsarSharp/PickleTools/PickleIterator.cs +++ b/AsarSharp/PickleTools/PickleIterator.cs @@ -18,10 +18,7 @@ public PickleIterator(Pickle pickle) _endIndex = pickle.GetPayloadSize(); } - public bool ReadBool() - { - return ReadInt() != 0; - } + public int ReadInt() { @@ -33,25 +30,7 @@ public uint ReadUInt32() return ReadBytes(Pickle.SIZE_UINT32, BitConverter.ToUInt32); } - public long ReadInt64() - { - return ReadBytes(Pickle.SIZE_INT64, BitConverter.ToInt64); - } - public ulong ReadUInt64() - { - return ReadBytes(Pickle.SIZE_UINT64, BitConverter.ToUInt64); - } - - public float ReadFloat() - { - return ReadBytes(Pickle.SIZE_FLOAT, BitConverter.ToSingle); - } - - public double ReadDouble() - { - return ReadBytes(Pickle.SIZE_DOUBLE, BitConverter.ToDouble); - } public string ReadString() { @@ -75,7 +54,7 @@ private byte[] ReadBytes(int length) private int GetReadPayloadOffsetAndAdvance(int length) { - if (length > _endIndex - _readIndex) + if (length < 0 || length > _endIndex - _readIndex) { _readIndex = _endIndex; throw new InvalidOperationException($"Failed to read data with length of {length}"); diff --git a/AsarSharp/Utils/Extensions.cs b/AsarSharp/Utils/Extensions.cs index 3abaf5f3..34dad7f2 100644 --- a/AsarSharp/Utils/Extensions.cs +++ b/AsarSharp/Utils/Extensions.cs @@ -5,8 +5,30 @@ namespace AsarSharp.Utils { - internal static class Extensions + public static class Extensions { + /// + /// Fills bytes. Stream.Read may legally return fewer than + /// asked for; treating a short read as EOF corrupts header parsing and block hashes. + /// Returns the bytes actually read, which is less than count only at end of stream. + /// + public static int ReadFull(this Stream stream, byte[] buffer, int offset, int count) + { + int total = 0; + while (total < count) + { + int read = stream.Read(buffer, offset + total, count - total); + if (read <= 0) + { + break; + } + + total += read; + } + + return total; + } + /// /// Compute path relative to . /// Fast common-case (path is inside relativeTo): plain prefix-strip. @@ -170,19 +192,7 @@ public static void SetUnixFilePermission(string filePath, string permission) if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return; - var process = new System.Diagnostics.Process - { - StartInfo = new System.Diagnostics.ProcessStartInfo - { - FileName = "chmod", - Arguments = $"{permission} \"{filePath}\"", - UseShellExecute = false, - RedirectStandardOutput = true, - CreateNoWindow = true - } - }; - process.Start(); - process.WaitForExit(); + RunTool("chmod", $"{permission} \"{filePath}\""); } @@ -190,32 +200,41 @@ public static void CreateSymbolicLink(string linkTarget, string linkPath) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - NativeMethods.CreateSymbolicLink(linkPath, linkTarget, + bool success = NativeMethods.CreateSymbolicLink(linkPath, linkTarget, Directory.Exists(linkTarget) ? NativeMethods.SymLinkFlag.Directory : NativeMethods.SymLinkFlag.File); + if (!success) + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); return; } - var process = new System.Diagnostics.Process - { - StartInfo = new System.Diagnostics.ProcessStartInfo - { - FileName = "ln", - Arguments = $"-s \"{linkTarget}\" \"{linkPath}\"", - UseShellExecute = false, - RedirectStandardOutput = true, - CreateNoWindow = true - } - }; - process.Start(); - process.WaitForExit(); + RunTool("ln", $"-s \"{linkTarget}\" \"{linkPath}\""); } - public static bool IsWindowsPlatform() { - return Environment.OSVersion.Platform == PlatformID.Win32NT; + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + } + + private static void RunTool(string fileName, string arguments) + { + using (var process = new System.Diagnostics.Process + { + StartInfo = new System.Diagnostics.ProcessStartInfo + { + FileName = fileName, + Arguments = arguments, + UseShellExecute = false, + CreateNoWindow = true + } + }) + { + process.Start(); + process.WaitForExit(); + if (process.ExitCode != 0) + throw new InvalidOperationException($"Tool {fileName} failed with exit code {process.ExitCode}."); + } } } } From 6716da5c80497d53852501a0dca3e492c9267843 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Sat, 29 Aug 2026 16:56:09 +0300 Subject: [PATCH 03/15] feat(patch-engine): locate patches structurally instead of by signature Anchor each patch on a stable string (API endpoint, IPC channel, method name) and walk the delimiter structure via JsCursor to the edit site, reading minified identifiers out of the located region. Move injected JavaScript into WandEnhancer/Patches/*.js as embedded resources. Declare patches as PatchEntry rows in EnhancerConfig with CandidateFileNames, SearchHints and optional CapabilityHints. Recognise keyword-preceded regex literals in JsCursor so `return/re/.test(x)` no longer desynchronises the scan. Require the remote setValue anchor to match exactly once; Wand ships sibling call sites for other sources. Require both backup halves in IsPatched so a partial backup no longer blocks patch and restore at the same time. Chain inner exceptions when unpack or pack fails. Rename Common to ProcessTerminator and Utils.Extensions to WeModInstalls. --- WandEnhancer/Core/Enhancer.cs | 353 +++++++------- WandEnhancer/Core/EnhancerConfig.cs | 449 +++++++++++------- WandEnhancer/Core/JavaScriptPatchApplier.cs | 82 ++++ WandEnhancer/Core/Js/JsCursor.cs | 409 ++++++++++++++++ WandEnhancer/Core/Js/JsFunction.cs | 129 +++++ WandEnhancer/Core/Js/PatchPayload.cs | 63 +++ WandEnhancer/Models/PatchConfig.cs | 27 +- WandEnhancer/Models/Signature.cs | 48 -- WandEnhancer/Patches/devtools-f12.js | 1 + .../Patches/disable-native-pairing.js | 1 + WandEnhancer/Patches/disable-updates.js | 1 + WandEnhancer/Patches/pro-account-reducer.js | 1 + WandEnhancer/Patches/pro-subscription.js | 1 + WandEnhancer/Patches/remote-bridge-boot.js | 1 + .../Patches/remote-bridge-renderer.js | 1 + WandEnhancer/Patches/remote-bridge-reset.js | 1 + WandEnhancer/Patches/remote-bridge-sync.js | 1 + .../Patches/remote-bridge-value-delta.js | 1 + WandEnhancer/Utils/Common.cs | 59 --- WandEnhancer/Utils/ProcessTerminator.cs | 85 ++++ .../Utils/{Extensions.cs => WeModInstalls.cs} | 21 +- 21 files changed, 1249 insertions(+), 486 deletions(-) create mode 100644 WandEnhancer/Core/JavaScriptPatchApplier.cs create mode 100644 WandEnhancer/Core/Js/JsCursor.cs create mode 100644 WandEnhancer/Core/Js/JsFunction.cs create mode 100644 WandEnhancer/Core/Js/PatchPayload.cs delete mode 100644 WandEnhancer/Models/Signature.cs create mode 100644 WandEnhancer/Patches/devtools-f12.js create mode 100644 WandEnhancer/Patches/disable-native-pairing.js create mode 100644 WandEnhancer/Patches/disable-updates.js create mode 100644 WandEnhancer/Patches/pro-account-reducer.js create mode 100644 WandEnhancer/Patches/pro-subscription.js create mode 100644 WandEnhancer/Patches/remote-bridge-boot.js create mode 100644 WandEnhancer/Patches/remote-bridge-renderer.js create mode 100644 WandEnhancer/Patches/remote-bridge-reset.js create mode 100644 WandEnhancer/Patches/remote-bridge-sync.js create mode 100644 WandEnhancer/Patches/remote-bridge-value-delta.js delete mode 100644 WandEnhancer/Utils/Common.cs create mode 100644 WandEnhancer/Utils/ProcessTerminator.cs rename WandEnhancer/Utils/{Extensions.cs => WeModInstalls.cs} (88%) diff --git a/WandEnhancer/Core/Enhancer.cs b/WandEnhancer/Core/Enhancer.cs index de59311a..28411c00 100644 --- a/WandEnhancer/Core/Enhancer.cs +++ b/WandEnhancer/Core/Enhancer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -18,6 +18,8 @@ public class Enhancer private const string AppAsarUnpackedDirectoryName = "app.asar.unpacked"; private const string AppAsarBackupFileName = "app.asar.backup"; private const string AppAsarUnpackedBackupDirectoryName = "app.asar.unpacked.backup"; + private const string ProxyDllFileName = "version.dll"; + private const string StubBackupSuffix = ".stub"; private const string WebPanelDirectoryName = "web-panel"; private const string WebPanelDistDirectoryName = "dist"; private const string LocalCustomScriptsDirectoryName = "renderer-scripts"; @@ -28,7 +30,6 @@ public class Enhancer private const string AppBundleFilePrefix = "app-"; private const string AppBundleFileSuffix = ".bundle.js"; private const string IndexBundleFileName = "index.js"; - private const string JavaScriptFileExtension = ".js"; private const string JavaScriptFileSearchPattern = "*.js"; private const string DuplicateScriptSuffix = ".custom"; private const int FirstDuplicateScriptIndex = 1; @@ -36,92 +37,46 @@ public class Enhancer private readonly WeModConfig _weModConfig; private readonly Action _logger; private readonly PatchConfig _config; + private readonly JavaScriptPatchApplier _jsPatchApplier; private readonly string _asarPath; private readonly string _backupPath; private readonly string _unpackedPath; private readonly string _unpackedBackupPath; + /// For , which needs the install paths but no patch selection. + public Enhancer(WeModConfig weModConfig, Action logger) + : this(weModConfig, logger, null) + { + } + public Enhancer(WeModConfig weModConfig, Action logger, PatchConfig config) { _weModConfig = weModConfig; _logger = logger; _config = config; + _jsPatchApplier = new JavaScriptPatchApplier(logger); _asarPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarFileName); _unpackedPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarUnpackedDirectoryName); _backupPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarBackupFileName); _unpackedBackupPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarUnpackedBackupDirectoryName); } - - private string ApplyJsPatch(string fileName, string js, EnhancerConfig.PatchEntry patch, EPatchType patchType, out bool patchApplied) - { - patchApplied = false; - - if (patch.Applied) - { - return js; - } - if (!CanSearchPatchInFile(fileName, patch) || !ContainsSearchHint(js, patch.SearchHints)) - { - return js; - } - - var match = patch.Target.Match(js); - if (!match.Success) - { - return js; - } - - var prefix = $"[ENHANCER] [{patchType} -> {patch.Name}]"; - - if(patch.SingleMatch && match.NextMatch().Success) - { - throw new Exception( - $"{prefix} Patch failed. Multiple target functions found. Looks like the version is not supported"); - } - - string patchSource = patch.PatchFactory != null - ? patch.PatchFactory(match) - : patch.Patch; - - if (patch.Resolver != null) - { - string resolvedField = patch.Resolver.Handler(match.Value); - if (string.IsNullOrEmpty(resolvedField)) - { - throw new Exception($"{prefix} Resolver failed to find field name"); - } - - patchSource = patchSource.Replace(patch.Resolver.Placeholder, resolvedField); - } - - _logger($"{prefix} Found target function in: " + Path.GetFileName(fileName), ELogType.Info); - - string newJs; - if (patch.PatchFactory != null) - { - newJs = patch.SingleMatch - ? patch.Target.Replace(js, _ => patchSource, 1) - : patch.Target.Replace(js, _ => patchSource); - } - else - { - newJs = patch.SingleMatch - ? patch.Target.Replace(js, patchSource, 1) - : patch.Target.Replace(js, patchSource); - } - - _logger($"{prefix} Patch applied", ELogType.Success); - patch.Applied = true; - patchApplied = true; - - return newJs; + /// + /// Both halves of the backup must exist. Accepting either one on its own reported a + /// half-written backup as patched, which blocked patching while + /// refused to run - leaving the user with no way forward. + /// + public static bool IsPatched(string rootDirectory) + { + var resources = Path.Combine(rootDirectory, ResourcesDirectoryName); + return File.Exists(Path.Combine(resources, AppAsarBackupFileName)) + && Directory.Exists(Path.Combine(resources, AppAsarUnpackedBackupDirectoryName)); } private void PatchAsar() { - var items = Directory.EnumerateFiles(_unpackedPath, $"*{JavaScriptFileExtension}", SearchOption.TopDirectoryOnly) + var items = Directory.EnumerateFiles(_unpackedPath, JavaScriptFileSearchPattern, SearchOption.TopDirectoryOnly) .Where(IsCandidateBundleFile) .ToList(); @@ -129,7 +84,7 @@ private void PatchAsar() { throw new Exception("[ENHANCER] No app bundle found"); } - + var remainingPatches = new HashSet(_config.PatchTypes); var enhancerConfig = EnhancerConfig.GetInstance(); @@ -144,20 +99,22 @@ private void PatchAsar() { continue; } - + string data = File.ReadAllText(item); bool fileChanged = false; - + foreach (var entry in remainingPatches.ToList()) { var entries = enhancerConfig[entry]; foreach (var patchEntry in entries) { bool patchApplied; - data = ApplyJsPatch(item, data, patchEntry, entry, out patchApplied); + data = _jsPatchApplier.Apply(item, data, patchEntry, entry, out patchApplied); fileChanged = fileChanged || patchApplied; } + // Optional patches stay in the scan until every file has been checked, because + // their capability may still show up in a bundle we have not read yet. if (entries.All(x => x.Applied)) { remainingPatches.Remove(entry); @@ -169,62 +126,43 @@ private void PatchAsar() File.WriteAllText(item, data); } } - - if(remainingPatches.Count > 0) - { - var failedPatches = string.Join(", ", remainingPatches.Select(p => p.ToString())); - throw new Exception($"[ENHANCER] Failed to apply patches: {failedPatches}. The version may not be supported."); - } - } - private static bool IsCandidateBundleFile(string filePath) - { - string fileName = Path.GetFileName(filePath); - return fileName.Equals(IndexBundleFileName, StringComparison.OrdinalIgnoreCase) - || (fileName.StartsWith(AppBundleFilePrefix, StringComparison.OrdinalIgnoreCase) - && fileName.EndsWith(AppBundleFileSuffix, StringComparison.OrdinalIgnoreCase)); + ReportUnappliedPatches(remainingPatches, enhancerConfig); } - private static bool CouldFileContainRemainingPatch(string filePath, IEnumerable remainingPatches, Dictionary enhancerConfig) + private void ReportUnappliedPatches(IEnumerable remainingPatches, Dictionary enhancerConfig) { - foreach (var patchType in remainingPatches) - { - foreach (var patchEntry in enhancerConfig[patchType]) - { - if (patchEntry.Applied) - { - continue; - } + var unapplied = remainingPatches + .SelectMany(patchType => enhancerConfig[patchType] + .Where(patch => !patch.Applied) + .Select(patch => new { Label = JavaScriptPatchApplier.FormatLabel(patchType, patch), Patch = patch })) + .ToList(); - if (CanSearchPatchInFile(filePath, patchEntry)) - { - return true; - } - } + foreach (var skipped in unapplied.Where(entry => entry.Patch.IsResolved)) + { + _logger($"[ENHANCER] [{skipped.Label}] Capability not present, skipping", ELogType.Info); } - return false; - } - - private static bool CanSearchPatchInFile(string filePath, EnhancerConfig.PatchEntry patch) - { - if (patch.CandidateFileNames == null || patch.CandidateFileNames.Length == 0) + var failed = unapplied.Where(entry => !entry.Patch.IsResolved).Select(entry => entry.Label).ToList(); + if (failed.Count > 0) { - return true; + throw new Exception($"[ENHANCER] Failed to apply patches: {string.Join(", ", failed)}. The version may not be supported."); } + } + private static bool IsCandidateBundleFile(string filePath) + { string fileName = Path.GetFileName(filePath); - return patch.CandidateFileNames.Any(candidate => fileName.Equals(candidate, StringComparison.OrdinalIgnoreCase)); + return fileName.Equals(IndexBundleFileName, StringComparison.OrdinalIgnoreCase) + || (fileName.StartsWith(AppBundleFilePrefix, StringComparison.OrdinalIgnoreCase) + && fileName.EndsWith(AppBundleFileSuffix, StringComparison.OrdinalIgnoreCase)); } - private static bool ContainsSearchHint(string source, string[] searchHints) + private static bool CouldFileContainRemainingPatch(string filePath, IEnumerable remainingPatches, Dictionary enhancerConfig) { - if (searchHints == null || searchHints.Length == 0) - { - return true; - } - - return searchHints.Any(searchHint => source.IndexOf(searchHint, StringComparison.Ordinal) >= 0); + return remainingPatches + .SelectMany(patchType => enhancerConfig[patchType]) + .Any(patchEntry => !patchEntry.Applied && JavaScriptPatchApplier.CanSearchFile(filePath, patchEntry)); } private static string FindWorkspacePath(params string[] segments) @@ -244,25 +182,6 @@ private static string FindWorkspacePath(params string[] segments) throw new FileNotFoundException($"Required workspace artifact not found: {Path.Combine(segments)}"); } - internal static void CopyDirectory(string sourceDir, string destinationDir) - { - Directory.CreateDirectory(destinationDir); - - foreach (var directory in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories)) - { - var relativePath = directory.Substring(sourceDir.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - Directory.CreateDirectory(Path.Combine(destinationDir, relativePath)); - } - - foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories)) - { - var relativePath = file.Substring(sourceDir.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - var destinationPath = Path.Combine(destinationDir, relativePath); - Directory.CreateDirectory(Path.GetDirectoryName(destinationPath) ?? destinationDir); - File.Copy(file, destinationPath, true); - } - } - private static int CopyJavaScriptFiles(string sourceDir, string destinationDir) { if (string.IsNullOrEmpty(sourceDir) || !Directory.Exists(sourceDir)) @@ -270,16 +189,9 @@ private static int CopyJavaScriptFiles(string sourceDir, string destinationDir) return 0; } - Directory.CreateDirectory(destinationDir); - - int copied = 0; - foreach (var file in Directory.GetFiles(sourceDir, JavaScriptFileSearchPattern, SearchOption.TopDirectoryOnly)) - { - File.Copy(file, GetAvailableScriptPath(destinationDir, Path.GetFileName(file))); - copied++; - } - - return copied; + return CopySelectedJavaScriptFiles( + Directory.GetFiles(sourceDir, JavaScriptFileSearchPattern, SearchOption.TopDirectoryOnly), + destinationDir); } private static string GetAvailableScriptPath(string destinationDir, string fileName) @@ -363,7 +275,7 @@ private static int CopySelectedJavaScriptFiles(IEnumerable files, string Directory.CreateDirectory(destinationDir); int copied = 0; - foreach (var file in files.Where(IsJavaScriptFile).Distinct(StringComparer.OrdinalIgnoreCase)) + foreach (var file in files.Where(WeModInstalls.IsJavaScriptFile).Distinct(StringComparer.OrdinalIgnoreCase)) { File.Copy(file, GetAvailableScriptPath(destinationDir, Path.GetFileName(file))); copied++; @@ -372,11 +284,6 @@ private static int CopySelectedJavaScriptFiles(IEnumerable files, string return copied; } - private static bool IsJavaScriptFile(string file) - { - return File.Exists(file) && string.Equals(Path.GetExtension(file), JavaScriptFileExtension, StringComparison.OrdinalIgnoreCase); - } - private void InjectRemotePanelFiles() { if (!_config.PatchTypes.Contains(EPatchType.RemoteWebPanelPreview)) @@ -396,7 +303,7 @@ private void InjectRemotePanelFiles() if (CopyEmbeddedDirectory(EmbeddedRemotePanelDistPrefix, targetRoot) == 0) { - CopyDirectory(FindWorkspacePath(WebPanelDirectoryName, WebPanelDistDirectoryName), targetRoot); + AsarSharp.Utils.Extensions.CopyDirectory(FindWorkspacePath(WebPanelDirectoryName, WebPanelDistDirectoryName), targetRoot); } if (!File.Exists(targetBridgePath)) @@ -418,25 +325,79 @@ private void InjectRemotePanelFiles() _logger($"[ENHANCER] Injected remote panel assets and renderer scripts into app.asar (default: {defaultScriptCount}, selected: {selectedScriptCount}, local: {localScriptCount})", ELogType.Info); } - private void AttachProxyDll() + private string SquirrelRoot { - var assembly = Assembly.GetExecutingAssembly(); - var dll = assembly.GetManifestResourceStream(Constants.ProxyDllResouceName); - if (dll == null) + get + { + string root = Directory.GetParent(_weModConfig.RootDirectory)?.FullName; + if (string.IsNullOrEmpty(root)) + { + throw new Exception("[ENHANCER] Cannot determine Squirrel root directory"); + } + + return root; + } + } + + private void DeployLauncher() + { + string stubPath = Path.Combine(SquirrelRoot, _weModConfig.ExecutableName); + string stubBackup = stubPath + StubBackupSuffix; + string self = Assembly.GetExecutingAssembly().Location; + + // Auto-patch runs from inside the deployed launcher: it cannot overwrite its own + // running image, and does not need to - it is already in place. + if (string.Equals(self, stubPath, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (File.Exists(stubPath) && !File.Exists(stubBackup)) + { + File.Copy(stubPath, stubBackup); + } + + File.Copy(self, stubPath, true); + _logger("[ENHANCER] Launcher deployed to root directory", ELogType.Info); + } + + private void SaveAutoPatchConfig() + { + string path = Path.Combine(SquirrelRoot, Constants.AutoPatchConfigFileName); + File.WriteAllText(path, Newtonsoft.Json.JsonConvert.SerializeObject(_config, Newtonsoft.Json.Formatting.Indented)); + } + + private void DeleteAutoPatchConfig() + { + string path = Path.Combine(SquirrelRoot, Constants.AutoPatchConfigFileName); + if (File.Exists(path)) + { + File.Delete(path); + } + } + + /// Reads the patch selection saved next to the launcher, or null when absent or unreadable. + public static PatchConfig LoadAutoPatchConfig(string launcherDirectory) + { + try { - throw new Exception("[ENHANCER] Proxy DLL resource not found"); + string path = Path.Combine(launcherDirectory, Constants.AutoPatchConfigFileName); + if (!File.Exists(path)) + { + return null; + } + + return Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(path)); } - var destPath = Path.Combine(_weModConfig.RootDirectory, "version.dll"); - using (var fileStream = File.Create(destPath)) + catch (Exception e) when (e is IOException || e is Newtonsoft.Json.JsonException || e is UnauthorizedAccessException) { - dll.CopyTo(fileStream); + return null; } - _logger("[ENHANCER] Proxy DLL attached", ELogType.Info); } public void Patch() { - Common.TryKillProcess(_weModConfig.BrandName); + ProcessTerminator.TryKillProcess(_weModConfig.BrandName); if (!File.Exists(_backupPath)) { _logger("[ENHANCER] Creating backup...", ELogType.Info); @@ -451,7 +412,7 @@ public void Patch() if (!Directory.Exists(_unpackedBackupPath) && Directory.Exists(_unpackedPath)) { _logger("[ENHANCER] Creating backup of app.asar.unpacked...", ELogType.Info); - CopyDirectory(_unpackedPath, _unpackedBackupPath); + AsarSharp.Utils.Extensions.CopyDirectory(_unpackedPath, _unpackedBackupPath); } else if (Directory.Exists(_unpackedBackupPath)) { @@ -461,14 +422,14 @@ public void Patch() Directory.Delete(_unpackedPath, true); } - CopyDirectory(_unpackedBackupPath, _unpackedPath); + AsarSharp.Utils.Extensions.CopyDirectory(_unpackedBackupPath, _unpackedPath); } else if (!Directory.Exists(_unpackedPath)) { throw new Exception("[ENHANCER] app.asar.unpacked is missing and no backup exists. Restore the original Wand installation files or reinstall Wand, then patch again."); } - if(!File.Exists(_asarPath)) + if (!File.Exists(_asarPath)) { throw new Exception("app.asar not found"); } @@ -480,9 +441,9 @@ public void Patch() } catch (Exception e) { - throw new Exception($"[ENHANCER] Failed to unpack app.asar: {e.Message}"); + throw new Exception($"[ENHANCER] Failed to unpack app.asar: {e.Message}", e); } - + PatchAsar(); InjectRemotePanelFiles(); @@ -495,12 +456,68 @@ public void Patch() } catch (Exception e) { - throw new Exception($"[ENHANCER] Failed to pack app.asar: {e.Message}"); + throw new Exception($"[ENHANCER] Failed to pack app.asar: {e.Message}", e); } - - AttachProxyDll(); - + + DeployLauncher(); + + // enhancer.json only exists to drive auto-patch. Without it the launcher still + // runs Wand (fuse patch only), so drop it when the user opts out. + if (_config.AutoApplyAfterUpdate) + { + SaveAutoPatchConfig(); + } + else + { + DeleteAutoPatchConfig(); + } + _logger("[ENHANCER] Done!", ELogType.Success); } + + public void Restore() + { + if (!File.Exists(_backupPath) || !Directory.Exists(_unpackedBackupPath)) + { + throw new Exception("[ENHANCER] Backup is incomplete. Restore the original Wand installation files or reinstall Wand."); + } + + ProcessTerminator.TryKillProcess(_weModConfig.BrandName); + File.Copy(_backupPath, _asarPath, true); + + if (Directory.Exists(_unpackedPath)) + { + Directory.Delete(_unpackedPath, true); + } + + AsarSharp.Utils.Extensions.CopyDirectory(_unpackedBackupPath, _unpackedPath); + + // Clean up legacy proxy DLL + var proxyDllPath = Path.Combine(_weModConfig.RootDirectory, ProxyDllFileName); + if (File.Exists(proxyDllPath)) + { + File.Delete(proxyDllPath); + } + + // Restore original Squirrel stub and drop the auto-patch config + string squirrelRoot = SquirrelRoot; + string stubPath = Path.Combine(squirrelRoot, _weModConfig.ExecutableName); + string stubBackup = stubPath + StubBackupSuffix; + if (File.Exists(stubBackup)) + { + File.Copy(stubBackup, stubPath, true); + File.Delete(stubBackup); + } + + string autoPatchConfig = Path.Combine(squirrelRoot, Constants.AutoPatchConfigFileName); + if (File.Exists(autoPatchConfig)) + { + File.Delete(autoPatchConfig); + } + + File.Delete(_backupPath); + Directory.Delete(_unpackedBackupPath, true); + _logger("[ENHANCER] Backup restored successfully.", ELogType.Success); + } } } diff --git a/WandEnhancer/Core/EnhancerConfig.cs b/WandEnhancer/Core/EnhancerConfig.cs index ab23c495..594283aa 100644 --- a/WandEnhancer/Core/EnhancerConfig.cs +++ b/WandEnhancer/Core/EnhancerConfig.cs @@ -1,105 +1,44 @@ using System; using System.Collections.Generic; using System.Text.RegularExpressions; +using WandEnhancer.Core.Js; using WandEnhancer.Models; namespace WandEnhancer.Core { - public static class EnhancerConfig + /// + /// Patch definitions. Each entry anchors on something Wand does not rename between builds - + /// an API endpoint, an IPC channel name or a public method name - and then navigates the + /// delimiter structure to the edit site. Minified identifiers are read out of the located + /// region rather than baked into a pattern, so a rebuild does not invalidate a patch. + /// + internal static class EnhancerConfig { - public class ResolveContext - { - public string Placeholder { get; set; } - public Func Handler { get; set; } - } + /// Locates the edits a patch must make, or null when the anchor is absent from this file. + public delegate JsEdit[] PatchLocator(JsCursor js); - public class PatchEntry + public sealed class PatchEntry { - public Regex Target { get; set; } - public string Patch { get; set; } - public Func PatchFactory { get; set; } public string Name { get; set; } - public bool Applied { get; set; } - public bool SingleMatch { get; set; } = true; + public PatchLocator Locate { get; set; } public string[] CandidateFileNames { get; set; } public string[] SearchHints { get; set; } - public ResolveContext Resolver { get; set; } - } - - private static string RequireGroup(Match match, string groupName, string patchName) - { - var group = match.Groups[groupName]; - if (!group.Success || string.IsNullOrEmpty(group.Value)) - { - throw new Exception($"{patchName} failed to resolve {groupName}"); - } - return group.Value; - } - - private static string RequirePattern(string source, string pattern, string groupName, string patchName) - { - var match = Regex.Match(source, pattern, RegexOptions.Singleline); - return RequireGroup(match, groupName, patchName); - } - - private static string BuildSetAccountLanguagePatch(Match match) - { - var parameters = RequireGroup(match, "params", "setAccountLanguage"); - var expr = RequireGroup(match, "expr", "setAccountLanguage"); - return $"setAccountLanguage({parameters}){{return ({expr}).then(response=>{{response&&\"object\"==typeof response&&(response.subscription={{period:\"yearly\",state:\"active\"}});return response;}})}}"; - } + /// Marks the patch optional: builds without these strings lack the feature entirely. + public string[] CapabilityHints { get; set; } - private static string BuildSetAccountReducerPatch(Match match) - { - var decl = RequireGroup(match, "decl", "setAccountReducer"); - var fn = RequireGroup(match, "fn", "setAccountReducer"); - var parameters = RequireGroup(match, "params", "setAccountReducer"); - var state = RequireGroup(match, "state", "setAccountReducer"); - var account = RequireGroup(match, "account", "setAccountReducer"); - return - $"const {decl}=\"ACTION_SET_ACCOUNT\";function {fn}({parameters}){{const a={account}&&\"object\"==typeof {account}?{{...{account},subscription:{{period:\"yearly\",state:\"active\"}}}}:{account};return{{...{state},account:a}}}}"; - } + public bool Applied { get; set; } + public bool CapabilityDetected { get; set; } - private static string BuildRemoteBridgeResetPatch(Match match) - { - var source = match.Value; - var method = RequireGroup(match, "method", "remoteBridgeReset"); - var disposableField = RequirePattern(source, @"this\.(?#[\w$]+)\s*&&\s*\(\s*this\.\k\.dispose\(\)", "disposable", "remoteBridgeReset"); - var instanceField = RequirePattern(source, @"this\.(?#[\w$]+)\s*=\s*Date\.now\(\)\.toString\(\)", "instance", "remoteBridgeReset"); - var trainerIdField = RequirePattern(source, @"Date\.now\(\)\.toString\(\)\s*\)?\s*,\s*\(?\s*this\.(?#[\w$]+)\s*=\s*null", "trainerId", "remoteBridgeReset"); - var supportedVersionsField = RequirePattern(source, @"this\.(?#[\w$]+)\s*=\s*\[\]", "versions", "remoteBridgeReset"); - var trainerField = RequirePattern(source, @"this\.(?#[\w$]+)\s*=\s*\[\]\s*\)?\s*,\s*\(?\s*this\.(?#[\w$]+)\s*=\s*null", "trainer", "remoteBridgeReset"); - - return $"{method}(){{this.{disposableField}&&(this.{disposableField}.dispose(),this.{disposableField}=null),this.{instanceField}=Date.now().toString(),this.{trainerIdField}=null,this.{supportedVersionsField}=[],this.{trainerField}=null,this.__wandRemoteTrainerInfo=null,this.__wandRemoteBridge?.sync(null)}}"; - } + public bool IsOptional => CapabilityHints != null && CapabilityHints.Length > 0; - private static string BuildRemoteBridgeSyncSnapshotPatch(Match match) - { - var source = match.Value; - var method = RequireGroup(match, "method", "remoteBridgeSyncSnapshot"); - var statusAlias = RequirePattern(source, @"this\.status\s*===\s*(?[\w$]+)\.Connected", "value", "remoteBridgeSyncSnapshot"); - var trainerField = RequirePattern(source, @"this\.(?#[\w$]+)\?\.\s*getMetadata\s*\(\s*(?[\w$]+\.[\w$]+)\s*\)\?\.\s*gameVersion", "trainer", "remoteBridgeSyncSnapshot"); - var metadataExport = RequirePattern(source, @"this\.(?#[\w$]+)\?\.\s*getMetadata\s*\(\s*(?[\w$]+\.[\w$]+)\s*\)\?\.\s*gameVersion", "metadata", "remoteBridgeSyncSnapshot"); - var notesField = RequirePattern(source, @"this\.(?#[\w$]+)\s*\[\s*this\.(?#[\w$]+)\s*\?\?\s*""""\s*\]", "notes", "remoteBridgeSyncSnapshot"); - var trainerIdField = RequirePattern(source, @"this\.(?#[\w$]+)\s*\[\s*this\.(?#[\w$]+)\s*\?\?\s*""""\s*\]", "trainerId", "remoteBridgeSyncSnapshot"); - var gameField = RequirePattern(source, @"this\.(?#[\w$]+)\s*&&.*?getPreferredInstallationInfo\s*\(\s*this\.\k\s*\)", "game", "remoteBridgeSyncSnapshot"); - var installationField = RequirePattern(source, @"this\.(?#[\w$]+)\s*&&.*?this\.(?#[\w$]+)\.getPreferredInstallationInfo\s*\(\s*this\.\k\s*\)", "installation", "remoteBridgeSyncSnapshot"); - var supportedVersionsField = RequirePattern(source, @"!\s*this\.(?#[\w$]+)\.includes\s*\(\s*[\w$]+\.version\s*\)", "versions", "remoteBridgeSyncSnapshot"); - var remoteChannelField = RequirePattern(source, @"this\.(?#[\w$]+)\?\.\s*send\s*\(\s*""client-state""", "remote", "remoteBridgeSyncSnapshot"); - var valuesMethod = RequirePattern(source, @"values\s*:\s*this\.(?#[\w$]+)\s*\(\s*\)", "values", "remoteBridgeSyncSnapshot"); - var instanceField = RequirePattern(source, @"instanceId\s*:\s*this\.(?#[\w$]+)", "instance", "remoteBridgeSyncSnapshot"); - var themeField = RequirePattern(source, @"themeId\s*:\s*this\.(?#[\w$]+)", "theme", "remoteBridgeSyncSnapshot"); - var settingsHelper = RequirePattern(source, @"settings\s*:\s*(?[\w$]+)\s*\(\s*this\.settings\s*\)", "settings", "remoteBridgeSyncSnapshot"); - var languageField = RequirePattern(source, @"language\s*:\s*this\.(?#[\w$]+)", "language", "remoteBridgeSyncSnapshot"); - var timerField = RequirePattern(source, @"isTimeLimitExpired\s*:\s*""expired""\s*===\s*this\.(?#[\w$]+)\.timerState", "timer", "remoteBridgeSyncSnapshot"); - - return $"{method}(){{let e,t=!1,s=this.{trainerField}?.getMetadata({metadataExport})?.gameVersion??null,o=!1;const n=this.{notesField}[this.{trainerIdField}??\"\"]||null;this.{gameField}&&(e=this.{installationField}.getPreferredInstallationInfo(this.{gameField}),e.app&&(t=!0,s??=e.version??null,o=\"number\"==typeof e.version&&!this.{supportedVersionsField}.includes(e.version)));this.status==={statusAlias}.Connected&&this.{remoteChannelField}?.send(\"client-state\",{{instanceId:this.{instanceField},trainerId:this.{trainerIdField},trainerLoading:this.{trainerField}?.isLoading(),gameInstalled:t,gameVersion:s,needsCompatibilityWarning:o,values:this.{valuesMethod}(),themeId:this.{themeField},settings:{settingsHelper}(this.settings),language:this.{languageField},accountUuid:this.account.uuid,notesReadHash:n,isTimeLimitExpired:\"expired\"===this.{timerField}.timerState}});this.__wandRemoteBridge?.sync({{instanceId:this.{instanceField},trainerId:this.{trainerIdField},trainerInfo:this.__wandRemoteTrainerInfo??null,metadata:this.{trainerField}?.getMetadata({metadataExport})??null,trainerLoading:this.{trainerField}?.isLoading()??false,gameInstalled:t,gameVersion:s,needsCompatibilityWarning:o,language:this.{languageField},themeId:this.{themeField},notesReadHash:n,isTimeLimitExpired:\"expired\"===this.{timerField}.timerState,values:this.{valuesMethod}()}})}}"; + /// True once the patch is applied, or once a scan proved the feature is absent. + public bool IsResolved => Applied || (IsOptional && !CapabilityDetected); } public static Dictionary GetInstance() { - return new Dictionary() + return new Dictionary { { EPatchType.ActivatePro, @@ -107,80 +46,41 @@ public static Dictionary GetInstance() { new PatchEntry { - SearchHints = new[] { "getUserAccount()", "/v3/account" }, - Resolver = new ResolveContext - { - Handler = (targetFunction) => - { - var fetchMatch = Regex.Match(targetFunction, @"return\s+this\.#(\w+)\.fetch"); - return fetchMatch.Success ? fetchMatch.Groups[1].Value : null; - }, - Placeholder = "" - }, Name = "getUserAccount", - Target = new Regex(@"getUserAccount\(\)\{.*?return\s+this\.#\w+\.fetch\(\{.*?\}\)\}", - RegexOptions.Singleline), - Patch = - "getUserAccount(){return this.#.fetch({endpoint:\"/v3/account\",method:\"GET\",name:\"/v3/account\",collectMetrics:0}).then(response=>{response.subscription={period:\"yearly\",state:\"active\"};return response;})}" + SearchHints = new[] { "getUserAccount(" }, + Locate = js => ForceProSubscription(js, "getUserAccount") }, new PatchEntry { - SearchHints = new[] { "setAccountWandBrandExperience()", "/v3/account/brand_experience_wand" }, - Resolver = new ResolveContext - { - Handler = (targetFunction) => - { - var match = Regex.Match(targetFunction, @"return\s+this\.#(\w+)\.post"); - return match.Success ? match.Groups[1].Value : null; - }, - Placeholder = "" - }, Name = "setAccountWandBrandExperience", - Target = new Regex( - @"setAccountWandBrandExperience\(\)\{.*?return\s+this\.#\w+\.post\(""/v3/account/brand_experience_wand""\)\}", - RegexOptions.Singleline), - Patch = - "setAccountWandBrandExperience(){return this.#.post(\"/v3/account/brand_experience_wand\").then(response=>{response.subscription={period:\"yearly\",state:\"active\"};return response;})}" + SearchHints = new[] { "setAccountWandBrandExperience(" }, + CapabilityHints = new[] { "/v3/account/brand_experience_wand" }, + Locate = js => ForceProSubscription(js, "setAccountWandBrandExperience") }, new PatchEntry { - // Account-returning endpoint the original patches missed: changing - // language dispatches its (non-Pro) response into the store and - // wiped Pro. Wrap the result the same way. Param names are captured - // so the rewritten body keeps the real argument identifiers. + // Changing language returns a fresh account object that would otherwise + // overwrite the patched subscription in the store. Name = "setAccountLanguage", - SearchHints = new[] { "setAccountLanguage(", "/v3/account/language" }, - Target = new Regex( - @"setAccountLanguage\((?[^)]*)\)\{\s*return\s+(?this\.#\w+\.post\(""/v3/account/language"",\{[^}]*\}\))\s*;?\s*\}", - RegexOptions.Singleline), - PatchFactory = BuildSetAccountLanguagePatch + SearchHints = new[] { "setAccountLanguage(" }, + Locate = js => ForceProSubscription(js, "setAccountLanguage") }, new PatchEntry { - // Last-resort guard: any code path that dispatches ACTION_SET_ACCOUNT - // (periodic refreshAccount, push updates, profile edits, etc.) must keep - // subscription on the store object even when it bypasses the account API - // service methods patched above. + // Catches every path that dispatches ACTION_SET_ACCOUNT without going + // through the account API methods above (refresh, push, profile edits). Name = "setAccountReducer", SearchHints = new[] { "ACTION_SET_ACCOUNT" }, - Target = new Regex( - @"const (?\w+)=""ACTION_SET_ACCOUNT"";function (?\w+)\((?[^)]*)\)\{return\{\.\.\.(?\w+),account:(?\w+)\}\}", - RegexOptions.Singleline), - PatchFactory = BuildSetAccountReducerPatch + Locate = LocateAccountReducer }, new PatchEntry { - // Wand's native "connect phone" pairing (POST /v3/auth/remote_code) - // triggers a server-side device handoff that deauthorizes this desktop - // session - the reported "entered the mobile activation key and got - // signed out" bug. Neutralize the code issuer so native pairing can - // never start. The injected remote panel is independent of this flow - // (IPC bridge, not Wand's Pusher pairing) and keeps working. The - // rejection is swallowed by the caller's try/catch (renders no code). + // Wand's own phone pairing performs a server-side device handoff that + // signs this desktop session out. The injected panel does not use it. Name = "disableNativeRemotePairing", - SearchHints = new[] { "requestRemoteAuthCode", "/v3/auth/remote_code" }, - Target = new Regex(@"requestRemoteAuthCode\(\)\{return this\.#[\w$]+\.post\(""/v3/auth/remote_code""\)\}"), - Patch = "requestRemoteAuthCode(){return Promise.reject(new Error(\"wand-enhancer: native mobile pairing disabled\"))}" + SearchHints = new[] { "requestRemoteAuthCode" }, + Locate = js => Edits(js.FindFunction("requestRemoteAuthCode")? + .ReplaceBody(PatchPayload.Load("disable-native-pairing"))) } } }, @@ -188,15 +88,12 @@ public static Dictionary GetInstance() EPatchType.DisableUpdates, new[] { - // Regex consumes 4 closing parens (`)))) `); the 5th (registerHandler's own close) - // remains in the original file after replacement. Patch must end with 3 parens — NOT 4. new PatchEntry { + Name = "disableUpdateCheck", CandidateFileNames = new[] { "index.js" }, SearchHints = new[] { "ACTION_CHECK_FOR_UPDATE" }, - Target = new Regex(@"registerHandler\(""ACTION_CHECK_FOR_UPDATE"".*?\)\)\)\)", - RegexOptions.Singleline), - Patch = "registerHandler(\"ACTION_CHECK_FOR_UPDATE\",(e=>expectUpdateFeedUrl(e,(e=>null)))" + Locate = LocateUpdateHandler } } }, @@ -206,18 +103,12 @@ public static Dictionary GetInstance() { new PatchEntry { + // Hooked in the main process: the renderer's keydown dispatcher is + // reshaped on every Wand release, the Electron app API is not. Name = "devToolsBeforeInputEvent", CandidateFileNames = new[] { "index.js" }, SearchHints = new[] { "whenReady().then(" }, - // Anchor on the Electron main-process `.whenReady().then(` - // call. This site is far more stable than the minified renderer - // keydown listener that previously held the F12 -> ACTION_OPEN_DEV_TOOLS - // dispatch (its identifiers and shape change on every Wand release). - // We attach a `before-input-event` hook to every BrowserWindow's - // webContents which toggles DevTools on F12 directly from the main - // process, bypassing the renderer dispatcher entirely. - Target = new Regex(@"(?\w+)\.whenReady\(\)\.then\("), - Patch = "${app}.on(\"browser-window-created\",((_,w)=>{try{w.webContents.on(\"before-input-event\",((_,i)=>{if(\"F12\"===i.key&&\"keyDown\"===i.type){w.webContents.isDevToolsOpened()?w.webContents.closeDevTools():w.webContents.openDevTools({mode:\"detach\"})}}))}catch(e){}})),${app}.whenReady().then(" + Locate = LocateDevToolsHook } } }, @@ -230,53 +121,261 @@ public static Dictionary GetInstance() Name = "remoteBridgeMainBoot", CandidateFileNames = new[] { "index.js" }, SearchHints = new[] { "whenReady().then(run)" }, - Target = new Regex(@"(?\w+)\.whenReady\(\)\.then\(run\)"), - Patch = "${app}.whenReady().then(()=>{try{const p=require(\"node:path\");require(p.join(__dirname,\"remote-panel\",\"bridge.cjs\")).installWandRuntime(require(\"electron\"));}catch(e){try{const fs=require(\"node:fs\"),os=require(\"node:os\"),p=require(\"node:path\");fs.appendFileSync(p.join(os.tmpdir(),\"wand-remote-bridge.log\"),\"[\"+new Date().toISOString()+\"] [boot-error] \"+(e&&e.stack||e)+\"\\n\");}catch(_){}}return run()})" + Locate = LocateBridgeBoot }, new PatchEntry { Name = "remoteBridgeReset", SearchHints = new[] { "client-state" }, - Target = new Regex(@"(?#[\w$]+)\(\)\s*\{\s*(?(?:(?!__wandRemoteBridge|}\s*#[\w$]+\(\)).)*?Date\.now\(\)\.toString\(\)(?:(?!__wandRemoteBridge|}\s*#[\w$]+\(\)).)*?\[\](?:(?!__wandRemoteBridge|}\s*#[\w$]+\(\)).)*?)\s*\}\s*(?=#[\w$]+\(\)\s*\{\s*if\s*\(\s*this\.status\s*===\s*[\w$]+\.Connected\s*\).*?""client-state"")", - RegexOptions.Singleline), - PatchFactory = BuildRemoteBridgeResetPatch + Locate = LocateBridgeReset }, new PatchEntry { Name = "remoteBridgeSyncSnapshot", SearchHints = new[] { "client-state" }, - Target = new Regex(@"(?#[\w$]+)\(\)\s*\{\s*if\s*\(\s*this\.status\s*===\s*[\w$]+\.Connected\s*\)\s*\{(?.*?""client-state"".*?isTimeLimitExpired\s*:\s*""expired""\s*===\s*this\.\#[\w$]+\.timerState.*?\)\s*;?\s*\)?\s*;?)\s*\}\s*\}(?=\s*#[\w$]+\(\)\s*\{\s*if\s*\(\s*!this\.\#[\w$]+\?\.\s*isActive\(\)\s*\)\s*return\s*null)", - RegexOptions.Singleline), - PatchFactory = BuildRemoteBridgeSyncSnapshotPatch + Locate = LocateBridgeSync }, new PatchEntry { - // Inject the bridge init + setHandler right after the method's opening - // brace; the rest of setCurrentTrainer is left untouched. Only `${trainer}` - // (active-trainer field) and `${remoteSource}` (value-source enum, taken - // via lookahead from the sole `e.source!==` site) vary between builds and - // are resolved from the match — nothing is hardcoded. Name = "remoteBridgeBindHandler", - SearchHints = new[] { "client-state" }, - Target = new Regex(@"(?setCurrentTrainer\(e,t=null\)\{)(?=const s=e\?\.trainerId\|\|null,i=\(s\?e\?\.gameId:null\)\|\|null,n=\(s\?e\?\.supportedVersions:null\)\|\|\[\];if\(s===this\.#[\w$]+&&t===this\.(?#[\w$]+)\)return;)(?=.*?e\.source!==(?[\w$]+\.[\w$]+\.Remote))", - RegexOptions.Singleline), - Patch = "${head}this.__wandRemoteBridge||(this.__wandRemoteBridge=(()=>{try{const r=globalThis.require||require;const{ipcRenderer:c}=r(\"electron\");try{c.invoke(\"wand-remote-url\").then((u=>{u&&(globalThis.__wandRemoteBridgeUrl=u)}))}catch(e){}const send=(ch,p)=>{try{return c.invoke(ch,p&&JSON.parse(JSON.stringify(p)))}catch(e){}};return{sync:(s)=>send(\"wand-remote-sync\",s),valueChanged:(s)=>send(\"wand-remote-value-changed\",s),setHandler:(h)=>{if(this.__wandRemoteBridgeBound)return;this.__wandRemoteBridgeBound=true;try{c.invoke(\"wand-remote-set-handler-bind\")}catch(e){}c.on(\"wand-remote-set-value\",(_e,req)=>{try{h(req)}catch(e){}})}}}catch(e){try{const r=globalThis.require||require,fs=r(\"node:fs\"),os=r(\"node:os\"),p=r(\"node:path\");fs.appendFileSync(p.join(os.tmpdir(),\"wand-remote-bridge.log\"),\"[\"+new Date().toISOString()+\"] [renderer-bind-error] \"+(e&&e.stack||e)+\"\\n\");}catch(_){}return null}})());this.__wandRemoteBridge?.setHandler((e=>{if(!this.${trainer}||!e?.target)return!1;return this.${trainer}.isActive()?this.${trainer}.setValue(e.target,e.value,${remoteSource},e.cheatId):!1}));this.__wandRemoteTrainerInfo=e??null;" + SearchHints = new[] { "setCurrentTrainer(" }, + Locate = LocateBridgeBindHandler }, new PatchEntry { - // Pure insertion: splice one `valueChanged` bridge call in after the - // existing `client-value-changed` send, before the onValueSet callback - // closes. Resolves no private names — `${head}`/`${tail}` carry the - // original text verbatim. trainerId is omitted from the payload; - // bridge-state falls back to the active snapshot trainer. Name = "remoteBridgeValueDelta", SearchHints = new[] { "client-value-changed" }, - Target = new Regex(@"(?#[\w$]+\(e,t\)\{t\.push\(e\.onValueSet\(e=>\{this\.status===[\w$]+\.Connected&&e\.source!==[\w$]+\.[\w$]+\.Remote&&this\.#[\w$]+\?\.send\(""client-value-changed"",\{instanceId:this\.#[\w$]+,name:e\.name,value:e\.value,cheatId:e\.cheatId\}\))(?\}\)\),this\.#[\w$]+\(\)\})"), - Patch = "${head},this.__wandRemoteBridge?.valueChanged({target:e.name,value:e.value,oldValue:e.oldValue,source:String(e.source??\"desktop\"),cheatId:e.cheatId})${tail}" + Locate = LocateBridgeValueDelta } } } }; } + + /// Wraps the account-returning promise so the resolved account always reports an active subscription. + private static JsEdit[] ForceProSubscription(JsCursor js, string methodName) + { + return Edits(js.FindFunction(methodName)?.WrapReturn(PatchPayload.Load("pro-subscription"))); + } + + private static JsEdit[] LocateAccountReducer(JsCursor js) + { + int anchor = js.IndexOf("\"ACTION_SET_ACCOUNT\""); + var reducer = anchor < 0 ? null : js.FindFunctionAfter(anchor); + if (reducer == null) + { + return null; + } + + // The payload's ${account} survives PatchPayload untouched and is resolved by the + // regex replacement below, which is what carries the original identifier through. + return Edits(reducer.ReplaceInBody( + @"account:\s*(?[\w$]+)", + PatchPayload.Load("pro-account-reducer"))); + } + + private static JsEdit[] LocateUpdateHandler(JsCursor js) + { + int callOpen = js.FindCall("registerHandler", "\"ACTION_CHECK_FOR_UPDATE\""); + if (callOpen < 0) + { + return null; + } + + return Edits(new JsEdit(callOpen + 1, js.MatchClose(callOpen), PatchPayload.Load("disable-updates"))); + } + + private static JsEdit[] LocateDevToolsHook(JsCursor js) + { + var match = WhenReady.Match(js.Text); + if (!match.Success) + { + return null; + } + + var payload = PatchPayload.Load("devtools-f12", "app", match.Groups["app"].Value); + return Edits(new JsEdit(match.Index, match.Index, payload)); + } + + private static JsEdit[] LocateBridgeBoot(JsCursor js) + { + var match = WhenReadyThenRun.Match(js.Text); + if (!match.Success) + { + return null; + } + + var payload = PatchPayload.Load("remote-bridge-boot", "app", match.Groups["app"].Value); + return Edits(new JsEdit(match.Index, match.Index + match.Length, payload)); + } + + /// Clears the bridge alongside the session fields the reset method already nulls out. + private static JsEdit[] LocateBridgeReset(JsCursor js) + { + var sync = FindClientStateMethod(js); + var reset = sync == null ? null : js.FunctionEndingAt(js.SkipWhitespaceBack(sync.Start - 1)); + if (reset == null || reset.Body.IndexOf("Date.now()", StringComparison.Ordinal) < 0) + { + return null; + } + + return Edits(reset.InsertAtEnd(PatchPayload.Load("remote-bridge-reset"))); + } + + /// + /// Mirrors Wand's own client-state payload to the bridge by copying the object literal + /// verbatim, so fields Wand adds or drops between builds carry over untouched. + /// + private static JsEdit[] LocateBridgeSync(JsCursor js) + { + int sendOpen = js.FindCall("send", "\"client-state\""); + if (sendOpen < 0) + { + return null; + } + + var method = js.EnclosingFunction(sendOpen); + int snapshotOpen = js.IndexOf("{", sendOpen); + int snapshotClose = js.MatchClose(snapshotOpen); + if (method == null || snapshotOpen < 0 || snapshotClose < 0) + { + throw new Exception("client-state payload object could not be located"); + } + + // Prettified builds leave a trailing comma inside the literal; appending after it + // would produce an illegal hole. + string snapshot = js.Text.Substring(snapshotOpen + 1, snapshotClose - snapshotOpen - 1) + .Trim() + .TrimEnd(','); + + var payload = PatchPayload.Load( + "remote-bridge-sync", + "snapshot", snapshot, + "trainer", method.Resolve(@"this\.(?#[\w$]+)\s*\?\.\s*getMetadata", "trainer"), + "metadata", method.Resolve(@"getMetadata\(\s*(?[\w$]+\.[\w$]+)\s*\)", "metadata")); + + var edits = new List { new JsEdit(js.MatchClose(sendOpen) + 1, payload) }; + edits.AddRange(HoistConnectedGuard(js, sendOpen)); + return edits.ToArray(); + } + + /// + /// Some builds wrap the whole snapshot method in if (status === Connected). The bridge + /// must publish regardless of Wand's own remote status, so the guard is moved onto the send + /// itself, leaving the block - and the locals the payload reads - intact. + /// + private static IEnumerable HoistConnectedGuard(JsCursor js, int sendOpen) + { + int blockOpen = js.EnclosingOpener(sendOpen, '{'); + int closeParen = blockOpen < 0 ? -1 : js.SkipWhitespaceBack(blockOpen - 1); + if (closeParen < 0 || js.Text[closeParen] != ')') + { + yield break; + } + + var stack = js.OpenerStack(closeParen); + if (stack.Count == 0 || js.NameBefore(stack[0]) != "if") + { + yield break; + } + + int openParen = stack[0]; + string test = js.Text.Substring(openParen + 1, closeParen - openParen - 1); + + // Only the connection guard may be hoisted. A nested unrelated `if` would otherwise + // have its condition moved onto the send, and an `else` branch would be orphaned by + // turning the block into a bare one. + if (test.IndexOf("this.status", StringComparison.Ordinal) < 0 || HasElseBranch(js, blockOpen)) + { + yield break; + } + + int guardStart = js.SkipWhitespaceBack(openParen - 1) - 1; + + int calleeStart = sendOpen; + while (calleeStart > 0 && IsCalleeChar(js.Text[calleeStart - 1])) + { + calleeStart--; + } + + yield return new JsEdit(calleeStart, calleeStart, $"({test})&&"); + yield return new JsEdit(guardStart, blockOpen, string.Empty); + } + + private static bool HasElseBranch(JsCursor js, int blockOpen) + { + int afterBlock = js.SkipWhitespaceForward(js.MatchClose(blockOpen) + 1); + return string.CompareOrdinal(js.Text, afterBlock, "else", 0, 4) == 0; + } + + private static JsEdit[] LocateBridgeBindHandler(JsCursor js) + { + var method = js.FindFunction("setCurrentTrainer"); + if (method == null) + { + return null; + } + + // The same call reveals both the active-trainer field and the numeric or enum value + // Wand uses for a remote-originated write. Wand has sibling call sites for other + // sources (Overlay), so an ambiguous match would silently bind the wrong one. + var setValue = MatchExactlyOnce(RemoteSetValue, js.Text, "Remote setValue call"); + + return Edits(method.InsertAtStart(PatchPayload.Load( + "remote-bridge-renderer", + "trainer", setValue.Groups["trainer"].Value, + "remoteSource", setValue.Groups["source"].Value))); + } + + private static JsEdit[] LocateBridgeValueDelta(JsCursor js) + { + int sendOpen = js.FindCall("send", "\"client-value-changed\""); + if (sendOpen < 0) + { + return null; + } + + int sendClose = js.MatchClose(sendOpen); + return Edits(new JsEdit(sendClose + 1, PatchPayload.Load("remote-bridge-value-delta"))); + } + + private static JsFunction FindClientStateMethod(JsCursor js) + { + int sendOpen = js.FindCall("send", "\"client-state\""); + return sendOpen < 0 ? null : js.EnclosingFunction(sendOpen); + } + + private static JsEdit[] Edits(JsEdit edit) + { + return edit == null ? null : new[] { edit }; + } + + private static bool IsCalleeChar(char value) + { + return char.IsLetterOrDigit(value) || value == '_' || value == '$' || value == '#' + || value == '.' || value == '?'; + } + + /// Match that must be unambiguous: zero or several hits mean an unsupported build. + private static Match MatchExactlyOnce(Regex pattern, string text, string what) + { + var match = pattern.Match(text); + if (!match.Success) + { + throw new Exception($"{what} could not be located"); + } + + if (match.NextMatch().Success) + { + throw new Exception($"{what} matched more than once; cannot tell which call site is the right one"); + } + + return match; + } + + private static readonly Regex WhenReady = new Regex(@"(?[\w$]+)\.whenReady\(\)\.then\("); + private static readonly Regex WhenReadyThenRun = new Regex(@"(?[\w$]+)\.whenReady\(\)\.then\(run\)"); + private static readonly Regex RemoteSetValue = + new Regex(@"this\.(?#[\w$]+)\.setValue\(\s*e\.name\s*,\s*e\.value\s*,\s*(?[^,]+?)\s*,"); } } diff --git a/WandEnhancer/Core/JavaScriptPatchApplier.cs b/WandEnhancer/Core/JavaScriptPatchApplier.cs new file mode 100644 index 00000000..2e78286e --- /dev/null +++ b/WandEnhancer/Core/JavaScriptPatchApplier.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Linq; +using WandEnhancer.Core.Js; +using WandEnhancer.Models; +using WandEnhancer.View.MainWindow; + +namespace WandEnhancer.Core +{ + internal sealed class JavaScriptPatchApplier + { + private readonly Action _logger; + + public JavaScriptPatchApplier(Action logger) + { + _logger = logger; + } + + public string Apply(string fileName, string source, EnhancerConfig.PatchEntry patch, EPatchType patchType, out bool patchApplied) + { + patchApplied = false; + if (patch.Applied || !CanSearchFile(fileName, patch)) + { + return source; + } + + patch.CapabilityDetected |= ContainsAny(source, patch.CapabilityHints); + if (!ContainsAny(source, patch.SearchHints)) + { + return source; + } + + string label = FormatLabel(patchType, patch); + JsEdit[] edits; + try + { + edits = patch.Locate(new JsCursor(source)); + } + catch (Exception e) + { + throw new Exception($"[ENHANCER] [{label}] {e.Message}. The version may not be supported.", e); + } + + if (edits == null || edits.Length == 0) + { + return source; + } + + _logger($"[ENHANCER] [{label}] Found target in: {Path.GetFileName(fileName)}", ELogType.Info); + foreach (var edit in edits.OrderByDescending(edit => edit.Start)) + { + source = edit.ApplyTo(source); + } + + _logger($"[ENHANCER] [{label}] Patch applied", ELogType.Success); + patch.Applied = true; + patchApplied = true; + return source; + } + + public static string FormatLabel(EPatchType patchType, EnhancerConfig.PatchEntry patch) + { + return string.IsNullOrEmpty(patch.Name) ? patchType.ToString() : $"{patchType} -> {patch.Name}"; + } + + public static bool CanSearchFile(string filePath, EnhancerConfig.PatchEntry patch) + { + if (patch.CandidateFileNames == null || patch.CandidateFileNames.Length == 0) + { + return true; + } + + string fileName = Path.GetFileName(filePath); + return patch.CandidateFileNames.Any(candidate => fileName.Equals(candidate, StringComparison.OrdinalIgnoreCase)); + } + + private static bool ContainsAny(string source, string[] hints) + { + return hints != null && hints.Any(hint => source.IndexOf(hint, StringComparison.Ordinal) >= 0); + } + } +} diff --git a/WandEnhancer/Core/Js/JsCursor.cs b/WandEnhancer/Core/Js/JsCursor.cs new file mode 100644 index 00000000..e4e5aa3e --- /dev/null +++ b/WandEnhancer/Core/Js/JsCursor.cs @@ -0,0 +1,409 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace WandEnhancer.Core.Js +{ + /// + /// Navigates minified JavaScript by matching delimiters rather than by matching shape. + /// Wand renames identifiers on every build but never renames its API endpoints, IPC + /// channel names or public method names, so anchoring on those and walking the + /// delimiter structure keeps a patch valid across builds. + /// + internal sealed class JsCursor + { + private const string RegexPrecedingChars = "(,=:[!&|?{};+-*%~^<>"; + private const int NameLookbackChars = 128; + private static readonly Regex NameBeforeParen = new Regex(@"[#\w$]+$"); + private static readonly Regex FunctionKeyword = new Regex(@"(? BlockKeywords = + new HashSet(StringComparer.Ordinal) { "if", "for", "while", "switch", "catch", "with", "do", "else" }; + + // A slash after one of these is a regex literal, not division. Minifiers emit + // `return/re/.test(x)` with no space, so missing these desyncs the whole scan. + private static readonly HashSet RegexPrecedingKeywords = + new HashSet(StringComparer.Ordinal) + { + "return", "typeof", "instanceof", "in", "of", "new", "delete", "void", + "throw", "case", "do", "else", "yield", "await" + }; + + private readonly string _text; + + public JsCursor(string text) + { + _text = text; + } + + public string Text => _text; + + public int IndexOf(string value, int from = 0) + { + return from >= _text.Length ? -1 : _text.IndexOf(value, from, StringComparison.Ordinal); + } + + /// Index of the delimiter closing the one at , or -1. + public int MatchClose(int openIndex) + { + char open = _text[openIndex]; + char close = CloserOf(open); + int depth = 0; + + for (int index = openIndex; index < _text.Length;) + { + char current = _text[index]; + if (current == open) + { + depth++; + index++; + } + else if (current == close) + { + if (--depth == 0) + { + return index; + } + + index++; + } + else + { + index = SkipToken(index); + } + } + + return -1; + } + + /// Open delimiters enclosing , innermost first. + public List OpenerStack(int index) + { + var stack = new List(); + for (int cursor = 0; cursor < index && cursor < _text.Length;) + { + char current = _text[cursor]; + if (current == '{' || current == '(' || current == '[') + { + stack.Add(cursor); + cursor++; + } + else if (current == '}' || current == ')' || current == ']') + { + if (stack.Count > 0) + { + stack.RemoveAt(stack.Count - 1); + } + + cursor++; + } + else + { + cursor = SkipToken(cursor); + } + } + + stack.Reverse(); + return stack; + } + + /// Innermost enclosing delimiter of the given kind, or -1. + public int EnclosingOpener(int index, char kind) + { + foreach (int opener in OpenerStack(index)) + { + if (_text[opener] == kind) + { + return opener; + } + } + + return -1; + } + + /// Innermost named function or method whose body contains . + public JsFunction EnclosingFunction(int index) + { + foreach (int opener in OpenerStack(index)) + { + if (_text[opener] != '{') + { + continue; + } + + var function = ReadFunctionAt(opener); + if (function != null) + { + return function; + } + } + + return null; + } + + /// The named function whose body closes at , or null. + public JsFunction FunctionEndingAt(int closeIndex) + { + if (closeIndex < 0 || closeIndex >= _text.Length || _text[closeIndex] != '}') + { + return null; + } + + var stack = OpenerStack(closeIndex); + return stack.Count == 0 ? null : ReadFunctionAt(stack[0]); + } + + /// First function declared as name(...), ignoring property and call sites. + public JsFunction FindFunction(string name) + { + var pattern = new Regex($@"(?First function name(...) { } declared at or after . + public JsFunction FindFunctionAfter(int index) + { + var match = FunctionKeyword.Match(_text, index); + if (!match.Success) + { + return null; + } + + int closeParen = MatchClose(match.Index + match.Length - 1); + if (closeParen < 0) + { + return null; + } + + int bodyOpen = SkipWhitespaceForward(closeParen + 1); + return bodyOpen < _text.Length && _text[bodyOpen] == '{' ? ReadFunctionAt(bodyOpen) : null; + } + + /// + /// Index of the opening parenthesis of callee(... "literal" ...), or -1. Wand reuses the + /// same channel names for inbound listeners and outbound sends, so the callee disambiguates. + /// + public int FindCall(string callee, string literal) + { + for (int anchor = IndexOf(literal); anchor >= 0; anchor = IndexOf(literal, anchor + 1)) + { + int open = EnclosingOpener(anchor, '('); + if (open >= 0 && NameBefore(open) == callee) + { + return open; + } + } + + return -1; + } + + /// Trailing identifier directly before , e.g. send of a?.send(. + public string NameBefore(int index) + { + int end = SkipWhitespaceBack(index - 1) + 1; + var match = MatchNameEndingAt(end); + return match.Success ? match.Value.TrimStart('#') : null; + } + + /// Identifier ending at , searched in a bounded window so + /// multi-megabyte bundles are not copied on every lookup. + private Match MatchNameEndingAt(int end) + { + int windowStart = Math.Max(0, end - NameLookbackChars); + return NameBeforeParen.Match(_text.Substring(windowStart, end - windowStart)); + } + + public int SkipWhitespaceBack(int index) + { + while (index >= 0 && char.IsWhiteSpace(_text[index])) + { + index--; + } + + return index; + } + + public int SkipWhitespaceForward(int index) + { + while (index < _text.Length && char.IsWhiteSpace(_text[index])) + { + index++; + } + + return index; + } + + private JsFunction ReadFunctionAt(int bodyOpen) + { + int closeParen = SkipWhitespaceBack(bodyOpen - 1); + if (closeParen < 0 || _text[closeParen] != ')') + { + return null; + } + + var stack = OpenerStack(closeParen); + if (stack.Count == 0 || _text[stack[0]] != '(') + { + return null; + } + + int nameEnd = SkipWhitespaceBack(stack[0] - 1) + 1; + var nameMatch = MatchNameEndingAt(nameEnd); + if (!nameMatch.Success || BlockKeywords.Contains(nameMatch.Value)) + { + return null; + } + + int bodyClose = MatchClose(bodyOpen); + return bodyClose < 0 + ? null + : new JsFunction(nameMatch.Value, nameEnd - nameMatch.Length, bodyOpen, bodyClose, _text); + } + + private int SkipToken(int index) + { + char current = _text[index]; + if (current == '"' || current == '\'' || current == '`') + { + return SkipString(index, current); + } + + if (current != '/' || index + 1 >= _text.Length) + { + return index + 1; + } + + char next = _text[index + 1]; + if (next == '/') + { + int lineEnd = _text.IndexOf('\n', index); + return lineEnd < 0 ? _text.Length : lineEnd + 1; + } + + if (next == '*') + { + int commentEnd = _text.IndexOf("*/", index + 2, StringComparison.Ordinal); + return commentEnd < 0 ? _text.Length : commentEnd + 2; + } + + return StartsRegexLiteral(index) ? SkipRegexLiteral(index) : index + 1; + } + + private int SkipString(int index, char quote) + { + for (int cursor = index + 1; cursor < _text.Length; cursor++) + { + char current = _text[cursor]; + if (current == '\\') + { + cursor++; + } + else if (current == quote) + { + return cursor + 1; + } + else if (quote == '`' && current == '$' && cursor + 1 < _text.Length && _text[cursor + 1] == '{') + { + int interpolationEnd = MatchClose(cursor + 1); + cursor = interpolationEnd < 0 ? _text.Length : interpolationEnd; + } + } + + return _text.Length; + } + + private int SkipRegexLiteral(int index) + { + bool inCharacterClass = false; + for (int cursor = index + 1; cursor < _text.Length; cursor++) + { + char current = _text[cursor]; + if (current == '\\') + { + cursor++; + } + else if (current == '[') + { + inCharacterClass = true; + } + else if (current == ']') + { + inCharacterClass = false; + } + else if (current == '\n') + { + return index + 1; + } + else if (current == '/' && !inCharacterClass) + { + return cursor + 1; + } + } + + return _text.Length; + } + + private bool StartsRegexLiteral(int index) + { + int previous = SkipWhitespaceBack(index - 1); + if (previous < 0 || RegexPrecedingChars.IndexOf(_text[previous]) >= 0) + { + return true; + } + + return IsIdentifierChar(_text[previous]) && RegexPrecedingKeywords.Contains(WordEndingAt(previous)); + } + + /// The identifier ending at inclusive, or "" when there is none. + private string WordEndingAt(int end) + { + int start = end; + while (start >= 0 && IsIdentifierChar(_text[start])) + { + start--; + } + + // A preceding '.' makes it a member name (`x.in`), never a keyword. + if (start >= 0 && _text[start] == '.') + { + return string.Empty; + } + + return _text.Substring(start + 1, end - start); + } + + private static bool IsIdentifierChar(char value) + { + return char.IsLetterOrDigit(value) || value == '_' || value == '$'; + } + + private static char CloserOf(char open) + { + switch (open) + { + case '{': return '}'; + case '(': return ')'; + case '[': return ']'; + default: throw new ArgumentException($"Not an opening delimiter: {open}", nameof(open)); + } + } + } +} diff --git a/WandEnhancer/Core/Js/JsFunction.cs b/WandEnhancer/Core/Js/JsFunction.cs new file mode 100644 index 00000000..d5335c47 --- /dev/null +++ b/WandEnhancer/Core/Js/JsFunction.cs @@ -0,0 +1,129 @@ +using System; +using System.Text.RegularExpressions; + +namespace WandEnhancer.Core.Js +{ + /// A named function or class method located in a bundle, addressed by delimiter position. + internal sealed class JsFunction + { + private static readonly Regex ReturnKeyword = new Regex(@"(? _source.Substring(BodyOpen + 1, BodyClose - BodyOpen - 1); + + private JsCursor BodyCursor => _body ?? (_body = new JsCursor(Body)); + + /// Captures a group from a pattern matched against this body only, not the whole bundle. + public string Resolve(string pattern, string group) + { + var match = Regex.Match(Body, pattern, RegexOptions.Singleline); + if (!match.Success || string.IsNullOrEmpty(match.Groups[group].Value)) + { + throw new Exception($"Could not resolve '{group}' inside {Name}()"); + } + + return match.Groups[group].Value; + } + + /// Rewrites the first match of a pattern scoped to this body; ${group} back-references work. + public JsEdit ReplaceInBody(string pattern, string replacement) + { + var match = Regex.Match(Body, pattern, RegexOptions.Singleline); + if (!match.Success) + { + throw new Exception($"Pattern '{pattern}' not found inside {Name}()"); + } + + int start = BodyOpen + 1 + match.Index; + return new JsEdit(start, start + match.Length, match.Result(replacement)); + } + + public JsEdit InsertAtStart(string code) => new JsEdit(BodyOpen + 1, BodyOpen + 1, code); + + public JsEdit InsertAtEnd(string code) => new JsEdit(BodyClose, BodyClose, code); + + public JsEdit ReplaceBody(string code) => new JsEdit(BodyOpen + 1, BodyClose, code); + + /// + /// Rewrites the last top-level return X as return WRAPPER, where the wrapper's + /// $0 placeholder receives the original expression. + /// + public JsEdit WrapReturn(string wrapper) + { + var body = BodyCursor; + int keywordEnd = -1; + for (var match = ReturnKeyword.Match(body.Text); match.Success; match = match.NextMatch()) + { + if (body.OpenerStack(match.Index).Count == 0) + { + keywordEnd = match.Index + match.Length; + } + } + + if (keywordEnd < 0) + { + throw new Exception($"No top-level return statement in {Name}()"); + } + + int expressionStart = body.SkipWhitespaceForward(keywordEnd); + int expressionEnd = FindStatementEnd(body, expressionStart); + string expression = body.Text.Substring(expressionStart, expressionEnd - expressionStart); + + return new JsEdit( + BodyOpen + 1 + expressionStart, + BodyOpen + 1 + expressionEnd, + wrapper.Replace("$0", $"({expression})")); + } + + private static int FindStatementEnd(JsCursor body, int start) + { + for (int cursor = start; cursor < body.Text.Length; cursor++) + { + if (body.Text[cursor] == ';' && body.OpenerStack(cursor).Count == 0) + { + return cursor; + } + } + + return body.Text.Length; + } + } + + /// A splice: replace [Start, End) of the bundle with . + internal sealed class JsEdit + { + public JsEdit(int start, int end, string text) + { + Start = start; + End = end; + Text = text; + } + + /// An insertion at , replacing nothing. + public JsEdit(int at, string text) : this(at, at, text) + { + } + + public int Start { get; } + public int End { get; } + public string Text { get; } + + public string ApplyTo(string source) => source.Substring(0, Start) + Text + source.Substring(End); + } +} diff --git a/WandEnhancer/Core/Js/PatchPayload.cs b/WandEnhancer/Core/Js/PatchPayload.cs new file mode 100644 index 00000000..742c7e8f --- /dev/null +++ b/WandEnhancer/Core/Js/PatchPayload.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text.RegularExpressions; + +namespace WandEnhancer.Core.Js +{ + /// + /// Loads injected JavaScript from embedded Patches/*.js files so payloads stay + /// lintable source rather than escaped C# string literals. + /// + internal static class PatchPayload + { + private const string ResourcePrefix = "patches/"; + + private static readonly ConcurrentDictionary Cache = + new ConcurrentDictionary(StringComparer.Ordinal); + + private static readonly Regex Placeholder = new Regex(@"\$\{(?\w+)\}"); + + /// + /// Loads a payload, replacing each ${name} placeholder from alternating name/value pairs. + /// Substitution is a single pass, so injected bundle text is never rescanned for placeholders. + /// Unknown placeholders are left intact for the caller's own regex replacement to resolve. + /// + public static string Load(string name, params string[] placeholders) + { + if (placeholders.Length % 2 != 0) + { + throw new ArgumentException("Placeholders must be name/value pairs", nameof(placeholders)); + } + + var values = new Dictionary(StringComparer.Ordinal); + for (int index = 0; index < placeholders.Length; index += 2) + { + values[placeholders[index]] = placeholders[index + 1]; + } + + return Placeholder.Replace( + Cache.GetOrAdd(name, ReadResource), + match => values.TryGetValue(match.Groups["name"].Value, out var value) ? value : match.Value); + } + + private static string ReadResource(string name) + { + string resourceName = $"{ResourcePrefix}{name}.js"; + using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) + { + if (stream == null) + { + throw new FileNotFoundException($"Embedded patch payload not found: {resourceName}"); + } + + using (var reader = new StreamReader(stream)) + { + return reader.ReadToEnd().Trim(); + } + } + } + } +} diff --git a/WandEnhancer/Models/PatchConfig.cs b/WandEnhancer/Models/PatchConfig.cs index c050324c..2d9811c1 100644 --- a/WandEnhancer/Models/PatchConfig.cs +++ b/WandEnhancer/Models/PatchConfig.cs @@ -1,41 +1,22 @@ -using System; using System.Collections.Generic; -using Newtonsoft.Json; -using WandEnhancer.Utils; namespace WandEnhancer.Models { - public enum EPatchType { ActivatePro = 1, DisableUpdates = 2, - DisableTelemetry = 4, DevToolsOnF12 = 8, RemoteWebPanelPreview = 16 } - + public sealed class PatchConfig { - private string _path; public HashSet PatchTypes { get; set; } public List CustomScriptPaths { get; set; } = new List(); - - public bool AutoApplyPatches { get; set; } - - [JsonIgnore] - public WeModConfig AppProps { get; private set; } - public string Path - { - get => _path; - set - { - _path = value; - AppProps = Extensions.CheckWeModPath(_path) ?? throw new Exception("Invalid WeMod path"); - } - } + /// When set, the patch selection is saved so the launcher re-applies it after a Wand update. + public bool AutoApplyAfterUpdate { get; set; } } - -} \ No newline at end of file +} diff --git a/WandEnhancer/Models/Signature.cs b/WandEnhancer/Models/Signature.cs deleted file mode 100644 index 789d3a43..00000000 --- a/WandEnhancer/Models/Signature.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; - -namespace WandEnhancer.Models -{ - public sealed class Signature - { - public readonly byte[] OriginalBytes; - public readonly byte[] PatchBytes; - public readonly byte[] Sequence; - public readonly byte[] Mask; - public readonly int Offset; - - public int Length => Sequence.Length; - - public static implicit operator byte[](Signature signature) => signature.Sequence; - - public Signature(string signature, int offset, byte[] patchBytes, byte[] originalBytes) - { - Parse(signature, out Sequence, out Mask); - PatchBytes = patchBytes; - OriginalBytes = originalBytes; - Offset = offset; - } - - private static void Parse(string signatureStr, out byte[] pattern, out byte[] mask) - { - var parts = signatureStr.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); - var length = parts.Length; - - pattern = new byte[length]; - mask = new byte[length]; - - for (var i = 0; i < length; i++) - { - if (parts[i] == "??" || parts[i] == "?") - { - pattern[i] = 0; - // wildcard byte - mask[i] = 0; - continue; - } - - pattern[i] = Convert.ToByte(parts[i], 16); - mask[i] = 1; - } - } - } -} diff --git a/WandEnhancer/Patches/devtools-f12.js b/WandEnhancer/Patches/devtools-f12.js new file mode 100644 index 00000000..037fff45 --- /dev/null +++ b/WandEnhancer/Patches/devtools-f12.js @@ -0,0 +1 @@ +${app}.on("browser-window-created",((_,w)=>{try{w.webContents.on("before-input-event",((_,i)=>{if("F12"===i.key&&"keyDown"===i.type){w.webContents.isDevToolsOpened()?w.webContents.closeDevTools():w.webContents.openDevTools({mode:"detach"})}}))}catch(e){}})), diff --git a/WandEnhancer/Patches/disable-native-pairing.js b/WandEnhancer/Patches/disable-native-pairing.js new file mode 100644 index 00000000..36aec00e --- /dev/null +++ b/WandEnhancer/Patches/disable-native-pairing.js @@ -0,0 +1 @@ +return Promise.reject(new Error("wand-enhancer: native mobile pairing disabled")) diff --git a/WandEnhancer/Patches/disable-updates.js b/WandEnhancer/Patches/disable-updates.js new file mode 100644 index 00000000..ffbc3ae0 --- /dev/null +++ b/WandEnhancer/Patches/disable-updates.js @@ -0,0 +1 @@ +"ACTION_CHECK_FOR_UPDATE",(e=>expectUpdateFeedUrl(e,(e=>null))) diff --git a/WandEnhancer/Patches/pro-account-reducer.js b/WandEnhancer/Patches/pro-account-reducer.js new file mode 100644 index 00000000..674add69 --- /dev/null +++ b/WandEnhancer/Patches/pro-account-reducer.js @@ -0,0 +1 @@ +account:((account)=>account&&"object"==typeof account?{...account,subscription:{period:"yearly",state:"active"}}:account)(${account}) diff --git a/WandEnhancer/Patches/pro-subscription.js b/WandEnhancer/Patches/pro-subscription.js new file mode 100644 index 00000000..36397ef9 --- /dev/null +++ b/WandEnhancer/Patches/pro-subscription.js @@ -0,0 +1 @@ +$0.then((response)=>{response&&"object"==typeof response&&(response.subscription={period:"yearly",state:"active"});return response}) diff --git a/WandEnhancer/Patches/remote-bridge-boot.js b/WandEnhancer/Patches/remote-bridge-boot.js new file mode 100644 index 00000000..61f08b74 --- /dev/null +++ b/WandEnhancer/Patches/remote-bridge-boot.js @@ -0,0 +1 @@ +${app}.whenReady().then(()=>{try{const p=require("node:path");require(p.join(__dirname,"remote-panel","bridge.cjs")).installWandRuntime(require("electron"))}catch(e){try{const fs=require("node:fs"),os=require("node:os"),p=require("node:path");fs.appendFileSync(p.join(os.tmpdir(),"wand-remote-bridge.log"),"["+new Date().toISOString()+"] [boot-error] "+(e&&e.stack||e)+"\n")}catch(_){}}return run()}) diff --git a/WandEnhancer/Patches/remote-bridge-renderer.js b/WandEnhancer/Patches/remote-bridge-renderer.js new file mode 100644 index 00000000..3f99f3dc --- /dev/null +++ b/WandEnhancer/Patches/remote-bridge-renderer.js @@ -0,0 +1 @@ +this.__wandRemoteBridge||(this.__wandRemoteBridge=(()=>{try{const r=globalThis.require||require;const{ipcRenderer:c}=r("electron");try{c.invoke("wand-remote-url").then((u=>{u&&(globalThis.__wandRemoteBridgeUrl=u)}))}catch(e){}const send=(ch,p)=>{try{return c.invoke(ch,p&&JSON.parse(JSON.stringify(p)))}catch(e){}};return{sync:(s)=>send("wand-remote-sync",s),valueChanged:(s)=>send("wand-remote-value-changed",s),setHandler:(h)=>{if(this.__wandRemoteBridgeBound)return;this.__wandRemoteBridgeBound=true;try{c.invoke("wand-remote-set-handler-bind")}catch(e){}c.on("wand-remote-set-value",(_e,req)=>{try{h(req)}catch(e){}})}}}catch(e){try{const r=globalThis.require||require,fs=r("node:fs"),os=r("node:os"),p=r("node:path");fs.appendFileSync(p.join(os.tmpdir(),"wand-remote-bridge.log"),"["+new Date().toISOString()+"] [renderer-bind-error] "+(e&&e.stack||e)+"\n")}catch(_){}return null}})());this.__wandRemoteBridge?.setHandler((e=>{if(!this.${trainer}||!e?.target)return!1;return this.${trainer}.isActive()?this.${trainer}.setValue(e.target,e.value,${remoteSource},e.cheatId):!1}));this.__wandRemoteTrainerInfo=e??null; diff --git a/WandEnhancer/Patches/remote-bridge-reset.js b/WandEnhancer/Patches/remote-bridge-reset.js new file mode 100644 index 00000000..373f7091 --- /dev/null +++ b/WandEnhancer/Patches/remote-bridge-reset.js @@ -0,0 +1 @@ +;this.__wandRemoteTrainerInfo=null,this.__wandRemoteBridge?.sync(null) diff --git a/WandEnhancer/Patches/remote-bridge-sync.js b/WandEnhancer/Patches/remote-bridge-sync.js new file mode 100644 index 00000000..aa8cecbe --- /dev/null +++ b/WandEnhancer/Patches/remote-bridge-sync.js @@ -0,0 +1 @@ +,this.__wandRemoteBridge?.sync({${snapshot},trainerInfo:this.__wandRemoteTrainerInfo??null,metadata:this.${trainer}?.getMetadata(${metadata})??null}) diff --git a/WandEnhancer/Patches/remote-bridge-value-delta.js b/WandEnhancer/Patches/remote-bridge-value-delta.js new file mode 100644 index 00000000..a47a0f64 --- /dev/null +++ b/WandEnhancer/Patches/remote-bridge-value-delta.js @@ -0,0 +1 @@ +,this.__wandRemoteBridge?.valueChanged({target:e.name,value:e.value,oldValue:e.oldValue,source:String(e.source??"desktop"),cheatId:e.cheatId}) diff --git a/WandEnhancer/Utils/Common.cs b/WandEnhancer/Utils/Common.cs deleted file mode 100644 index ca9e49e5..00000000 --- a/WandEnhancer/Utils/Common.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.Reflection; -using System.Threading; - -namespace WandEnhancer.Utils -{ - public static class Common - { - public static void TryKillProcess(string processName) - { - Process[] processes = Process.GetProcessesByName(processName); - // Retry while any target process is still alive, capped at 5 attempts. - // The previous condition (processes.Length > i || i < 5) compared the - // process count to the loop index and, because of the "|| i < 5", always - // ran at least 5 iterations — sleeping ~1.25s even when the process was - // never running. - for (int i = 0; processes.Length > 0 && i < 5; i++) - { - foreach (var process in processes) - { - try - { - process.Kill(); - } - catch - { - // ignored - } - } - - processes = Process.GetProcessesByName(processName); - Thread.Sleep(250); - } - - if (processes.Length > 0) - { - throw new Exception("Failed to kill WeMod"); - } - } - - public static string GetCurrentDir() - { - var assemblyLocation = Assembly.GetExecutingAssembly().Location; - return Path.GetDirectoryName(assemblyLocation) ?? throw new InvalidOperationException(); - } - - public static string ComputeSha256Hash(string input) - { - using (var sha256 = System.Security.Cryptography.SHA256.Create()) - { - var bytes = System.Text.Encoding.UTF8.GetBytes(input); - var hashBytes = sha256.ComputeHash(bytes); - return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); - } - } - } -} \ No newline at end of file diff --git a/WandEnhancer/Utils/ProcessTerminator.cs b/WandEnhancer/Utils/ProcessTerminator.cs new file mode 100644 index 00000000..47904158 --- /dev/null +++ b/WandEnhancer/Utils/ProcessTerminator.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace WandEnhancer.Utils +{ + public static class ProcessTerminator + { + private const int KillAttempts = 5; + private const int KillRetryDelayMs = 250; + + public static void TryKillProcess(string processName) + { + // The launcher itself runs as Wand.exe; never target our own process. + int selfId = Process.GetCurrentProcess().Id; + + for (int attempt = 0; attempt < KillAttempts; attempt++) + { + var processes = Others(Process.GetProcessesByName(processName), selfId); + try + { + if (processes.Length == 0) + { + return; + } + + foreach (var process in processes) + { + try + { + process.Kill(); + } + catch (Exception e) when (e is InvalidOperationException || e is System.ComponentModel.Win32Exception) + { + // Already exited, or protected: the post-loop check decides the outcome. + } + } + } + finally + { + foreach (var process in processes) + { + process.Dispose(); + } + } + + Thread.Sleep(KillRetryDelayMs); + } + + var survivors = Others(Process.GetProcessesByName(processName), selfId); + try + { + if (survivors.Length > 0) + { + throw new InvalidOperationException($"Failed to close {processName}. Close it manually and try again."); + } + } + finally + { + foreach (var process in survivors) + { + process.Dispose(); + } + } + } + + private static Process[] Others(Process[] processes, int selfId) + { + var result = new List(processes.Length); + foreach (var process in processes) + { + if (process.Id == selfId) + { + process.Dispose(); + continue; + } + + result.Add(process); + } + + return result.ToArray(); + } + } +} diff --git a/WandEnhancer/Utils/Extensions.cs b/WandEnhancer/Utils/WeModInstalls.cs similarity index 88% rename from WandEnhancer/Utils/Extensions.cs rename to WandEnhancer/Utils/WeModInstalls.cs index f2b3936c..c491a236 100644 --- a/WandEnhancer/Utils/Extensions.cs +++ b/WandEnhancer/Utils/WeModInstalls.cs @@ -7,13 +7,14 @@ namespace WandEnhancer.Utils { - public static class Extensions + public static class WeModInstalls { + public const string JavaScriptFileExtension = ".js"; + public static WeModConfig CheckWeModPath(string versionRoot) { try { - foreach (var name in Constants.WeModBrandNames) { var exeName = $"{name}.exe"; @@ -29,9 +30,9 @@ public static WeModConfig CheckWeModPath(string versionRoot) } } } - catch + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentException) { - // ignored + // An unreadable or malformed candidate directory is not this install. } return null; @@ -113,16 +114,10 @@ private static WeModConfig FindWeModFromRunningProcess() return null; } - public static string Base64Decode(string base64EncodedData) - { - var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData); - return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); - } - - public static string Base64Encode(string plainText) + public static bool IsJavaScriptFile(string path) { - var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); - return System.Convert.ToBase64String(plainTextBytes); + return File.Exists(path) + && string.Equals(Path.GetExtension(path), JavaScriptFileExtension, StringComparison.OrdinalIgnoreCase); } public static WeModConfig FindLatestWeMod(string root) From 572b61ac25472e04cfa81553a9b3bfaef82f07c4 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Sat, 29 Aug 2026 16:56:25 +0300 Subject: [PATCH 04/15] feat(launcher): clear the ASAR fuse from a debugger instead of a proxy DLL Launch Wand with DEBUG_PROCESS and patch the integrity fuse byte in every process Electron spawns, then detach once the startup burst settles. Electron respawns children from its own on-disk exe, so patching only the main process left renderers crashing with -36861. Remove the version.dll proxy project and its CMake build step; the launcher no longer ships a native helper. Update the README to describe the debugger-based mechanism and drop CMake from the build requirements. Time the detach with Stopwatch instead of Environment.TickCount, which wraps. Check the PatchFuse result and surface a failure to the startup log. Scan for the fuse sentinel byte by byte rather than assuming 8-byte alignment. Close the image handle the kernel hands over with each process event. Name the DEBUG_EVENT and fuse wire offsets. Re-quote forwarded argv so Squirrel paths containing spaces survive. Keep an unobserved task exception from terminating the process. --- README.md | 13 +- WandEnhancer/Constants.cs | 30 +-- WandEnhancer/Core/FuseLauncher.cs | 291 +++++++++++++++++++++++++ WandEnhancer/Program.cs | 138 +++++++++++- WandEnhancer/Utils/Win32/Shortcut.cs | 61 ------ tools/asar-fuses-bypass/.gitignore | 78 ------- tools/asar-fuses-bypass/CMakeLists.txt | 21 -- tools/asar-fuses-bypass/fuses.c | 190 ---------------- tools/asar-fuses-bypass/library.c | 147 ------------- tools/asar-fuses-bypass/library.def | 20 -- 10 files changed, 425 insertions(+), 564 deletions(-) create mode 100644 WandEnhancer/Core/FuseLauncher.cs delete mode 100644 WandEnhancer/Utils/Win32/Shortcut.cs delete mode 100644 tools/asar-fuses-bypass/.gitignore delete mode 100644 tools/asar-fuses-bypass/CMakeLists.txt delete mode 100644 tools/asar-fuses-bypass/fuses.c delete mode 100644 tools/asar-fuses-bypass/library.c delete mode 100644 tools/asar-fuses-bypass/library.def diff --git a/README.md b/README.md index 8c7bb789..cd1db709 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ There are no official videos showing how to install or use this tool. Scammers a ## 👾 What does it access? -The .NET patcher modifies files in the selected local Wand installation and does not contact an update or telemetry service. The bundled `version.dll` proxy is loaded by Wand and changes Electron's ASAR-integrity fuse byte inside Wand's own process; it does not inject into another process. Wand itself remains an online application, build tools restore declared dependencies, and the optional Remote Web Panel deliberately starts a LAN HTTP/WebSocket server and uses Wand API/CDN data. Review the source and build the executable from your own fork; unsigned patching tools can trigger generic antivirus heuristics. +The .NET patcher modifies files in the selected local Wand installation and does not contact an update or telemetry service. Wand itself remains an online application, build tools restore declared dependencies, and the optional Remote Web Panel deliberately starts a LAN HTTP/WebSocket server and uses Wand API/CDN data. Review the source and build the executable from your own fork; unsigned patching tools can trigger generic antivirus heuristics. ## 💫 What features are improved? @@ -102,19 +102,17 @@ Building from source on Windows requires a local development environment. ### Requirements -- `CMake` - `Node.js` and `pnpm` - `Visual Studio 2022` or `Build Tools for Visual Studio 2022` with `MSBuild` -- Visual Studio `Desktop development with C++` workload - .NET Framework 4.8 desktop build tools / targeting pack ### Build steps 1. Clone this repository. -2. Install the requirements above and make sure `cmake`, `pnpm`, and `MSBuild` are available. +2. Install the requirements above and make sure `pnpm` and `MSBuild` are available. 3. Run `build.cmd` from Command Prompt or PowerShell. -The build script installs the web panel dependencies, builds the frontend, compiles the native helper with CMake, restores NuGet packages, and builds the WPF solution. +The build script installs the web panel dependencies, type-checks and lints the panel, builds the frontend and bridge, restores NuGet packages, and builds the WPF solution. --- @@ -141,12 +139,11 @@ The build script installs the web panel dependencies, builds the frontend, compi ![2](./assets/screenshots/app2.png) ---- ## 📜 License This project is licensed under the Apache-2.0 - see the [LICENSE](LICENSE.md) file for details. ---- + ## ❤️ Support If you find this project useful, you can support its development using any of the options below 🙌 @@ -163,5 +160,3 @@ If you find this project useful, you can support its development using any of th > This project is a third-party enhancement tool intended solely for educational, research, and local interoperability purposes. It does not distribute any proprietary code or bypass server-side validations. All modifications are performed locally to customize the user's interface. --- - -[![Star History Chart](https://api.star-history.com/svg?repos=k1tbyte/Wand-Enhancer&type=Date)](https://www.star-history.com/#k1tbyte/Wand-Enhancer&Date) diff --git a/WandEnhancer/Constants.cs b/WandEnhancer/Constants.cs index cb5bbcbe..1ea79d9d 100644 --- a/WandEnhancer/Constants.cs +++ b/WandEnhancer/Constants.cs @@ -1,6 +1,5 @@ -using System; +using System; using System.Reflection; -using WandEnhancer.Models; namespace WandEnhancer { @@ -8,36 +7,15 @@ public static class Constants { public const string RepoName = "Wand-Enhancer"; public const string Owner = "k1tbyte"; - /*public const string PatchRegistryName = "patchRegistry.json";*/ public static readonly string RepositoryUrl = $"https://github.com/{Owner}/{RepoName}"; public static readonly Version Version; public static readonly string[] WeModBrandNames = { "Wand", "WeMod" }; public const string AppSettingsFileName = "appsettings.json"; - - public const string ProxyDllResouceName = "proxydll"; + public const string AutoPatchConfigFileName = "enhancer.json"; - // cmp dword ptr [rdx], 0 - // jnz loc_XXXXXXXX - // mov rsi, rdx - /*public static Signature ExePatchSignature = new Signature( - "83 3A 00 0F ?? ?? 01 00 00 48 89 D6 48 B8", - 4, - new byte[]{ 0x84, 0x17 }, - new byte[]{ 0x85, 0x22 } - );*/ - - /*// ... - // test eax, eax (0x85 for r/m16/32/64) - // jnz short loc_1403A4DD2 (Integrity check failed) - // call near ptr funk_1445527E0 - // ... - private const string PatchSignature = "E8 ?? ?? ?? ?? ?? C0 75 ?? F6 C3 01 74 ?? 48 89 F9 E8 ?? ?? ?? ??"; - private static readonly byte[] PatchBytes = { 0x31 }; - private const int PatchOffset = 0x5;*/ - - static Constants() + static Constants() { Version = Assembly.GetExecutingAssembly().GetName().Version; } } -} \ No newline at end of file +} diff --git a/WandEnhancer/Core/FuseLauncher.cs b/WandEnhancer/Core/FuseLauncher.cs new file mode 100644 index 00000000..f2569983 --- /dev/null +++ b/WandEnhancer/Core/FuseLauncher.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; + +namespace WandEnhancer.Core +{ + /// + /// Launches Electron under a startup-only debugger and clears the ASAR integrity + /// fuse in every process it spawns (main, renderer, gpu, utility). Electron respawns + /// children from its own on-disk exe where the fuse is still enabled, so patching only + /// the main process leaves renderers crashing with -36861. The debugger stops each child + /// at creation, so there is no race, and memory patching is immune to Chromium's sandbox + /// DLL-signature mitigations. We detach once the window is up - long before any game + /// launch - so game anti-debug/DRM is never exposed to a debugger. + /// + internal static class FuseLauncher + { + private const int FuseAsarIntegrity = 4; + private const byte FuseStateRemoved = (byte)'r'; + private const int SentinelLength = 32; + private const int ScanChunkSize = 0x100000; + + // Electron's fuse wire follows the sentinel: [version][fuseCount][state per fuse]. + private const int FuseWireVersionOffset = 0; + private const int FuseWireCountOffset = 1; + private const int FuseWireStatesOffset = 2; + private const byte FuseWireSupportedVersion = 1; + private const int FuseWireMinCount = 5; + // Longest tail read past a sentinel hit: version + count + the fuse we edit. + private const int FuseWireTailBytes = FuseWireStatesOffset + FuseAsarIntegrity + 1; + + // x64 DEBUG_EVENT: dwDebugEventCode, dwProcessId, dwThreadId, 4 bytes padding, + // then the union. CREATE_PROCESS_DEBUG_INFO starts with hFile, hProcess, hThread, + // lpBaseOfImage; EXCEPTION_DEBUG_INFO starts with the exception code. + private const int DebugEventSize = 192; + private const int OffsetDebugEventCode = 0; + private const int OffsetProcessId = 4; + private const int OffsetThreadId = 8; + private const int OffsetUnion = 16; + private const int OffsetExceptionCode = OffsetUnion; + private const int OffsetCreateProcessFile = OffsetUnion; + private const int OffsetCreateProcessHandle = OffsetUnion + 8; + private const int OffsetCreateProcessImageBase = OffsetUnion + 24; + + // Detach after the startup process burst settles (all children spawned and patched), + // capped hard so we never linger into gameplay. + private const long MinDebugMs = 3000; + private const long QuietMs = 1500; + private const long MaxDebugMs = 9000; + + private static readonly byte[] Sentinel = + Encoding.ASCII.GetBytes("dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX"); + + public static bool Launch(string exePath, string args, Action log = null) + { + var si = new STARTUPINFO { cb = Marshal.SizeOf() }; + var cmdLine = new StringBuilder( + string.IsNullOrEmpty(args) ? $"\"{exePath}\"" : $"\"{exePath}\" {args}"); + + if (!CreateProcessW(null, cmdLine, IntPtr.Zero, IntPtr.Zero, + false, DEBUG_PROCESS, IntPtr.Zero, + Path.GetDirectoryName(exePath), ref si, out var pi)) + { + log?.Invoke($"Could not start Wand under the fuse patcher (win32 error {Marshal.GetLastWin32Error()})."); + return false; + } + + // Debugged processes must survive after we detach and exit. + DebugSetProcessKillOnExit(false); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + + DrivePatchingDebugLoop(pi.dwProcessId, log); + return true; + } + + private static void DrivePatchingDebugLoop(int mainPid, Action log) + { + var pids = new List(); + var brokeIn = new HashSet(); + var evt = new byte[DebugEventSize]; + // Stopwatch, not TickCount: TickCount is a 32-bit millisecond counter that wraps + // every ~25 days, and a negative elapsed would keep the debugger attached forever. + var clock = Stopwatch.StartNew(); + long lastCreate = 0; + + while (true) + { + long now = clock.ElapsedMilliseconds; + + if (!WaitForDebugEvent(evt, 200)) + { + if (ShouldDetach(now, now - lastCreate)) break; + continue; + } + + int code = BitConverter.ToInt32(evt, OffsetDebugEventCode); + int pid = BitConverter.ToInt32(evt, OffsetProcessId); + int tid = BitConverter.ToInt32(evt, OffsetThreadId); + uint status = DBG_CONTINUE; + + switch (code) + { + case CREATE_PROCESS_DEBUG_EVENT: + var hFile = (IntPtr)BitConverter.ToInt64(evt, OffsetCreateProcessFile); + var hProc = (IntPtr)BitConverter.ToInt64(evt, OffsetCreateProcessHandle); + var baseImg = (IntPtr)BitConverter.ToInt64(evt, OffsetCreateProcessImageBase); + if (!pids.Contains(pid)) pids.Add(pid); + if (!PatchFuse(hProc, baseImg)) + log?.Invoke($"Fuse not cleared in pid {pid}; renderers may fail with -36861."); + // The debugger owns the image handle the kernel hands over with this event. + if (hFile != IntPtr.Zero) CloseHandle(hFile); + lastCreate = now; + break; + + case EXCEPTION_DEBUG_EVENT: + int exCode = BitConverter.ToInt32(evt, OffsetExceptionCode); + // Pass the one-shot startup breakpoint, let the app own the rest. + status = (exCode == EXCEPTION_BREAKPOINT && brokeIn.Add(pid)) + ? DBG_CONTINUE + : DBG_EXCEPTION_NOT_HANDLED; + break; + + case EXIT_PROCESS_DEBUG_EVENT: + pids.Remove(pid); + if (pid == mainPid) + { + ContinueDebugEvent(pid, tid, status); + return; + } + break; + } + + ContinueDebugEvent(pid, tid, status); + + now = clock.ElapsedMilliseconds; + if (ShouldDetach(now, now - lastCreate)) + break; + } + + foreach (var pid in pids) + DebugActiveProcessStop(pid); + } + + private static bool ShouldDetach(long elapsed, long sinceLastCreate) + { + if (elapsed > MaxDebugMs) return true; + return elapsed > MinDebugMs && sinceLastCreate > QuietMs; + } + + private static bool PatchFuse(IntPtr hProcess, IntPtr imageBase) + { + if (imageBase == IntPtr.Zero) return false; + + int sizeOfImage = ReadSizeOfImage(hProcess, imageBase); + if (sizeOfImage == 0) return false; + + const int overlap = 64; + var buffer = new byte[ScanChunkSize + overlap]; + + for (long offset = 0; offset < sizeOfImage; offset += ScanChunkSize) + { + int toRead = (int)Math.Min(ScanChunkSize + overlap, sizeOfImage - offset); + if (toRead < SentinelLength + FuseWireTailBytes) break; + + var addr = new IntPtr(imageBase.ToInt64() + offset); + if (!ReadProcessMemory(hProcess, addr, buffer, toRead, out int bytesRead)) + continue; + if (bytesRead < SentinelLength + FuseWireTailBytes) continue; + + int limit = bytesRead - SentinelLength - FuseWireTailBytes; + // Byte-by-byte: the linker is free to place the sentinel at any alignment, + // and a miss means every renderer dies with -36861. + for (int i = 0; i <= limit; i++) + { + if (buffer[i] != Sentinel[0] || !MatchesSentinel(buffer, i)) continue; + + int wireOffset = i + SentinelLength; + if (buffer[wireOffset + FuseWireVersionOffset] != FuseWireSupportedVersion || + buffer[wireOffset + FuseWireCountOffset] < FuseWireMinCount) continue; + + int fusePos = wireOffset + FuseWireStatesOffset + FuseAsarIntegrity; + if (buffer[fusePos] == FuseStateRemoved) return true; + + var target = new IntPtr(imageBase.ToInt64() + offset + fusePos); + VirtualProtectEx(hProcess, target, (UIntPtr)1, PAGE_READWRITE, out uint oldProt); + bool ok = WriteProcessMemory(hProcess, target, new[] { FuseStateRemoved }, 1, out _); + VirtualProtectEx(hProcess, target, (UIntPtr)1, oldProt, out _); + return ok; + } + } + + return false; + } + + private static bool MatchesSentinel(byte[] buffer, int offset) + { + for (int j = 1; j < SentinelLength; j++) + if (buffer[offset + j] != Sentinel[j]) return false; + return true; + } + + private static int ReadSizeOfImage(IntPtr hProcess, IntPtr imageBase) + { + var dosHeader = new byte[64]; + if (!ReadProcessMemory(hProcess, imageBase, dosHeader, 64, out _)) + return 0; + + int peOffset = BitConverter.ToInt32(dosHeader, 0x3C); + var buf = new byte[4]; + // SizeOfImage sits at optional-header offset 56 (PE signature + COFF header = 24). + var addr = new IntPtr(imageBase.ToInt64() + peOffset + 80); + if (!ReadProcessMemory(hProcess, addr, buf, 4, out _)) + return 0; + + return BitConverter.ToInt32(buf, 0); + } + + #region P/Invoke + + private const uint DEBUG_PROCESS = 0x1; + private const uint PAGE_READWRITE = 0x04; + private const uint DBG_CONTINUE = 0x00010002; + private const uint DBG_EXCEPTION_NOT_HANDLED = 0x80010001; + private const int EXCEPTION_DEBUG_EVENT = 1; + private const int CREATE_PROCESS_DEBUG_EVENT = 3; + private const int EXIT_PROCESS_DEBUG_EVENT = 5; + private const int EXCEPTION_BREAKPOINT = unchecked((int)0x80000003); + + [StructLayout(LayoutKind.Sequential)] + private struct STARTUPINFO + { + public int cb; + public IntPtr lpReserved, lpDesktop, lpTitle; + public int dwX, dwY, dwXSize, dwYSize; + public int dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags; + public short wShowWindow, cbReserved2; + public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError; + } + + [StructLayout(LayoutKind.Sequential)] + private struct PROCESS_INFORMATION + { + public IntPtr hProcess, hThread; + public int dwProcessId, dwThreadId; + } + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool CreateProcessW( + string lpApplicationName, StringBuilder lpCommandLine, + IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, + bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, + string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, + out PROCESS_INFORMATION lpProcessInformation); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool ReadProcessMemory( + IntPtr hProcess, IntPtr lpBaseAddress, + byte[] lpBuffer, int dwSize, out int lpNumberOfBytesRead); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool WriteProcessMemory( + IntPtr hProcess, IntPtr lpBaseAddress, + byte[] lpBuffer, int dwSize, out int lpNumberOfBytesWritten); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool VirtualProtectEx( + IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, + uint flNewProtect, out uint lpflOldProtect); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool WaitForDebugEvent(byte[] lpDebugEvent, int dwMilliseconds); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool ContinueDebugEvent(int dwProcessId, int dwThreadId, uint dwContinueStatus); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool DebugActiveProcessStop(int dwProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool DebugSetProcessKillOnExit(bool KillOnExit); + + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr hObject); + + #endregion + } +} diff --git a/WandEnhancer/Program.cs b/WandEnhancer/Program.cs index c27be549..07866e77 100644 --- a/WandEnhancer/Program.cs +++ b/WandEnhancer/Program.cs @@ -1,45 +1,159 @@ using System; using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; using System.Threading.Tasks; using System.Windows.Forms; +using WandEnhancer.Core; +using WandEnhancer.Models; +using WandEnhancer.Utils; using WandEnhancer.View.MainWindow; namespace WandEnhancer { public static class Program { + /// Log lines from a failed startup auto-patch, replayed by the UI when it opens. + public static readonly List> StartupLog = + new List>(); + [STAThread] public static void Main(string[] args) { + if (TryLaunchMode(args)) + return; + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; TaskScheduler.UnobservedTaskException += OnUnobservedTaskException; - - List logEntries = new List(); - if (args.Length > 0) - { - // TODO: Command line arguments handling - } var application = new App(); application.InitializeComponent(); application.MainWindow = new MainWindow(); - foreach (var logEntry in logEntries) + application.Run(); + } + + private static bool TryLaunchMode(string[] args) + { + string myExe = Assembly.GetExecutingAssembly().Location; + string myName = Path.GetFileNameWithoutExtension(myExe); + + if (!Constants.WeModBrandNames.Any( + n => n.Equals(myName, StringComparison.OrdinalIgnoreCase))) + return false; + + string myDir = Path.GetDirectoryName(myExe); + + if (args.Length > 0 && + args[0].StartsWith("--squirrel", StringComparison.OrdinalIgnoreCase)) { - MainWindow.Instance.ViewModel.LogList.Add(logEntry); + string updateExe = Path.Combine(myDir, "Update.exe"); + if (File.Exists(updateExe)) + Process.Start(updateExe, QuoteArguments(args)); + return true; } - application.Run(); + + var config = WeModInstalls.FindLatestWeMod(myDir); + if (config == null) + return false; + + // A fresh Wand version drops our patches; re-apply the saved selection automatically. + // On failure fall through to the UI so the user sees which patch broke. + if (!Enhancer.IsPatched(config.RootDirectory) && !TryAutoPatch(config, myDir)) + return false; + + string forwardedArgs = args.Length > 0 ? QuoteArguments(args) : null; + FuseLauncher.Launch(config.ExecutablePath, forwardedArgs, + message => RecordStartupLog(message, ELogType.Warn)); + return true; + } + + /// + /// Re-quotes argv for a command line. Squirrel hands us paths with spaces + /// (`--squirrel-install "C:\Users\Some Name\..."`); re-joining on spaces splits them. + /// + private static string QuoteArguments(IEnumerable args) + { + return string.Join(" ", args.Select(QuoteArgument)); + } + + private static string QuoteArgument(string value) + { + if (!string.IsNullOrEmpty(value) && value.IndexOfAny(new[] { ' ', '\t', '"' }) < 0) + { + return value; + } + + // Backslashes are literal unless they run into the closing quote, where they double. + var quoted = new System.Text.StringBuilder("\""); + int backslashes = 0; + foreach (char current in value ?? string.Empty) + { + if (current == '\\') + { + backslashes++; + continue; + } + + if (current == '"') + { + quoted.Append('\\', backslashes * 2 + 1).Append('"'); + } + else + { + quoted.Append('\\', backslashes).Append(current); + } + + backslashes = 0; + } + + return quoted.Append('\\', backslashes * 2).Append('"').ToString(); + } + + private static bool TryAutoPatch(WeModConfig config, string launcherDir) + { + var patchConfig = Enhancer.LoadAutoPatchConfig(launcherDir); + if (patchConfig == null) + return true; // nothing saved to replay; launch as-is + + try + { + new Enhancer(config, RecordStartupLog, patchConfig).Patch(); + return true; + } + catch (Exception e) + { + // Localization resources are not loaded yet in launcher mode (no Application), + // so these two replay into the UI log in English by design. + RecordStartupLog($"Auto-patch failed: {e.Message}", ELogType.Error); + RecordStartupLog("The new Wand version may need updated patches. Restore the backup and patch again.", ELogType.Warn); + return false; + } + } + + private static void RecordStartupLog(string message, ELogType type) + { + StartupLog.Add(new KeyValuePair(message, type)); } + // Fires on the finalizer thread for a task nobody awaited. Non-fatal since .NET 4.5: + // record it and mark it observed rather than killing a patch mid-run. private static void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { - MessageBox.Show(e.Exception.ToString()); - Environment.Exit(1); + e.SetObserved(); + RecordStartupLog($"Background task failed: {e.Exception.GetBaseException().Message}", ELogType.Error); } private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { - MessageBox.Show(e.ExceptionObject.ToString()); + var error = e.ExceptionObject as Exception; + MessageBox.Show( + error?.Message ?? e.ExceptionObject?.ToString() ?? "Unknown error", + Constants.RepoName, + MessageBoxButtons.OK, + MessageBoxIcon.Error); Environment.Exit(1); } } diff --git a/WandEnhancer/Utils/Win32/Shortcut.cs b/WandEnhancer/Utils/Win32/Shortcut.cs deleted file mode 100644 index a179f720..00000000 --- a/WandEnhancer/Utils/Win32/Shortcut.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Runtime.InteropServices; - -namespace WandEnhancer.Utils.Win32 -{ - public class Shortcut - { - public class ShortcutParams - { - public string FileName { get; set; } - public string TargetPath { get; set; } - public string Arguments { get; set; } - public string WorkingDirectory { get; set; } - public string Description { get; set; } - public string Hotkey { get; set; } - public string IconPath { get; set; } - }; - - private static readonly Type m_type = Type.GetTypeFromProgID("WScript.Shell"); - private static readonly object m_shell = Activator.CreateInstance(m_type); - - [ComImport, TypeLibType(0x1040), Guid("F935DC23-1CF0-11D0-ADB9-00C04FD58A0B")] - private interface IWshShortcut - { - [DispId(0)] - string FullName { [return: MarshalAs(UnmanagedType.BStr)][DispId(0)] get; } - [DispId(0x3e8)] - string Arguments { [return: MarshalAs(UnmanagedType.BStr)][DispId(0x3e8)] get; [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3e8)] set; } - [DispId(0x3e9)] - string Description { [return: MarshalAs(UnmanagedType.BStr)][DispId(0x3e9)] get; [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3e9)] set; } - [DispId(0x3ea)] - string Hotkey { [return: MarshalAs(UnmanagedType.BStr)][DispId(0x3ea)] get; [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3ea)] set; } - [DispId(0x3eb)] - string IconLocation { [return: MarshalAs(UnmanagedType.BStr)][DispId(0x3eb)] get; [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3eb)] set; } - [DispId(0x3ec)] - string RelativePath { [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3ec)] set; } - [DispId(0x3ed)] - string TargetPath { [return: MarshalAs(UnmanagedType.BStr)][DispId(0x3ed)] get; [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3ed)] set; } - [DispId(0x3ee)] - int WindowStyle { [DispId(0x3ee)] get; [param: In][DispId(0x3ee)] set; } - [DispId(0x3ef)] - string WorkingDirectory { [return: MarshalAs(UnmanagedType.BStr)][DispId(0x3ef)] get; [param: In, MarshalAs(UnmanagedType.BStr)][DispId(0x3ef)] set; } - [TypeLibFunc((short)0x40), DispId(0x7d0)] - void Load([In, MarshalAs(UnmanagedType.BStr)] string PathLink); - [DispId(0x7d1)] - void Save(); - } - - public static void CreateShortcut(string fileName, string targetPath, string arguments, string workingDirectory, string description, string iconPath) - { - IWshShortcut shortcut = (IWshShortcut)m_type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, m_shell, new object[] { fileName }); - shortcut.Description = description; - shortcut.TargetPath = targetPath; - shortcut.WorkingDirectory = workingDirectory; - shortcut.Arguments = arguments; - if (!string.IsNullOrEmpty(iconPath)) - shortcut.IconLocation = iconPath; - shortcut.Save(); - } - } -} \ No newline at end of file diff --git a/tools/asar-fuses-bypass/.gitignore b/tools/asar-fuses-bypass/.gitignore deleted file mode 100644 index b0098937..00000000 --- a/tools/asar-fuses-bypass/.gitignore +++ /dev/null @@ -1,78 +0,0 @@ -# Build directories -/build/ -/build-debug/ -/build-release/ -/out/ - -# CMake generated files -CMakeCache.txt -CMakeFiles/ -cmake_install.cmake -CTestTestfile.cmake -Makefile -install_manifest.txt - -# Compiled binaries -*.o -*.obj -*.lo -*.la -*.a -*.so -*.so.* -*.dylib -*.dll -*.exe -*.out -*.app - -# Debug files -*.pch -*.pdb -*.mod -*.map - -# Generated configuration headers -config.h -config.hpp - -# Logs -*.log - -# IDE files -# VS Code -.vscode/ -*.code-workspace - -# CLion -.idea/ - -# Visual Studio -*.user -*.suo -*.vcxproj.user -*.vcxproj.* -*.sln - -# Xcode -*.pbxuser -*.mode1v3 -*.mode2v3 -*.perspectivev3 -*.xcworkspace/ -xcuserdata/ - -# OS junk -# macOS -.DS_Store - -# Windows -Thumbs.db -ehthumbs.db -Desktop.ini -$RECYCLE.BIN/ - -# Backup files -*~ -*.swp -*.tmp diff --git a/tools/asar-fuses-bypass/CMakeLists.txt b/tools/asar-fuses-bypass/CMakeLists.txt deleted file mode 100644 index eec5677f..00000000 --- a/tools/asar-fuses-bypass/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -cmake_minimum_required(VERSION 3.16) -cmake_policy(SET CMP0091 NEW) -project(asar_fuses_bypass C) - -set(CMAKE_C_STANDARD 11) - -#[[ -add_executable(asar_fuses_bypass main.c) -]] - -set(CMAKE_SHARED_LIBRARY_PREFIX "") -set(CMAKE_STATIC_LIBRARY_PREFIX "") - -add_library(version SHARED library.c library.def fuses.c) - -if(MSVC) - set_property(TARGET version PROPERTY - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") - target_link_options(version PRIVATE -static -static-libgcc -static-libstdc++) -endif() diff --git a/tools/asar-fuses-bypass/fuses.c b/tools/asar-fuses-bypass/fuses.c deleted file mode 100644 index fcf4a4cd..00000000 --- a/tools/asar-fuses-bypass/fuses.c +++ /dev/null @@ -1,190 +0,0 @@ -// -// Created by kitbyte on 30.11.2025. -// - -#include -#include -#include - -#define ENABLE_LOGGING 0 - -#ifndef _DEBUG -#undef ENABLE_LOGGING -#define ENABLE_LOGGING 0 -#endif - -#define FUSE_SENTINEL_LENGTH 32 -#define FUSE_VERSION_SUPPORTED 1 -#define FUSE_MIN_WIRE_LENGTH 5 - -#define ALIGN8(ptr, mod) ((((ULONG_PTR)(ptr) + 7) & ~7) + ((mod) * 8)) - -#if defined(_WIN64) - #define SENTINEL_PART1 0x6E64474B70374C64ULL - #define SENTINEL_PART2 0x6262503639377A4EULL - #define SENTINEL_PART3 0x58486D4B4E57516AULL - #define SENTINEL_PART4 0x5873743942615A42ULL -#else - static const DWORD SENTINEL_PARTS[8] = { - 0x70374C64, 0x6E64474B, - 0x39377A4E, 0x62625036, - 0x4E57516A, 0x58486D4B, - 0x42615A42, 0x58737439 - }; -#endif - -typedef enum { - FUSE_RUN_AS_NODE = 0, - FUSE_COOKIE_ENCRYPTION = 1, - FUSE_NODE_OPTIONS = 2, - FUSE_NODE_CLI_INSPECT = 3, - FUSE_ASAR_INTEGRITY_VALIDATION = 4, - FUSE_ONLY_LOAD_APP_FROM_ASAR = 5, - FUSE_LOAD_BROWSER_V8_SNAPSHOT = 6, - FUSE_GRANT_FILE_PROTOCOL = 7 -} ElectronFuseIndex; - -typedef enum { - FUSE_STATE_DISABLED = '0', - FUSE_STATE_ENABLED = '1', - FUSE_STATE_REMOVED = 'r' -} FuseState; - -typedef struct { - char sentinel[FUSE_SENTINEL_LENGTH]; - unsigned char version; - unsigned char wire_length; - unsigned char fuses[]; -} FuseWire; - -#if ENABLE_LOGGING - -static FILE* g_logFile = NULL; - -static void log_init(void) { - char path[MAX_PATH]; - GetModuleFileNameA(NULL, path, MAX_PATH); - char* dot = strrchr(path, '.'); - if (dot) strcpy(dot, ".log"); - else strcat(path, ". log"); - - g_logFile = fopen(path, "a"); - if (g_logFile) { - time_t now = time(NULL); - fprintf(g_logFile, "\n=== Session: %s", ctime(&now)); - fflush(g_logFile); - } -} - -static void log_close(void) { - if (g_logFile) { - fclose(g_logFile); - g_logFile = NULL; - } -} - -static void log_msg(const char* fmt, .. .) { - if (!g_logFile) return; - va_list args; - va_start(args, fmt); - vfprintf(g_logFile, fmt, args); - va_end(args); - fflush(g_logFile); -} - -#else - #define log_init() ((void)0) - #define log_close() ((void)0) - #define log_msg(...) ((void)0) -#endif - -static FuseWire* find_fuse_wire(int offset) { - char* base = (char*)GetModuleHandleA(NULL); - if (!base) return NULL; - - IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)base; - if (dos->e_magic != IMAGE_DOS_SIGNATURE) return NULL; - - IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + dos->e_lfanew); - if (nt->Signature != IMAGE_NT_SIGNATURE) return NULL; - - DWORD size = nt->OptionalHeader.SizeOfImage; - char* start = (char*)ALIGN8(base, 1) + offset; - char* end = (char*)ALIGN8(base + size - FUSE_SENTINEL_LENGTH, -1) - offset; - -#if defined(_WIN64) - for (DWORD64* p = (DWORD64*)start; p < (DWORD64*)end; p++) { - if (p[0] == SENTINEL_PART1 && p[1] == SENTINEL_PART2 && - p[2] == SENTINEL_PART3 && p[3] == SENTINEL_PART4) { - log_msg("[+] Sentinel at: %p\n", p); - return (FuseWire*)p; - } - } -#else - for (DWORD* p = (DWORD*)start; p < (DWORD*)end; p += 2) { - if (p[0] == SENTINEL_PARTS[0] && p[1] == SENTINEL_PARTS[1] && - p[2] == SENTINEL_PARTS[2] && p[3] == SENTINEL_PARTS[3] && - p[4] == SENTINEL_PARTS[4] && p[5] == SENTINEL_PARTS[5] && - p[6] == SENTINEL_PARTS[6] && p[7] == SENTINEL_PARTS[7]) { - log_msg("[+] Sentinel at: %p\n", p); - return (FuseWire*)p; - } - } -#endif - return NULL; -} - -static BOOL patch_fuse(unsigned char* fuse) { - DWORD prot; - if (!VirtualProtect(fuse, 1, PAGE_READWRITE, &prot)) { - log_msg("[-] VirtualProtect failed: %lu\n", GetLastError()); - return FALSE; - } - *fuse = FUSE_STATE_REMOVED; - VirtualProtect(fuse, 1, prot, &prot); - return TRUE; -} - -BOOL disable_asar_integrity(void) { - log_init(); - - FuseWire* wire = find_fuse_wire(0); - if (! wire) wire = find_fuse_wire(4); - - if (! wire) { - log_msg("[-] Fuse wire not found\n"); - log_close(); - return FALSE; - } - - log_msg("[+] Wire at %p, ver=%d, len=%d\n", wire, wire->version, wire->wire_length); - - if (wire->version != FUSE_VERSION_SUPPORTED) { - log_msg("[-] Unsupported version: %d\n", wire->version); - log_close(); - return FALSE; - } - - if (wire->wire_length < FUSE_MIN_WIRE_LENGTH) { - log_msg("[*] Wire too short, skip\n"); - log_close(); - return TRUE; - } - - unsigned char* target = &wire->fuses[FUSE_ASAR_INTEGRITY_VALIDATION]; - - if (*target == FUSE_STATE_REMOVED) { - log_msg("[*] Already patched\n"); - log_close(); - return TRUE; - } - - log_msg("[*] Patching fuse[%d]: 0x%02X -> 0x%02X\n", - FUSE_ASAR_INTEGRITY_VALIDATION, *target, FUSE_STATE_REMOVED); - - BOOL result = patch_fuse(target); - log_msg(result ? "[+] Success\n" : "[-] Failed\n"); - - log_close(); - return result; -} \ No newline at end of file diff --git a/tools/asar-fuses-bypass/library.c b/tools/asar-fuses-bypass/library.c deleted file mode 100644 index 9c96af5a..00000000 --- a/tools/asar-fuses-bypass/library.c +++ /dev/null @@ -1,147 +0,0 @@ -// -// Created by kitbyte on 30.11.2025. -// -#include -#include - -extern BOOL disable_asar_integrity(void); - -static HMODULE g_originalVersionDll; - -#define FOR_EACH_VERSION_FORWARDER(X) \ - X(GetFileVersionInfoA, BOOL, FALSE, \ - (LPCSTR filename, DWORD handle, DWORD length, LPVOID data), \ - (filename, handle, length, data)) \ - X(GetFileVersionInfoExA, BOOL, FALSE, \ - (DWORD flags, LPCSTR filename, DWORD handle, DWORD length, LPVOID data), \ - (flags, filename, handle, length, data)) \ - X(GetFileVersionInfoExW, BOOL, FALSE, \ - (DWORD flags, LPCWSTR filename, DWORD handle, DWORD length, LPVOID data), \ - (flags, filename, handle, length, data)) \ - X(GetFileVersionInfoSizeA, DWORD, 0, \ - (LPCSTR filename, LPDWORD handle), \ - (filename, handle)) \ - X(GetFileVersionInfoSizeExA, DWORD, 0, \ - (DWORD flags, LPCSTR filename, LPDWORD handle), \ - (flags, filename, handle)) \ - X(GetFileVersionInfoSizeExW, DWORD, 0, \ - (DWORD flags, LPCWSTR filename, LPDWORD handle), \ - (flags, filename, handle)) \ - X(GetFileVersionInfoSizeW, DWORD, 0, \ - (LPCWSTR filename, LPDWORD handle), \ - (filename, handle)) \ - X(GetFileVersionInfoW, BOOL, FALSE, \ - (LPCWSTR filename, DWORD handle, DWORD length, LPVOID data), \ - (filename, handle, length, data)) \ - X(VerFindFileA, DWORD, 0, \ - (DWORD flags, LPCSTR fileName, LPCSTR winDir, LPCSTR appDir, LPSTR curDir, PUINT curDirLen, LPSTR destDir, PUINT destDirLen), \ - (flags, fileName, winDir, appDir, curDir, curDirLen, destDir, destDirLen)) \ - X(VerFindFileW, DWORD, 0, \ - (DWORD flags, LPCWSTR fileName, LPCWSTR winDir, LPCWSTR appDir, LPWSTR curDir, PUINT curDirLen, LPWSTR destDir, PUINT destDirLen), \ - (flags, fileName, winDir, appDir, curDir, curDirLen, destDir, destDirLen)) \ - X(VerInstallFileA, DWORD, 0, \ - (DWORD flags, LPCSTR srcFileName, LPCSTR destFileName, LPCSTR srcDir, LPCSTR destDir, LPCSTR curDir, LPSTR tempFile, PUINT tempFileLen), \ - (flags, srcFileName, destFileName, srcDir, destDir, curDir, tempFile, tempFileLen)) \ - X(VerInstallFileW, DWORD, 0, \ - (DWORD flags, LPCWSTR srcFileName, LPCWSTR destFileName, LPCWSTR srcDir, LPCWSTR destDir, LPCWSTR curDir, LPWSTR tempFile, PUINT tempFileLen), \ - (flags, srcFileName, destFileName, srcDir, destDir, curDir, tempFile, tempFileLen)) \ - X(VerLanguageNameA, DWORD, 0, \ - (DWORD language, LPSTR buffer, DWORD bufferLength), \ - (language, buffer, bufferLength)) \ - X(VerLanguageNameW, DWORD, 0, \ - (DWORD language, LPWSTR buffer, DWORD bufferLength), \ - (language, buffer, bufferLength)) \ - X(VerQueryValueA, BOOL, FALSE, \ - (LPCVOID block, LPCSTR subBlock, LPVOID* buffer, PUINT bufferLength), \ - (block, subBlock, buffer, bufferLength)) \ - X(VerQueryValueW, BOOL, FALSE, \ - (LPCVOID block, LPCWSTR subBlock, LPVOID* buffer, PUINT bufferLength), \ - (block, subBlock, buffer, bufferLength)) - -#if defined(_MSC_VER) && !defined(_WIN64) - -#define DECLARE_FORWARDER(name, return_type, default_value, params, args) \ - static FARPROC s_##name; \ - __declspec(naked) return_type WINAPI name params \ - { \ - __asm \ - { \ - jmp dword ptr [s_##name] \ - } \ - } - -#define LOAD_FORWARDER(name, return_type, default_value, params, args) \ - s_##name = GetProcAddress(g_originalVersionDll, #name); - -#else - -#define DECLARE_FORWARDER(name, return_type, default_value, params, args) \ - typedef return_type (WINAPI *name##_fn) params; \ - static name##_fn s_##name; \ - return_type WINAPI name params \ - { \ - if (s_##name == NULL) \ - { \ - SetLastError(ERROR_PROC_NOT_FOUND); \ - return default_value; \ - } \ - return s_##name args; \ - } - -#define LOAD_FORWARDER(name, return_type, default_value, params, args) \ - s_##name = (name##_fn)GetProcAddress(g_originalVersionDll, #name); - -#endif - -FOR_EACH_VERSION_FORWARDER(DECLARE_FORWARDER) - -BOOL WINAPI GetFileVersionInfoByHandle(void) -{ - SetLastError(ERROR_CALL_NOT_IMPLEMENTED); - return FALSE; -} - -static BOOL SourceInit(void) -{ - WCHAR source[MAX_PATH]; - UINT sourceLength = GetSystemDirectoryW(source, MAX_PATH); - - if (sourceLength == 0 || sourceLength >= MAX_PATH) - { - return FALSE; - } - - if (wcscat_s(source, MAX_PATH, L"\\version.dll") != 0) - { - return FALSE; - } - - g_originalVersionDll = LoadLibraryW(source); - if (!g_originalVersionDll) - { - return FALSE; - } - - FOR_EACH_VERSION_FORWARDER(LOAD_FORWARDER); - - return TRUE; -} - -BOOL WINAPI DllMain(HMODULE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) -{ - (void)lpvReserved; - - if (fdwReason == DLL_PROCESS_ATTACH) - { - DisableThreadLibraryCalls(hinstDLL); - - if (!SourceInit()) - { - return FALSE; - } - - disable_asar_integrity(); - } - - return TRUE; -} \ No newline at end of file diff --git a/tools/asar-fuses-bypass/library.def b/tools/asar-fuses-bypass/library.def deleted file mode 100644 index 739d3dbd..00000000 --- a/tools/asar-fuses-bypass/library.def +++ /dev/null @@ -1,20 +0,0 @@ -LIBRARY "VERSION" -EXPORTS - -GetFileVersionInfoA -GetFileVersionInfoByHandle -GetFileVersionInfoExA -GetFileVersionInfoExW -GetFileVersionInfoSizeA -GetFileVersionInfoSizeExA -GetFileVersionInfoSizeExW -GetFileVersionInfoSizeW -GetFileVersionInfoW -VerFindFileA -VerFindFileW -VerInstallFileA -VerInstallFileW -VerLanguageNameA -VerLanguageNameW -VerQueryValueA -VerQueryValueW \ No newline at end of file From e04e313fa38ab91e338ec2a95554dd2232c87a30 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Sat, 29 Aug 2026 16:56:36 +0300 Subject: [PATCH 05/15] refactor(wpf): decouple the view model from the window and localize its output Introduce IShellView and IFileDialogs so MainWindowVm no longer holds the concrete window or reaches through MainWindow.Instance, and file pickers are injectable. Run Restore off the UI thread like Patch and gate both buttons on IsBusy. Gate the log commands on a non-empty log. Move runtime log messages into the locale dictionaries and add the 14 new keys to all 12 languages. Track the injected locale dictionary so switching language replaces it instead of appending a new one each time. Remove the unused InfoItem control, ToVisibilityInvertedConverter, mw_title and the popup placeholder title. --- WandEnhancer/App.xaml | 1 - .../Converters/BaseBooleanConverter.cs | 24 +- .../Converters/ToVisibilityConverter.cs | 6 - .../Core/Services/LocalizationManager.cs | 33 ++- WandEnhancer/Core/Services/SettingsManager.cs | 6 +- WandEnhancer/Locale/lang.de-DE.xaml | 19 +- WandEnhancer/Locale/lang.en-US.xaml | 19 +- WandEnhancer/Locale/lang.es-ES.xaml | 19 +- WandEnhancer/Locale/lang.fr-FR.xaml | 19 +- WandEnhancer/Locale/lang.it-IT.xaml | 19 +- WandEnhancer/Locale/lang.ja-JP.xaml | 19 +- WandEnhancer/Locale/lang.pl-PL.xaml | 19 +- WandEnhancer/Locale/lang.pt-BR.xaml | 19 +- WandEnhancer/Locale/lang.ru-RU.xaml | 19 +- WandEnhancer/Locale/lang.tr-TR.xaml | 19 +- WandEnhancer/Locale/lang.uk-UA.xaml | 19 +- WandEnhancer/Locale/lang.zh-CN.xaml | 19 +- .../ReactiveUICore/AsyncRelayCommand.cs | 47 ---- WandEnhancer/View/Controls/InfoItem.xaml | 20 -- WandEnhancer/View/Controls/InfoItem.xaml.cs | 42 ---- WandEnhancer/View/Controls/PopupHost.xaml | 2 +- WandEnhancer/View/MainWindow/IShellView.cs | 26 ++ WandEnhancer/View/MainWindow/MainWindow.xaml | 5 +- .../View/MainWindow/MainWindow.xaml.cs | 24 +- WandEnhancer/View/MainWindow/MainWindowVm.cs | 225 +++++++++--------- .../View/MainWindow/WindowsFileDialogs.cs | 28 +++ .../View/Popups/PatchVectorsPopup.xaml | 9 +- .../View/Popups/PatchVectorsPopup.xaml.cs | 11 +- .../View/Popups/SettingsPopup.xaml.cs | 2 +- WandEnhancer/WandEnhancer.csproj | 44 ++-- 30 files changed, 460 insertions(+), 323 deletions(-) delete mode 100644 WandEnhancer/ReactiveUICore/AsyncRelayCommand.cs delete mode 100644 WandEnhancer/View/Controls/InfoItem.xaml delete mode 100644 WandEnhancer/View/Controls/InfoItem.xaml.cs create mode 100644 WandEnhancer/View/MainWindow/IShellView.cs create mode 100644 WandEnhancer/View/MainWindow/WindowsFileDialogs.cs diff --git a/WandEnhancer/App.xaml b/WandEnhancer/App.xaml index dafdfba3..273e31e6 100644 --- a/WandEnhancer/App.xaml +++ b/WandEnhancer/App.xaml @@ -15,7 +15,6 @@ pack://application:,,,/Style/#Inter 18pt 18pt - \ No newline at end of file diff --git a/WandEnhancer/Converters/BaseBooleanConverter.cs b/WandEnhancer/Converters/BaseBooleanConverter.cs index 501878bd..69265806 100644 --- a/WandEnhancer/Converters/BaseBooleanConverter.cs +++ b/WandEnhancer/Converters/BaseBooleanConverter.cs @@ -18,29 +18,7 @@ protected BaseBooleanConverter(T trueValue, T falseValue) public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - switch (value) - { - case null: - return False; - case bool booleanValue: - return booleanValue ? True : False; - } - - if (!(value is int intValue)) - { - return True; - } - - switch (parameter) - { - case null: - return intValue == 0 ? False : True; - case int param: - return intValue > param ? True : False; - default: - //Because object not null - return True; - } + return value is bool booleanValue && booleanValue ? True : False; } public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) diff --git a/WandEnhancer/Converters/ToVisibilityConverter.cs b/WandEnhancer/Converters/ToVisibilityConverter.cs index 66c72801..282762bf 100644 --- a/WandEnhancer/Converters/ToVisibilityConverter.cs +++ b/WandEnhancer/Converters/ToVisibilityConverter.cs @@ -9,10 +9,4 @@ public ToVisibilityConverter() : { } } - internal sealed class ToVisibilityInvertedConverter : BaseBooleanConverter - { - public ToVisibilityInvertedConverter() : - base(Visibility.Collapsed, Visibility.Visible) - { } - } } \ No newline at end of file diff --git a/WandEnhancer/Core/Services/LocalizationManager.cs b/WandEnhancer/Core/Services/LocalizationManager.cs index 254f1258..c4a9b252 100644 --- a/WandEnhancer/Core/Services/LocalizationManager.cs +++ b/WandEnhancer/Core/Services/LocalizationManager.cs @@ -28,6 +28,22 @@ public static class LocalizationManager private static CultureInfo _currentLanguage; private static ResourceDictionary _englishBaseDictionary; + private static ResourceDictionary _activeLocaleDictionary; + + /// + /// Localized string for , falling back to the key itself so a + /// missing entry is visible rather than silently blank. + /// + public static string Get(string key) + { + return Application.Current?.TryFindResource(key) as string ?? key; + } + + /// Localized format string filled with . + public static string Format(string key, params object[] args) + { + return string.Format(Get(key), args); + } public static CultureInfo CurrentLanguage { @@ -104,20 +120,19 @@ private static void SetLanguage(CultureInfo culture, bool saveSettings = true) localeDict[entry.Key] = targetDict[entry.Key]; } - // Find and replace the old locale dictionary - var oldDict = Application.Current.Resources.MergedDictionaries - .FirstOrDefault(d => d.Source != null && d.Source.OriginalString.StartsWith("Locale/lang.")); - - if (oldDict != null) + // Track the dictionary we injected: it is built by merging entries, so its Source is + // null and a Source-based lookup never finds it - every switch used to append another. + var merged = Application.Current.Resources.MergedDictionaries; + if (_activeLocaleDictionary != null && merged.Contains(_activeLocaleDictionary)) { - var index = Application.Current.Resources.MergedDictionaries.IndexOf(oldDict); - Application.Current.Resources.MergedDictionaries.Remove(oldDict); - Application.Current.Resources.MergedDictionaries.Insert(index, localeDict); + merged[merged.IndexOf(_activeLocaleDictionary)] = localeDict; } else { - Application.Current.Resources.MergedDictionaries.Add(localeDict); + merged.Add(localeDict); } + + _activeLocaleDictionary = localeDict; if (saveSettings) { diff --git a/WandEnhancer/Core/Services/SettingsManager.cs b/WandEnhancer/Core/Services/SettingsManager.cs index 33a9e73d..03d70245 100644 --- a/WandEnhancer/Core/Services/SettingsManager.cs +++ b/WandEnhancer/Core/Services/SettingsManager.cs @@ -27,8 +27,7 @@ public static AppSettings LoadSettings() } catch (Exception) { - // Settings loading is non-critical - silently fall back to defaults - // This can fail due to file permissions, corrupted JSON, etc. + // Unreadable or corrupt settings must not block startup; defaults apply. } return null; } @@ -42,8 +41,7 @@ public static void SaveSettings(AppSettings settings) } catch (Exception) { - // Settings saving is non-critical - silently ignore errors - // This can fail due to file permissions or read-only directories + // A read-only install directory must not break the app; the choice is lost, not fatal. } } } diff --git a/WandEnhancer/Locale/lang.de-DE.xaml b/WandEnhancer/Locale/lang.de-DE.xaml index 6c2a7371..b975833f 100644 --- a/WandEnhancer/Locale/lang.de-DE.xaml +++ b/WandEnhancer/Locale/lang.de-DE.xaml @@ -7,7 +7,6 @@ - WandEnhancer Ordnerpfad Ordner nicht gefunden Anwenden @@ -35,7 +34,25 @@ Ausgewählte .js-Dateien werden in Wand gepackt und im Renderer geladen. Keine Skripte ausgewählt Starten + Nach Updates automatisch anwenden Was werden wir verbessern? + + WeMod-Verzeichnis unter {0} ({1}) gefunden + WeMod ist bereits gepatcht. Wenn Sie erneut patchen möchten, stellen Sie bitte zuerst das Backup wieder her. + Bereit zum Patchen. + WeMod-Verzeichnis nicht gefunden. + Vorgang nicht möglich. Bitte geben Sie zuerst das Verzeichnis an. + Der ausgewählte Ordner {0} ist kein gültiges WeMod-Verzeichnis. + Fehler beim Wiederherstellen des Backups: {0} + Fehler beim Patchen: {0} + Protokolle in die Zwischenablage kopiert. + Fehler beim Kopieren der Protokolle: {0} + Protokolle nach {0} exportiert. + Fehler beim Exportieren der Protokolle: {0} + {0} konnte nicht in einem Browser geöffnet werden. + Wählen Sie das WeMod-Verzeichnis aus + + diff --git a/WandEnhancer/Locale/lang.en-US.xaml b/WandEnhancer/Locale/lang.en-US.xaml index 9db07b47..216e2b30 100644 --- a/WandEnhancer/Locale/lang.en-US.xaml +++ b/WandEnhancer/Locale/lang.en-US.xaml @@ -7,7 +7,6 @@ - WandEnhancer Folder path Folder not found Enhance @@ -35,7 +34,25 @@ Selected .js files are packed into Wand and loaded in the renderer. No scripts selected Start + Auto-apply after updates What are we gonna enhance? + + WeMod directory found at {0} ({1}) + WeMod already patched. If you want to patch again, please restore the backup first. + Ready for patching. + WeMod directory not found. + Cant be done. Please specify the directory first. + The selected folder {0} is not a valid WeMod directory. + Failed to restore backup: {0} + Failed to patch: {0} + Logs copied to clipboard. + Failed to copy logs: {0} + Logs exported to {0}. + Failed to export logs: {0} + Could not open {0} in a browser. + Select the WeMod directory + + diff --git a/WandEnhancer/Locale/lang.es-ES.xaml b/WandEnhancer/Locale/lang.es-ES.xaml index 53907126..8a8893e4 100644 --- a/WandEnhancer/Locale/lang.es-ES.xaml +++ b/WandEnhancer/Locale/lang.es-ES.xaml @@ -7,7 +7,6 @@ - WandEnhancer Ruta de la carpeta Carpeta no encontrada Aplicar @@ -35,7 +34,25 @@ Los archivos .js seleccionados se empaquetan en Wand y se cargan en el renderer. No hay scripts seleccionados Iniciar + Aplicar automáticamente tras actualizar ¿Qué vamos a mejorar? + + Directorio de WeMod encontrado en {0} ({1}) + WeMod ya está parcheado. Si quieres parchear de nuevo, restaura la copia de seguridad primero. + Listo para parchear. + Directorio de WeMod no encontrado. + No se puede realizar. Por favor, especifica el directorio primero. + La carpeta seleccionada {0} no es un directorio de WeMod válido. + Error al restaurar la copia de seguridad: {0} + Error al parchear: {0} + Registros copiados al portapapeles. + Error al copiar los registros: {0} + Registros exportados a {0}. + Error al exportar los registros: {0} + No se pudo abrir {0} en un navegador. + Selecciona el directorio de WeMod + + diff --git a/WandEnhancer/Locale/lang.fr-FR.xaml b/WandEnhancer/Locale/lang.fr-FR.xaml index 9f6f00f6..0246c11b 100644 --- a/WandEnhancer/Locale/lang.fr-FR.xaml +++ b/WandEnhancer/Locale/lang.fr-FR.xaml @@ -7,7 +7,6 @@ - WandEnhancer Chemin du dossier Dossier non trouvé Appliquer @@ -35,7 +34,25 @@ Les fichiers .js sélectionnés sont intégrés dans Wand et chargés dans le renderer. Aucun script sélectionné Démarrer + Appliquer automatiquement après les mises à jour Qu'allons-nous modifier ? + + Répertoire WeMod trouvé à {0} ({1}) + WeMod est déjà patché. Si vous souhaitez le patcher à nouveau, veuillez d'abord restaurer la sauvegarde. + Prêt pour le patch. + Répertoire WeMod introuvable. + Impossible. Veuillez d'abord spécifier le répertoire. + Le dossier sélectionné {0} n'est pas un répertoire WeMod valide. + Échec de la restauration de la sauvegarde : {0} + Échec du patch : {0} + Journaux copiés dans le presse-papiers. + Échec de la copie des journaux : {0} + Journaux exportés vers {0}. + Échec de l'exportation des journaux : {0} + Impossible d'ouvrir {0} dans un navigateur. + Sélectionnez le répertoire WeMod + + diff --git a/WandEnhancer/Locale/lang.it-IT.xaml b/WandEnhancer/Locale/lang.it-IT.xaml index 2ca0fb40..1a4914d0 100644 --- a/WandEnhancer/Locale/lang.it-IT.xaml +++ b/WandEnhancer/Locale/lang.it-IT.xaml @@ -7,7 +7,6 @@ - WandEnhancer Percorso cartella Cartella non trovata Applica @@ -35,7 +34,25 @@ I file .js selezionati vengono inseriti in Wand e caricati nel renderer. Nessuno script selezionato Avvia + Applica automaticamente dopo gli aggiornamenti Cosa modificheremo? + + Directory di WeMod trovata in {0} ({1}) + WeMod è già stato patchato. Se vuoi patchare di nuovo, ripristina prima il backup. + Pronto per il patching. + Directory di WeMod non trovata. + Impossibile procedere. Specifica prima la directory. + La cartella selezionata {0} non è una directory valida di WeMod. + Impossibile ripristinare il backup: {0} + Impossibile eseguire il patch: {0} + Log copiati negli appunti. + Impossibile copiare i log: {0} + Log esportati in {0}. + Impossibile esportare i log: {0} + Impossibile aprire {0} in un browser. + Seleziona la directory di WeMod + + diff --git a/WandEnhancer/Locale/lang.ja-JP.xaml b/WandEnhancer/Locale/lang.ja-JP.xaml index 44e9f49e..90884980 100644 --- a/WandEnhancer/Locale/lang.ja-JP.xaml +++ b/WandEnhancer/Locale/lang.ja-JP.xaml @@ -7,7 +7,6 @@ - WandEnhancer フォルダパス フォルダが見つかりません 適用 @@ -35,7 +34,25 @@ 選択した .js ファイルは Wand に組み込まれ、レンダラーで読み込まれます。 スクリプトが選択されていません 開始 + 更新後に自動適用 何を改善しますか? + + WeModディレクトリが {0} ({1}) に見つかりました + WeModは既にパッチが適用されています。もう一度パッチを適用する場合は、まずバックアップを復元してください。 + パッチ適用の準備ができました。 + WeModディレクトリが見つかりません。 + 実行できません。先にディレクトリを指定してください。 + 選択したフォルダ {0} は有効なWeModディレクトリではありません。 + バックアップの復元に失敗しました: {0} + パッチの適用に失敗しました: {0} + ログをクリップボードにコピーしました。 + ログのコピーに失敗しました: {0} + ログを {0} にエクスポートしました。 + ログのエクスポートに失敗しました: {0} + {0} をブラウザで開くことができませんでした。 + WeModディレクトリを選択してください + + diff --git a/WandEnhancer/Locale/lang.pl-PL.xaml b/WandEnhancer/Locale/lang.pl-PL.xaml index 37b1ade5..bb77eda3 100644 --- a/WandEnhancer/Locale/lang.pl-PL.xaml +++ b/WandEnhancer/Locale/lang.pl-PL.xaml @@ -7,7 +7,6 @@ - WandEnhancer Ścieżka folderu Folder nie znaleziony Zastosuj @@ -35,7 +34,25 @@ Wybrane pliki .js są pakowane do Wand i ładowane w rendererze. Nie wybrano skryptów Rozpocznij + Zastosuj automatycznie po aktualizacji Co będziemy ulepszać? + + Katalog WeMod znaleziony w {0} ({1}) + WeMod został już zaktualizowany. Jeśli chcesz zaktualizować ponownie, najpierw przywróć kopię zapasową. + Gotowy do aktualizacji (patchowania). + Nie znaleziono katalogu WeMod. + Nie można tego zrobić. Proszę najpierw określić katalog. + Wybrany folder {0} nie jest prawidłowym katalogiem WeMod. + Nie udało się przywrócić kopii zapasowej: {0} + Nie udało się zaktualizować: {0} + Logi skopiowane do schowka. + Nie udało się skopiować logów: {0} + Logi wyeksportowane do {0}. + Nie udało się wyeksportować logów: {0} + Nie można otworzyć {0} w przeglądarce. + Wybierz katalog WeMod + + diff --git a/WandEnhancer/Locale/lang.pt-BR.xaml b/WandEnhancer/Locale/lang.pt-BR.xaml index 6f26576c..985142a5 100644 --- a/WandEnhancer/Locale/lang.pt-BR.xaml +++ b/WandEnhancer/Locale/lang.pt-BR.xaml @@ -7,7 +7,6 @@ - WandEnhancer Caminho da pasta Pasta não encontrada Aplicar @@ -35,7 +34,25 @@ Os arquivos .js selecionados são empacotados no Wand e carregados no renderer. Nenhum script selecionado Iniciar + Aplicar automaticamente após atualizações O que vamos melhorar? + + Diretório do WeMod encontrado em {0} ({1}) + O WeMod já foi modificado. Se quiser modificar novamente, restaure o backup primeiro. + Pronto para modificar. + Diretório do WeMod não encontrado. + Não é possível fazer isso. Por favor, especifique o diretório primeiro. + A pasta selecionada {0} não é um diretório válido do WeMod. + Falha ao restaurar o backup: {0} + Falha ao modificar: {0} + Logs copiados para a área de transferência. + Falha ao copiar logs: {0} + Logs exportados para {0}. + Falha ao exportar logs: {0} + Não foi possível abrir {0} no navegador. + Selecione o diretório do WeMod + + diff --git a/WandEnhancer/Locale/lang.ru-RU.xaml b/WandEnhancer/Locale/lang.ru-RU.xaml index 1c24c509..fa470b5d 100644 --- a/WandEnhancer/Locale/lang.ru-RU.xaml +++ b/WandEnhancer/Locale/lang.ru-RU.xaml @@ -7,7 +7,6 @@ - WandEnhancer Путь к папке Папка не найдена Применить @@ -35,7 +34,25 @@ Выбранные .js попадут в Wand и загрузятся в renderer. Скрипты не выбраны Начать + Авто-патч после обновлений Что будем улучшать? + + Директория WeMod найдена в {0} ({1}) + WeMod уже пропатчен. Если вы хотите пропатчить снова, сначала восстановите резервную копию. + Готово к патчингу. + Директория WeMod не найдена. + Невозможно выполнить. Пожалуйста, сначала укажите директорию. + Выбранная папка {0} не является допустимой директорией WeMod. + Не удалось восстановить резервную копию: {0} + Не удалось пропатчить: {0} + Логи скопированы в буфер обмена. + Не удалось скопировать логи: {0} + Логи экспортированы в {0}. + Не удалось экспортировать логи: {0} + Не удалось открыть {0} в браузере. + Выберите директорию WeMod + + diff --git a/WandEnhancer/Locale/lang.tr-TR.xaml b/WandEnhancer/Locale/lang.tr-TR.xaml index 30a4af6f..6ebc108c 100644 --- a/WandEnhancer/Locale/lang.tr-TR.xaml +++ b/WandEnhancer/Locale/lang.tr-TR.xaml @@ -7,7 +7,6 @@ - WandEnhancer Klasör yolu Klasör bulunamadı Uygula @@ -35,7 +34,25 @@ Seçilen .js dosyaları Wand içine paketlenir ve renderer'da yüklenir. Betik seçilmedi Başlat + Güncellemelerden sonra otomatik uygula Neyi geliştireceğiz? + + WeMod dizini {0} konumunda bulundu ({1}) + WeMod zaten yamanmış. Tekrar yamamak istiyorsanız, lütfen önce yedeği geri yükleyin. + Yama işlemi için hazır. + WeMod dizini bulunamadı. + İşlem yapılamıyor. Lütfen önce dizini belirtin. + Seçilen {0} klasörü geçerli bir WeMod dizini değil. + Yedek geri yüklenemedi: {0} + Yama yapılamadı: {0} + Günlükler panoya kopyalandı. + Günlükler kopyalanamadı: {0} + Günlükler {0} konumuna dışa aktarıldı. + Günlükler dışa aktarılamadı: {0} + {0} bir tarayıcıda açılamadı. + WeMod dizinini seçin + + diff --git a/WandEnhancer/Locale/lang.uk-UA.xaml b/WandEnhancer/Locale/lang.uk-UA.xaml index 47a77b19..6093129b 100644 --- a/WandEnhancer/Locale/lang.uk-UA.xaml +++ b/WandEnhancer/Locale/lang.uk-UA.xaml @@ -7,7 +7,6 @@ - WandEnhancer Шлях до папки Папку не знайдено Застосувати @@ -35,7 +34,25 @@ Вибрані файли .js пакуються у Wand і завантажуються в рендерері. Скрипти не вибрано Почати + Автоматично застосовувати після оновлень Що будемо покращувати? + + Директорію WeMod знайдено в {0} ({1}) + WeMod вже пропатчено. Якщо ви хочете пропатчити знову, спершу відновіть резервну копію. + Готово до патчингу. + Директорію WeMod не знайдено. + Не вдається виконати. Будь ласка, спочатку вкажіть директорію. + Вибрана папка {0} не є дійсною директорією WeMod. + Не вдалося відновити резервну копію: {0} + Не вдалося пропатчити: {0} + Логи скопійовано в буфер обміну. + Не вдалося скопіювати логи: {0} + Логи експортовано до {0}. + Не вдалося експортувати логи: {0} + Не вдалося відкрити {0} у браузері. + Виберіть директорію WeMod + + diff --git a/WandEnhancer/Locale/lang.zh-CN.xaml b/WandEnhancer/Locale/lang.zh-CN.xaml index f0624f38..c4130b11 100644 --- a/WandEnhancer/Locale/lang.zh-CN.xaml +++ b/WandEnhancer/Locale/lang.zh-CN.xaml @@ -7,7 +7,6 @@ - WandEnhancer 文件夹路径 未找到文件夹 增强 @@ -35,7 +34,25 @@ 选中的 .js 文件会打包到 Wand 并在渲染器中加载。 未选择脚本 开始 + 更新后自动应用 我们要增强什么? + + 在 {0} ({1}) 找到 WeMod 目录 + WeMod 已经修补过。如果想再次修补,请先恢复备份。 + 准备修补。 + 未找到 WeMod 目录。 + 无法执行。请先指定目录。 + 选择的文件夹 {0} 不是有效的 WeMod 目录。 + 恢复备份失败: {0} + 修补失败: {0} + 日志已复制到剪贴板。 + 复制日志失败: {0} + 日志已导出至 {0}。 + 导出日志失败: {0} + 无法在浏览器中打开 {0}。 + 选择 WeMod 目录 + + diff --git a/WandEnhancer/ReactiveUICore/AsyncRelayCommand.cs b/WandEnhancer/ReactiveUICore/AsyncRelayCommand.cs deleted file mode 100644 index ebe47878..00000000 --- a/WandEnhancer/ReactiveUICore/AsyncRelayCommand.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Input; - -namespace WandEnhancer.ReactiveUICore -{ - public sealed class AsyncRelayCommand : ICommand - { - private readonly Func _execute; - private readonly Func _canExecute; - - private long _isExecuting; - - public AsyncRelayCommand(Func execute, Func canExecute = null) - { - this._execute = execute; - this._canExecute = canExecute ?? (o => true); - } - - public event EventHandler CanExecuteChanged - { - add => CommandManager.RequerySuggested += value; - remove => CommandManager.RequerySuggested -= value; - } - - private static void RaiseCanExecuteChanged() => CommandManager.InvalidateRequerySuggested(); - - public bool CanExecute(object parameter) => Interlocked.Read(ref _isExecuting) == 0 && _canExecute(parameter); - - public async void Execute(object parameter) - { - Interlocked.Exchange(ref _isExecuting, 1); - RaiseCanExecuteChanged(); - - try - { - await _execute(parameter); - } - finally - { - Interlocked.Exchange(ref _isExecuting, 0); - RaiseCanExecuteChanged(); - } - } - } -} \ No newline at end of file diff --git a/WandEnhancer/View/Controls/InfoItem.xaml b/WandEnhancer/View/Controls/InfoItem.xaml deleted file mode 100644 index f67623cf..00000000 --- a/WandEnhancer/View/Controls/InfoItem.xaml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - diff --git a/WandEnhancer/View/Controls/InfoItem.xaml.cs b/WandEnhancer/View/Controls/InfoItem.xaml.cs deleted file mode 100644 index 4fba9cd7..00000000 --- a/WandEnhancer/View/Controls/InfoItem.xaml.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; - -namespace WandEnhancer.View.Controls -{ - public partial class InfoItem : UserControl - { - public static readonly DependencyProperty IconDataProperty = - DependencyProperty.Register(nameof(IconData), typeof(Geometry), typeof(InfoItem)); - - public static readonly DependencyProperty IconColorProperty = - DependencyProperty.Register(nameof(IconColor), typeof(Brush), typeof(InfoItem)); - - public static readonly DependencyProperty TextProperty = - DependencyProperty.Register(nameof(Text), typeof(string), typeof(InfoItem)); - - public Geometry IconData - { - get => (Geometry)GetValue(IconDataProperty); - set => SetValue(IconDataProperty, value); - } - - public Brush IconColor - { - get => (Brush)GetValue(IconColorProperty); - set => SetValue(IconColorProperty, value); - } - - public string Text - { - get => (string)GetValue(TextProperty); - set => SetValue(TextProperty, value); - } - - public InfoItem() - { - InitializeComponent(); - this.DataContext = this; - } - } -} \ No newline at end of file diff --git a/WandEnhancer/View/Controls/PopupHost.xaml b/WandEnhancer/View/Controls/PopupHost.xaml index b6f3723e..f63ede7c 100644 --- a/WandEnhancer/View/Controls/PopupHost.xaml +++ b/WandEnhancer/View/Controls/PopupHost.xaml @@ -38,7 +38,7 @@ - diff --git a/WandEnhancer/View/MainWindow/IShellView.cs b/WandEnhancer/View/MainWindow/IShellView.cs new file mode 100644 index 00000000..4dbb7b02 --- /dev/null +++ b/WandEnhancer/View/MainWindow/IShellView.cs @@ -0,0 +1,26 @@ +using System.Windows; + +namespace WandEnhancer.View.MainWindow +{ + /// + /// What the view model needs from the shell window. Exists so the view model does not + /// hold the concrete window or reach through a static Instance, which made every command + /// untestable and crashed whenever the singleton was not set yet. + /// + public interface IShellView + { + void OpenPopup(FrameworkElement content, string title); + void ClosePopup(); + void ScrollLogIntoView(LogEntry entry); + } + + /// Modal file/folder pickers, kept behind a seam so commands stay headless-testable. + public interface IFileDialogs + { + /// Chosen folder, or null when cancelled. + string PickFolder(string description, string initialPath); + + /// Chosen file path, or null when cancelled. + string PickSaveFile(string filter, string suggestedFileName); + } +} diff --git a/WandEnhancer/View/MainWindow/MainWindow.xaml b/WandEnhancer/View/MainWindow/MainWindow.xaml index 5bc0fa9b..e8b8c59c 100644 --- a/WandEnhancer/View/MainWindow/MainWindow.xaml +++ b/WandEnhancer/View/MainWindow/MainWindow.xaml @@ -183,9 +183,10 @@ Content="{DynamicResource mw_patch}"/> +
diff --git a/web-panel/src/app/ui/TopBar.tsx b/web-panel/src/app/ui/TopBar.tsx index 105fbbbf..2a429d08 100644 --- a/web-panel/src/app/ui/TopBar.tsx +++ b/web-panel/src/app/ui/TopBar.tsx @@ -2,7 +2,7 @@ import { msg } from '@lingui/core/macro'; import { Trans } from '@lingui/react/macro'; import { useLingui } from '@lingui/react'; -import { Icon } from '@/shared/ui/Icon'; +import { IconButton } from '@/shared/ui/IconButton'; import type { LibraryGame } from '@/library/model/games'; import type { TrainerSummary } from '../../../protocol/messages'; @@ -22,9 +22,7 @@ export const TopBar = ({ status, currentGame, runningTrainer, onOpenSettings }: return (
- +
WAND · REMOTE DECK
diff --git a/web-panel/src/app/use-remote-panel.ts b/web-panel/src/app/use-remote-panel.ts index f1df4645..0dce91d1 100644 --- a/web-panel/src/app/use-remote-panel.ts +++ b/web-panel/src/app/use-remote-panel.ts @@ -48,31 +48,32 @@ export function useRemotePanel() { onError: session.reportError, }); + const { changeCheat, launchGame } = session; + const { trainerMeta, values } = session.state; + const panic = useCallback(() => { - const trainerMeta = session.state.trainerMeta; if (!trainerMeta) return; for (const cheat of trainerMeta.schema.cheats) { - if (cheat.type === ECheatType.Toggle && Boolean(session.state.values[cheat.target])) { - session.changeCheat(cheat, false); + if (cheat.type === ECheatType.Toggle && Boolean(values[cheat.target])) { + changeCheat(cheat, false); } } - }, [session]); + }, [trainerMeta, values, changeCheat]); const applyPreset = useCallback((preset: RemotePreset) => { - const trainerMeta = session.state.trainerMeta; if (!trainerMeta) return; for (const cheat of trainerMeta.schema.cheats) { if (cheat.target in preset.values) { - session.changeCheat(cheat, preset.values[cheat.target]); + changeCheat(cheat, preset.values[cheat.target]); } } - }, [session]); + }, [trainerMeta, changeCheat]); const playGame = useCallback((game: LibraryGame) => { - if (session.launchGame(game.app)) { + if (launchGame(game.app)) { setRightOpen(false); } - }, [session]); + }, [launchGame]); const totalVisibleCheats = filteredGroups.reduce( (count, group) => count + group.cheats.length, @@ -87,7 +88,6 @@ export function useRemotePanel() { values: session.state.values, pendingTargets: session.pendingTargets, connected: session.connected, - socketReady: session.socketReady, connect: session.connect, disconnect: session.disconnect, setWsUrl: session.setWsUrl, diff --git a/web-panel/src/library/ui/LibraryDrawer.tsx b/web-panel/src/library/ui/LibraryDrawer.tsx index c6cc2d1a..e2828757 100644 --- a/web-panel/src/library/ui/LibraryDrawer.tsx +++ b/web-panel/src/library/ui/LibraryDrawer.tsx @@ -4,6 +4,7 @@ import { Plural, Trans } from '@lingui/react/macro'; import { useLingui } from '@lingui/react'; import { Icon, type IconName } from '@/shared/ui/Icon'; +import { IconButton } from '@/shared/ui/IconButton'; import { cn } from '@/shared/lib/ui'; import { SearchInput } from '@/shared/ui/SearchInput'; @@ -38,9 +39,7 @@ const LibraryDrawerBase = ({ games, query, canLaunch, onClose, onPin, onPlay, on

- +
@@ -121,45 +120,17 @@ const GameRow = ({ game, canLaunch, query, onPin, onPlay, onStop }: GameRowProps
- + {game.running ? ( - + ) : ( - + )}
); }; -type IconButtonProps = { - icon: IconName; - label: string; - active?: boolean; - danger?: boolean; - disabled?: boolean; - play?: boolean; - onClick: () => void; -}; - -const IconButton = ({ icon, label, active = false, danger = false, disabled = false, play = false, onClick }: IconButtonProps) => { - return ( - - ); -}; function highlightTitle(title: string, query: string): ReactNode { const normalized = query.trim().toLowerCase(); diff --git a/web-panel/src/remote-session/use-remote-session.ts b/web-panel/src/remote-session/use-remote-session.ts index f06be947..8656652c 100644 --- a/web-panel/src/remote-session/use-remote-session.ts +++ b/web-panel/src/remote-session/use-remote-session.ts @@ -12,13 +12,17 @@ import { import { protocolAction } from './remote-session.protocol'; import { selectIsConnected, selectPendingTargets } from './selectors'; -const RECONNECT_DELAY_MS = 2000; +const RECONNECT_BASE_DELAY_MS = 2000; +const RECONNECT_MAX_DELAY_MS = 30000; export function useRemoteSession() { const [state, dispatch] = useReducer(remoteSessionReducer, undefined, createInitialRemoteSessionState); const stateRef = useRef(state); const clientRef = useRef(null); const reconnectTimeoutRef = useRef(null); + const reconnectAttemptRef = useRef(0); + // Set when the user disconnects on purpose, so refocus does not silently reconnect. + const userDisconnectedRef = useRef(false); const connectRef = useRef<() => void>(() => {}); useEffect(() => { stateRef.current = state; @@ -33,19 +37,26 @@ export function useRemoteSession() { const scheduleReconnect = useCallback(() => { clearReconnect(); - if (document.visibilityState !== 'visible') { + if (document.visibilityState !== 'visible' || userDisconnectedRef.current) { return; } + + // Back off: the bridge is usually down because Wand is closed, and a phone + // retrying every 2s until the tab is hidden drains the battery for nothing. + const delay = Math.min(RECONNECT_BASE_DELAY_MS * 2 ** reconnectAttemptRef.current, RECONNECT_MAX_DELAY_MS); + reconnectAttemptRef.current += 1; + reconnectTimeoutRef.current = window.setTimeout(() => { if (document.visibilityState === 'visible' && stateRef.current.wsUrl.trim()) { connectRef.current(); } - }, RECONNECT_DELAY_MS); + }, delay); }, [clearReconnect]); const connect = useCallback(() => { clientRef.current?.disconnect(); clearReconnect(); + userDisconnectedRef.current = false; const wsUrl = stateRef.current.wsUrl.trim(); if (!wsUrl) { @@ -58,7 +69,9 @@ export function useRemoteSession() { type: 'connecting', reconnecting: stateRef.current.connectionStatus === EConnectionStatus.Reconnecting, }), - onTransportOpen: () => undefined, + onTransportOpen: () => { + reconnectAttemptRef.current = 0; + }, onMessage: (message) => { const action = protocolAction(message); if (!action) return; @@ -76,6 +89,8 @@ export function useRemoteSession() { }, [clearReconnect, scheduleReconnect]); const disconnect = useCallback(() => { + userDisconnectedRef.current = true; + reconnectAttemptRef.current = 0; clearReconnect(); clientRef.current?.disconnect(); clientRef.current = null; @@ -132,7 +147,7 @@ export function useRemoteSession() { } const gameId = current.gameStatus?.session.gameId ?? current.gameStatus?.trainer.gameId ?? undefined; const titleId = current.gameStatus?.session.titleId ?? current.gameStatus?.trainer.titleId ?? undefined; - if (!clientRef.current?.stopPlaying(gameId ?? undefined, titleId ?? undefined)) { + if (!clientRef.current?.stopPlaying(gameId, titleId)) { dispatch({ type: 'error', message: 'Failed to send the stop command to the bridge.' }); } }, []); @@ -143,7 +158,10 @@ export function useRemoteSession() { useEffect(() => { const onVisibilityChange = () => { - if (document.visibilityState === 'visible' && !clientRef.current?.isOpen()) { + if (document.visibilityState !== 'visible' || userDisconnectedRef.current) { + return; + } + if (!clientRef.current?.isOpen()) { connectRef.current(); } }; @@ -169,7 +187,6 @@ export function useRemoteSession() { state, connected, pendingTargets, - socketReady: connected, connect, disconnect, setWsUrl, diff --git a/web-panel/src/shared/storage.ts b/web-panel/src/shared/storage.ts index 124b7d95..d9a1a2fb 100644 --- a/web-panel/src/shared/storage.ts +++ b/web-panel/src/shared/storage.ts @@ -19,6 +19,33 @@ export function getTrainerStorageId(trainer: TrainerSummary | null | undefined): return id || null; } +export function loadString(key: string | null): string | null { + const store = getStore(); + if (!key || !store) { + return null; + } + + try { + return store.getItem(key); + } catch { + return null; + } +} + +export function saveString(key: string | null, value: string): boolean { + const store = getStore(); + if (!key || !store) { + return false; + } + + try { + store.setItem(key, value); + return true; + } catch { + return false; + } +} + export function loadJson(key: string | null, revive: Reviver, fallback: T): T { const store = getStore(); if (!key || !store) { diff --git a/web-panel/src/shared/ui/Drawer.tsx b/web-panel/src/shared/ui/Drawer.tsx index 105e36df..51995d71 100644 --- a/web-panel/src/shared/ui/Drawer.tsx +++ b/web-panel/src/shared/ui/Drawer.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { useEffect, useRef, type ReactNode } from 'react'; import { msg } from '@lingui/core/macro'; import { useLingui } from '@lingui/react'; @@ -17,29 +17,97 @@ const DRAWER_CLOSED_CLASSES = { const DRAWER_OVERLAY_CLASS = 'remote-drawer-overlay absolute inset-0 z-30 transition-opacity duration-200 ease-out motion-reduce:transition-none'; const DRAWER_PANEL_CLASS = 'remote-drawer-panel absolute bottom-0 top-0 z-40 flex w-[88%] max-w-90 flex-col border-white/10 transition-transform duration-300 ease-out motion-reduce:transition-none'; +const FOCUSABLE_SELECTOR = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])'; + type DrawerProps = { open: boolean; side: 'left' | 'right'; + /** Accessible name for the dialog; an icon-only drawer has no other one. */ + label: string; children: ReactNode; onClose: () => void; }; -export const Drawer = ({ open, side, children, onClose }: DrawerProps) => { +export const Drawer = ({ open, side, label, children, onClose }: DrawerProps) => { const { _ } = useLingui(); + const panelRef = useRef(null); + const restoreFocusRef = useRef(null); const sideClassName = DRAWER_SIDE_CLASSES[side]; const closedClassName = DRAWER_CLOSED_CLASSES[side]; + useEffect(() => { + if (!open) { + return; + } + + restoreFocusRef.current = document.activeElement as HTMLElement | null; + focusFirst(panelRef.current); + + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + onClose(); + return; + } + if (event.key === 'Tab') { + trapTab(event, panelRef.current); + } + }; + + document.addEventListener('keydown', handleKeyDown); + return () => { + document.removeEventListener('keydown', handleKeyDown); + restoreFocusRef.current?.focus?.(); + }; + }, [open, onClose]); + return ( <> + ); +}; diff --git a/web-panel/src/shared/ui/SearchInput.tsx b/web-panel/src/shared/ui/SearchInput.tsx index 0ecda01a..1690d190 100644 --- a/web-panel/src/shared/ui/SearchInput.tsx +++ b/web-panel/src/shared/ui/SearchInput.tsx @@ -24,6 +24,7 @@ export const SearchInput = ({ value, placeholder, className, onChange }: SearchI { - const options = (cheat.args.options ?? []).map(resolveOption); + const options = useMemo(() => (cheat.args.options ?? []).map(resolveOption), [cheat.args.options]); if (options.length === 0) { return ; } - const currentIndex = options.findIndex((option) => isSameOption(option.value, value)); + const matchedIndex = options.findIndex((option) => isSameOption(option.value, value)); + // An unrecognised value must not strand the user: treat it as "before the first + // option" so stepping forward still walks the list. + const currentIndex = matchedIndex >= 0 ? matchedIndex : -1; const previous = currentIndex > 0 ? options[currentIndex - 1] : null; - const next = currentIndex >= 0 && currentIndex < options.length - 1 ? options[currentIndex + 1] : null; + const next = currentIndex < options.length - 1 ? options[currentIndex + 1] : null; const currentLabel = options[currentIndex]?.label ?? String(value ?? '--'); return ( -
- previous && onChange(previous.value)} /> +
+ previous && onChange(previous.value)} /> {currentLabel}{cheat.args.postfix ?? ''} - next && onChange(next.value)} /> + next && onChange(next.value)} />
); }; - -function isSameOption(left: unknown, right: unknown): boolean { - return String(left) === String(right); -} diff --git a/web-panel/src/trainer/controls/NumberControl.tsx b/web-panel/src/trainer/controls/NumberControl.tsx index 6a5df5aa..a7672803 100644 --- a/web-panel/src/trainer/controls/NumberControl.tsx +++ b/web-panel/src/trainer/controls/NumberControl.tsx @@ -1,30 +1,48 @@ -import { type FormEvent } from 'react'; +import { useState, type FormEvent } from 'react'; import { cn } from '@/shared/lib/ui'; import { formatInputNumber, numericValue, stripNumberGrouping } from './format-number'; -import { StepButton, type ControlInternalProps } from './shared'; +import { snapToStep } from './step'; +import { STEPPER_SHELL_CLASS, StepButton, type ControlInternalProps } from './shared'; const NUMBER_STEP_GRID = 'grid-cols-[48px_minmax(0,1fr)_48px]'; export const NumberControl = ({ cheat, value, disabled, onChange }: ControlInternalProps) => { const step = cheat.args.step ?? 1; const currentValue = numericValue(value, 0); - const handleInput = (event: FormEvent) => onChange(stripNumberGrouping(event.currentTarget.value)); - const decrement = () => onChange(Math.max(cheat.args.min ?? Number.NEGATIVE_INFINITY, currentValue - step)); - const increment = () => onChange(Math.min(cheat.args.max ?? Number.POSITIVE_INFINITY, currentValue + step)); + // While focused the raw text is authoritative, otherwise formatting would eat the + // decimal point in "0." and re-group digits under the caret as the user types. + const [draft, setDraft] = useState(null); + + const handleInput = (event: FormEvent) => { + const raw = event.currentTarget.value; + setDraft(raw); + onChange(stripNumberGrouping(raw)); + }; + + const commit = (next: number) => { + setDraft(null); + onChange(next); + }; + + const decrement = () => commit(snapToStep(Math.max(cheat.args.min ?? Number.NEGATIVE_INFINITY, currentValue - step), step)); + const increment = () => commit(snapToStep(Math.min(cheat.args.max ?? Number.POSITIVE_INFINITY, currentValue + step), step)); return ( -
- +
+ setDraft(null)} /> - +
); }; diff --git a/web-panel/src/trainer/controls/ScalarControl.tsx b/web-panel/src/trainer/controls/ScalarControl.tsx index 60e6dc84..d474b5b3 100644 --- a/web-panel/src/trainer/controls/ScalarControl.tsx +++ b/web-panel/src/trainer/controls/ScalarControl.tsx @@ -1,12 +1,12 @@ -import { type FormEvent } from 'react'; +import { useMemo, type FormEvent } from 'react'; import type { CheatSchema } from '../../../protocol/messages'; import { resolveOption } from '../model/values'; -import { formatNumber, numericValue } from './format-number'; -import { SliderTrack, type ControlInternalProps } from './shared'; +import { numericValue } from './format-number'; +import { SliderReadout, type ControlInternalProps } from './shared'; export const ScalarControl = ({ cheat, value, disabled, onChange }: ControlInternalProps) => { - const numericOptions = getNumericOptions(cheat.args.options ?? []); + const numericOptions = useMemo(() => getNumericOptions(cheat.args.options ?? []), [cheat.args.options]); const min = cheat.args.min ?? numericOptions[0] ?? 0; const max = cheat.args.max ?? numericOptions[numericOptions.length - 1] ?? 100; const step = cheat.args.step ?? inferStep(numericOptions) ?? 1; @@ -15,10 +15,7 @@ export const ScalarControl = ({ cheat, value, disabled, onChange }: ControlInter return (
-
- {formatNumber(currentValue, step)}{cheat.args.postfix ?? ''} -
- +
{min}{cheat.args.postfix ?? ''} {max}{cheat.args.postfix ?? ''} diff --git a/web-panel/src/trainer/controls/SelectionControl.tsx b/web-panel/src/trainer/controls/SelectionControl.tsx index 6b849cc4..d06e498a 100644 --- a/web-panel/src/trainer/controls/SelectionControl.tsx +++ b/web-panel/src/trainer/controls/SelectionControl.tsx @@ -1,21 +1,48 @@ -import { useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import { Trans } from '@lingui/react/macro'; import { Icon } from '@/shared/ui/Icon'; import { cn } from '@/shared/lib/ui'; import type { CheatOption } from '../../../protocol/messages'; -import { resolveOption } from '../model/values'; -import type { ControlInternalProps } from './shared'; +import { isSameOption, resolveOption } from '../model/values'; +import { type ControlInternalProps } from './shared'; export const SelectionControl = ({ cheat, value, disabled, onChange }: ControlInternalProps) => { - const options = (cheat.args.options ?? []).map(resolveOption); + const options = useMemo(() => (cheat.args.options ?? []).map(resolveOption), [cheat.args.options]); const [open, setOpen] = useState(false); + const rootRef = useRef(null); + + // Without these the list can only be dismissed by picking something. + useEffect(() => { + if (!open) { + return; + } + + const handlePointerDown = (event: PointerEvent) => { + if (!rootRef.current?.contains(event.target as Node)) { + setOpen(false); + } + }; + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + setOpen(false); + } + }; + + document.addEventListener('pointerdown', handlePointerDown); + document.addEventListener('keydown', handleKeyDown); + return () => { + document.removeEventListener('pointerdown', handlePointerDown); + document.removeEventListener('keydown', handleKeyDown); + }; + }, [open]); + if (options.length === 0) { return No options; } - const selectedOption = findOption(options, String(value ?? options[0].value)) ?? options[0]; + const selectedOption = options.find((option) => isSameOption(option.value, value ?? options[0].value)) ?? options[0]; const handleToggle = () => { if (disabled) { return; @@ -29,10 +56,11 @@ export const SelectionControl = ({ cheat, value, disabled, onChange }: ControlIn }; return ( -
+
{open ? ( -
+
{options.map((option) => { const active = isSameOption(selectedOption.value, option.value); return (
void; }; -export const StepButton = ({ icon, border, disabled, onClick }: StepButtonProps) => { +export const StepButton = ({ icon, border, label, disabled, onClick }: StepButtonProps) => { return ( -
- {group.cheats.map((cheat, index) => ( - - ))} +
+
+ {group.cheats.map((cheat, index) => ( + + ))} +
); @@ -98,6 +106,10 @@ export const CategorySection = memo(CategorySectionBase, (prev, next) => { if (prev.group !== next.group) return false; if (prev.disabled !== next.disabled) return false; if (prev.forceOpen !== next.forceOpen) return false; + // Skipping these would keep stale handlers alive whenever the parent stops + // memoising them - a correctness guarantee should not rest on that assumption. + if (prev.onCheatChange !== next.onCheatChange) return false; + if (prev.onTogglePin !== next.onTogglePin) return false; for (const cheat of next.group.cheats) { if (prev.values[cheat.target] !== next.values[cheat.target]) return false; if (prev.pendingTargets[cheat.target] !== next.pendingTargets[cheat.target]) return false; @@ -106,10 +118,13 @@ export const CategorySection = memo(CategorySectionBase, (prev, next) => { return true; }); -function getEnabledToggleCount(cheats: CheatSchema[], values: Record): number { - return cheats.filter((cheat) => cheat.type === ECheatType.Toggle && Boolean(values[cheat.target])).length; -} - -function getToggleCount(cheats: CheatSchema[]): number { - return cheats.filter((cheat) => cheat.type === ECheatType.Toggle).length; +function countToggles(cheats: CheatSchema[], values: Record): { toggleCount: number; enabledCount: number } { + let toggleCount = 0; + let enabledCount = 0; + for (const cheat of cheats) { + if (cheat.type !== ECheatType.Toggle) continue; + toggleCount += 1; + if (values[cheat.target]) enabledCount += 1; + } + return { toggleCount, enabledCount }; } diff --git a/web-panel/src/trainer/ui/CheatTile.tsx b/web-panel/src/trainer/ui/CheatTile.tsx index 41864005..fa7d86be 100644 --- a/web-panel/src/trainer/ui/CheatTile.tsx +++ b/web-panel/src/trainer/ui/CheatTile.tsx @@ -1,6 +1,9 @@ import { memo, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'; +import { msg } from '@lingui/core/macro'; +import { useLingui } from '@lingui/react'; import { Icon } from '@/shared/ui/Icon'; +import { IconButton } from '@/shared/ui/IconButton'; import { cn } from '@/shared/lib/ui'; import type { CheatSchema } from '../../../protocol/messages'; @@ -21,23 +24,38 @@ type CheatTileProps = { const SWIPE_REVEAL = 80; const SWIPE_TRIGGER = 56; const SWIPE_DEAD_ZONE = 8; -const SWIPE_ANIMATION_MS = 220; +const SWIPE_ANIMATION_MS = 200; const CheatTileBase = ({ cheat, value, pending, disabled, pinned, first, onChange, onTogglePin }: CheatTileProps) => { + const { _ } = useLingui(); const [offset, setOffset] = useState(0); const [animating, setAnimating] = useState(false); const [armed, setArmed] = useState(false); const dragRef = useRef<{ id: number; startX: number; startY: number; locked: boolean | null } | null>(null); + const settleTimerRef = useRef(null); useEffect(() => { setOffset(0); setArmed(false); }, [pinned]); + // Cleared on unmount: the tile unmounts on category change while the timer is pending. + useEffect(() => () => { + if (settleTimerRef.current !== null) { + window.clearTimeout(settleTimerRef.current); + } + }, []); + const settle = (target: number) => { setAnimating(true); setOffset(target); - window.setTimeout(() => setAnimating(false), SWIPE_ANIMATION_MS); + if (settleTimerRef.current !== null) { + window.clearTimeout(settleTimerRef.current); + } + settleTimerRef.current = window.setTimeout(() => { + settleTimerRef.current = null; + setAnimating(false); + }, SWIPE_ANIMATION_MS); }; const handlePointerDown = (event: ReactPointerEvent) => { @@ -97,8 +115,8 @@ const CheatTileBase = ({ cheat, value, pending, disabled, pinned, first, onChang
{showReveal ? : null}

{cheat.name}

{pending ? : null} + {/* The swipe gesture is pointer-only; this is the keyboard and screen-reader path. */} +
{cheat.description ?

{cheat.description}

: null}
diff --git a/web-panel/src/trainer/ui/QuickActions.tsx b/web-panel/src/trainer/ui/QuickActions.tsx index 96b6efa3..0c264ed6 100644 --- a/web-panel/src/trainer/ui/QuickActions.tsx +++ b/web-panel/src/trainer/ui/QuickActions.tsx @@ -4,6 +4,7 @@ import { msg } from '@lingui/core/macro'; import { Trans } from '@lingui/react/macro'; import { useLingui } from '@lingui/react'; +import { IconButton } from '@/shared/ui/IconButton'; import { Icon } from '@/shared/ui/Icon'; import { cn } from '@/shared/lib/ui'; @@ -137,9 +138,7 @@ const PresetModal = ({ draftName, onClose, onDraftNameChange, onSubmit }: Preset Add Preset
- +