Compare commits

..
Author SHA1 Message Date
kitbyte 6c0e4dc36a feat(launcher): show the window when Wand fails to start
Launch mode pushes its log into the UI and opens it on failure instead of
leaving only launcher.log. Exit codes of Wand child processes are read
again by keeping their handles, which the job object does not carry.
2026-08-30 20:48:51 +03:00
kitbyte 318a12b133 fix(launcher): clear the fuse in every process Wand spawns
Wand now runs inside a job object and each new process is patched from
the job completion port. Replaces the startup-only debugger, which
detached before the in-game overlay renderer was created and left it
exiting with -36861.
2026-08-30 16:42:56 +03:00
kitbyte 56e1fc2137 refactor(web-panel): migrate to biome, drop baseUrl, normalize eol 2026-08-29 23:39:21 +03:00
kitbyte a236456960 feat(patch): report what is blocking a denied copy
An access-denied copy now names the destination's attributes, owner and
the account running the patcher.
2026-08-29 22:02:07 +03:00
kitbyte df9aedcadc fix(patch): stop the deployed launcher inheriting a read-only flag 2026-08-29 21:52:50 +03:00
kitbyte 2cac40558d feat(launcher): write startup diagnostics to launcher.log
Records spawned processes and their fuse state, exit and unhandled
exception codes, detach timing and reason, and the exit code after detach.
2026-08-29 21:49:29 +03:00
kitbyte ff0c8615f8 docs(changelog): note the failed-patch rollback 2026-08-29 18:45:26 +03:00
kitbyte 9bcb4bb991 fix(patch): roll back the installation when patching fails
Patching mutated the install in place with no recovery, so a failure left a
partly patched Wand behind: rewritten bundles in app.asar.unpacked, or a patched
app.asar with no launcher deployed, which cannot clear the fuse and fails with
-36861. Restore both backups on any failure and rethrow the original error.

Pack the archive into a sibling file and swap it in at the end. Writing straight
into app.asar truncated it when the stream opened, so a failed pack destroyed
the archive it was replacing.
2026-08-29 18:44:24 +03:00
kitbyte 8b83750bf2 chore(release): prepare 2.0.0.0 and support pre-release tags
Bump AssemblyInfo to 2.0.0.0 and add the 2.0.0.0 changelog section.
Resolve a tag suffix (2.0.0.0-rc.1) to its base version so release metadata
validation and changelog extraction accept pre-release tags.
Publish suffixed tags as a pre-release and keep them off "Latest release".
2026-08-29 17:34:16 +03:00
kitbyte 43e898c66c feat(panel): add IconButton primitive and fix input, reconnect and a11y gaps
Extract IconButton into shared/ui and reuse it across the drawers, top bar and
cheat tiles instead of repeating the glass button markup.

Render the app even when the locale catalog fails to load; a rejected import
previously left a blank page.
Keep a draft string while a number input is focused so typing a decimal point
survives formatting, and snap stepper results to the step precision.
Let IncrementalControl step forward from an unrecognised value.
Back off reconnect attempts and stop reconnecting after an explicit disconnect.
Route locale storage through shared/storage.

Give the drawers dialog semantics, Escape and focus containment; add listbox
semantics plus click-away and Escape to the selection dropdown; add
aria-expanded to category headers and accessible names to the controls.
Add a pin button to cheat tiles, which were previously pin-by-swipe only.
Compare handler props in the CategorySection memo comparator.
Clear the swipe settle timer on unmount.
2026-08-29 16:57:00 +03:00
kitbyte f2e88e9247 fix(renderer-scripts): await the bridge bind and retry it on poll
ipcRenderer.invoke rejects asynchronously, so marking the bridge bound before
awaiting left set-value dead for the session while the log reported success.

Compare installed-app snapshots structurally instead of by an explicit field
list, which had already drifted from the bridge copy and hid location changes.
2026-08-29 16:56:51 +03:00
kitbyte 5d1aa69a97 refactor(bridge): type the bridge and harden the websocket and file server
Type every module under bridge/src against a shared types.ts vocabulary and the
protocol payload types; narrow Wand IPC input as unknown instead of any.
Keep the Electron port types out of the CommonJS runtime files, where an export
statement makes esbuild treat the module as ESM and drop module.exports.

Reject unmasked client frames, enforce control-frame length and fragmentation
limits, and echo the peer close code.
Resolve static requests inside the panel root and serve the whole root, not
only assets/.
Ignore value-changed events that name a different trainer.
Validate envelopes through the shared protocol validator.
Bind the renderer destroyed listener once per sender.
Handle https response errors while fetching trainer strings.
Compare installed-app snapshots structurally so no field is missed.
2026-08-29 16:56:45 +03:00
kitbyte e04e313fa3 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.
2026-08-29 16:56:36 +03:00
kitbyte 572b61ac25 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.
2026-08-29 16:56:25 +03:00
kitbyte 6716da5c80 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.
2026-08-29 16:56:09 +03:00
kitbyte 20956c3228 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.
2026-08-29 16:55:55 +03:00
kitbyte f798714f8d 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.
2026-08-29 16:55:07 +03:00
kitbyte 643c8f8b62 fix: bump version to 1.0.9.4, update changelog 2026-07-22 00:03:38 +03:00
k1tbyte e7c7beb621 Merge pull request #143 from divya0795/fix/asar-extraction-safety-and-process-kill
fix(asar): path traversal (zip-slip) on extract + Pickle buffer overrun
2026-07-21 23:22:42 +03:00
k1tbyte 710e717677 Merge pull request #145 from divya0795/fix/trykillprocess-retry-loop
fix: correct TryKillProcess retry loop condition
2026-07-21 23:22:04 +03:00
dchukkapalli-devandClaude Opus 4.8 7e8cadff24 fix: correct TryKillProcess retry loop condition
The loop "for (int i = 0; processes.Length > i || i < 5; i++)" compared the
process count to the loop index and, because of the "|| i < 5", always ran
at least 5 iterations of Thread.Sleep(250) -- stalling ~1.25s before every
patch/restore even when WeMod was not running.

Use "processes.Length > 0 && i < 5" so it retries only while a target
process is still alive, capped at 5 attempts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 20:21:07 +00:00
dchukkapalli-devandClaude Opus 4.8 7d28eb7d52 fix(asar): correct Pickle payload buffer allocation
Pickle.Resize allocated the backing array as _header.Length + newCapacity
but advertised _capacityAfterHeader = newCapacity. On the first growth
_header is still empty, so the array ended up _headerSize (4) bytes short of
the header + capacity it claimed. A write that fills the payload then
overran the buffer, throwing an ArgumentException when the serialised asar
header was 4089-4092 bytes.

Allocate _headerSize + newCapacity instead, matching Chromium's
realloc(header_size_ + new_capacity).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 19:59:06 +00:00
dchukkapalli-devandClaude Opus 4.8 413c38dbcb fix(asar): prevent path traversal (zip-slip) during extraction
AsarExtractor's path-traversal guard called Extensions.GetRelativePath,
whose fast path strips the destination prefix literally without resolving
".." segments. A crafted archive entry such as "a/../../evil" produced a
relative path that did not start with "..", so the guard passed and the
file was written outside the extraction directory once the OS resolved the
"..". The out-of-package symlink guard shared the same weakness.

Add Extensions.IsPathInside, which normalises both paths with
Path.GetFullPath before the containment check, and use it for both the
file/directory and symlink guards.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 19:59:06 +00:00
kitbyte 3b776c52fc fix: bump version to 1.0.9.3 and update changelog with recent fixes 2026-07-04 11:36:51 +03:00
k1tbyte 9c88caf49b Update CHANGELOG for version 1.0.9.2
Updated changelog to reflect changes in version 1.0.9.2, including removal of downloadable .exe files and the built-in updater.
2026-06-28 20:14:43 +03:00
209 changed files with 11973 additions and 9042 deletions
+41 -1
View File
@@ -1,4 +1,44 @@
# Auto-detect text files and normalize line endings to LF
* text=auto eol=lf
# Web panel & source files
*.ts text eol=lf
*.tsx text eol=lf
*.js text eol=lf
*.mjs text eol=lf
*.cjs text eol=lf
*.json text eol=lf
*.css text eol=lf
*.html text eol=lf
*.md text eol=lf
*.svg text eol=lf
*.po text eol=lf
# Windows scripts / C# solutions
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=lf
*.cs text eol=crlf
*.sln text eol=crlf
*.csproj text eol=crlf
# Binary files
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.webp binary
*.woff binary
*.woff2 binary
*.ttf binary
*.eot binary
*.dll binary
*.exe binary
*.zip binary
# GitHub Linguist
# The web panel is the bundled frontend shipped inside the C# patcher.
# Mark it as vendored so GitHub Linguist keeps it out of the repository's
# language statistics the project is a C# app, not a TypeScript one.
# language statistics - the project is a C# app, not a TypeScript one.
web-panel/** linguist-vendored
+8 -5
View File
@@ -2,6 +2,9 @@ name: Build executable
on:
workflow_dispatch:
pull_request:
push:
branches: [master]
jobs:
build:
@@ -10,13 +13,13 @@ jobs:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v4
- uses: pnpm/action-setup@v5
with:
version: 10
version: 10.17.0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version: 22
cache: pnpm
@@ -27,7 +30,7 @@ jobs:
run: ./build.ps1 -Configuration Release
- name: Upload unsigned executable
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: WandEnhancer-unsigned
path: WandEnhancer/bin/Release/WandEnhancer.exe
+4 -1
View File
@@ -10,9 +10,12 @@ on:
jobs:
mirror:
if: github.repository == 'k1tbyte/Wand-Enhancer'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
+7 -3
View File
@@ -16,15 +16,15 @@ jobs:
RELEASE_VERSION: ${{ github.ref_name }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
- uses: pnpm/action-setup@v4
- uses: pnpm/action-setup@v5
with:
version: 10
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version: 22
cache: pnpm
@@ -50,3 +50,7 @@ jobs:
body_path: release-notes.md
files: CHANGELOG.md
fail_on_unmatched_files: true
# A tag carrying a suffix (1.1.0.0-rc.1) publishes as a pre-release and
# does not become the "Latest release" on the repository page.
prerelease: ${{ contains(github.ref_name, '-') }}
make_latest: ${{ !contains(github.ref_name, '-') }}
@@ -9,10 +9,12 @@ on:
jobs:
validate-release-metadata:
runs-on: windows-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Validate version and changelog sync
shell: pwsh
run: ./scripts/validate-release-metadata.ps1
run: ./scripts/validate-release-metadata.ps1
+3 -1
View File
@@ -145,4 +145,6 @@ appsettings.json
*DotSettings.user
.tmp
.source
web-panel/bridge/wand-remote-bridge.cjs
web-panel/bridge/wand-remote-bridge.cjs
.vscode
docs
+12 -1
View File
@@ -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 `<service_name>` 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/<name>.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
+11 -7
View File
@@ -73,22 +73,26 @@ namespace AsarSharp
filesystem.InsertFile(filename, shouldUnpack, file, placeholder);
break;
case FileType.Link:
throw new NotImplementedException();
throw new NotSupportedException($"Packing symlinks is not supported: '{filename}'");
}
}
private bool ShouldUnpackPath(string relativePath)
/// <summary>
/// Matches the directory path (relative to the archive root) against the unpack regex.
/// </summary>
private bool ShouldUnpackPath(string relativeParentPath)
{
return _options?.Unpack?.IsMatch(relativePath) == true;
return _options?.Unpack?.IsMatch(relativeParentPath) == true;
}
private void InsertsDone(Filesystem filesystem, List<Disk.BasicFileInfo> 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);
}
}
}
+16 -12
View File
@@ -41,9 +41,12 @@ namespace AsarSharp
var destFilename = Path.Combine(dest, filename);
var file = filesystem.GetFile(filename, followLinks);
// Path-traversal guard.
string relativePath = Extensions.GetRelativePath(dest, destFilename);
if (relativePath.StartsWith(".."))
// Path-traversal (zip-slip) guard. Uses the normalising
// containment check: GetRelativePath's fast path strips the
// prefix literally without resolving "..", so a crafted entry
// such as "a/../../evil" would otherwise pass this check and be
// written outside "dest".
if (!Extensions.IsPathInside(dest, destFilename))
{
throw new InvalidOperationException(
$"{fullPath}: file \"{destFilename}\" writes out of the package");
@@ -156,20 +159,19 @@ namespace AsarSharp
FilesystemEntry file, HashSet<string> 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.GetRelativePath(dest, linkSrcPath).StartsWith(".."))
if (!Extensions.IsPathInside(dest, linkSrcPath))
{
throw new InvalidOperationException(
$"{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));
@@ -186,8 +188,10 @@ namespace AsarSharp
}
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);
}
}
}
+78 -54
View File
@@ -12,8 +12,6 @@ namespace AsarSharp.AsarFileSystem
public static class Disk
{
private const int StreamBufferSize = 1024 * 1024;
private static readonly ConcurrentDictionary<string, Filesystem> _filesystemCache =
new ConcurrentDictionary<string, Filesystem>(StringComparer.OrdinalIgnoreCase);
public class ArchiveHeader
{
@@ -25,7 +23,6 @@ namespace AsarSharp.AsarFileSystem
public class FilesystemFilesAndLinks
{
public List<BasicFileInfo> Files { get; set; } = new List<BasicFileInfo>();
public List<BasicFileInfo> Links { get; set; } = new List<BasicFileInfo>();
}
public class BasicFileInfo
@@ -42,14 +39,14 @@ namespace AsarSharp.AsarFileSystem
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 @@ namespace AsarSharp.AsarFileSystem
}
}
/// <summary>
/// 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.
/// </summary>
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);
@@ -165,7 +128,56 @@ namespace AsarSharp.AsarFileSystem
var buf = new byte[StreamBufferSize];
var blockBuf = new byte[4 * 1024 * 1024]; // shared across all files — avoids 4MB alloc per file
using (var fs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None, StreamBufferSize, FileOptions.SequentialScan))
// Build beside the target and swap at the end. Writing straight into dest truncates
// it on open, so any failure mid-write left the caller with a destroyed archive.
string tempPath = dest + ".building";
try
{
WriteArchive(tempPath, dest, fileSystem, lists, serializerSettings,
headerPickle, sizePickle, sizePickleSize, buf, blockBuf);
ReplaceFile(tempPath, dest);
}
catch
{
TryDelete(tempPath);
throw;
}
}
private static void ReplaceFile(string tempPath, string dest)
{
if (!File.Exists(dest))
{
File.Move(tempPath, dest);
return;
}
// A read-only or hidden archive would fail the swap the same way an overwrite does.
Extensions.ClearAttributes(dest);
// File.Replace swaps in one step, so dest is never observed missing or half-written.
File.Replace(tempPath, dest, null, true);
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
{
// Leftover build file only wastes space; the real failure is already propagating.
}
}
private static void WriteArchive(string archivePath, string dest, Filesystem fileSystem,
FilesystemFilesAndLinks lists, JsonSerializerSettings serializerSettings,
Pickle headerPickle, Pickle sizePickle, int sizePickleSize, byte[] buf, byte[] blockBuf)
{
using (var fs = new FileStream(archivePath, FileMode.Create, FileAccess.Write, FileShare.None, StreamBufferSize, FileOptions.SequentialScan))
{
sizePickle.WriteTo(fs);
headerPickle.WriteTo(fs);
@@ -192,6 +204,18 @@ namespace AsarSharp.AsarFileSystem
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);
+40 -15
View File
@@ -33,7 +33,7 @@ namespace AsarSharp.AsarFileSystem
_headerSize = headerSize;
}
public FilesystemEntry SearchNodeFromDirectory(string p)
public FilesystemEntry SearchNodeFromDirectory(string p, bool create = true)
{
FilesystemEntry json = _header;
@@ -59,12 +59,31 @@ namespace AsarSharp.AsarFileSystem
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<string, FilesystemEntry>(StringComparer.Ordinal);
else
return null;
}
if (!json.Files.TryGetValue(seg, out var child))
{
child = new FilesystemEntry { Files = new Dictionary<string, FilesystemEntry>(StringComparer.Ordinal) };
json.Files[seg] = child;
if (create)
{
child = new FilesystemEntry { Files = new Dictionary<string, FilesystemEntry>(StringComparer.Ordinal) };
json.Files[seg] = child;
}
else
{
return null;
}
}
json = child;
start = end + 1;
@@ -81,7 +100,7 @@ namespace AsarSharp.AsarFileSystem
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<string, FilesystemEntry>(StringComparer.Ordinal);
@@ -111,18 +130,23 @@ namespace AsarSharp.AsarFileSystem
}
}
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 @@ namespace AsarSharp.AsarFileSystem
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 @@ namespace AsarSharp.AsarFileSystem
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;
+4 -11
View File
@@ -9,13 +9,6 @@ namespace AsarSharp.AsarFileSystem
{
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 @@ namespace AsarSharp.AsarFileSystem
}
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 @@ namespace AsarSharp.AsarFileSystem
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 @@ namespace AsarSharp.AsarFileSystem
{
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 @@ namespace AsarSharp.AsarFileSystem
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);
}
}
+4 -1
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using AsarSharp.Utils;
using Newtonsoft.Json;
namespace AsarSharp.Integrity
@@ -60,7 +61,9 @@ namespace AsarSharp.Integrity
var blockHashes = new List<string>(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);
+24 -99
View File
@@ -28,16 +28,18 @@ namespace AsarSharp.PickleTools
{
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 @@ namespace AsarSharp.PickleTools
}
public bool WriteBool(bool value) => WriteInt(value ? 1 : 0);
public bool WriteInt(int value)
{
@@ -121,74 +123,7 @@ namespace AsarSharp.PickleTools
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,13 +161,25 @@ namespace AsarSharp.PickleTools
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)
{
newCapacity = AlignInt(newCapacity, PAYLOAD_UNIT);
byte[] newHeader = new byte[_header.Length + newCapacity];
Buffer.BlockCopy(_header, 0, newHeader, 0, _header.Length);
// The backing array must hold the header plus the full advertised
// payload capacity (matches Chromium's realloc(header_size_ + new_capacity)).
// Sizing it from _header.Length under-allocates by _headerSize on the
// first growth (when _header is still empty), leaving the payload region
// _headerSize bytes short of _capacityAfterHeader and overrunning the
// buffer when a write fills the payload.
byte[] newHeader = new byte[_headerSize + newCapacity];
Buffer.BlockCopy(_header, 0, newHeader, 0, Math.Min(_header.Length, newHeader.Length));
_header = newHeader;
_capacityAfterHeader = newCapacity;
}
@@ -269,29 +216,7 @@ namespace AsarSharp.PickleTools
_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
+2 -23
View File
@@ -18,10 +18,7 @@ namespace AsarSharp.PickleTools
_endIndex = pickle.GetPayloadSize();
}
public bool ReadBool()
{
return ReadInt() != 0;
}
public int ReadInt()
{
@@ -33,25 +30,7 @@ namespace AsarSharp.PickleTools
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 @@ namespace AsarSharp.PickleTools
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}");
+150 -31
View File
@@ -1,12 +1,36 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
namespace AsarSharp.Utils
{
internal static class Extensions
public static class Extensions
{
/// <summary>
/// Fills <paramref name="count"/> 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.
/// </summary>
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;
}
/// <summary>
/// Compute path relative to <paramref name="relativeTo"/>.
/// Fast common-case (path is inside relativeTo): plain prefix-strip.
@@ -97,6 +121,27 @@ namespace AsarSharp.Utils
private static bool IsSeparator(char c) => c == '/' || c == '\\';
/// <summary>
/// Security check for archive extraction: returns true only when
/// <paramref name="candidate"/> resolves to a location inside
/// <paramref name="root"/>. Both paths are fully normalised first, so
/// embedded ".." segments cannot escape the root (zip-slip). The
/// <see cref="GetRelativePath"/> fast path must not be used here because
/// it strips the prefix literally without resolving "..".
/// </summary>
public static bool IsPathInside(string root, string candidate)
{
string fullRoot = TrimTrailingSeparators(Path.GetFullPath(root));
string fullCandidate = TrimTrailingSeparators(Path.GetFullPath(candidate));
if (string.Equals(fullRoot, fullCandidate, StringComparison.OrdinalIgnoreCase))
return true;
return fullCandidate.Length > fullRoot.Length
&& fullCandidate.StartsWith(fullRoot, StringComparison.OrdinalIgnoreCase)
&& IsSeparator(fullCandidate[fullRoot.Length]);
}
public static string GetDirectoryName(string path)
{
if (string.IsNullOrEmpty(path))
@@ -110,6 +155,83 @@ namespace AsarSharp.Utils
return result;
}
/// <summary>
/// Overwrites <paramref name="destination"/>, clearing attributes on both ends. CopyFile
/// carries the source's ReadOnly flag onto the copy and then refuses to overwrite what it
/// produced, failing with "Access to the path is denied" - so one read-only source (an exe
/// run straight out of a .zip, say) poisons the destination for every later run.
/// </summary>
public static void CopyOver(string source, string destination)
{
ClearAttributes(destination);
try
{
File.Copy(source, destination, true);
}
catch (UnauthorizedAccessException e)
{
throw new UnauthorizedAccessException($"{e.Message} {DescribeDenial(destination)}", e);
}
ClearAttributes(destination);
}
/// <summary>
/// "Access to the path is denied" names none of the half-dozen things that cause it, and
/// the state is gone by the time anyone reads the report. Attributes were already cleared
/// above, which rules the most common cause out before the message is even written.
/// </summary>
private static string DescribeDenial(string destination)
{
if (Directory.Exists(destination))
{
return "The destination is a directory, not a file.";
}
if (!File.Exists(destination))
{
return "The destination does not exist, so the containing folder is refusing new files.";
}
return $"Attributes {File.GetAttributes(destination)}, owner {DescribeOwner(destination)}, " +
$"running as {Environment.UserName}. A read-only flag, antivirus, folder " +
"permissions or a delete still pending on the file are the usual causes.";
}
private static string DescribeOwner(string path)
{
try
{
return File.GetAccessControl(path).GetOwner(typeof(NTAccount)).Value;
}
catch (Exception e) when (e is IdentityNotMappedException || e is UnauthorizedAccessException ||
e is InvalidOperationException || e is PrivilegeNotHeldException ||
e is PlatformNotSupportedException)
{
return "unreadable";
}
}
/// <summary>
/// Resets a file to Normal: ReadOnly, Hidden and System all block an overwrite. Best
/// effort - a file that denies even this reports it properly through the write that follows.
/// </summary>
public static void ClearAttributes(string path)
{
try
{
if (File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal);
}
}
catch (Exception e) when (e is UnauthorizedAccessException || e is IOException)
{
// Swallowed so the caller's own failure is the one that surfaces.
}
}
public static void CopyDirectory(string sourceDir, string destinationDir)
{
Directory.CreateDirectory(destinationDir);
@@ -117,7 +239,7 @@ namespace AsarSharp.Utils
foreach (var file in Directory.GetFiles(sourceDir))
{
var destFile = Path.Combine(destinationDir, Path.GetFileName(file));
File.Copy(file, destFile, true);
CopyOver(file, destFile);
}
foreach (var dir in Directory.GetDirectories(sourceDir))
@@ -149,19 +271,7 @@ namespace AsarSharp.Utils
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}\"");
}
@@ -169,32 +279,41 @@ namespace AsarSharp.Utils
{
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}.");
}
}
}
}
+87
View File
@@ -3,12 +3,99 @@
This file is the source of truth for release notes.
The newest entry must match the version in `WandEnhancer/Properties/AssemblyInfo.cs`.
## [2.0.0.0] - 2026-08-29
### Important
- The bundled `version.dll` proxy is gone. The launcher now starts Wand and keeps the patch applied in every process Electron spawns, for as long as Wand runs. This is what fixes Wand refusing to launch after enhancing on related issues: #207 #210 #211 #213 #214 #217
- The native helper and its CMake build step were removed. Building from source no longer needs `CMake` or the Visual Studio C++ workload.
- WandEnhancer now installs itself as the Wand launcher entry point, so starting Wand goes through the patcher. Restoring a backup puts the original launcher back.
### Features
- **Auto-patch after Wand updates.** Enable *Auto-apply after updates* in the patch dialog and your selection is saved next to the launcher. When Wand updates and drops the patches, the next launch re-applies them. On failure the UI opens and shows which patch broke instead of silently starting an unpatched client.
- **Rewritten patch engine with legacy version support.** Patches are located structurally instead of by regex signature: each anchors on something Wand does not rename between builds. A client rebuild that only re-minifies no longer breaks patching, and older clients keep working. #178 #186
- A patch whose feature is missing from your client is now reported as skipped instead of failing the whole run, and failures name the patch that broke.
### Fixes
- Fixed the in-game overlay never appearing after enhancing, while Wand itself looked healthy. Wand creates the process that draws the overlay when a game starts, minutes or hours after launch, and only the startup processes were being covered - that one shut down the instant it opened the patched files, so nothing ever drew the overlay.
- Fixed the "Buy Pro" banner still showing after a successful patch, and Pro not activating on newer clients.
- Fixed the Enhancer closing itself when any button was pressed. #184
- A failed patch now puts your original Wand files back instead of leaving a half-patched install behind. Packing also builds the archive beside the old one and swaps it in at the end, so a failure can no longer destroy `app.asar`. #221
- Fixed patching and *Restore* both failing with "Access to the path is denied" after the first successful patch. Copying carried the read-only flag from the patcher onto the launcher it installs, and then refused to overwrite what it had written - so running WandEnhancer straight out of the downloaded `.zip`, which Windows marks read-only, broke every later run. #214
- Fixed a half-written backup reporting the installation as patched, which blocked patching and restore at the same time.
- Fixed invalid ASAR integrity metadata produced from short reads, which could yield an archive the client rejects. #170
- Fixed the packer silently dropping files it could not read, for example while Wand was still running.
- Fixed archive tree lookups resolving the wrong parent and creating phantom directories in the header.
- Fixed hangs on symlink cycles and directory junctions while reading or packing an archive.
- Fixed the language switcher leaking a resource dictionary on every switch. #164
- Fixed *Restore* freezing the window while it ran.
- Fixed Squirrel install and update arguments breaking when the Windows user profile path contains spaces.
- Fixed a latent crash path from a patch type that had no configuration entry. #172
- Remote panel: fixed a blank page when the interface translations failed to load.
- Remote panel: fixed number inputs eating the decimal point while typing, and steppers drifting on fractional steps.
- Remote panel: fixed the increment control refusing to step from a value outside its option list.
- Remote panel: fixed endless two-second reconnect attempts, and reconnecting again after you disconnected on purpose.
- Remote panel: fixed installed-game updates not arriving when only the install location changed.
- Remote panel: fixed value writes silently doing nothing when the client bound to the bridge before it was ready.
### Improvements
- When Wand fails to start, the Enhancer window now opens by itself with the reason already in the log, instead of leaving you to find a log file. The same lines are still written to a `launcher.log` next to the launcher: every process Electron starts and whether the patch reached it, plus exit and crash codes.
- Log messages in the desktop app are now translated into all 12 supported languages.
- The remote panel is now usable with a keyboard and a screen reader: dialogs trap focus and close on Escape, and controls have accessible names. Pinning a mod previously required a swipe and had no keyboard path at all, so mod rows now have a pin button.
### Security and Privacy
- The panel's static file server now resolves every request inside the panel directory.
- The local bridge enforces the WebSocket framing rules required of a server (RFC 6455).
- Late trainer events naming a different trainer no longer overwrite the active trainer's values.
### Maintenance
- The Electron bridge is now fully type-checked; roughly 200 latent typing gaps were fixed.
- `build.ps1` and CI now run lint, type-check, and a dist verification step that syntax-checks the bundles and fails when dev-only payloads leak into a production build. CI runs on pull requests and pushes to `master`.
- Removed dead code: the `version.dll` project, an unused control and converter, and unused Pickle helpers.
## [1.0.9.4] - 2026-07-21
### Fixes
- Fixed the Remote Web Panel QR code still opening the official Wand mobile client after Wand changed its bundled QR renderer export. The renderer bridge now resolves the current export without adding a fragile C# ASAR patch. #140
- Fixed Quick Presets reporting that a preset was saved when browser local storage rejected the write. Failed writes now leave the existing preset list unchanged and show an error, and the save dialog now stays above the bottom navigation dock.
- Fixed the patcher giving up on process termination because it reused a stale process snapshot by @divya0795 in #145. Related issue: #136
- Fixed ASAR extraction path traversal and corrupt Pickle payload allocation by @divya0795 in #143.
- Fixed backup restore so `app.asar.unpacked` is restored together with `app.asar`, and the injected `version.dll` is removed after a successful restore.
- Fixed `version.dll` requiring Visual C++ runtime DLLs on some systems by statically linking the runtime. Release builds now reject accidental dynamic VCRUNTIME, MSVCP, or UCRT dependencies. #128
### Security and Privacy
- Removed bearer credentials and local installation paths from the Remote Web Panel WebSocket protocol. Trainer localization now stays inside the Electron bridge.
- Hardened the local bridge against malformed HTTP URLs, invalid Host headers, and oversized WebSocket frames, and removed the production installed-apps debug endpoint.
### Maintenance
- GitLab mirror jobs are now skipped in forks instead of failing when the upstream mirror credentials are unavailable.
## [1.0.9.3] - 2026-07-04
### Fixes
- Fixed the Remote Web Panel no longer applying on newer Wand builds and reporting "unsupported version". The remote bridge patches now resolve Wand's minified internal names dynamically instead of relying on hardcoded ones that broke on Wand updates. #118 #123 #124 #126
- Fixed Pro reverting to Free (with random sign-outs and the return of ads and the time limit) after linking a phone with Wand's mobile activation code. That native pairing triggers a server-side sign-out on a patched client, so the patcher now disables it; use the built-in Remote Web Panel to control Wand from another device instead. #120
## [1.0.9.2] - 2026-06-28
### Important
- Official releases no longer include downloadable `.exe` files. To update, sync your fork and rerun the `Build executable` workflow, or follow the instructions in [How to use](https://github.com/k1tbyte/Wand-Enhancer#-how-to-use).
### Changed
- Removed the built-in WandEnhancer updater. Official GitHub releases no longer ship executable assets.
- Removed System.Net.Http
- Removed self-signed certificate generation to prevent AV false positives.
- Switched official releases to publish release notes only.
## [1.0.9.1] - 2026-06-24
+17 -17
View File
@@ -13,9 +13,9 @@
**🚨 IMPORTANT NOTICE: THIS PROJECT HAS NO OFFICIAL YOUTUBE TUTORIALS, GUIDES, OR PREBUILT EXECUTABLE DOWNLOADS. 🚨
There are no official videos showing how to install or use this tool. Scammers are creating fake tutorials using this project's name and placing malware/password stealers in the video descriptions. Official GitHub releases contain release notes only, not `.exe` files. If you downloaded an `.exe` or archive from a YouTube link, a random website, or a third-party mirror, you did not get it from this project. We are not responsible for third-party downloads.**
## 👾 Is it safe to use?
## 👾 What does it access?
Yes. This project is entirely open-source, allowing anyone to audit the code. It operates strictly locally, does not require internet access, and makes zero network requests. It simply adjusts local client settings to enhance your user experience.
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?
@@ -36,21 +36,24 @@ WandEnhancer includes a built-in **Remote Web Panel** allowing you to control ap
### Troubleshooting & Remote Access:
- **Page isn't loading?** First, ensure both your PC and phone are connected to the **same local network**. Some routers and guest Wi-Fi networks enable client isolation/AP isolation, which blocks devices on the same SSID from reaching each other. If it still does not load, check Windows Firewall and allow inbound traffic on TCP port `3223` for your local network. If Windows marked your connection as **Public**, switching it to **Private** can also help.
- **Using mobile data or a different network?** If you want to use the panel over mobile data (LTE/5G) or from an entirely different network, you can use [Tailscale](https://tailscale.com/) or similar VPN tools.
- The panel uses plain HTTP on port `3223` and has no pairing code. Anyone who can reach that port can view the panel and control the active trainer, so use it only on a trusted LAN/VPN and never expose the port directly to the internet.
- The panel protocol does not include your Wand bearer token or installation-path fields.
## 👀 How to use?
This repository does not publish official compiled binaries. Build your own executable from your own fork using GitHub Actions.
1. Sign in to GitHub and fork this repository.
2. Open your fork, go to the **Actions** tab, and enable workflows if GitHub asks you to.
3. Select the **Build executable** workflow.
4. Click **Run workflow**, keep the default branch, and start the run.
5. Wait for the workflow to finish, open the completed run, and download the artifact.
6. Extract the artifact zip and run `WandEnhancer.exe` to apply local client modifications.
2. Use **Sync fork** before each build so your fork contains the latest fixes.
3. Open your fork, go to the **Actions** tab, and enable workflows if GitHub asks you to.
4. Select the **Build executable** workflow.
5. Click **Run workflow**, keep the default branch, and start the run.
6. Wait for the workflow to finish, open the completed run, and download the artifact.
7. Extract the artifact zip and run `WandEnhancer.exe` to apply local client modifications.
*Here how you do it:*
https://github.com/user-attachments/assets/b03eeed4-ceb8-45c0-b09c-2b64cf098c64
https://github.com/user-attachments/assets/7966cabe-0aa6-424d-8c2f-981ad91e0f91
@@ -99,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.
---
@@ -126,7 +127,9 @@ The build script installs the web panel dependencies, builds the frontend, compi
- **Can I use a binary built by someone else?**
- You can, but you should treat it as untrusted. This repository cannot verify or support third-party builds.
- **Does this send data anywhere?**
- The desktop patching work is local to your machine. The Remote Web Panel is served from your PC on your local network.
- The .NET patching step is local. The optional Remote Web Panel listens on your LAN and may request trainer translations/artwork through Wand's existing API/CDN paths; it does not include an updater or project telemetry.
- **How do I learn about a new version without an in-app update check?**
- On GitHub choose **Watch → Custom → Releases**, then sync your fork and run **Build executable** when a release is published.
---
## 🖼️ Screenshots
@@ -136,12 +139,11 @@ The build script installs the web panel dependencies, builds the frontend, compi
![2](./assets/screenshots/app2.png)
</div>
---
## 📜 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 🙌
@@ -158,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)
-1
View File
@@ -15,7 +15,6 @@
<FontFamily x:Key="Inter" >pack://application:,,,/Style/#Inter 18pt 18pt</FontFamily>
<converters:ToVisibilityConverter x:Key="ToVisibilityConverter"/>
<converters:ToVisibilityInvertedConverter x:Key="ToVisibilityInvertedConverter"/>
</ResourceDictionary>
</Application.Resources>
</Application>
+4 -26
View File
@@ -1,6 +1,5 @@
using System;
using System;
using System.Reflection;
using WandEnhancer.Models;
namespace WandEnhancer
{
@@ -8,36 +7,15 @@ namespace WandEnhancer
{
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;
}
}
}
}
@@ -18,29 +18,7 @@ namespace WandEnhancer.Converters
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)
@@ -9,10 +9,4 @@ namespace WandEnhancer.Converters
{ }
}
internal sealed class ToVisibilityInvertedConverter : BaseBooleanConverter<Visibility>
{
public ToVisibilityInvertedConverter() :
base(Visibility.Collapsed, Visibility.Visible)
{ }
}
}
+243
View File
@@ -0,0 +1,243 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using AsarSharp.Utils;
namespace WandEnhancer.Core
{
/// <summary>
/// Electron's fuse wire: a 32-byte sentinel followed by [version][fuseCount][state per fuse].
/// Clearing the ASAR integrity fuse is what lets a patched app.asar load at all - the archive
/// no longer hashes to the value baked into the executable, and a process that opens it with
/// the fuse still set exits with -36861.
/// </summary>
internal static class ElectronFuse
{
private const int AsarIntegrityIndex = 4;
private const byte StateRemoved = (byte)'r';
private const byte SupportedWireVersion = 1;
private const int MinFuseCount = 5;
private const int SentinelLength = 32;
private const int WireHeaderLength = 2;
private const int StateFromSentinel = SentinelLength + WireHeaderLength + AsarIntegrityIndex;
private const int MatchLength = StateFromSentinel + 1;
private const int ChunkSize = 1 << 20;
private static readonly byte[] Sentinel =
Encoding.ASCII.GetBytes("dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX");
/// <summary>
/// Offset of the fuse state from the image base, read once from the file on disk. Every
/// process started from that file maps it at the same offset, so the scan is not repeated
/// per process - reading 200+ MB out of each one would not fit in the second we have
/// before Electron opens the archive.
/// </summary>
/// <returns>-1 when the file carries no fuse block.</returns>
public static long FindStateRva(string exePath)
{
// Share everything: Wand is normally already running when this is asked again.
using (var stream = new FileStream(exePath, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, ChunkSize, FileOptions.SequentialScan))
{
long offset = FindStateOffset(stream);
return offset < 0 ? -1 : ToRva(stream, offset);
}
}
/// <summary>
/// Clears the fuse in a running process. False when the image does not look like the one
/// <see cref="FindStateRva"/> measured, or the write was refused.
/// </summary>
public static bool ClearIn(IntPtr process, long stateRva)
{
IntPtr imageBase = GetImageBase(process);
if (imageBase == IntPtr.Zero)
{
return false;
}
var block = new byte[MatchLength];
var start = new IntPtr(imageBase.ToInt64() + stateRva - StateFromSentinel);
if (!ReadProcessMemory(process, start, block, block.Length, out int read) || read != block.Length)
{
return false;
}
// The sentinel is checked again inside the process: a Wand update swaps the
// executable under a running launcher, and a stale offset would otherwise put a
// byte into unrelated memory.
if (!MatchesSentinel(block, 0) ||
block[SentinelLength] != SupportedWireVersion ||
block[SentinelLength + 1] < MinFuseCount)
{
return false;
}
if (block[StateFromSentinel] == StateRemoved)
{
return true;
}
var target = new IntPtr(imageBase.ToInt64() + stateRva);
if (!VirtualProtectEx(process, target, (UIntPtr)1, PAGE_READWRITE, out uint previous))
{
return false;
}
bool written = WriteProcessMemory(process, target, new[] { StateRemoved }, 1, out _);
VirtualProtectEx(process, target, (UIntPtr)1, previous, out _);
return written;
}
/// <summary>
/// Read out of the PEB rather than the module list: a process that has only just been
/// created - or one still suspended, which is where the main process is patched - has no
/// module list yet, but the kernel fills in the image base before the first instruction.
/// </summary>
private static IntPtr GetImageBase(IntPtr process)
{
var info = new PROCESS_BASIC_INFORMATION();
if (NtQueryInformationProcess(process, ProcessBasicInformation, ref info,
Marshal.SizeOf(info), out _) != 0 || info.PebBaseAddress == IntPtr.Zero)
{
return IntPtr.Zero;
}
var buffer = new byte[IntPtr.Size];
var address = new IntPtr(info.PebBaseAddress.ToInt64() + PebImageBaseOffset);
return ReadProcessMemory(process, address, buffer, buffer.Length, out int read) && read == buffer.Length
? new IntPtr(BitConverter.ToInt64(buffer, 0))
: IntPtr.Zero;
}
private static long FindStateOffset(Stream stream)
{
var buffer = new byte[ChunkSize + MatchLength];
long bufferStart = 0;
int filled = 0;
while (true)
{
filled += stream.ReadFull(buffer, filled, buffer.Length - filled);
if (filled < MatchLength)
{
return -1;
}
int limit = filled - MatchLength;
// Byte by byte: the linker is free to place the sentinel at any alignment.
for (int i = 0; i <= limit; i++)
{
if (buffer[i] != Sentinel[0] || !MatchesSentinel(buffer, i))
{
continue;
}
int wire = i + SentinelLength;
if (buffer[wire] != SupportedWireVersion || buffer[wire + 1] < MinFuseCount)
{
continue;
}
return bufferStart + i + StateFromSentinel;
}
// A short fill is end of file, and a tail shorter than a match cannot hold one.
if (filled < buffer.Length)
{
return -1;
}
Buffer.BlockCopy(buffer, limit, buffer, 0, MatchLength);
bufferStart += limit;
filled = MatchLength;
}
}
/// <summary>Maps a file offset through the section table to an offset from the image base.</summary>
private static long ToRva(Stream stream, long fileOffset)
{
var head = new byte[4096];
stream.Position = 0;
if (stream.ReadFull(head, 0, head.Length) < head.Length)
{
return -1;
}
int peHeader = BitConverter.ToInt32(head, 0x3C);
int sectionCount = BitConverter.ToUInt16(head, peHeader + 6);
int sectionTable = peHeader + 24 + BitConverter.ToUInt16(head, peHeader + 20);
if (sectionTable + sectionCount * SectionEntrySize > head.Length)
{
return -1;
}
for (int i = 0; i < sectionCount; i++)
{
int entry = sectionTable + i * SectionEntrySize;
long virtualAddress = BitConverter.ToUInt32(head, entry + 12);
long rawSize = BitConverter.ToUInt32(head, entry + 16);
long rawStart = BitConverter.ToUInt32(head, entry + 20);
if (fileOffset >= rawStart && fileOffset < rawStart + rawSize)
{
return virtualAddress + (fileOffset - rawStart);
}
}
return -1;
}
private static bool MatchesSentinel(byte[] buffer, int offset)
{
for (int i = 0; i < SentinelLength; i++)
{
if (buffer[offset + i] != Sentinel[i])
{
return false;
}
}
return true;
}
#region P/Invoke
private const int SectionEntrySize = 40;
private const uint PAGE_READWRITE = 0x04;
private const int ProcessBasicInformation = 0;
private const int PebImageBaseOffset = 0x10;
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_BASIC_INFORMATION
{
public IntPtr ExitStatus;
public IntPtr PebBaseAddress;
public IntPtr AffinityMask;
public IntPtr BasePriority;
public IntPtr UniqueProcessId;
public IntPtr InheritedFromUniqueProcessId;
}
[DllImport("ntdll.dll")]
private static extern int NtQueryInformationProcess(
IntPtr hProcess, int processInformationClass, ref PROCESS_BASIC_INFORMATION processInformation,
int processInformationLength, out int returnLength);
[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);
#endregion
}
}
+244 -174
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -18,6 +18,8 @@ namespace WandEnhancer.Core
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 @@ namespace WandEnhancer.Core
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 @@ namespace WandEnhancer.Core
private readonly WeModConfig _weModConfig;
private readonly Action<string, ELogType> _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;
/// <summary>For <see cref="Restore"/>, which needs the install paths but no patch selection.</summary>
public Enhancer(WeModConfig weModConfig, Action<string, ELogType> logger)
: this(weModConfig, logger, null)
{
}
public Enhancer(WeModConfig weModConfig, Action<string, ELogType> 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)
/// <summary>
/// Both halves of the backup must exist. Accepting either one on its own reported a
/// half-written backup as patched, which blocked patching while <see cref="Restore"/>
/// refused to run - leaving the user with no way forward.
/// </summary>
public static bool IsPatched(string rootDirectory)
{
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;
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 @@ namespace WandEnhancer.Core
{
throw new Exception("[ENHANCER] No app bundle found");
}
var remainingPatches = new HashSet<EPatchType>(_config.PatchTypes);
var enhancerConfig = EnhancerConfig.GetInstance();
@@ -144,20 +99,22 @@ namespace WandEnhancer.Core
{
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,11 +126,27 @@ namespace WandEnhancer.Core
File.WriteAllText(item, data);
}
}
if(remainingPatches.Count > 0)
ReportUnappliedPatches(remainingPatches, enhancerConfig);
}
private void ReportUnappliedPatches(IEnumerable<EPatchType> remainingPatches, Dictionary<EPatchType, EnhancerConfig.PatchEntry[]> enhancerConfig)
{
var unapplied = remainingPatches
.SelectMany(patchType => enhancerConfig[patchType]
.Where(patch => !patch.Applied)
.Select(patch => new { Label = JavaScriptPatchApplier.FormatLabel(patchType, patch), Patch = patch }))
.ToList();
foreach (var skipped in unapplied.Where(entry => entry.Patch.IsResolved))
{
var failedPatches = string.Join(", ", remainingPatches.Select(p => p.ToString()));
throw new Exception($"[ENHANCER] Failed to apply patches: {failedPatches}. The version may not be supported.");
_logger($"[ENHANCER] [{skipped.Label}] Capability not present, skipping", ELogType.Info);
}
var failed = unapplied.Where(entry => !entry.Patch.IsResolved).Select(entry => entry.Label).ToList();
if (failed.Count > 0)
{
throw new Exception($"[ENHANCER] Failed to apply patches: {string.Join(", ", failed)}. The version may not be supported.");
}
}
@@ -187,44 +160,9 @@ namespace WandEnhancer.Core
private static bool CouldFileContainRemainingPatch(string filePath, IEnumerable<EPatchType> remainingPatches, Dictionary<EPatchType, EnhancerConfig.PatchEntry[]> enhancerConfig)
{
foreach (var patchType in remainingPatches)
{
foreach (var patchEntry in enhancerConfig[patchType])
{
if (patchEntry.Applied)
{
continue;
}
if (CanSearchPatchInFile(filePath, patchEntry))
{
return true;
}
}
}
return false;
}
private static bool CanSearchPatchInFile(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 ContainsSearchHint(string source, string[] searchHints)
{
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 @@ namespace WandEnhancer.Core
throw new FileNotFoundException($"Required workspace artifact not found: {Path.Combine(segments)}");
}
private 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 @@ namespace WandEnhancer.Core
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,20 +275,15 @@ namespace WandEnhancer.Core
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)));
AsarSharp.Utils.Extensions.CopyOver(file, GetAvailableScriptPath(destinationDir, Path.GetFileName(file)));
copied++;
}
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 @@ namespace WandEnhancer.Core
if (CopyEmbeddedDirectory(EmbeddedRemotePanelDistPrefix, targetRoot) == 0)
{
CopyDirectory(FindWorkspacePath(WebPanelDirectoryName, WebPanelDistDirectoryName), targetRoot);
AsarSharp.Utils.Extensions.CopyDirectory(FindWorkspacePath(WebPanelDirectoryName, WebPanelDistDirectoryName), targetRoot);
}
if (!File.Exists(targetBridgePath))
@@ -418,40 +325,94 @@ namespace WandEnhancer.Core
_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
{
throw new Exception("[ENHANCER] Proxy DLL resource not found");
string root = Directory.GetParent(_weModConfig.RootDirectory)?.FullName;
if (string.IsNullOrEmpty(root))
{
throw new Exception("[ENHANCER] Cannot determine Squirrel root directory");
}
return root;
}
var destPath = Path.Combine(_weModConfig.RootDirectory, "version.dll");
using (var fileStream = File.Create(destPath))
}
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))
{
dll.CopyTo(fileStream);
return;
}
if (File.Exists(stubPath) && !File.Exists(stubBackup))
{
AsarSharp.Utils.Extensions.CopyOver(stubPath, stubBackup);
}
AsarSharp.Utils.Extensions.CopyOver(self, stubPath);
_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);
}
}
/// <summary>Reads the patch selection saved next to the launcher, or null when absent or unreadable.</summary>
public static PatchConfig LoadAutoPatchConfig(string launcherDirectory)
{
try
{
string path = Path.Combine(launcherDirectory, Constants.AutoPatchConfigFileName);
if (!File.Exists(path))
{
return null;
}
return Newtonsoft.Json.JsonConvert.DeserializeObject<PatchConfig>(File.ReadAllText(path));
}
catch (Exception e) when (e is IOException || e is Newtonsoft.Json.JsonException || e is UnauthorizedAccessException)
{
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);
File.Copy(_asarPath, _backupPath);
AsarSharp.Utils.Extensions.CopyOver(_asarPath, _backupPath);
}
else
{
_logger("[ENHANCER] Backup found, restoring pristine app.asar before patching...", ELogType.Info);
File.Copy(_backupPath, _asarPath, true);
AsarSharp.Utils.Extensions.CopyOver(_backupPath, _asarPath);
}
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,18 +422,51 @@ namespace WandEnhancer.Core
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");
}
// Everything past this point mutates the installation. A half-applied patch does
// not boot - the fuse is only cleared by the deployed launcher, so a patched
// app.asar without it dies with -36861 - so failure has to put the files back.
try
{
ExtractSources();
PatchAsar();
InjectRemotePanelFiles();
PackSources();
DeployLauncher();
}
catch
{
RollbackQuietly();
throw;
}
// 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);
}
private void ExtractSources()
{
try
{
_logger("[ENHANCER] Extracting app.asar...", ELogType.Info);
@@ -480,12 +474,12 @@ namespace WandEnhancer.Core
}
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();
}
private void PackSources()
{
try
{
new AsarCreator(_unpackedPath, _asarPath, new CreateOptions
@@ -495,12 +489,88 @@ namespace WandEnhancer.Core
}
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();
_logger("[ENHANCER] Done!", ELogType.Success);
}
/// <summary>
/// Best-effort restore after a failed patch. Never throws: the caller is already
/// propagating the real failure and it must not be replaced by a cleanup error.
/// </summary>
private void RollbackQuietly()
{
try
{
if (File.Exists(_backupPath))
{
AsarSharp.Utils.Extensions.CopyOver(_backupPath, _asarPath);
}
if (Directory.Exists(_unpackedBackupPath))
{
if (Directory.Exists(_unpackedPath))
{
Directory.Delete(_unpackedPath, true);
}
AsarSharp.Utils.Extensions.CopyDirectory(_unpackedBackupPath, _unpackedPath);
}
_logger("[ENHANCER] Patch failed - the original Wand files were restored.", ELogType.Warn);
}
catch (Exception e)
{
_logger($"[ENHANCER] Patch failed and the rollback did not finish: {e.Message}. " +
"Use Restore before launching Wand.", ELogType.Error);
}
}
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);
AsarSharp.Utils.Extensions.CopyOver(_backupPath, _asarPath);
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))
{
AsarSharp.Utils.Extensions.CopyOver(stubBackup, stubPath);
File.Delete(stubBackup);
}
foreach (var leftover in new[] { Constants.AutoPatchConfigFileName, LauncherLog.FileName })
{
string path = Path.Combine(squirrelRoot, leftover);
if (File.Exists(path))
{
File.Delete(path);
}
}
File.Delete(_backupPath);
Directory.Delete(_unpackedBackupPath, true);
_logger("[ENHANCER] Backup restored successfully.", ELogType.Success);
}
}
}
+278 -154
View File
@@ -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
/// <summary>
/// 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.
/// </summary>
internal static class EnhancerConfig
{
public class ResolveContext
{
public string Placeholder { get; set; }
public Func<string, string> Handler { get; set; }
}
/// <summary>Locates the edits a patch must make, or null when the anchor is absent from this file.</summary>
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<Match, string> 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}");
}
/// <summary>Marks the patch optional: builds without these strings lack the feature entirely.</summary>
public string[] CapabilityHints { get; set; }
return group.Value;
}
public bool Applied { get; set; }
public bool CapabilityDetected { get; set; }
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);
}
public bool IsOptional => CapabilityHints != null && CapabilityHints.Length > 0;
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;}})}}";
}
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}}}}";
}
private static string BuildRemoteBridgeResetPatch(Match match)
{
var source = match.Value;
var method = RequireGroup(match, "method", "remoteBridgeReset");
var disposableField = RequirePattern(source, @"this\.(?<disposable>#[\w$]+)\s*&&\s*\(\s*this\.\k<disposable>\.dispose\(\)", "disposable", "remoteBridgeReset");
var instanceField = RequirePattern(source, @"this\.(?<instance>#[\w$]+)\s*=\s*Date\.now\(\)\.toString\(\)", "instance", "remoteBridgeReset");
var trainerIdField = RequirePattern(source, @"Date\.now\(\)\.toString\(\)\s*\)?\s*,\s*\(?\s*this\.(?<trainerId>#[\w$]+)\s*=\s*null", "trainerId", "remoteBridgeReset");
var supportedVersionsField = RequirePattern(source, @"this\.(?<versions>#[\w$]+)\s*=\s*\[\]", "versions", "remoteBridgeReset");
var trainerField = RequirePattern(source, @"this\.(?<versions>#[\w$]+)\s*=\s*\[\]\s*\)?\s*,\s*\(?\s*this\.(?<trainer>#[\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)}}";
}
private static string BuildRemoteBridgeSyncSnapshotPatch(Match match)
{
var source = match.Value;
var method = RequireGroup(match, "method", "remoteBridgeSyncSnapshot");
var statusAlias = RequirePattern(source, @"this\.status\s*===\s*(?<value>[\w$]+)\.Connected", "value", "remoteBridgeSyncSnapshot");
var trainerField = RequirePattern(source, @"this\.(?<trainer>#[\w$]+)\?\.\s*getMetadata\s*\(\s*(?<metadata>[\w$]+\.[\w$]+)\s*\)\?\.\s*gameVersion", "trainer", "remoteBridgeSyncSnapshot");
var metadataExport = RequirePattern(source, @"this\.(?<trainer>#[\w$]+)\?\.\s*getMetadata\s*\(\s*(?<metadata>[\w$]+\.[\w$]+)\s*\)\?\.\s*gameVersion", "metadata", "remoteBridgeSyncSnapshot");
var notesField = RequirePattern(source, @"this\.(?<notes>#[\w$]+)\s*\[\s*this\.(?<trainerId>#[\w$]+)\s*\?\?\s*""""\s*\]", "notes", "remoteBridgeSyncSnapshot");
var trainerIdField = RequirePattern(source, @"this\.(?<notes>#[\w$]+)\s*\[\s*this\.(?<trainerId>#[\w$]+)\s*\?\?\s*""""\s*\]", "trainerId", "remoteBridgeSyncSnapshot");
var gameField = RequirePattern(source, @"this\.(?<game>#[\w$]+)\s*&&.*?getPreferredInstallationInfo\s*\(\s*this\.\k<game>\s*\)", "game", "remoteBridgeSyncSnapshot");
var installationField = RequirePattern(source, @"this\.(?<game>#[\w$]+)\s*&&.*?this\.(?<installation>#[\w$]+)\.getPreferredInstallationInfo\s*\(\s*this\.\k<game>\s*\)", "installation", "remoteBridgeSyncSnapshot");
var supportedVersionsField = RequirePattern(source, @"!\s*this\.(?<versions>#[\w$]+)\.includes\s*\(\s*[\w$]+\.version\s*\)", "versions", "remoteBridgeSyncSnapshot");
var remoteChannelField = RequirePattern(source, @"this\.(?<remote>#[\w$]+)\?\.\s*send\s*\(\s*""client-state""", "remote", "remoteBridgeSyncSnapshot");
var valuesMethod = RequirePattern(source, @"values\s*:\s*this\.(?<values>#[\w$]+)\s*\(\s*\)", "values", "remoteBridgeSyncSnapshot");
var instanceField = RequirePattern(source, @"instanceId\s*:\s*this\.(?<instance>#[\w$]+)", "instance", "remoteBridgeSyncSnapshot");
var themeField = RequirePattern(source, @"themeId\s*:\s*this\.(?<theme>#[\w$]+)", "theme", "remoteBridgeSyncSnapshot");
var settingsHelper = RequirePattern(source, @"settings\s*:\s*(?<settings>[\w$]+)\s*\(\s*this\.settings\s*\)", "settings", "remoteBridgeSyncSnapshot");
var languageField = RequirePattern(source, @"language\s*:\s*this\.(?<language>#[\w$]+)", "language", "remoteBridgeSyncSnapshot");
var timerField = RequirePattern(source, @"isTimeLimitExpired\s*:\s*""expired""\s*===\s*this\.(?<timer>#[\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}()}})}}";
/// <summary>True once the patch is applied, or once a scan proved the feature is absent.</summary>
public bool IsResolved => Applied || (IsOptional && !CapabilityDetected);
}
public static Dictionary<EPatchType, PatchEntry[]> GetInstance()
{
return new Dictionary<EPatchType, PatchEntry[]>()
return new Dictionary<EPatchType, PatchEntry[]>
{
{
EPatchType.ActivatePro,
@@ -107,66 +46,41 @@ namespace WandEnhancer.Core
{
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 = "<service_name>"
},
Name = "getUserAccount",
Target = new Regex(@"getUserAccount\(\)\{.*?return\s+this\.#\w+\.fetch\(\{.*?\}\)\}",
RegexOptions.Singleline),
Patch =
"getUserAccount(){return this.#<service_name>.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 = "<service_name>"
},
Name = "setAccountWandBrandExperience",
Target = new Regex(
@"setAccountWandBrandExperience\(\)\{.*?return\s+this\.#\w+\.post\(""/v3/account/brand_experience_wand""\)\}",
RegexOptions.Singleline),
Patch =
"setAccountWandBrandExperience(){return this.#<service_name>.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\((?<params>[^)]*)\)\{\s*return\s+(?<expr>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 (?<decl>\w+)=""ACTION_SET_ACCOUNT"";function (?<fn>\w+)\((?<params>[^)]*)\)\{return\{\.\.\.(?<state>\w+),account:(?<account>\w+)\}\}",
RegexOptions.Singleline),
PatchFactory = BuildSetAccountReducerPatch
Locate = LocateAccountReducer
},
new PatchEntry
{
// 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" },
Locate = js => Edits(js.FindFunction("requestRemoteAuthCode")?
.ReplaceBody(PatchPayload.Load("disable-native-pairing")))
}
}
},
@@ -174,15 +88,12 @@ namespace WandEnhancer.Core
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
}
}
},
@@ -192,18 +103,12 @@ namespace WandEnhancer.Core
{
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 `<app>.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(@"(?<app>\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
}
}
},
@@ -216,42 +121,261 @@ namespace WandEnhancer.Core
Name = "remoteBridgeMainBoot",
CandidateFileNames = new[] { "index.js" },
SearchHints = new[] { "whenReady().then(run)" },
Target = new Regex(@"(?<app>\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(@"(?<method>#[\w$]+)\(\)\s*\{\s*(?<body>(?:(?!__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(@"(?<method>#[\w$]+)\(\)\s*\{\s*if\s*\(\s*this\.status\s*===\s*[\w$]+\.Connected\s*\)\s*\{(?<body>.*?""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
{
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\.#ke&&t===this\.#Ee\)return;"),
Patch = "setCurrentTrainer(e,t=null){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.#Ee||!e?.target)return!1;return this.#Ee.isActive()?this.#Ee.setValue(e.target,e.value,g.kL.Remote,e.cheatId):!1}));this.__wandRemoteTrainerInfo=e??null;const s=e?.trainerId||null,i=(s?e?.gameId:null)||null,n=(s?e?.supportedVersions:null)||[];if(s===this.#ke&&t===this.#Ee)return;"
SearchHints = new[] { "setCurrentTrainer(" },
Locate = LocateBridgeBindHandler
},
new PatchEntry
{
Name = "remoteBridgeValueDelta",
SearchHints = new[] { "client-value-changed" },
Target = new Regex(@"#ct\(e,t\)\{t\.push\(e\.onValueSet\(e=>\{this\.status===i\.Connected&&e\.source!==g\.kL\.Remote&&this\.#Me\?\.send\(""client-value-changed"",\{instanceId:this\.#Pe,name:e\.name,value:e\.value,cheatId:e\.cheatId\}\)\}\)\),this\.#Be\(\)\}"),
Patch = "#ct(e,t){t.push(e.onValueSet(e=>{this.status===i.Connected&&e.source!==g.kL.Remote&&this.#Me?.send(\"client-value-changed\",{instanceId:this.#Pe,name:e.name,value:e.value,cheatId:e.cheatId}),this.__wandRemoteBridge?.valueChanged({trainerId:this.#ke,target:e.name,value:e.value,oldValue:e.oldValue,source:String(e.source??\"desktop\"),cheatId:e.cheatId})})),this.#Be()}"
Locate = LocateBridgeValueDelta
}
}
}
};
}
/// <summary>Wraps the account-returning promise so the resolved account always reports an active subscription.</summary>
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*(?<account>[\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));
}
/// <summary>Clears the bridge alongside the session fields the reset method already nulls out.</summary>
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")));
}
/// <summary>
/// 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.
/// </summary>
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\.(?<trainer>#[\w$]+)\s*\?\.\s*getMetadata", "trainer"),
"metadata", method.Resolve(@"getMetadata\(\s*(?<metadata>[\w$]+\.[\w$]+)\s*\)", "metadata"));
var edits = new List<JsEdit> { new JsEdit(js.MatchClose(sendOpen) + 1, payload) };
edits.AddRange(HoistConnectedGuard(js, sendOpen));
return edits.ToArray();
}
/// <summary>
/// Some builds wrap the whole snapshot method in <c>if (status === Connected)</c>. 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.
/// </summary>
private static IEnumerable<JsEdit> 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 == '?';
}
/// <summary>Match that must be unambiguous: zero or several hits mean an unsupported build.</summary>
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(@"(?<app>[\w$]+)\.whenReady\(\)\.then\(");
private static readonly Regex WhenReadyThenRun = new Regex(@"(?<app>[\w$]+)\.whenReady\(\)\.then\(run\)");
private static readonly Regex RemoteSetValue =
new Regex(@"this\.(?<trainer>#[\w$]+)\.setValue\(\s*e\.name\s*,\s*e\.value\s*,\s*(?<source>[^,]+?)\s*,");
}
}
+343
View File
@@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using WandEnhancer.View.MainWindow;
namespace WandEnhancer.Core
{
/// <summary>
/// Starts Wand and keeps the ASAR integrity fuse cleared in every process Electron spawns,
/// for as long as Wand runs. Covering only the startup burst is not enough: the renderer
/// behind the in-game overlay is created when a game launches, and exits with -36861 the
/// moment it opens the patched archive, leaving the overlay dead while Wand itself looks
/// healthy.
/// Wand is put in a job object, which every descendant joins on its own, and the kernel
/// posts each new process to a completion port. A debugger would report the same events, but
/// it is inherited too - by a game started from Wand included - and games treat a debug port
/// as tampering. Nothing here is attached to the game beyond reading its image path.
/// </summary>
internal static class FuseLauncher
{
private const int AsarIntegrityExitCode = -36861;
/// <returns>False when the session ended badly enough to be worth showing the user.</returns>
public static bool Launch(string exePath, string args, Action<string, ELogType> log = null)
{
long stateRva = ElectronFuse.FindStateRva(exePath);
var startupInfo = new STARTUPINFO { cb = Marshal.SizeOf<STARTUPINFO>() };
var commandLine = new StringBuilder(
string.IsNullOrEmpty(args) ? $"\"{exePath}\"" : $"\"{exePath}\" {args}");
// Suspended, so the fuse is cleared and the job is attached before Wand runs its
// first instruction. Every child is then born inside the job.
if (!CreateProcessW(null, commandLine, IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED,
IntPtr.Zero, System.IO.Path.GetDirectoryName(exePath), ref startupInfo, out var info))
{
log?.Invoke($"Could not start Wand (win32 error {Marshal.GetLastWin32Error()}).", ELogType.Error);
return false;
}
IntPtr job = IntPtr.Zero;
IntPtr port = IntPtr.Zero;
bool resumed = false;
try
{
log?.Invoke($"Started {exePath} as pid {info.dwProcessId}.", ELogType.Info);
if (stateRva < 0)
{
log?.Invoke($"No Electron fuse block in {exePath}. A patched Wand will exit " +
$"with {AsarIntegrityExitCode}; an unpatched one is unaffected.", ELogType.Error);
return false;
}
bool mainCleared = ElectronFuse.ClearIn(info.hProcess, stateRva);
log?.Invoke(mainCleared
? $"pid {info.dwProcessId} started - fuse cleared."
: $"Fuse not cleared in pid {info.dwProcessId}; it may exit with {AsarIntegrityExitCode}.",
mainCleared ? ELogType.Info : ELogType.Warn);
if (!TryTrackChildren(info.hProcess, out job, out port))
{
log?.Invoke($"Could not watch Wand for new processes (win32 error {Marshal.GetLastWin32Error()}). " +
"Wand will run, but the in-game overlay will not.", ELogType.Error);
return false;
}
ResumeThread(info.hThread);
resumed = true;
ClearFuseInNewProcesses(port, exePath, stateRva, info.dwProcessId, mainCleared, log);
if (!GetExitCodeProcess(info.hProcess, out int exitCode))
{
log?.Invoke("Wand exited, and its exit code could not be read.", ELogType.Error);
return false;
}
log?.Invoke($"Wand exited with code {DescribeCode(exitCode)}.",
exitCode == 0 ? ELogType.Info : ELogType.Error);
return exitCode == 0;
}
finally
{
if (!resumed)
{
ResumeThread(info.hThread);
}
CloseHandle(info.hThread);
CloseHandle(info.hProcess);
if (port != IntPtr.Zero)
{
CloseHandle(port);
}
if (job != IntPtr.Zero)
{
CloseHandle(job);
}
}
}
/// <summary>
/// No limits are set on the job: it exists only to be told about new processes. That also
/// keeps KILL_ON_JOB_CLOSE off, so Wand outlives the launcher rather than dying with it.
/// </summary>
private static bool TryTrackChildren(IntPtr process, out IntPtr job, out IntPtr port)
{
port = IntPtr.Zero;
job = CreateJobObject(IntPtr.Zero, null);
if (job == IntPtr.Zero)
{
return false;
}
port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, IntPtr.Zero, UIntPtr.Zero, 1);
if (port == IntPtr.Zero)
{
return false;
}
var association = new JOBOBJECT_ASSOCIATE_COMPLETION_PORT { CompletionKey = IntPtr.Zero, CompletionPort = port };
return SetInformationJobObject(job, JobObjectAssociateCompletionPortInformation,
ref association, Marshal.SizeOf(association))
&& AssignProcessToJobObject(job, process);
}
/// <summary>Blocks until the last process in the job is gone.</summary>
private static void ClearFuseInNewProcesses(IntPtr port, string exePath, long stateRva,
int mainProcessId, bool mainCleared, Action<string, ELogType> log)
{
var tracked = new Dictionary<int, IntPtr>();
int cleared = mainCleared ? 1 : 0;
int missed = mainCleared ? 0 : 1;
try
{
while (GetQueuedCompletionStatus(port, out uint message, out _, out IntPtr value, INFINITE))
{
if (message == JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO)
{
break;
}
int processId = value.ToInt32();
if (message == JOB_OBJECT_MSG_EXIT_PROCESS || message == JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS)
{
ReportExit(tracked, processId, log);
continue;
}
// The main process is announced here too, having been patched while it was
// still suspended, and a game started from Wand joins the job like any child.
if (message != JOB_OBJECT_MSG_NEW_PROCESS || processId == mainProcessId ||
!IsImage(processId, exePath))
{
continue;
}
// The handle is kept open: it is what makes the exit code readable later, and
// it also stops Windows handing the pid to someone else in the meantime.
IntPtr process = OpenProcess(ProcessAccess, false, processId);
if (process != IntPtr.Zero)
{
tracked[processId] = process;
}
if (process != IntPtr.Zero && ElectronFuse.ClearIn(process, stateRva))
{
cleared++;
log?.Invoke($"pid {processId} started - fuse cleared.", ELogType.Info);
}
else
{
missed++;
log?.Invoke($"Fuse not cleared in pid {processId}; it may exit with {AsarIntegrityExitCode}.",
ELogType.Warn);
}
}
}
finally
{
foreach (var handle in tracked.Values)
{
CloseHandle(handle);
}
}
log?.Invoke($"Wand closed: fuse cleared in {cleared} processes" + (missed == 0 ? "." : $", {missed} missed."),
missed == 0 ? ELogType.Info : ELogType.Warn);
}
/// <summary>
/// Only anomalies are reported: on a normal shutdown every process exits with 0, and a
/// line each would bury the one death that matters.
/// </summary>
private static void ReportExit(Dictionary<int, IntPtr> tracked, int processId, Action<string, ELogType> log)
{
if (!tracked.TryGetValue(processId, out IntPtr process))
{
return;
}
tracked.Remove(processId);
if (GetExitCodeProcess(process, out int exitCode) && exitCode != 0)
{
log?.Invoke($"pid {processId} exited with code {DescribeCode(exitCode)}.", ELogType.Error);
}
CloseHandle(process);
}
/// <summary>
/// Identity check before anything heavier: a game started from Wand is in the job as well,
/// and is opened for nothing beyond the right the task manager uses to read a path.
/// </summary>
private static bool IsImage(int processId, string exePath)
{
IntPtr process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId);
if (process == IntPtr.Zero)
{
return false;
}
try
{
var path = new StringBuilder(MaxPathLength);
int length = path.Capacity;
return QueryFullProcessImageName(process, 0, path, ref length) &&
string.Equals(path.ToString(), exePath, StringComparison.OrdinalIgnoreCase);
}
finally
{
CloseHandle(process);
}
}
private static string DescribeCode(int code)
{
switch (code)
{
case 0: return "0";
case AsarIntegrityExitCode:
return $"{code} (ASAR integrity check failed - the fuse was not cleared in time)";
// Chromium breaks into a debugger that is not there when it hits a fatal error.
case unchecked((int)0x80000003): return $"0x{code:X8} (Wand aborted itself during startup)";
case unchecked((int)0xC0000005): return $"0x{code:X8} (access violation)";
case unchecked((int)0xC0000135): return $"0x{code:X8} (a required DLL is missing)";
case unchecked((int)0xC0000142): return $"0x{code:X8} (a DLL failed to initialise)";
case unchecked((int)0xC0000409): return $"0x{code:X8} (stack buffer overrun)";
default: return $"{code} (0x{code:X8})";
}
}
#region P/Invoke
private const uint CREATE_SUSPENDED = 0x4;
private const uint ProcessAccess = 0x0008 | 0x0010 | 0x0020 | 0x0400;
private const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
private const int MaxPathLength = 260;
private const int JobObjectAssociateCompletionPortInformation = 7;
private const uint JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO = 4;
private const uint JOB_OBJECT_MSG_NEW_PROCESS = 6;
private const uint JOB_OBJECT_MSG_EXIT_PROCESS = 7;
private const uint JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS = 8;
private const uint INFINITE = 0xFFFFFFFF;
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[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;
}
[StructLayout(LayoutKind.Sequential)]
private struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT
{
public IntPtr CompletionKey;
public IntPtr CompletionPort;
}
[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 uint ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetInformationJobObject(
IntPtr hJob, int jobObjectInformationClass,
ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT lpJobObjectInformation, int cbJobObjectInformationLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateIoCompletionPort(
IntPtr fileHandle, IntPtr existingCompletionPort, UIntPtr completionKey, uint numberOfConcurrentThreads);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetQueuedCompletionStatus(
IntPtr completionPort, out uint lpNumberOfBytes, out IntPtr lpCompletionKey,
out IntPtr lpOverlapped, uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool QueryFullProcessImageName(
IntPtr hProcess, uint dwFlags, StringBuilder lpExeName, ref int lpdwSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetExitCodeProcess(IntPtr hProcess, out int lpExitCode);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
#endregion
}
}
@@ -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<string, ELogType> _logger;
public JavaScriptPatchApplier(Action<string, ELogType> 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);
}
}
}
+409
View File
@@ -0,0 +1,409 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace WandEnhancer.Core.Js
{
/// <summary>
/// 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.
/// </summary>
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(@"(?<![\w$.])function\s*\*?\s*[\w$]*\s*\(");
private static readonly HashSet<string> BlockKeywords =
new HashSet<string>(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<string> RegexPrecedingKeywords =
new HashSet<string>(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);
}
/// <summary>Index of the delimiter closing the one at <paramref name="openIndex"/>, or -1.</summary>
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;
}
/// <summary>Open delimiters enclosing <paramref name="index"/>, innermost first.</summary>
public List<int> OpenerStack(int index)
{
var stack = new List<int>();
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;
}
/// <summary>Innermost enclosing delimiter of the given kind, or -1.</summary>
public int EnclosingOpener(int index, char kind)
{
foreach (int opener in OpenerStack(index))
{
if (_text[opener] == kind)
{
return opener;
}
}
return -1;
}
/// <summary>Innermost named function or method whose body contains <paramref name="index"/>.</summary>
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;
}
/// <summary>The named function whose body closes at <paramref name="closeIndex"/>, or null.</summary>
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]);
}
/// <summary>First function declared as <c>name(...)</c>, ignoring property and call sites.</summary>
public JsFunction FindFunction(string name)
{
var pattern = new Regex($@"(?<![#\w$.]){Regex.Escape(name)}\s*\(");
for (var match = pattern.Match(_text); match.Success; match = match.NextMatch())
{
int closeParen = MatchClose(match.Index + match.Length - 1);
if (closeParen < 0)
{
continue;
}
int bodyOpen = SkipWhitespaceForward(closeParen + 1);
if (bodyOpen < _text.Length && _text[bodyOpen] == '{')
{
var function = ReadFunctionAt(bodyOpen);
if (function != null && function.Name == name)
{
return function;
}
}
}
return null;
}
/// <summary>First <c>function name(...) { }</c> declared at or after <paramref name="index"/>.</summary>
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;
}
/// <summary>
/// Index of the opening parenthesis of <c>callee(... "literal" ...)</c>, or -1. Wand reuses the
/// same channel names for inbound listeners and outbound sends, so the callee disambiguates.
/// </summary>
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;
}
/// <summary>Trailing identifier directly before <paramref name="index"/>, e.g. <c>send</c> of <c>a?.send(</c>.</summary>
public string NameBefore(int index)
{
int end = SkipWhitespaceBack(index - 1) + 1;
var match = MatchNameEndingAt(end);
return match.Success ? match.Value.TrimStart('#') : null;
}
/// <summary>Identifier ending at <paramref name="end"/>, searched in a bounded window so
/// multi-megabyte bundles are not copied on every lookup.</summary>
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));
}
/// <summary>The identifier ending at <paramref name="end"/> inclusive, or "" when there is none.</summary>
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));
}
}
}
}
+129
View File
@@ -0,0 +1,129 @@
using System;
using System.Text.RegularExpressions;
namespace WandEnhancer.Core.Js
{
/// <summary>A named function or class method located in a bundle, addressed by delimiter position.</summary>
internal sealed class JsFunction
{
private static readonly Regex ReturnKeyword = new Regex(@"(?<![\w$])return(?![\w$])");
private readonly string _source;
private JsCursor _body;
public JsFunction(string name, int start, int bodyOpen, int bodyClose, string source)
{
Name = name;
Start = start;
BodyOpen = bodyOpen;
BodyClose = bodyClose;
_source = source;
}
public string Name { get; }
public int Start { get; }
public int BodyOpen { get; }
public int BodyClose { get; }
public string Body => _source.Substring(BodyOpen + 1, BodyClose - BodyOpen - 1);
private JsCursor BodyCursor => _body ?? (_body = new JsCursor(Body));
/// <summary>Captures a group from a pattern matched against this body only, not the whole bundle.</summary>
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;
}
/// <summary>Rewrites the first match of a pattern scoped to this body; <c>${group}</c> back-references work.</summary>
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);
/// <summary>
/// Rewrites the last top-level <c>return X</c> as <c>return WRAPPER</c>, where the wrapper's
/// <c>$0</c> placeholder receives the original expression.
/// </summary>
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;
}
}
/// <summary>A splice: replace <c>[Start, End)</c> of the bundle with <see cref="Text"/>.</summary>
internal sealed class JsEdit
{
public JsEdit(int start, int end, string text)
{
Start = start;
End = end;
Text = text;
}
/// <summary>An insertion at <paramref name="at"/>, replacing nothing.</summary>
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);
}
}
+63
View File
@@ -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
{
/// <summary>
/// Loads injected JavaScript from embedded <c>Patches/*.js</c> files so payloads stay
/// lintable source rather than escaped C# string literals.
/// </summary>
internal static class PatchPayload
{
private const string ResourcePrefix = "patches/";
private static readonly ConcurrentDictionary<string, string> Cache =
new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
private static readonly Regex Placeholder = new Regex(@"\$\{(?<name>\w+)\}");
/// <summary>
/// Loads a payload, replacing each <c>${name}</c> 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.
/// </summary>
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<string, string>(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();
}
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
using System;
using System.IO;
using WandEnhancer.View.MainWindow;
namespace WandEnhancer.Core
{
/// <summary>
/// Append-only log written next to the deployed launcher. Launch mode has no window and
/// exits as soon as Wand is up, so without this file a "Wand does not start" report
/// carries no evidence at all. Every operation swallows its own failure: diagnostics must
/// never be the reason Wand fails to launch.
/// </summary>
internal static class LauncherLog
{
public const string FileName = "launcher.log";
private const long MaxBytes = 512 * 1024;
private static string _path;
public static void Open(string launcherDirectory, string header)
{
try
{
var file = new FileInfo(Path.Combine(launcherDirectory, FileName));
// Dropped whole rather than trimmed: the session being diagnosed is the last
// one, and keeping half a rotated file is not worth the code.
if (file.Exists && file.Length > MaxBytes)
{
file.Delete();
}
_path = file.FullName;
Write($"=== {DateTime.Now:yyyy-MM-dd} {header}", ELogType.Info);
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException ||
e is ArgumentException || e is NotSupportedException)
{
_path = null;
}
}
public static void Write(string message, ELogType type)
{
if (_path == null)
{
return;
}
try
{
File.AppendAllText(_path,
$"{DateTime.Now:HH:mm:ss.fff} [{type.ToString().ToUpperInvariant()}] {message}{Environment.NewLine}");
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
{
// A log line lost to a locked or full disk must not abort the launch.
}
}
}
}
@@ -28,6 +28,22 @@ namespace WandEnhancer.Core.Services
private static CultureInfo _currentLanguage;
private static ResourceDictionary _englishBaseDictionary;
private static ResourceDictionary _activeLocaleDictionary;
/// <summary>
/// Localized string for <paramref name="key"/>, falling back to the key itself so a
/// missing entry is visible rather than silently blank.
/// </summary>
public static string Get(string key)
{
return Application.Current?.TryFindResource(key) as string ?? key;
}
/// <summary>Localized format string filled with <paramref name="args"/>.</summary>
public static string Format(string key, params object[] args)
{
return string.Format(Get(key), args);
}
public static CultureInfo CurrentLanguage
{
@@ -104,20 +120,19 @@ namespace WandEnhancer.Core.Services
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)
{
@@ -27,8 +27,7 @@ namespace WandEnhancer.Core.Services
}
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 @@ namespace WandEnhancer.Core.Services
}
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.
}
}
}
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Ordnerpfad</s:String>
<s:String x:Key="mw_folder_not_found">Ordner nicht gefunden</s:String>
<s:String x:Key="mw_patch">Anwenden</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Ausgewählte .js-Dateien werden in Wand gepackt und im Renderer geladen.</s:String>
<s:String x:Key="pv_no_custom_scripts">Keine Skripte ausgewählt</s:String>
<s:String x:Key="pv_start">Starten</s:String>
<s:String x:Key="pv_auto_apply">Nach Updates automatisch anwenden</s:String>
<s:String x:Key="pv_popup_title">Was werden wir verbessern?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">WeMod-Verzeichnis unter {0} ({1}) gefunden</s:String>
<s:String x:Key="log_already_patched">WeMod ist bereits gepatcht. Wenn Sie erneut patchen möchten, stellen Sie bitte zuerst das Backup wieder her.</s:String>
<s:String x:Key="log_ready">Bereit zum Patchen.</s:String>
<s:String x:Key="log_install_not_found">WeMod-Verzeichnis nicht gefunden.</s:String>
<s:String x:Key="log_no_directory">Vorgang nicht möglich. Bitte geben Sie zuerst das Verzeichnis an.</s:String>
<s:String x:Key="log_invalid_directory">Der ausgewählte Ordner {0} ist kein gültiges WeMod-Verzeichnis.</s:String>
<s:String x:Key="log_restore_failed">Fehler beim Wiederherstellen des Backups: {0}</s:String>
<s:String x:Key="log_patch_failed">Fehler beim Patchen: {0}</s:String>
<s:String x:Key="log_copied">Protokolle in die Zwischenablage kopiert.</s:String>
<s:String x:Key="log_copy_failed">Fehler beim Kopieren der Protokolle: {0}</s:String>
<s:String x:Key="log_exported">Protokolle nach {0} exportiert.</s:String>
<s:String x:Key="log_export_failed">Fehler beim Exportieren der Protokolle: {0}</s:String>
<s:String x:Key="log_open_link_failed">{0} konnte nicht in einem Browser geöffnet werden.</s:String>
<s:String x:Key="dialog_pick_install">Wählen Sie das WeMod-Verzeichnis aus</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Folder path</s:String>
<s:String x:Key="mw_folder_not_found">Folder not found</s:String>
<s:String x:Key="mw_patch">Enhance</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Selected .js files are packed into Wand and loaded in the renderer.</s:String>
<s:String x:Key="pv_no_custom_scripts">No scripts selected</s:String>
<s:String x:Key="pv_start">Start</s:String>
<s:String x:Key="pv_auto_apply">Auto-apply after updates</s:String>
<s:String x:Key="pv_popup_title">What are we gonna enhance?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">WeMod directory found at {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod already patched. If you want to patch again, please restore the backup first.</s:String>
<s:String x:Key="log_ready">Ready for patching.</s:String>
<s:String x:Key="log_install_not_found">WeMod directory not found.</s:String>
<s:String x:Key="log_no_directory">Cant be done. Please specify the directory first.</s:String>
<s:String x:Key="log_invalid_directory">The selected folder {0} is not a valid WeMod directory.</s:String>
<s:String x:Key="log_restore_failed">Failed to restore backup: {0}</s:String>
<s:String x:Key="log_patch_failed">Failed to patch: {0}</s:String>
<s:String x:Key="log_copied">Logs copied to clipboard.</s:String>
<s:String x:Key="log_copy_failed">Failed to copy logs: {0}</s:String>
<s:String x:Key="log_exported">Logs exported to {0}.</s:String>
<s:String x:Key="log_export_failed">Failed to export logs: {0}</s:String>
<s:String x:Key="log_open_link_failed">Could not open {0} in a browser.</s:String>
<s:String x:Key="dialog_pick_install">Select the WeMod directory</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Ruta de la carpeta</s:String>
<s:String x:Key="mw_folder_not_found">Carpeta no encontrada</s:String>
<s:String x:Key="mw_patch">Aplicar</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Los archivos .js seleccionados se empaquetan en Wand y se cargan en el renderer.</s:String>
<s:String x:Key="pv_no_custom_scripts">No hay scripts seleccionados</s:String>
<s:String x:Key="pv_start">Iniciar</s:String>
<s:String x:Key="pv_auto_apply">Aplicar automáticamente tras actualizar</s:String>
<s:String x:Key="pv_popup_title">¿Qué vamos a mejorar?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Directorio de WeMod encontrado en {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod ya está parcheado. Si quieres parchear de nuevo, restaura la copia de seguridad primero.</s:String>
<s:String x:Key="log_ready">Listo para parchear.</s:String>
<s:String x:Key="log_install_not_found">Directorio de WeMod no encontrado.</s:String>
<s:String x:Key="log_no_directory">No se puede realizar. Por favor, especifica el directorio primero.</s:String>
<s:String x:Key="log_invalid_directory">La carpeta seleccionada {0} no es un directorio de WeMod válido.</s:String>
<s:String x:Key="log_restore_failed">Error al restaurar la copia de seguridad: {0}</s:String>
<s:String x:Key="log_patch_failed">Error al parchear: {0}</s:String>
<s:String x:Key="log_copied">Registros copiados al portapapeles.</s:String>
<s:String x:Key="log_copy_failed">Error al copiar los registros: {0}</s:String>
<s:String x:Key="log_exported">Registros exportados a {0}.</s:String>
<s:String x:Key="log_export_failed">Error al exportar los registros: {0}</s:String>
<s:String x:Key="log_open_link_failed">No se pudo abrir {0} en un navegador.</s:String>
<s:String x:Key="dialog_pick_install">Selecciona el directorio de WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Chemin du dossier</s:String>
<s:String x:Key="mw_folder_not_found">Dossier non trouvé</s:String>
<s:String x:Key="mw_patch">Appliquer</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Les fichiers .js sélectionnés sont intégrés dans Wand et chargés dans le renderer.</s:String>
<s:String x:Key="pv_no_custom_scripts">Aucun script sélectionné</s:String>
<s:String x:Key="pv_start">Démarrer</s:String>
<s:String x:Key="pv_auto_apply">Appliquer automatiquement après les mises à jour</s:String>
<s:String x:Key="pv_popup_title">Qu'allons-nous modifier ?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Répertoire WeMod trouvé à {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod est déjà patché. Si vous souhaitez le patcher à nouveau, veuillez d'abord restaurer la sauvegarde.</s:String>
<s:String x:Key="log_ready">Prêt pour le patch.</s:String>
<s:String x:Key="log_install_not_found">Répertoire WeMod introuvable.</s:String>
<s:String x:Key="log_no_directory">Impossible. Veuillez d'abord spécifier le répertoire.</s:String>
<s:String x:Key="log_invalid_directory">Le dossier sélectionné {0} n'est pas un répertoire WeMod valide.</s:String>
<s:String x:Key="log_restore_failed">Échec de la restauration de la sauvegarde : {0}</s:String>
<s:String x:Key="log_patch_failed">Échec du patch : {0}</s:String>
<s:String x:Key="log_copied">Journaux copiés dans le presse-papiers.</s:String>
<s:String x:Key="log_copy_failed">Échec de la copie des journaux : {0}</s:String>
<s:String x:Key="log_exported">Journaux exportés vers {0}.</s:String>
<s:String x:Key="log_export_failed">Échec de l'exportation des journaux : {0}</s:String>
<s:String x:Key="log_open_link_failed">Impossible d'ouvrir {0} dans un navigateur.</s:String>
<s:String x:Key="dialog_pick_install">Sélectionnez le répertoire WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Percorso cartella</s:String>
<s:String x:Key="mw_folder_not_found">Cartella non trovata</s:String>
<s:String x:Key="mw_patch">Applica</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">I file .js selezionati vengono inseriti in Wand e caricati nel renderer.</s:String>
<s:String x:Key="pv_no_custom_scripts">Nessuno script selezionato</s:String>
<s:String x:Key="pv_start">Avvia</s:String>
<s:String x:Key="pv_auto_apply">Applica automaticamente dopo gli aggiornamenti</s:String>
<s:String x:Key="pv_popup_title">Cosa modificheremo?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Directory di WeMod trovata in {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod è già stato patchato. Se vuoi patchare di nuovo, ripristina prima il backup.</s:String>
<s:String x:Key="log_ready">Pronto per il patching.</s:String>
<s:String x:Key="log_install_not_found">Directory di WeMod non trovata.</s:String>
<s:String x:Key="log_no_directory">Impossibile procedere. Specifica prima la directory.</s:String>
<s:String x:Key="log_invalid_directory">La cartella selezionata {0} non è una directory valida di WeMod.</s:String>
<s:String x:Key="log_restore_failed">Impossibile ripristinare il backup: {0}</s:String>
<s:String x:Key="log_patch_failed">Impossibile eseguire il patch: {0}</s:String>
<s:String x:Key="log_copied">Log copiati negli appunti.</s:String>
<s:String x:Key="log_copy_failed">Impossibile copiare i log: {0}</s:String>
<s:String x:Key="log_exported">Log esportati in {0}.</s:String>
<s:String x:Key="log_export_failed">Impossibile esportare i log: {0}</s:String>
<s:String x:Key="log_open_link_failed">Impossibile aprire {0} in un browser.</s:String>
<s:String x:Key="dialog_pick_install">Seleziona la directory di WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">フォルダパス</s:String>
<s:String x:Key="mw_folder_not_found">フォルダが見つかりません</s:String>
<s:String x:Key="mw_patch">適用</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">選択した .js ファイルは Wand に組み込まれ、レンダラーで読み込まれます。</s:String>
<s:String x:Key="pv_no_custom_scripts">スクリプトが選択されていません</s:String>
<s:String x:Key="pv_start">開始</s:String>
<s:String x:Key="pv_auto_apply">更新後に自動適用</s:String>
<s:String x:Key="pv_popup_title">何を改善しますか?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">WeModディレクトリが {0} ({1}) に見つかりました</s:String>
<s:String x:Key="log_already_patched">WeModは既にパッチが適用されています。もう一度パッチを適用する場合は、まずバックアップを復元してください。</s:String>
<s:String x:Key="log_ready">パッチ適用の準備ができました。</s:String>
<s:String x:Key="log_install_not_found">WeModディレクトリが見つかりません。</s:String>
<s:String x:Key="log_no_directory">実行できません。先にディレクトリを指定してください。</s:String>
<s:String x:Key="log_invalid_directory">選択したフォルダ {0} は有効なWeModディレクトリではありません。</s:String>
<s:String x:Key="log_restore_failed">バックアップの復元に失敗しました: {0}</s:String>
<s:String x:Key="log_patch_failed">パッチの適用に失敗しました: {0}</s:String>
<s:String x:Key="log_copied">ログをクリップボードにコピーしました。</s:String>
<s:String x:Key="log_copy_failed">ログのコピーに失敗しました: {0}</s:String>
<s:String x:Key="log_exported">ログを {0} にエクスポートしました。</s:String>
<s:String x:Key="log_export_failed">ログのエクスポートに失敗しました: {0}</s:String>
<s:String x:Key="log_open_link_failed">{0} をブラウザで開くことができませんでした。</s:String>
<s:String x:Key="dialog_pick_install">WeModディレクトリを選択してください</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Ścieżka folderu</s:String>
<s:String x:Key="mw_folder_not_found">Folder nie znaleziony</s:String>
<s:String x:Key="mw_patch">Zastosuj</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Wybrane pliki .js są pakowane do Wand i ładowane w rendererze.</s:String>
<s:String x:Key="pv_no_custom_scripts">Nie wybrano skryptów</s:String>
<s:String x:Key="pv_start">Rozpocznij</s:String>
<s:String x:Key="pv_auto_apply">Zastosuj automatycznie po aktualizacji</s:String>
<s:String x:Key="pv_popup_title">Co będziemy ulepszać?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Katalog WeMod znaleziony w {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod został już zaktualizowany. Jeśli chcesz zaktualizować ponownie, najpierw przywróć kopię zapasową.</s:String>
<s:String x:Key="log_ready">Gotowy do aktualizacji (patchowania).</s:String>
<s:String x:Key="log_install_not_found">Nie znaleziono katalogu WeMod.</s:String>
<s:String x:Key="log_no_directory">Nie można tego zrobić. Proszę najpierw określić katalog.</s:String>
<s:String x:Key="log_invalid_directory">Wybrany folder {0} nie jest prawidłowym katalogiem WeMod.</s:String>
<s:String x:Key="log_restore_failed">Nie udało się przywrócić kopii zapasowej: {0}</s:String>
<s:String x:Key="log_patch_failed">Nie udało się zaktualizować: {0}</s:String>
<s:String x:Key="log_copied">Logi skopiowane do schowka.</s:String>
<s:String x:Key="log_copy_failed">Nie udało się skopiować logów: {0}</s:String>
<s:String x:Key="log_exported">Logi wyeksportowane do {0}.</s:String>
<s:String x:Key="log_export_failed">Nie udało się wyeksportować logów: {0}</s:String>
<s:String x:Key="log_open_link_failed">Nie można otworzyć {0} w przeglądarce.</s:String>
<s:String x:Key="dialog_pick_install">Wybierz katalog WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Caminho da pasta</s:String>
<s:String x:Key="mw_folder_not_found">Pasta não encontrada</s:String>
<s:String x:Key="mw_patch">Aplicar</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Os arquivos .js selecionados são empacotados no Wand e carregados no renderer.</s:String>
<s:String x:Key="pv_no_custom_scripts">Nenhum script selecionado</s:String>
<s:String x:Key="pv_start">Iniciar</s:String>
<s:String x:Key="pv_auto_apply">Aplicar automaticamente após atualizações</s:String>
<s:String x:Key="pv_popup_title">O que vamos melhorar?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Diretório do WeMod encontrado em {0} ({1})</s:String>
<s:String x:Key="log_already_patched">O WeMod já foi modificado. Se quiser modificar novamente, restaure o backup primeiro.</s:String>
<s:String x:Key="log_ready">Pronto para modificar.</s:String>
<s:String x:Key="log_install_not_found">Diretório do WeMod não encontrado.</s:String>
<s:String x:Key="log_no_directory">Não é possível fazer isso. Por favor, especifique o diretório primeiro.</s:String>
<s:String x:Key="log_invalid_directory">A pasta selecionada {0} não é um diretório válido do WeMod.</s:String>
<s:String x:Key="log_restore_failed">Falha ao restaurar o backup: {0}</s:String>
<s:String x:Key="log_patch_failed">Falha ao modificar: {0}</s:String>
<s:String x:Key="log_copied">Logs copiados para a área de transferência.</s:String>
<s:String x:Key="log_copy_failed">Falha ao copiar logs: {0}</s:String>
<s:String x:Key="log_exported">Logs exportados para {0}.</s:String>
<s:String x:Key="log_export_failed">Falha ao exportar logs: {0}</s:String>
<s:String x:Key="log_open_link_failed">Não foi possível abrir {0} no navegador.</s:String>
<s:String x:Key="dialog_pick_install">Selecione o diretório do WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Путь к папке</s:String>
<s:String x:Key="mw_folder_not_found">Папка не найдена</s:String>
<s:String x:Key="mw_patch">Применить</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Выбранные .js попадут в Wand и загрузятся в renderer.</s:String>
<s:String x:Key="pv_no_custom_scripts">Скрипты не выбраны</s:String>
<s:String x:Key="pv_start">Начать</s:String>
<s:String x:Key="pv_auto_apply">Авто-патч после обновлений</s:String>
<s:String x:Key="pv_popup_title">Что будем улучшать?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Директория WeMod найдена в {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod уже пропатчен. Если вы хотите пропатчить снова, сначала восстановите резервную копию.</s:String>
<s:String x:Key="log_ready">Готово к патчингу.</s:String>
<s:String x:Key="log_install_not_found">Директория WeMod не найдена.</s:String>
<s:String x:Key="log_no_directory">Невозможно выполнить. Пожалуйста, сначала укажите директорию.</s:String>
<s:String x:Key="log_invalid_directory">Выбранная папка {0} не является допустимой директорией WeMod.</s:String>
<s:String x:Key="log_restore_failed">Не удалось восстановить резервную копию: {0}</s:String>
<s:String x:Key="log_patch_failed">Не удалось пропатчить: {0}</s:String>
<s:String x:Key="log_copied">Логи скопированы в буфер обмена.</s:String>
<s:String x:Key="log_copy_failed">Не удалось скопировать логи: {0}</s:String>
<s:String x:Key="log_exported">Логи экспортированы в {0}.</s:String>
<s:String x:Key="log_export_failed">Не удалось экспортировать логи: {0}</s:String>
<s:String x:Key="log_open_link_failed">Не удалось открыть {0} в браузере.</s:String>
<s:String x:Key="dialog_pick_install">Выберите директорию WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Klasör yolu</s:String>
<s:String x:Key="mw_folder_not_found">Klasör bulunamadı</s:String>
<s:String x:Key="mw_patch">Uygula</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Seçilen .js dosyaları Wand içine paketlenir ve renderer'da yüklenir.</s:String>
<s:String x:Key="pv_no_custom_scripts">Betik seçilmedi</s:String>
<s:String x:Key="pv_start">Başlat</s:String>
<s:String x:Key="pv_auto_apply">Güncellemelerden sonra otomatik uygula</s:String>
<s:String x:Key="pv_popup_title">Neyi geliştireceğiz?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">WeMod dizini {0} konumunda bulundu ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod zaten yamanmış. Tekrar yamamak istiyorsanız, lütfen önce yedeği geri yükleyin.</s:String>
<s:String x:Key="log_ready">Yama işlemi için hazır.</s:String>
<s:String x:Key="log_install_not_found">WeMod dizini bulunamadı.</s:String>
<s:String x:Key="log_no_directory">İşlem yapılamıyor. Lütfen önce dizini belirtin.</s:String>
<s:String x:Key="log_invalid_directory">Seçilen {0} klasörü geçerli bir WeMod dizini değil.</s:String>
<s:String x:Key="log_restore_failed">Yedek geri yüklenemedi: {0}</s:String>
<s:String x:Key="log_patch_failed">Yama yapılamadı: {0}</s:String>
<s:String x:Key="log_copied">Günlükler panoya kopyalandı.</s:String>
<s:String x:Key="log_copy_failed">Günlükler kopyalanamadı: {0}</s:String>
<s:String x:Key="log_exported">Günlükler {0} konumuna dışa aktarıldı.</s:String>
<s:String x:Key="log_export_failed">Günlükler dışa aktarılamadı: {0}</s:String>
<s:String x:Key="log_open_link_failed">{0} bir tarayıcıda açılamadı.</s:String>
<s:String x:Key="dialog_pick_install">WeMod dizinini seçin</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">Шлях до папки</s:String>
<s:String x:Key="mw_folder_not_found">Папку не знайдено</s:String>
<s:String x:Key="mw_patch">Застосувати</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">Вибрані файли .js пакуються у Wand і завантажуються в рендерері.</s:String>
<s:String x:Key="pv_no_custom_scripts">Скрипти не вибрано</s:String>
<s:String x:Key="pv_start">Почати</s:String>
<s:String x:Key="pv_auto_apply">Автоматично застосовувати після оновлень</s:String>
<s:String x:Key="pv_popup_title">Що будемо покращувати?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">Директорію WeMod знайдено в {0} ({1})</s:String>
<s:String x:Key="log_already_patched">WeMod вже пропатчено. Якщо ви хочете пропатчити знову, спершу відновіть резервну копію.</s:String>
<s:String x:Key="log_ready">Готово до патчингу.</s:String>
<s:String x:Key="log_install_not_found">Директорію WeMod не знайдено.</s:String>
<s:String x:Key="log_no_directory">Не вдається виконати. Будь ласка, спочатку вкажіть директорію.</s:String>
<s:String x:Key="log_invalid_directory">Вибрана папка {0} не є дійсною директорією WeMod.</s:String>
<s:String x:Key="log_restore_failed">Не вдалося відновити резервну копію: {0}</s:String>
<s:String x:Key="log_patch_failed">Не вдалося пропатчити: {0}</s:String>
<s:String x:Key="log_copied">Логи скопійовано в буфер обміну.</s:String>
<s:String x:Key="log_copy_failed">Не вдалося скопіювати логи: {0}</s:String>
<s:String x:Key="log_exported">Логи експортовано до {0}.</s:String>
<s:String x:Key="log_export_failed">Не вдалося експортувати логи: {0}</s:String>
<s:String x:Key="log_open_link_failed">Не вдалося відкрити {0} у браузері.</s:String>
<s:String x:Key="dialog_pick_install">Виберіть директорію WeMod</s:String>
<!--#endregion -->
</ResourceDictionary>
+18 -1
View File
@@ -7,7 +7,6 @@
<!--#endregion -->
<!--#region MainWindow -->
<s:String x:Key="mw_title">WandEnhancer</s:String>
<s:String x:Key="mw_folder_path">文件夹路径</s:String>
<s:String x:Key="mw_folder_not_found">未找到文件夹</s:String>
<s:String x:Key="mw_patch">增强</s:String>
@@ -35,7 +34,25 @@
<s:String x:Key="pv_custom_scripts_hint">选中的 .js 文件会打包到 Wand 并在渲染器中加载。</s:String>
<s:String x:Key="pv_no_custom_scripts">未选择脚本</s:String>
<s:String x:Key="pv_start">开始</s:String>
<s:String x:Key="pv_auto_apply">更新后自动应用</s:String>
<s:String x:Key="pv_popup_title">我们要增强什么?</s:String>
<!--#endregion -->
<!--#region Runtime log -->
<s:String x:Key="log_install_found">在 {0} ({1}) 找到 WeMod 目录</s:String>
<s:String x:Key="log_already_patched">WeMod 已经修补过。如果想再次修补,请先恢复备份。</s:String>
<s:String x:Key="log_ready">准备修补。</s:String>
<s:String x:Key="log_install_not_found">未找到 WeMod 目录。</s:String>
<s:String x:Key="log_no_directory">无法执行。请先指定目录。</s:String>
<s:String x:Key="log_invalid_directory">选择的文件夹 {0} 不是有效的 WeMod 目录。</s:String>
<s:String x:Key="log_restore_failed">恢复备份失败: {0}</s:String>
<s:String x:Key="log_patch_failed">修补失败: {0}</s:String>
<s:String x:Key="log_copied">日志已复制到剪贴板。</s:String>
<s:String x:Key="log_copy_failed">复制日志失败: {0}</s:String>
<s:String x:Key="log_exported">日志已导出至 {0}。</s:String>
<s:String x:Key="log_export_failed">导出日志失败: {0}</s:String>
<s:String x:Key="log_open_link_failed">无法在浏览器中打开 {0}。</s:String>
<s:String x:Key="dialog_pick_install">选择 WeMod 目录</s:String>
<!--#endregion -->
</ResourceDictionary>
+4 -23
View File
@@ -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<EPatchType> PatchTypes { get; set; }
public List<string> CustomScriptPaths { get; set; } = new List<string>();
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");
}
}
/// <summary>When set, the patch selection is saved so the launcher re-applies it after a Wand update.</summary>
public bool AutoApplyAfterUpdate { get; set; }
}
}
}
-48
View File
@@ -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;
}
}
}
}
+1
View File
@@ -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){}})),
@@ -0,0 +1 @@
return Promise.reject(new Error("wand-enhancer: native mobile pairing disabled"))
+1
View File
@@ -0,0 +1 @@
"ACTION_CHECK_FOR_UPDATE",(e=>expectUpdateFeedUrl(e,(e=>null)))
@@ -0,0 +1 @@
account:((account)=>account&&"object"==typeof account?{...account,subscription:{period:"yearly",state:"active"}}:account)(${account})
+1
View File
@@ -0,0 +1 @@
$0.then((response)=>{response&&"object"==typeof response&&(response.subscription={period:"yearly",state:"active"});return response})
@@ -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()})
@@ -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;
@@ -0,0 +1 @@
;this.__wandRemoteTrainerInfo=null,this.__wandRemoteBridge?.sync(null)
@@ -0,0 +1 @@
,this.__wandRemoteBridge?.sync({${snapshot},trainerInfo:this.__wandRemoteTrainerInfo??null,metadata:this.${trainer}?.getMetadata(${metadata})??null})
@@ -0,0 +1 @@
,this.__wandRemoteBridge?.valueChanged({target:e.name,value:e.value,oldValue:e.oldValue,source:String(e.source??"desktop"),cheatId:e.cheatId})
+164 -14
View File
@@ -1,45 +1,195 @@
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
{
/// <summary>Log lines from a failed startup auto-patch, replayed by the UI when it opens.</summary>
public static readonly List<KeyValuePair<string, ELogType>> StartupLog =
new List<KeyValuePair<string, ELogType>>();
[STAThread]
public static void Main(string[] args)
{
if (TryLaunchMode(args))
return;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
List<LogEntry> logEntries = new List<LogEntry>();
if (args.Length > 0)
{
// TODO: Command line arguments handling
}
bool startupFailed = StartupLog.Exists(entry => entry.Value == ELogType.Error);
var application = new App();
application.InitializeComponent();
application.MainWindow = new MainWindow();
foreach (var logEntry in logEntries)
{
MainWindow.Instance.ViewModel.LogList.Add(logEntry);
}
var window = new MainWindow();
// Launch mode has no window at all, so a user whose Wand never opened would have to
// be told where launcher.log lives. Put the same lines in front of them instead.
if (startupFailed)
window.Loaded += (sender, e) => BringToFront(window);
application.MainWindow = window;
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);
string forwardedArgs = args.Length > 0 ? QuoteArguments(args) : null;
LauncherLog.Open(myDir, $"WandEnhancer {Constants.Version} | {myExe}" +
(forwardedArgs == null ? "" : $" | args {forwardedArgs}"));
if (args.Length > 0 &&
args[0].StartsWith("--squirrel", StringComparison.OrdinalIgnoreCase))
{
string updateExe = Path.Combine(myDir, "Update.exe");
if (File.Exists(updateExe))
{
LauncherLog.Write($"Squirrel hook {args[0]} forwarded to Update.exe.", ELogType.Info);
Process.Start(updateExe, QuoteArguments(args));
}
else
{
LauncherLog.Write($"Squirrel hook {args[0]} ignored: Update.exe is missing.", ELogType.Warn);
}
return true;
}
var config = WeModInstalls.FindLatestWeMod(myDir);
if (config == null)
{
LauncherLog.Write($"No Wand install found under {myDir}; opening the UI instead.", ELogType.Error);
return false;
}
bool isPatched = Enhancer.IsPatched(config.RootDirectory);
LauncherLog.Write($"Install {config.ExecutablePath} is {(isPatched ? "patched" : "not patched")}.",
ELogType.Info);
// 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 (!isPatched && !TryAutoPatch(config, myDir))
return false;
// RecordStartupLog, not LauncherLog.Write: whatever the launcher says has to survive
// into the window on the failure path below.
return FuseLauncher.Launch(config.ExecutablePath, forwardedArgs, RecordStartupLog);
}
private static void BringToFront(System.Windows.Window window)
{
window.WindowState = System.Windows.WindowState.Normal;
window.Topmost = true;
window.Activate();
window.Topmost = false;
}
private static string QuoteArguments(IEnumerable<string> 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;
}
}
/// <summary>Buffers for the UI and mirrors to disk: auto-patch runs headless, so the
/// file is the only copy if the user never opens the window afterwards.</summary>
private static void RecordStartupLog(string message, ELogType type)
{
StartupLog.Add(new KeyValuePair<string, ELogType>(message, type));
LauncherLog.Write(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);
}
}
+2 -2
View File
@@ -51,5 +51,5 @@ using System.Windows;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.9.2")]
[assembly: AssemblyFileVersion("1.0.9.2")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
@@ -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<object, Task> _execute;
private readonly Func<object, bool> _canExecute;
private long _isExecuting;
public AsyncRelayCommand(Func<object, Task> execute, Func<object, bool> 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();
}
}
}
}
-54
View File
@@ -1,54 +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);
for (int i = 0; processes.Length > i || 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();
}
}
}
}
+85
View File
@@ -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<Process>(processes.Length);
foreach (var process in processes)
{
if (process.Id == selfId)
{
process.Dispose();
continue;
}
result.Add(process);
}
return result.ToArray();
}
}
}
@@ -7,13 +7,14 @@ using WandEnhancer.Models;
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 @@ namespace WandEnhancer.Utils
}
}
}
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 @@ namespace WandEnhancer.Utils
return null;
}
public static string Base64Decode(string base64EncodedData)
public static bool IsJavaScriptFile(string path)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
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)
-61
View File
@@ -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();
}
}
}
-20
View File
@@ -1,20 +0,0 @@
<UserControl x:Class="WandEnhancer.View.Controls.InfoItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WandEnhancer.View.Controls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Viewbox Width="20" Height="20" VerticalAlignment="Top">
<Path Fill="{Binding IconColor}" Data="{Binding IconData}"/>
</Viewbox>
<TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="5 0 5 0" TextWrapping="Wrap"
FontSize="12" Text="{Binding Text}"/>
</Grid>
</UserControl>
@@ -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;
}
}
}
+1 -1
View File
@@ -38,7 +38,7 @@
</Button>
<StackPanel Grid.Row="0" x:Name="TitleContainer" Orientation="Horizontal">
<TextBlock x:Name="Title" Text="This is title" Foreground="{DynamicResource Foreground}"
<TextBlock x:Name="Title" Foreground="{DynamicResource Foreground}"
HorizontalAlignment="Left" FontWeight="Bold" FontSize="16"
VerticalAlignment="Bottom"/>
</StackPanel>
@@ -0,0 +1,26 @@
using System.Windows;
namespace WandEnhancer.View.MainWindow
{
/// <summary>
/// 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.
/// </summary>
public interface IShellView
{
void OpenPopup(FrameworkElement content, string title);
void ClosePopup();
void ScrollLogIntoView(LogEntry entry);
}
/// <summary>Modal file/folder pickers, kept behind a seam so commands stay headless-testable.</summary>
public interface IFileDialogs
{
/// <summary>Chosen folder, or null when cancelled.</summary>
string PickFolder(string description, string initialPath);
/// <summary>Chosen file path, or null when cancelled.</summary>
string PickSaveFile(string filter, string suggestedFileName);
}
}
+3 -2
View File
@@ -183,9 +183,10 @@
Content="{DynamicResource mw_patch}"/>
</Grid>
<Button HorizontalAlignment="Right"
Command="{Binding RestoreBackupCommand }"
FontWeight="Bold" FontSize="16" Width="200"
Command="{Binding RestoreBackupCommand}"
FontWeight="Bold" FontSize="16" Width="200"
Style="{StaticResource ColoredButton}"
IsEnabled="{Binding IsIdle}"
Visibility="{Binding AlreadyPatched, Converter={StaticResource ToVisibilityConverter}}"
Content="{DynamicResource mw_restore}"/>
</Grid>
@@ -8,21 +8,20 @@ namespace WandEnhancer.View.MainWindow
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
public partial class MainWindow : IShellView
{
public static MainWindow Instance;
public readonly MainWindowVm ViewModel;
public MainWindow()
{
InitializeComponent();
this.ViewModel = new MainWindowVm(this);
this.ViewModel = new MainWindowVm(this, new WindowsFileDialogs());
this.DataContext = ViewModel;
VersionLabel.Text = Constants.Version.ToString();
Instance = this;
}
public void OpenPopup(FrameworkElement content, string title = null)
{
this.PopupHost.PopupContent = content;
@@ -30,6 +29,11 @@ namespace WandEnhancer.View.MainWindow
PopupHost.IsOpen = true;
}
public void ScrollLogIntoView(LogEntry entry)
{
this.LogList.ScrollIntoView(entry);
}
private void OnDragMove(object sender, MouseButtonEventArgs e)
{
this.DragMove();
@@ -47,7 +51,15 @@ namespace WandEnhancer.View.MainWindow
private void OpenSourceClicked(object sender, MouseButtonEventArgs e)
{
System.Diagnostics.Process.Start(Constants.RepositoryUrl);
// No browser association, or the shell refuses the URL: not worth killing the app.
try
{
System.Diagnostics.Process.Start(Constants.RepositoryUrl);
}
catch (Exception)
{
ViewModel.ReportRepositoryLinkFailure(Constants.RepositoryUrl);
}
}
}
}
+123 -111
View File
@@ -3,8 +3,8 @@ using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WandEnhancer.Core;
using WandEnhancer.Core.Services;
using WandEnhancer.Models;
using WandEnhancer.ReactiveUICore;
using WandEnhancer.Utils;
@@ -15,31 +15,33 @@ namespace WandEnhancer.View.MainWindow
{
public class MainWindowVm : ObservableObject
{
private readonly MainWindow _view;
public ObservableCollection<LogEntry> LogList { get; set; } = new ObservableCollection<LogEntry>();
private const string LogExportFilter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
private readonly IShellView _shell;
private readonly IFileDialogs _dialogs;
public ObservableCollection<LogEntry> LogList { get; } = new ObservableCollection<LogEntry>();
private WeModConfig _weModConfig;
public WeModConfig WeModInfo
{
get => _weModConfig;
set
set => SetProperty(ref _weModConfig, value);
}
private void UseInstall(WeModConfig config)
{
WeModInfo = config;
if (config == null)
{
SetProperty(ref _weModConfig, value);
if (value == null) return;
Log($"WeMod directory found at '{_weModConfig}' ({_weModConfig.ExecutableName})", ELogType.Success);
if (File.Exists(Path.Combine(_weModConfig.RootDirectory, "resources", "app.asar.backup")))
{
Log("WeMod already patched. If you want to patch again, please restore the backup first.",
ELogType.Warn);
IsPatchEnabled = false;
AlreadyPatched = true;
return;
}
Log("Ready for patching.", ELogType.Info);
IsPatchEnabled = true;
return;
}
Log(LocalizationManager.Format("log_install_found", config, config.ExecutableName), ELogType.Success);
AlreadyPatched = Enhancer.IsPatched(config.RootDirectory);
IsPatchEnabled = !AlreadyPatched;
Log(LocalizationManager.Get(AlreadyPatched ? "log_already_patched" : "log_ready"),
AlreadyPatched ? ELogType.Warn : ELogType.Info);
}
private bool _isPatchEnabled;
@@ -58,6 +60,24 @@ namespace WandEnhancer.View.MainWindow
set => SetProperty(ref _alreadyPatched, value);
}
private bool _isBusy;
/// <summary>True while a patch or restore runs; both are long file operations.</summary>
public bool IsBusy
{
get => _isBusy;
set
{
if (SetProperty(ref _isBusy, value))
{
OnPropertyChanged(nameof(IsIdle));
}
}
}
/// <summary>Bound by buttons that must not be clickable a second time mid-run.</summary>
public bool IsIdle => !_isBusy;
public RelayCommand SetFolderPathCommand { get; }
public RelayCommand ApplyPatchCommand { get; }
public RelayCommand RestoreBackupCommand { get; }
@@ -67,80 +87,69 @@ namespace WandEnhancer.View.MainWindow
private void OnFolderPathSelection(object obj)
{
using (var dialog = new FolderBrowserDialog())
string selectedPath = _dialogs.PickFolder(
LocalizationManager.Get("dialog_pick_install"),
Environment.GetEnvironmentVariable("LOCALAPPDATA"));
if (selectedPath == null)
{
dialog.SelectedPath = Environment.GetEnvironmentVariable("LOCALAPPDATA");
dialog.Description = "Select the WeMod directory";
dialog.ShowNewFolderButton = false;
if (dialog.ShowDialog() != DialogResult.OK) return;
string selectedPath = dialog.SelectedPath;
string fileName = Path.GetFileName(selectedPath);
var info = Extensions.CheckWeModPath(selectedPath);
if (info != null)
{
WeModInfo = info;
return;
}
LogList.Add(new LogEntry
{
LogType = ELogType.Error,
Message = $"The selected folder '{fileName}' is not a valid WeMod directory."
});
return;
}
var info = WeModInstalls.CheckWeModPath(selectedPath);
if (info == null)
{
Log(LocalizationManager.Format("log_invalid_directory", Path.GetFileName(selectedPath)), ELogType.Error);
return;
}
UseInstall(info);
}
private void OnBackupRestoring(object param)
// Restore does the same heavy file IO as Patch, so it runs off the UI thread too.
private async void OnBackupRestoring(object param)
{
var backupPath = Path.Combine(WeModInfo.RootDirectory, "resources", "app.asar.backup");
if (!File.Exists(backupPath))
if (WeModInfo == null)
{
Log("Backup not found. Please dont delete it manually", ELogType.Error);
Log(LocalizationManager.Get("log_no_directory"), ELogType.Warn);
return;
}
try
IsBusy = true;
bool restored = await Task.Run(() =>
{
// Try to lock the file to see if it's in use
using (File.Open(backupPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
try
{
new Enhancer(WeModInfo, Log).Restore();
return true;
}
var proxyDllPath = Path.Combine(WeModInfo.RootDirectory, "version.dll");
if(File.Exists(proxyDllPath))
catch (Exception e)
{
File.Delete(proxyDllPath);
Log(LocalizationManager.Format("log_restore_failed", e.Message), ELogType.Error);
return false;
}
}
catch
{
Log("Backup file is locked. Please close the WeMod and try again.", ELogType.Error);
return;
}
});
File.Copy(backupPath, Path.Combine(WeModInfo.RootDirectory, "resources", "app.asar"), true);
File.Delete(backupPath);
Log("Backup restored successfully.", ELogType.Success);
AlreadyPatched = false;
IsPatchEnabled = true;
IsBusy = false;
if (restored)
{
AlreadyPatched = false;
IsPatchEnabled = true;
}
}
private void OnPatching(object param)
{
if (WeModInfo == null)
{
Log("Can't be done. Please specify the directory first.", ELogType.Warn);
Log(LocalizationManager.Get("log_no_directory"), ELogType.Warn);
return;
}
MainWindow.Instance.OpenPopup(new PatchVectorsPopup(async config =>
_shell.OpenPopup(new PatchVectorsPopup(async config =>
{
MainWindow.Instance.ClosePopup();
_shell.ClosePopup();
IsPatchEnabled = false;
IsBusy = true;
await Task.Run(() =>
{
try
@@ -150,32 +159,34 @@ namespace WandEnhancer.View.MainWindow
}
catch (Exception e)
{
Log($"Failed to patch: {e.Message}", ELogType.Error);
Log(LocalizationManager.Format("log_patch_failed", e.Message), ELogType.Error);
IsPatchEnabled = true;
}
});
}), Application.Current.FindResource("pv_popup_title") as string);
IsBusy = false;
}), LocalizationManager.Get("pv_popup_title"));
}
private void Log(string message, ELogType logType)
{
Application.Current.Dispatcher.Invoke(() =>
{
message = $"[{logType.ToString().ToUpper()}] {message}";
var entry = new LogEntry
{
LogType = logType,
Message = message
Message = $"[{logType.ToString().ToUpper()}] {message}"
};
LogList.Add(entry);
_view.LogList.ScrollIntoView(entry);
_shell.ScrollLogIntoView(entry);
// The log commands are disabled while the list is empty, and appending a line
// is not user input, so nothing else would re-evaluate CanExecute.
System.Windows.Input.CommandManager.InvalidateRequerySuggested();
});
}
private void OnOpenSettings(object param)
{
MainWindow.Instance.OpenPopup(new SettingsPopup(), Application.Current.FindResource("settings_title") as string);
_shell.OpenPopup(new SettingsPopup(), LocalizationManager.Get("settings_title"));
}
private string BuildLogReport()
@@ -190,67 +201,68 @@ namespace WandEnhancer.View.MainWindow
private void OnCopyLogs(object param)
{
if (LogList.Count == 0)
try
{
System.Windows.Clipboard.SetText(BuildLogReport());
Log(LocalizationManager.Get("log_copied"), ELogType.Success);
}
catch (Exception e)
{
Log(LocalizationManager.Format("log_copy_failed", e.Message), ELogType.Error);
}
}
private void OnExportLogs(object param)
{
string path = _dialogs.PickSaveFile(
LogExportFilter,
$"wand-enhancer-log-{DateTime.Now:yyyyMMdd-HHmmss}.txt");
if (path == null)
{
return;
}
try
{
System.Windows.Clipboard.SetText(BuildLogReport());
Log("Logs copied to clipboard.", ELogType.Success);
File.WriteAllText(path, BuildLogReport());
Log(LocalizationManager.Format("log_exported", path), ELogType.Success);
}
catch (Exception e)
{
Log($"Failed to copy logs: {e.Message}", ELogType.Error);
Log(LocalizationManager.Format("log_export_failed", e.Message), ELogType.Error);
}
}
private void OnExportLogs(object param)
private bool HasLogs(object param) => LogList.Count > 0;
/// <summary>The shell could not hand the repository URL to a browser; show it instead.</summary>
public void ReportRepositoryLinkFailure(string url)
{
if (LogList.Count == 0)
{
return;
}
using (var dialog = new SaveFileDialog
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
FileName = $"wand-enhancer-log-{DateTime.Now:yyyyMMdd-HHmmss}.txt"
})
{
if (dialog.ShowDialog() != DialogResult.OK)
{
return;
}
try
{
File.WriteAllText(dialog.FileName, BuildLogReport());
Log($"Logs exported to '{dialog.FileName}'.", ELogType.Success);
}
catch (Exception e)
{
Log($"Failed to export logs: {e.Message}", ELogType.Error);
}
}
Log(LocalizationManager.Format("log_open_link_failed", url), ELogType.Warn);
}
public MainWindowVm(MainWindow view)
public MainWindowVm(IShellView shell, IFileDialogs dialogs)
{
_view = view;
_shell = shell;
_dialogs = dialogs;
SetFolderPathCommand = new RelayCommand(OnFolderPathSelection);
ApplyPatchCommand = new RelayCommand(OnPatching);
RestoreBackupCommand = new RelayCommand(OnBackupRestoring);
OpenSettingsCommand = new RelayCommand(OnOpenSettings);
CopyLogsCommand = new RelayCommand(OnCopyLogs);
ExportLogsCommand = new RelayCommand(OnExportLogs);
CopyLogsCommand = new RelayCommand(OnCopyLogs, HasLogs);
ExportLogsCommand = new RelayCommand(OnExportLogs, HasLogs);
WeModInfo = Extensions.FindWeMod();
UseInstall(WeModInstalls.FindWeMod());
if (WeModInfo == null)
{
Log("WeMod directory not found.", ELogType.Error);
Log(LocalizationManager.Get("log_install_not_found"), ELogType.Error);
}
foreach (var entry in Program.StartupLog)
{
Log(entry.Key, entry.Value);
}
Program.StartupLog.Clear();
}
}
}
@@ -0,0 +1,28 @@
using System.Windows.Forms;
namespace WandEnhancer.View.MainWindow
{
internal sealed class WindowsFileDialogs : IFileDialogs
{
public string PickFolder(string description, string initialPath)
{
using (var dialog = new FolderBrowserDialog
{
SelectedPath = initialPath,
Description = description,
ShowNewFolderButton = false,
})
{
return dialog.ShowDialog() == DialogResult.OK ? dialog.SelectedPath : null;
}
}
public string PickSaveFile(string filter, string suggestedFileName)
{
using (var dialog = new SaveFileDialog { Filter = filter, FileName = suggestedFileName })
{
return dialog.ShowDialog() == DialogResult.OK ? dialog.FileName : null;
}
}
}
}
@@ -18,6 +18,7 @@
<RowDefinition Height="27" />
<RowDefinition Height="27" />
<RowDefinition Height="27" />
<RowDefinition Height="27" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
@@ -39,7 +40,11 @@
<TextBlock Grid.Row="3" Grid.Column="0" VerticalAlignment="Center" Text="{DynamicResource pv_remote_web_panel_preview}" />
<CheckBox Grid.Row="3" Grid.Column="1" x:Name="RemoteWebPanelPreviewBox" HorizontalAlignment="Right" VerticalAlignment="Center" />
<Border Grid.Row="4" Grid.ColumnSpan="2" Margin="0 14 0 0" Padding="10"
<TextBlock Grid.Row="4" Grid.Column="0" VerticalAlignment="Center" Text="{DynamicResource pv_auto_apply}" />
<CheckBox Grid.Row="4" Grid.Column="1" x:Name="AutoApplyBox" HorizontalAlignment="Right" VerticalAlignment="Center"
IsChecked="True" />
<Border Grid.Row="5" Grid.ColumnSpan="2" Margin="0 14 0 0" Padding="10"
BorderBrush="{DynamicResource Border}" BorderThickness="1" CornerRadius="4"
Background="{DynamicResource Muted}">
<StackPanel>
@@ -91,7 +96,7 @@
</StackPanel>
</Border>
<Button Grid.Row="5" Grid.ColumnSpan="2" Padding="0 5 0 5" Margin="0 15 0 0" Content="{DynamicResource pv_start}"
<Button Grid.Row="6" Grid.ColumnSpan="2" Padding="0 5 0 5" Margin="0 15 0 0" Content="{DynamicResource pv_start}"
Click="OnPatchButtonClick" />
</Grid>
</Grid>
@@ -7,13 +7,13 @@ using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using WandEnhancer.Models;
using WandEnhancer.Utils;
namespace WandEnhancer.View.Popups
{
public partial class PatchVectorsPopup : UserControl
{
private const string JavaScriptDialogFilter = "JavaScript files (*.js)|*.js";
private const string JavaScriptFileExtension = ".js";
private readonly Action<PatchConfig> _onApply;
private readonly ObservableCollection<SelectedScript> _selectedScripts = new ObservableCollection<SelectedScript>();
@@ -40,7 +40,7 @@ namespace WandEnhancer.View.Popups
return;
}
foreach (var path in dialog.FileNames.Where(IsJavaScriptFile))
foreach (var path in dialog.FileNames.Where(WeModInstalls.IsJavaScriptFile))
{
AddScript(path);
}
@@ -99,7 +99,7 @@ namespace WandEnhancer.View.Popups
{
PatchTypes = result,
CustomScriptPaths = _selectedScripts.Select(script => script.FullPath).ToList(),
AutoApplyPatches = false
AutoApplyAfterUpdate = AutoApplyBox.IsChecked == true
});
}
@@ -114,11 +114,6 @@ namespace WandEnhancer.View.Popups
_selectedScripts.Add(new SelectedScript(fullPath));
}
private static bool IsJavaScriptFile(string path)
{
return File.Exists(path) && string.Equals(Path.GetExtension(path), JavaScriptFileExtension, StringComparison.OrdinalIgnoreCase);
}
private void UpdateScriptsEmptyState()
{
NoScriptsText.Visibility = _selectedScripts.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
@@ -56,7 +56,7 @@ namespace WandEnhancer.View.Popups
LocalizationManager.CurrentLanguage = _selectedLanguage;
}
MainWindow.MainWindow.Instance.ClosePopup();
MainWindow.MainWindow.Instance?.ClosePopup();
}
private class LanguageItem
+18 -28
View File
@@ -39,12 +39,6 @@
</PropertyGroup>
<PropertyGroup>
<StartupObject>WandEnhancer.Program</StartupObject>
<CMakeSourceDir>..\tools\asar-fuses-bypass</CMakeSourceDir>
<NativeBuildRoot>..\.tmp\cmake</NativeBuildRoot>
<NativeBuildConfiguration Condition="'$(Configuration)' == 'Debug'">Debug</NativeBuildConfiguration>
<NativeBuildConfiguration Condition="'$(NativeBuildConfiguration)' == ''">Release</NativeBuildConfiguration>
<CMakeBuildDir>$(NativeBuildRoot)\asar-fuses-bypass</CMakeBuildDir>
<ProxyDllPath>$(CMakeBuildDir)\$(NativeBuildConfiguration)\version.dll</ProxyDllPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
@@ -72,24 +66,29 @@
<Compile Include="Converters\ToVisibilityConverter.cs" />
<Compile Include="Core\Enhancer.cs" />
<Compile Include="Core\EnhancerConfig.cs" />
<Compile Include="Core\ElectronFuse.cs" />
<Compile Include="Core\FuseLauncher.cs" />
<Compile Include="Core\LauncherLog.cs" />
<Compile Include="Core\JavaScriptPatchApplier.cs" />
<Compile Include="Core\Js\JsCursor.cs" />
<Compile Include="Core\Js\JsFunction.cs" />
<Compile Include="Core\Js\PatchPayload.cs" />
<Compile Include="Core\Services\LocalizationManager.cs" />
<Compile Include="Core\Services\SettingsManager.cs" />
<Compile Include="Models\WeModConfig.cs" />
<Compile Include="Models\PatchConfig.cs" />
<Compile Include="Models\Signature.cs" />
<Compile Include="Program.cs" />
<Compile Include="ReactiveUICore\AsyncRelayCommand.cs" />
<Compile Include="ReactiveUICore\ObservableObject.cs" />
<Compile Include="ReactiveUICore\RelayCommand.cs" />
<Compile Include="Utils\Common.cs" />
<Compile Include="Utils\Extensions.cs" />
<Compile Include="Utils\Win32\Shortcut.cs" />
<Compile Include="View\Controls\InfoItem.xaml.cs">
<DependentUpon>InfoItem.xaml</DependentUpon>
<Compile Include="Utils\ProcessTerminator.cs" />
<Compile Include="Utils\WeModInstalls.cs" />
<Compile Include="View\Controls\PopupHost.xaml.cs">
<DependentUpon>PopupHost.xaml</DependentUpon>
</Compile>
<Compile Include="View\Controls\PopupHost.xaml.cs" />
<Compile Include="View\MainWindow\Logs.cs" />
<Compile Include="View\MainWindow\MainWindow.xaml.cs" />
<Compile Include="View\MainWindow\IShellView.cs" />
<Compile Include="View\MainWindow\WindowsFileDialogs.cs" />
<Compile Include="View\MainWindow\MainWindowVm.cs" />
<Compile Include="View\Popups\PatchVectorsPopup.xaml.cs">
<DependentUpon>PatchVectorsPopup.xaml</DependentUpon>
@@ -116,7 +115,6 @@
<Page Include="Style\ColorScheme.xaml" />
<Page Include="Style\Icons.xaml" />
<Page Include="Style\Styles.xaml" />
<Page Include="View\Controls\InfoItem.xaml" />
<Page Include="View\Controls\PopupHost.xaml" />
<Page Include="View\MainWindow\MainWindow.xaml" />
<Page Include="View\Popups\PatchVectorsPopup.xaml" />
@@ -152,16 +150,16 @@
<Name>AsarSharp</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="$(ProxyDllPath)">
<LogicalName>proxydll</LogicalName>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\web-panel\dist\**\*.*" Condition="Exists('..\web-panel\dist\index.html')">
<LogicalName>remote-panel/dist/%(RecursiveDir)%(Filename)%(Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Patches\*.js">
<LogicalName>patches/%(Filename)%(Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
@@ -171,14 +169,6 @@
<Error Condition="!Exists('..\packages\ILRepack.2.0.41\build\ILRepack.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\ILRepack.2.0.41\build\ILRepack.props'))" />
</Target>
<Target Name="ValidateNativeArtifacts" BeforeTargets="BeforeBuild">
<Error Text="Proxy DLL not found: $(ProxyDllPath)"
Condition="!Exists('$(ProxyDllPath)')" />
<Message Text="Embedding Proxy DLL as resource from $(ProxyDllPath)"
Importance="high" />
</Target>
<Target Name="ILRepack" AfterTargets="Build" Condition="'$(Configuration)' == 'Release'">
<PropertyGroup>
<ILRepackExe>..\packages\ILRepack.2.0.41\tools\ILRepack.exe</ILRepackExe>
Binary file not shown.
Binary file not shown.
+35 -45
View File
@@ -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 {
@@ -23,40 +20,24 @@ function Resolve-CommandPath {
return $command.Source
}
function Resolve-NuGetPath {
$nugetCommand = Get-Command 'nuget.exe' -ErrorAction SilentlyContinue
if (-not $nugetCommand) {
$nugetCommand = Get-Command 'nuget' -ErrorAction SilentlyContinue
}
if ($nugetCommand) {
return $nugetCommand.Source
}
$toolsDir = Join-Path $repoRoot '.tmp/tools'
$nugetPath = Join-Path $toolsDir 'nuget.exe'
if (-not (Test-Path $nugetPath)) {
New-Item -ItemType Directory -Path $toolsDir -Force | Out-Null
Invoke-WebRequest -Uri 'https://dist.nuget.org/win-x86-commandline/latest/nuget.exe' -OutFile $nugetPath
}
return $nugetPath
}
function Resolve-MSBuildPath {
function Resolve-VisualStudioPath {
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
if (-not (Test-Path $vswhere)) {
throw "vswhere.exe not found: $vswhere"
}
# No version pin: pick whatever VS the host has (2022/2026/newer) so CI
# keeps working when the runner image bumps its Visual Studio major.
$installationPath = & $vswhere -latest -prerelease -products '*' -requires Microsoft.Component.MSBuild -property installationPath
if ([string]::IsNullOrWhiteSpace($installationPath)) {
throw 'Visual Studio with MSBuild was not found.'
}
$msbuildPath = Join-Path $installationPath 'MSBuild\Current\Bin\MSBuild.exe'
return $installationPath
}
function Resolve-MSBuildPath {
param([string]$VisualStudioPath)
$msbuildPath = Join-Path $VisualStudioPath 'MSBuild\Current\Bin\MSBuild.exe'
if (-not (Test-Path $msbuildPath)) {
throw "MSBuild.exe not found: $msbuildPath"
}
@@ -77,38 +58,47 @@ function Invoke-Step {
}
}
$cmake = Resolve-CommandPath 'cmake'
$nuget = Resolve-NuGetPath
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'
$msbuild = Resolve-MSBuildPath
$visualStudio = Resolve-VisualStudioPath
$msbuild = Resolve-MSBuildPath $visualStudio
$targetFrameworkRoot = Resolve-TargetFrameworkRoot
$buildArgs = @('/m', "/p:Configuration=$Configuration", '/p:Platform=Any CPU')
if ($targetFrameworkRoot) {
$buildArgs += "/p:TargetFrameworkRootPath=$targetFrameworkRoot"
}
Invoke-Step 'Install web-panel dependencies' {
& $pnpm --dir $webPanelDir install --frozen-lockfile
}
Invoke-Step 'Lint web-panel' {
& $pnpm --dir $webPanelDir run lint
}
# 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 'Configure asar-fuses-bypass' {
# Let CMake choose its default Visual Studio generator (matches the host VS),
# avoiding a hardcoded/derived name that breaks when the runner bumps VS.
# Clearing CMAKE_GENERATOR ensures the default isn't overridden to a non-VS
# generator that would reject the -A architecture flag.
Remove-Item Env:CMAKE_GENERATOR -ErrorAction SilentlyContinue
& $cmake -S $asarFusesSourceDir -B $asarFusesBuildDir -A x64
}
Invoke-Step 'Build asar-fuses-bypass' {
& $cmake --build $asarFusesBuildDir --config $Configuration
}
Invoke-Step 'Restore NuGet packages' {
& $nuget restore $solutionPath -NonInteractive
& $msbuild $solutionPath /m /t:Restore /p:RestorePackagesConfig=true
}
Invoke-Step 'Build solution' {
& $msbuild $solutionPath /m /p:Configuration=$Configuration '/p:Platform=Any CPU' /t:Build
& $msbuild $solutionPath @buildArgs /t:Build
}
Write-Host ''
+2 -1
View File
@@ -18,7 +18,8 @@ function Normalize-Version {
throw 'Version value cannot be empty.'
}
return $Value.Trim().TrimStart('v', 'V')
# A pre-release tag (1.1.0.0-rc.1) reads the notes of its base version.
return ($Value.Trim().TrimStart('v', 'V') -replace '-.*$', '')
}
function Get-ChangelogSection {
+3 -1
View File
@@ -16,7 +16,9 @@ function Normalize-Version {
throw 'Version value cannot be empty.'
}
return $Value.Trim().TrimStart('v', 'V')
# AssemblyVersion holds four numbers only, so a pre-release tag such as
# 1.1.0.0-rc.1 must compare and look up its notes as 1.1.0.0.
return ($Value.Trim().TrimStart('v', 'V') -replace '-.*$', '')
}
function Get-ChangelogSection {
-78
View File
@@ -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
-17
View File
@@ -1,17 +0,0 @@
cmake_minimum_required(VERSION 3.16)
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 "")
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
add_link_options(-static -static-libgcc -static-libstdc++)
endif()
add_library(version SHARED library.c library.def fuses.c)
-190
View File
@@ -1,190 +0,0 @@
//
// Created by kitbyte on 30.11.2025.
//
#include <Windows.h>
#include <stdio.h>
#include <time.h>
#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;
}
-147
View File
@@ -1,147 +0,0 @@
//
// Created by kitbyte on 30.11.2025.
//
#include <Windows.h>
#include <winver.h>
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;
}
-20
View File
@@ -1,20 +0,0 @@
LIBRARY "VERSION"
EXPORTS
GetFileVersionInfoA
GetFileVersionInfoByHandle
GetFileVersionInfoExA
GetFileVersionInfoExW
GetFileVersionInfoSizeA
GetFileVersionInfoSizeExA
GetFileVersionInfoSizeExW
GetFileVersionInfoSizeW
GetFileVersionInfoW
VerFindFileA
VerFindFileW
VerInstallFileA
VerInstallFileW
VerLanguageNameA
VerLanguageNameW
VerQueryValueA
VerQueryValueW
-7
View File
@@ -1,7 +0,0 @@
node_modules/
coverage/
.pnpm-store/
pnpm-lock.yaml
package-lock.json
pnpm-lock.yaml
yarn.lock
-11
View File
@@ -1,11 +0,0 @@
{
"endOfLine": "lf",
"semi": false,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80,
"plugins": ["prettier-plugin-tailwindcss"],
"tailwindStylesheet": "src/index.css",
"tailwindFunctions": ["cn", "cva"]
}
+106
View File
@@ -0,0 +1,106 @@
{
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"files": {
"includes": [
"src/**",
"protocol/**",
"bridge/**",
"scripts/**",
"*.ts",
"*.js",
"*.json",
"*.html",
"*.css",
"!**/dist",
"!**/node_modules",
"!src/locales",
"!fixtures"
]
},
"formatter": {
"enabled": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentWidth": 4,
"lineEnding": "lf",
"lineWidth": 100
},
"javascript": {
"formatter": {
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"quoteStyle": "single",
"semicolons": "always",
"trailingCommas": "all",
"indentStyle": "space",
"indentWidth": 4
}
},
"json": {
"formatter": {
"indentStyle": "space",
"indentWidth": 4
}
},
"css": {
"parser": {
"tailwindDirectives": true
},
"formatter": {
"indentStyle": "space",
"indentWidth": 4
}
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"correctness": {
"noUnusedVariables": "warn"
},
"style": {
"noNonNullAssertion": "off",
"noDescendingSpecificity": "off"
},
"suspicious": {
"noExplicitAny": "off"
}
}
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on"
}
}
},
"overrides": [
{
"includes": ["bridge/scripts/**", "scripts/**"],
"linter": {
"rules": {
"correctness": {
"noUnusedVariables": "off",
"noUnusedFunctionParameters": "off"
}
}
}
},
{
"includes": ["bridge/src/**"],
"linter": {
"rules": {
"suspicious": {
"noExplicitAny": "off"
}
}
}
}
]
}
+32 -36
View File
@@ -1,63 +1,59 @@
import { build } from "esbuild"
import { readdir } from "node:fs/promises"
import { dirname, resolve } from "node:path"
import { fileURLToPath } from "node:url"
import { readdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { build } from 'esbuild';
const bridgeRoot = dirname(fileURLToPath(import.meta.url))
const webPanelRoot = resolve(bridgeRoot, "..")
const distRoot = resolve(webPanelRoot, "dist")
const bridgeEntryPoint = resolve(bridgeRoot, "src", "index.ts")
const bridgeOutfile = resolve(distRoot, "bridge.cjs")
const rendererScriptsRoot = resolve(bridgeRoot, "scripts", "default")
const rendererScriptsOutdir = resolve(distRoot, "renderer-scripts")
const bridgeRoot = dirname(fileURLToPath(import.meta.url));
const webPanelRoot = resolve(bridgeRoot, '..');
const distRoot = resolve(webPanelRoot, 'dist');
const bridgeEntryPoint = resolve(bridgeRoot, 'src', 'index.ts');
const bridgeOutfile = resolve(distRoot, 'bridge.cjs');
const rendererScriptsRoot = resolve(bridgeRoot, 'scripts', 'default');
const rendererScriptsOutdir = resolve(distRoot, 'renderer-scripts');
await build({
banner: {
js: "// Generated by bridge/build.mjs. Do not edit this bundle by hand.",
js: '// Generated by bridge/build.mjs. Do not edit this bundle by hand.',
},
bundle: true,
entryPoints: [bridgeEntryPoint],
format: "cjs",
legalComments: "none",
format: 'cjs',
legalComments: 'none',
minify: true,
outfile: bridgeOutfile,
platform: "node",
target: "node16",
})
platform: 'node',
target: 'node16',
});
const EXCLUDED_RENDERER_SCRIPTS = new Set(["activate-pro.js"])
const EXCLUDED_RENDERER_SCRIPTS = new Set(['activate-pro.js']);
const rendererEntries = (
await readdir(rendererScriptsRoot, { withFileTypes: true })
)
const rendererEntries = (await readdir(rendererScriptsRoot, { withFileTypes: true }))
.filter(
(entry) =>
entry.isFile() &&
entry.name.endsWith(".js") &&
!EXCLUDED_RENDERER_SCRIPTS.has(entry.name)
entry.name.endsWith('.js') &&
!EXCLUDED_RENDERER_SCRIPTS.has(entry.name),
)
.map((entry) => resolve(rendererScriptsRoot, entry.name))
.map((entry) => resolve(rendererScriptsRoot, entry.name));
if (rendererEntries.length === 0) {
throw new Error(`No renderer script entries found in ${rendererScriptsRoot}`)
throw new Error(`No renderer script entries found in ${rendererScriptsRoot}`);
}
await build({
banner: {
js: "// Generated by bridge/build.mjs. Do not edit this bundle by hand.",
js: '// Generated by bridge/build.mjs. Do not edit this bundle by hand.',
},
bundle: true,
entryNames: "[name]",
entryNames: '[name]',
entryPoints: rendererEntries,
format: "iife",
legalComments: "none",
format: 'iife',
legalComments: 'none',
minify: true,
outdir: rendererScriptsOutdir,
platform: "browser",
target: "es2020",
})
platform: 'browser',
target: 'es2020',
});
console.log(`Built ${bridgeOutfile}`)
console.log(
`Built ${rendererEntries.length} renderer script(s) in ${rendererScriptsOutdir}`
)
console.log(`Built ${bridgeOutfile}`);
console.log(`Built ${rendererEntries.length} renderer script(s) in ${rendererScriptsOutdir}`);
+179 -154
View File
@@ -1,5 +1,5 @@
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { WebSocketServer } from 'ws';
@@ -25,196 +25,221 @@ const trainerValues = structuredClone(demoSession.trainerValues);
const wss = new WebSocketServer({ noServer: true });
function jsonMessage(type, payload, requestId = null) {
return JSON.stringify({
type,
version: webContract.protocolVersion,
requestId,
payload,
});
return JSON.stringify({
type,
version: webContract.protocolVersion,
requestId,
payload,
});
}
function sendSnapshot(ws) {
ws.send(
jsonMessage('trainer_meta', trainerMeta)
);
ws.send(
jsonMessage('trainer_values', trainerValues)
);
ws.send(jsonMessage('trainer_meta', trainerMeta));
ws.send(jsonMessage('trainer_values', trainerValues));
}
function broadcast(type, payload, requestId = null) {
const serialized = jsonMessage(type, payload, requestId);
for (const client of wss.clients) {
if (client.readyState === 1) {
client.send(serialized);
const serialized = jsonMessage(type, payload, requestId);
for (const client of wss.clients) {
if (client.readyState === 1) {
client.send(serialized);
}
}
}
}
function normalizeValue(target, value) {
const cheat = trainerMeta.schema.cheats.find((entry) => entry.target === target);
if (!cheat) {
const cheat = trainerMeta.schema.cheats.find((entry) => entry.target === target);
if (!cheat) {
return value;
}
if (cheat.type === 'toggle') {
return Boolean(value);
}
if (cheat.type === 'slider' || cheat.type === 'number') {
const numeric = typeof value === 'string' ? Number(value) : value;
return Number.isFinite(numeric) ? numeric : trainerValues.values[target];
}
return value;
}
if (cheat.type === 'toggle') {
return Boolean(value);
}
if (cheat.type === 'slider' || cheat.type === 'number') {
const numeric = typeof value === 'string' ? Number(value) : value;
return Number.isFinite(numeric) ? numeric : trainerValues.values[target];
}
return value;
}
function contentTypeFor(filePath) {
if (filePath.endsWith('.html')) return 'text/html; charset=utf-8';
if (filePath.endsWith('.js')) return 'application/javascript; charset=utf-8';
if (filePath.endsWith('.css')) return 'text/css; charset=utf-8';
if (filePath.endsWith('.json')) return 'application/json; charset=utf-8';
if (filePath.endsWith('.svg')) return 'image/svg+xml';
return 'application/octet-stream';
if (filePath.endsWith('.html')) return 'text/html; charset=utf-8';
if (filePath.endsWith('.js')) return 'application/javascript; charset=utf-8';
if (filePath.endsWith('.css')) return 'text/css; charset=utf-8';
if (filePath.endsWith('.json')) return 'application/json; charset=utf-8';
if (filePath.endsWith('.svg')) return 'image/svg+xml';
return 'application/octet-stream';
}
async function serveFile(res, filePath) {
try {
const content = await readFile(filePath);
res.writeHead(200, {
'Content-Type': contentTypeFor(filePath),
'Cache-Control': 'no-store',
});
res.end(content);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
}
try {
const content = await readFile(filePath);
res.writeHead(200, {
'Content-Type': contentTypeFor(filePath),
'Cache-Control': 'no-store',
});
res.end(content);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
}
}
const server = createServer(async (req, res) => {
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
if (url.pathname === '/' || url.pathname === '') {
res.writeHead(302, { Location: REMOTE_BASE_PATH });
res.end();
return;
}
if (url.pathname === '/' || url.pathname === '') {
res.writeHead(302, { Location: REMOTE_BASE_PATH });
res.end();
return;
}
if (url.pathname === REMOTE_BASE_PATH.slice(0, -1)) {
res.writeHead(302, { Location: REMOTE_BASE_PATH });
res.end();
return;
}
if (url.pathname === REMOTE_BASE_PATH.slice(0, -1)) {
res.writeHead(302, { Location: REMOTE_BASE_PATH });
res.end();
return;
}
if (url.pathname === REMOTE_BASE_PATH) {
await serveFile(res, path.join(distDir, 'index.html'));
return;
}
if (url.pathname === REMOTE_BASE_PATH) {
await serveFile(res, path.join(distDir, 'index.html'));
return;
}
if (url.pathname === REMOTE_HEALTH_PATH) {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, trainerId: trainerMeta.trainer.trainerId }));
return;
}
if (url.pathname === REMOTE_HEALTH_PATH) {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, trainerId: trainerMeta.trainer.trainerId }));
return;
}
if (url.pathname.startsWith(REMOTE_ASSETS_PREFIX)) {
const relativePath = url.pathname.replace(REMOTE_BASE_PATH, '');
await serveFile(res, path.join(distDir, relativePath));
return;
}
if (url.pathname.startsWith(REMOTE_ASSETS_PREFIX)) {
const relativePath = url.pathname.replace(REMOTE_BASE_PATH, '');
await serveFile(res, path.join(distDir, relativePath));
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
});
server.on('upgrade', (request, socket, head) => {
const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`);
if (url.pathname !== REMOTE_WS_PATH) {
socket.destroy();
return;
}
const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`);
if (url.pathname !== REMOTE_WS_PATH) {
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
wss.on('connection', (ws) => {
ws.on('error', console.error);
ws.on('error', console.error);
ws.on('message', (raw) => {
try {
const message = JSON.parse(String(raw));
if (message?.version !== webContract.protocolVersion || typeof message?.type !== 'string' || !message?.payload) {
ws.send(jsonMessage('error', {
code: 'invalid_message',
message: 'Expected a compatible protocol envelope.',
}, message?.requestId ?? null));
return;
}
if (message?.type === 'hello') {
ws.send(
jsonMessage('hello_ack', {
sessionId: `sess_${Date.now()}`,
accepted: true,
serverVersion: '0.1.0-demo',
protocolVersion: webContract.protocolVersion,
}, message.requestId ?? null)
);
sendSnapshot(ws);
return;
}
ws.on('message', (raw) => {
try {
const message = JSON.parse(String(raw));
if (
message?.version !== webContract.protocolVersion ||
typeof message?.type !== 'string' ||
!message?.payload
) {
ws.send(
jsonMessage(
'error',
{
code: 'invalid_message',
message: 'Expected a compatible protocol envelope.',
},
message?.requestId ?? null,
),
);
return;
}
if (message?.type === 'hello') {
ws.send(
jsonMessage(
'hello_ack',
{
sessionId: `sess_${Date.now()}`,
accepted: true,
serverVersion: '0.1.0-demo',
protocolVersion: webContract.protocolVersion,
},
message.requestId ?? null,
),
);
sendSnapshot(ws);
return;
}
if (message?.type === 'set_value') {
const target = message.payload?.target;
if (message.payload?.trainerId !== trainerMeta.trainer.trainerId || typeof target !== 'string' || !(target in trainerValues.values)) {
ws.send(
jsonMessage('set_value_result', {
ok: false,
trainerId: trainerMeta.trainer.trainerId,
target: typeof target === 'string' ? target : '',
error: {
code: 'invalid_target',
message: 'Unknown cheat target.',
},
}, message.requestId ?? null)
);
return;
if (message?.type === 'set_value') {
const target = message.payload?.target;
if (
message.payload?.trainerId !== trainerMeta.trainer.trainerId ||
typeof target !== 'string' ||
!(target in trainerValues.values)
) {
ws.send(
jsonMessage(
'set_value_result',
{
ok: false,
trainerId: trainerMeta.trainer.trainerId,
target: typeof target === 'string' ? target : '',
error: {
code: 'invalid_target',
message: 'Unknown cheat target.',
},
},
message.requestId ?? null,
),
);
return;
}
const previousValue = trainerValues.values[target];
const nextValue = normalizeValue(target, message.payload?.value);
trainerValues.values[target] = nextValue;
ws.send(
jsonMessage(
'set_value_result',
{
ok: true,
trainerId: trainerMeta.trainer.trainerId,
target,
},
message.requestId ?? null,
),
);
broadcast('value_changed', {
trainerId: trainerMeta.trainer.trainerId,
target,
value: nextValue,
oldValue: previousValue,
source: 'remote',
cheatId: message.payload?.cheatId,
});
}
} catch (error) {
ws.send(
jsonMessage('error', {
code: 'invalid_message',
message:
error instanceof Error ? error.message : 'Failed to parse client message.',
}),
);
}
const previousValue = trainerValues.values[target];
const nextValue = normalizeValue(target, message.payload?.value);
trainerValues.values[target] = nextValue;
ws.send(
jsonMessage('set_value_result', {
ok: true,
trainerId: trainerMeta.trainer.trainerId,
target,
}, message.requestId ?? null)
);
broadcast('value_changed', {
trainerId: trainerMeta.trainer.trainerId,
target,
value: nextValue,
oldValue: previousValue,
source: 'remote',
cheatId: message.payload?.cheatId,
});
}
} catch (error) {
ws.send(
jsonMessage('error', {
code: 'invalid_message',
message: error instanceof Error ? error.message : 'Failed to parse client message.',
})
);
}
});
});
});
server.listen(port, host, () => {
console.log(`Wand web panel bridge listening on http://${host === DEFAULT_REMOTE_HOST ? 'localhost' : host}:${port}${REMOTE_BASE_PATH}`);
console.log(
`Wand web panel bridge listening on http://${host === DEFAULT_REMOTE_HOST ? 'localhost' : host}:${port}${REMOTE_BASE_PATH}`,
);
});
+1 -1
View File
@@ -1,3 +1,3 @@
{
"type": "commonjs"
"type": "commonjs"
}
+2 -2
View File
@@ -2,6 +2,6 @@
// patch (EPatchType.ActivatePro). This renderer-side variant is kept for future
// use and is excluded from bridge/build.mjs (EXCLUDED_RENDERER_SCRIPTS), so it is
// neither bundled nor injected. To re-enable, remove it from that exclusion list.
import { installActivatePro } from "./activate-pro/index.js"
import { installActivatePro } from './activate-pro/index.js';
installActivatePro(globalThis.WandEnhancer)
installActivatePro(globalThis.WandEnhancer);
+55 -62
View File
@@ -2,139 +2,132 @@
// (EPatchType.ActivatePro). This renderer-side variant patches the account service
// prototype to inject the Pro subscription at the source. Kept for future use;
// the entry `../activate-pro.js` is excluded from bridge/build.mjs.
import { createLogger } from "../installed-apps-sync/logger.js"
import { createLogger } from '../installed-apps-sync/logger.js';
import {
findExportedConstructor,
getWebpackRequire,
isRecord,
} from "../installed-apps-sync/runtime.js"
} from '../installed-apps-sync/runtime.js';
const GLOBAL_FLAG = "__wandActivateProInstalled"
const SERVICE_PATCH_KEY = "__wandEnhancerProAccountServicePatched"
const GLOBAL_FLAG = '__wandActivateProInstalled';
const SERVICE_PATCH_KEY = '__wandEnhancerProAccountServicePatched';
const ACCOUNT_SERVICE_METHODS = [
"getUserAccount",
"setAccountLanguage",
"setAccountWandBrandExperience",
]
const RETRY_DELAY_MS = 400
const MAX_ATTEMPTS = 90
const DEFAULT_SUBSCRIPTION = Object.freeze({ period: "yearly", state: "active" })
'getUserAccount',
'setAccountLanguage',
'setAccountWandBrandExperience',
];
const RETRY_DELAY_MS = 400;
const MAX_ATTEMPTS = 90;
const DEFAULT_SUBSCRIPTION = Object.freeze({ period: 'yearly', state: 'active' });
export function installActivatePro(WandEnhancer) {
if (globalThis[GLOBAL_FLAG]) {
return
return;
}
globalThis[GLOBAL_FLAG] = true
globalThis[GLOBAL_FLAG] = true;
const state = {
attempts: 0,
log: createLogger(WandEnhancer),
}
};
state.log("info", "Activate Pro bootstrap starting.")
retryBootstrap(state)
state.log('info', 'Activate Pro bootstrap starting.');
retryBootstrap(state);
}
function retryBootstrap(state) {
if (patchAccountService(state)) {
return
return;
}
state.attempts += 1
state.attempts += 1;
if (state.attempts < MAX_ATTEMPTS) {
setTimeout(() => retryBootstrap(state), RETRY_DELAY_MS)
return
setTimeout(() => retryBootstrap(state), RETRY_DELAY_MS);
return;
}
state.log("error", "Activate Pro bootstrap exhausted; account service not found.")
state.log('error', 'Activate Pro bootstrap exhausted; account service not found.');
}
function patchAccountService(state) {
const webpackRequire = getWebpackRequire()
const webpackRequire = getWebpackRequire();
if (!webpackRequire) {
return false
return false;
}
const ctor = findExportedConstructor(
webpackRequire,
(prototype) =>
typeof prototype.getUserAccount === "function" &&
typeof prototype.setAccountLanguage === "function" &&
typeof prototype.setAccountWandBrandExperience === "function"
)
typeof prototype.getUserAccount === 'function' &&
typeof prototype.setAccountLanguage === 'function' &&
typeof prototype.setAccountWandBrandExperience === 'function',
);
if (!ctor?.prototype) {
return false
return false;
}
const prototype = ctor.prototype
const prototype = ctor.prototype;
if (prototype[SERVICE_PATCH_KEY]) {
return true
return true;
}
try {
for (const name of ACCOUNT_SERVICE_METHODS) {
const original = prototype[name]
if (typeof original !== "function") {
continue
const original = prototype[name];
if (typeof original !== 'function') {
continue;
}
prototype[name] = function patchedAccountMethod(...args) {
return Promise.resolve(original.apply(this, args)).then((account) =>
normalizeProAccount(account)
)
}
normalizeProAccount(account),
);
};
}
Object.defineProperty(prototype, SERVICE_PATCH_KEY, { value: true })
state.log("info", "Pro account service patched.")
return true
Object.defineProperty(prototype, SERVICE_PATCH_KEY, { value: true });
state.log('info', 'Pro account service patched.');
return true;
} catch (error) {
state.log(
"warn",
"Failed to patch account service.",
error?.stack || String(error)
)
return false
state.log('warn', 'Failed to patch account service.', error?.stack || String(error));
return false;
}
}
function normalizeProAccount(account) {
if (!isRecord(account)) {
return account
return account;
}
const nextSubscription = normalizeProSubscription(account.subscription)
const nextSubscription = normalizeProSubscription(account.subscription);
if (nextSubscription === account.subscription) {
return account
return account;
}
return {
...account,
subscription: nextSubscription,
}
};
}
function normalizeProSubscription(subscription) {
if (!isRecord(subscription)) {
return { ...DEFAULT_SUBSCRIPTION }
return { ...DEFAULT_SUBSCRIPTION };
}
const nextSubscription = { ...subscription }
let changed = false
const nextSubscription = { ...subscription };
let changed = false;
if (
typeof nextSubscription.period !== "string" ||
!nextSubscription.period.trim()
) {
nextSubscription.period = DEFAULT_SUBSCRIPTION.period
changed = true
if (typeof nextSubscription.period !== 'string' || !nextSubscription.period.trim()) {
nextSubscription.period = DEFAULT_SUBSCRIPTION.period;
changed = true;
}
if (nextSubscription.state !== "active") {
nextSubscription.state = DEFAULT_SUBSCRIPTION.state
changed = true
if (nextSubscription.state !== 'active') {
nextSubscription.state = DEFAULT_SUBSCRIPTION.state;
changed = true;
}
return changed ? nextSubscription : subscription
return changed ? nextSubscription : subscription;
}
+2 -2
View File
@@ -1,3 +1,3 @@
import { installInstalledAppsSync } from "./installed-apps-sync/index.js"
import { installInstalledAppsSync } from './installed-apps-sync/index.js';
installInstalledAppsSync(globalThis.WandEnhancer)
installInstalledAppsSync(globalThis.WandEnhancer);
+199 -215
View File
@@ -1,255 +1,239 @@
import {
DATA_IMAGE_URL_PREFIX,
IMAGE_FIELD_NAMES,
MAX_IMAGE_URL_SEARCH_DEPTH,
PROTOCOL_RELATIVE_IMAGE_URL_PATTERN,
REMOTE_IMAGE_URL_PATTERN,
SIDEBAR_GAME_ROW_CONTAINER_SELECTOR,
SIDEBAR_GAME_ROW_IMAGE_SELECTOR,
SIDEBAR_GAME_ROW_MORE_SELECTOR,
SIDEBAR_GAME_ROW_TITLE_SELECTOR,
SIDEBAR_GAME_ROW_TOOLTIP_ID_PATTERN,
STEAM_APP_ID_FIELD_NAMES,
STEAM_APP_ID_PATTERN,
STEAM_CONTAINER_FIELD_PATTERN,
STEAM_CONTAINER_ID_FIELD_NAMES,
STEAM_PLATFORM,
WEMOD_STEAM_COMMUNITY_CDN_BASE_URL,
} from "./constants.js"
import { isRecord, safeString, toStringId } from "./runtime.js"
DATA_IMAGE_URL_PREFIX,
IMAGE_FIELD_NAMES,
MAX_IMAGE_URL_SEARCH_DEPTH,
PROTOCOL_RELATIVE_IMAGE_URL_PATTERN,
REMOTE_IMAGE_URL_PATTERN,
SIDEBAR_GAME_ROW_CONTAINER_SELECTOR,
SIDEBAR_GAME_ROW_IMAGE_SELECTOR,
SIDEBAR_GAME_ROW_MORE_SELECTOR,
SIDEBAR_GAME_ROW_TITLE_SELECTOR,
SIDEBAR_GAME_ROW_TOOLTIP_ID_PATTERN,
STEAM_APP_ID_FIELD_NAMES,
STEAM_APP_ID_PATTERN,
STEAM_CONTAINER_FIELD_PATTERN,
STEAM_CONTAINER_ID_FIELD_NAMES,
STEAM_PLATFORM,
WEMOD_STEAM_COMMUNITY_CDN_BASE_URL,
} from './constants.js';
import { isRecord, safeString, toStringId } from './runtime.js';
export function pickImageUrl(...values) {
for (const value of values) {
const imageUrl = normalizeImageUrl(value)
if (imageUrl) {
return imageUrl
for (const value of values) {
const imageUrl = normalizeImageUrl(value);
if (imageUrl) {
return imageUrl;
}
}
}
return null
return null;
}
export function normalizeImageUrl(value, depth = 0) {
if (typeof value === "string") {
const trimmed = value.trim()
if (
REMOTE_IMAGE_URL_PATTERN.test(trimmed) ||
trimmed.startsWith(DATA_IMAGE_URL_PREFIX)
) {
return trimmed
if (typeof value === 'string') {
const trimmed = value.trim();
if (REMOTE_IMAGE_URL_PATTERN.test(trimmed) || trimmed.startsWith(DATA_IMAGE_URL_PREFIX)) {
return trimmed;
}
if (PROTOCOL_RELATIVE_IMAGE_URL_PATTERN.test(trimmed)) {
return `https:${trimmed}`;
}
return null;
}
if (PROTOCOL_RELATIVE_IMAGE_URL_PATTERN.test(trimmed)) {
return `https:${trimmed}`
if (depth > MAX_IMAGE_URL_SEARCH_DEPTH || !value) {
return null;
}
return null
}
if (depth > MAX_IMAGE_URL_SEARCH_DEPTH || !value) {
return null
}
if (Array.isArray(value)) {
for (const entry of value) {
const imageUrl = normalizeImageUrl(entry, depth + 1)
if (imageUrl) {
return imageUrl
}
}
return null
}
if (!isRecord(value)) {
return null
}
for (const key of IMAGE_FIELD_NAMES) {
const imageUrl = normalizeImageUrl(value[key], depth + 1)
if (imageUrl) {
return imageUrl
}
}
return null
}
export function getSteamClientIconUrl(...values) {
for (const value of values) {
const steamAppId = toStringId(value)
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return `${WEMOD_STEAM_COMMUNITY_CDN_BASE_URL}/${steamAppId}/client_icon/96.webp`
}
}
return null
}
export function getSidebarGameRowClientIcons() {
const byTitleId = new Map()
const byTitleName = new Map()
if (typeof document === "undefined") {
return { byTitleId, byTitleName }
}
const containers = document.querySelectorAll(
SIDEBAR_GAME_ROW_CONTAINER_SELECTOR
)
for (const container of containers) {
const imageElement = container.querySelector(
SIDEBAR_GAME_ROW_IMAGE_SELECTOR
)
const titleElement = container.querySelector(
SIDEBAR_GAME_ROW_TITLE_SELECTOR
)
const moreButton = container.querySelector(SIDEBAR_GAME_ROW_MORE_SELECTOR)
if (!imageElement || !titleElement) {
continue
}
const backgroundImageUrl = getCssBackgroundImageUrl(
safeString(imageElement.style?.backgroundImage) ||
getComputedStyle(imageElement).backgroundImage
)
if (!backgroundImageUrl) {
continue
}
const tooltipId = safeString(
moreButton?.getAttribute?.("data-tooltip-trigger-for")
)
const titleId =
tooltipId.match(SIDEBAR_GAME_ROW_TOOLTIP_ID_PATTERN)?.[1] ?? null
const titleName = normalizeTitleMatchKey(titleElement.textContent)
if (titleId) {
byTitleId.set(titleId, backgroundImageUrl)
}
if (titleName) {
byTitleName.set(titleName, backgroundImageUrl)
}
}
return { byTitleId, byTitleName }
}
export function getSidebarGameRowClientIconUrl(
sidebarIcons,
titleId,
...names
) {
const normalizedTitleId = toStringId(titleId)
if (normalizedTitleId && sidebarIcons.byTitleId.has(normalizedTitleId)) {
return sidebarIcons.byTitleId.get(normalizedTitleId) ?? null
}
for (const name of names) {
const normalizedName = normalizeTitleMatchKey(name)
if (normalizedName && sidebarIcons.byTitleName.has(normalizedName)) {
return sidebarIcons.byTitleName.get(normalizedName) ?? null
}
}
return null
}
export function findSteamAppId(...roots) {
const seen = new Set()
const queue = roots.map((value) => ({ value, depth: 0, steamContext: false }))
while (queue.length > 0) {
const current = queue.shift()
const value = current?.value
const depth = current?.depth ?? 0
const steamContext = current?.steamContext ?? false
if (!value || depth > MAX_IMAGE_URL_SEARCH_DEPTH || seen.has(value)) {
continue
}
if (typeof value === "string" || typeof value === "number") {
const steamAppId = steamContext ? toStringId(value) : null
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return steamAppId
}
continue
}
seen.add(value)
if (Array.isArray(value)) {
for (const entry of value) {
queue.push({ value: entry, depth: depth + 1, steamContext })
}
continue
for (const entry of value) {
const imageUrl = normalizeImageUrl(entry, depth + 1);
if (imageUrl) {
return imageUrl;
}
}
return null;
}
if (!isRecord(value)) {
continue
return null;
}
for (const [key, entry] of Object.entries(value)) {
const steamAppId = getSteamAppIdFromEntry(key, entry, steamContext)
if (steamAppId) {
return steamAppId
}
if (isRecord(entry) || Array.isArray(entry)) {
queue.push({
value: entry,
depth: depth + 1,
steamContext: steamContext || STEAM_CONTAINER_FIELD_PATTERN.test(key),
})
}
for (const key of IMAGE_FIELD_NAMES) {
const imageUrl = normalizeImageUrl(value[key], depth + 1);
if (imageUrl) {
return imageUrl;
}
}
}
return null
return null;
}
export function getSteamClientIconUrl(...values) {
for (const value of values) {
const steamAppId = toStringId(value);
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return `${WEMOD_STEAM_COMMUNITY_CDN_BASE_URL}/${steamAppId}/client_icon/96.webp`;
}
}
return null;
}
export function getSidebarGameRowClientIcons() {
const byTitleId = new Map();
const byTitleName = new Map();
if (typeof document === 'undefined') {
return { byTitleId, byTitleName };
}
const containers = document.querySelectorAll(SIDEBAR_GAME_ROW_CONTAINER_SELECTOR);
for (const container of containers) {
const imageElement = container.querySelector(SIDEBAR_GAME_ROW_IMAGE_SELECTOR);
const titleElement = container.querySelector(SIDEBAR_GAME_ROW_TITLE_SELECTOR);
const moreButton = container.querySelector(SIDEBAR_GAME_ROW_MORE_SELECTOR);
if (!imageElement || !titleElement) {
continue;
}
const backgroundImageUrl = getCssBackgroundImageUrl(
safeString(imageElement.style?.backgroundImage) ||
getComputedStyle(imageElement).backgroundImage,
);
if (!backgroundImageUrl) {
continue;
}
const tooltipId = safeString(moreButton?.getAttribute?.('data-tooltip-trigger-for'));
const titleId = tooltipId.match(SIDEBAR_GAME_ROW_TOOLTIP_ID_PATTERN)?.[1] ?? null;
const titleName = normalizeTitleMatchKey(titleElement.textContent);
if (titleId) {
byTitleId.set(titleId, backgroundImageUrl);
}
if (titleName) {
byTitleName.set(titleName, backgroundImageUrl);
}
}
return { byTitleId, byTitleName };
}
export function getSidebarGameRowClientIconUrl(sidebarIcons, titleId, ...names) {
const normalizedTitleId = toStringId(titleId);
if (normalizedTitleId && sidebarIcons.byTitleId.has(normalizedTitleId)) {
return sidebarIcons.byTitleId.get(normalizedTitleId) ?? null;
}
for (const name of names) {
const normalizedName = normalizeTitleMatchKey(name);
if (normalizedName && sidebarIcons.byTitleName.has(normalizedName)) {
return sidebarIcons.byTitleName.get(normalizedName) ?? null;
}
}
return null;
}
export function findSteamAppId(...roots) {
const seen = new Set();
const queue = roots.map((value) => ({ value, depth: 0, steamContext: false }));
while (queue.length > 0) {
const current = queue.shift();
const value = current?.value;
const depth = current?.depth ?? 0;
const steamContext = current?.steamContext ?? false;
if (!value || depth > MAX_IMAGE_URL_SEARCH_DEPTH || seen.has(value)) {
continue;
}
if (typeof value === 'string' || typeof value === 'number') {
const steamAppId = steamContext ? toStringId(value) : null;
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return steamAppId;
}
continue;
}
seen.add(value);
if (Array.isArray(value)) {
for (const entry of value) {
queue.push({ value: entry, depth: depth + 1, steamContext });
}
continue;
}
if (!isRecord(value)) {
continue;
}
for (const [key, entry] of Object.entries(value)) {
const steamAppId = getSteamAppIdFromEntry(key, entry, steamContext);
if (steamAppId) {
return steamAppId;
}
if (isRecord(entry) || Array.isArray(entry)) {
queue.push({
value: entry,
depth: depth + 1,
steamContext: steamContext || STEAM_CONTAINER_FIELD_PATTERN.test(key),
});
}
}
}
return null;
}
export function getInstalledAppSteamAppId(platform, sku) {
if (safeString(platform).toLowerCase() !== STEAM_PLATFORM) {
return null
}
if (safeString(platform).toLowerCase() !== STEAM_PLATFORM) {
return null;
}
return sku
return sku;
}
function normalizeTitleMatchKey(value) {
const normalized = safeString(value).trim().toLowerCase().replace(/\s+/g, " ")
return normalized || null
const normalized = safeString(value).trim().toLowerCase().replace(/\s+/g, ' ');
return normalized || null;
}
function getCssBackgroundImageUrl(value) {
const backgroundImage = safeString(value)
if (!backgroundImage || backgroundImage === "none") {
return null
}
const backgroundImage = safeString(value);
if (!backgroundImage || backgroundImage === 'none') {
return null;
}
const match = backgroundImage.match(/url\((['"]?)(.*?)\1\)/i)
if (!match?.[2]) {
return null
}
const match = backgroundImage.match(/url\((['"]?)(.*?)\1\)/i);
if (!match?.[2]) {
return null;
}
return normalizeImageUrl(match[2])
return normalizeImageUrl(match[2]);
}
function getSteamAppIdFromEntry(key, entry, steamContext) {
if (STEAM_APP_ID_FIELD_NAMES.has(key)) {
const steamAppId = toStringId(entry)
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return steamAppId
if (STEAM_APP_ID_FIELD_NAMES.has(key)) {
const steamAppId = toStringId(entry);
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return steamAppId;
}
}
}
if (steamContext && STEAM_CONTAINER_ID_FIELD_NAMES.has(key)) {
const steamAppId = toStringId(entry)
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return steamAppId
if (steamContext && STEAM_CONTAINER_ID_FIELD_NAMES.has(key)) {
const steamAppId = toStringId(entry);
if (steamAppId && STEAM_APP_ID_PATTERN.test(steamAppId)) {
return steamAppId;
}
}
}
return null
return null;
}
@@ -1,95 +1,96 @@
export const GLOBAL_FLAG = "__wandInstalledAppsSyncInstalled"
export const BIND_CHANNEL = "wand-remote-set-handler-bind"
export const SYNC_CHANNEL = "wand-remote-installed-apps"
export const TRAINER_SNAPSHOT_CHANNEL = "wand-remote-sync"
export const GAME_STATUS_CHANNEL = "wand-remote-game-status"
export const COMMAND_REQUEST_CHANNEL = "wand-remote-command"
export const COMMAND_RESPONSE_CHANNEL = "wand-remote-command-response"
export const REMOTE_COMMAND_LAUNCH = "launch"
export const REMOTE_COMMAND_STOP = "stop"
export const REMOTE_COMMAND_TRIGGER = "remote"
export const RETRY_DELAY_MS = 1000
export const MAX_BOOTSTRAP_ATTEMPTS = 60
export const SYNC_INTERVAL_MS = 15000
export const OPTIONAL_SERVICES_RETRY_INTERVAL_MS = 1000
export const FOLLOW_UP_SYNC_DELAY_MS = 2500
export const UNAVAILABLE_TITLES_BATCH_SIZE = 250
export const BOOTSTRAP_LOG_THROTTLE_ATTEMPTS = 5
export const GLOBAL_FLAG = '__wandInstalledAppsSyncInstalled';
export const BIND_CHANNEL = 'wand-remote-set-handler-bind';
export const SYNC_CHANNEL = 'wand-remote-installed-apps';
export const TRAINER_SNAPSHOT_CHANNEL = 'wand-remote-sync';
export const GAME_STATUS_CHANNEL = 'wand-remote-game-status';
export const COMMAND_REQUEST_CHANNEL = 'wand-remote-command';
export const COMMAND_RESPONSE_CHANNEL = 'wand-remote-command-response';
export const REMOTE_COMMAND_LAUNCH = 'launch';
export const REMOTE_COMMAND_STOP = 'stop';
export const REMOTE_COMMAND_TRIGGER = 'remote';
export const RETRY_DELAY_MS = 1000;
export const MAX_BOOTSTRAP_ATTEMPTS = 60;
export const SYNC_INTERVAL_MS = 15000;
export const OPTIONAL_SERVICES_RETRY_INTERVAL_MS = 1000;
export const MAX_OPTIONAL_SERVICES_ATTEMPTS = 60;
export const FOLLOW_UP_SYNC_DELAY_MS = 2500;
export const UNAVAILABLE_TITLES_BATCH_SIZE = 250;
export const BOOTSTRAP_LOG_THROTTLE_ATTEMPTS = 5;
export const CONTAINER_LOG_THROTTLE_ATTEMPTS = 10;
export const CONTAINER_GRAPH_MAX_DEPTH = 4;
// Wand's webpack module exports the trainer-launch-request class under key `vO`.
// Required so `trainerService.launch(req)` records `getMetadata(vO)` state in Wand. See AGENTS.md "Remote Play".
export const TRAINER_LAUNCH_REQUEST_EXPORT_KEY = "vO"
export const TRAINER_LAUNCH_REQUEST_EXPORT_KEY = 'vO';
export const SNAPSHOT_ENTRY_KEY_PREFIX = Object.freeze({
TITLE: "title:",
GAME: "game:",
APP: "app:",
})
export const GAME_LAUNCHED_EVENT = "game-launched"
export const GAME_ENDED_EVENT = "game-ended"
export const SYNTHETIC_SESSION_RUNNING_EVENT = "trainer-running"
export const SYNTHETIC_SESSION_IDLE_EVENT = "trainer-idle"
export const TRAINER_ENDED_EVENT = "trainer-ended"
export const REMOTE_STOP_EVENT = "remote-stop"
export const STEAM_PLATFORM = "steam"
export const STEAM_APP_ID_PATTERN = /^\d+$/
export const WEMOD_STEAM_COMMUNITY_CDN_BASE_URL =
"https://api-cdn.wemod.com/steam_community"
export const REMOTE_IMAGE_URL_PATTERN = /^https?:\/\//i
export const PROTOCOL_RELATIVE_IMAGE_URL_PATTERN = /^\/\//
export const DATA_IMAGE_URL_PREFIX = "data:image/"
export const MAX_IMAGE_URL_SEARCH_DEPTH = 4
export const SIDEBAR_GAME_ROW_CONTAINER_SELECTOR = ".sidebar-game-row-container"
export const SIDEBAR_GAME_ROW_IMAGE_SELECTOR = ".sidebar-game-row-image"
export const SIDEBAR_GAME_ROW_TITLE_SELECTOR = ".sidebar-game-row-title"
export const SIDEBAR_GAME_ROW_MORE_SELECTOR = ".sidebar-game-row-more"
export const SIDEBAR_GAME_ROW_TOOLTIP_ID_PATTERN =
/sidebar-game-row-(.+?)-more-button-tooltip/
export const STEAM_APP_ID_FIELD_NAMES = new Set(["steamAppId", "steamAppID"])
export const STEAM_CONTAINER_FIELD_PATTERN = /steam/i
export const STEAM_CONTAINER_ID_FIELD_NAMES = new Set(["appId", "appID", "id"])
export const LOG_PREFIX = "[wand-installed-apps-sync]"
export const LOG_FILE_NAME = "wand-remote-installed-apps-sync.log"
export const EXCLUDED_UNAVAILABLE_TITLE_PLATFORMS = new Set(["standalone"])
TITLE: 'title:',
GAME: 'game:',
APP: 'app:',
});
export const GAME_LAUNCHED_EVENT = 'game-launched';
export const GAME_ENDED_EVENT = 'game-ended';
export const SYNTHETIC_SESSION_RUNNING_EVENT = 'trainer-running';
export const SYNTHETIC_SESSION_IDLE_EVENT = 'trainer-idle';
export const TRAINER_ENDED_EVENT = 'trainer-ended';
export const REMOTE_STOP_EVENT = 'remote-stop';
export const STEAM_PLATFORM = 'steam';
export const STEAM_APP_ID_PATTERN = /^\d+$/;
export const WEMOD_STEAM_COMMUNITY_CDN_BASE_URL = 'https://api-cdn.wemod.com/steam_community';
export const REMOTE_IMAGE_URL_PATTERN = /^https?:\/\//i;
export const PROTOCOL_RELATIVE_IMAGE_URL_PATTERN = /^\/\//;
export const DATA_IMAGE_URL_PREFIX = 'data:image/';
export const MAX_IMAGE_URL_SEARCH_DEPTH = 4;
export const SIDEBAR_GAME_ROW_CONTAINER_SELECTOR = '.sidebar-game-row-container';
export const SIDEBAR_GAME_ROW_IMAGE_SELECTOR = '.sidebar-game-row-image';
export const SIDEBAR_GAME_ROW_TITLE_SELECTOR = '.sidebar-game-row-title';
export const SIDEBAR_GAME_ROW_MORE_SELECTOR = '.sidebar-game-row-more';
export const SIDEBAR_GAME_ROW_TOOLTIP_ID_PATTERN = /sidebar-game-row-(.+?)-more-button-tooltip/;
export const STEAM_APP_ID_FIELD_NAMES = new Set(['steamAppId', 'steamAppID']);
export const STEAM_CONTAINER_FIELD_PATTERN = /steam/i;
export const STEAM_CONTAINER_ID_FIELD_NAMES = new Set(['appId', 'appID', 'id']);
export const LOG_PREFIX = '[wand-installed-apps-sync]';
export const LOG_FILE_NAME = 'wand-remote-installed-apps-sync.log';
export const EXCLUDED_UNAVAILABLE_TITLE_PLATFORMS = new Set(['standalone']);
export const IMAGE_FIELD_NAMES = [
"imageUrl",
"imageURL",
"iconUrl",
"iconURL",
"coverUrl",
"coverURL",
"thumbnailUrl",
"thumbnailURL",
"logoUrl",
"logoURL",
"headerImageUrl",
"headerImageURL",
"boxArtUrl",
"boxartUrl",
"posterUrl",
"tileUrl",
"capsuleUrl",
"heroUrl",
"backgroundUrl",
"image",
"icon",
"cover",
"thumbnail",
"logo",
"headerImage",
"header",
"boxArt",
"boxart",
"poster",
"tile",
"capsule",
"hero",
"background",
"large",
"medium",
"small",
"original",
"source",
"href",
"uri",
"url",
"src",
]
'imageUrl',
'imageURL',
'iconUrl',
'iconURL',
'coverUrl',
'coverURL',
'thumbnailUrl',
'thumbnailURL',
'logoUrl',
'logoURL',
'headerImageUrl',
'headerImageURL',
'boxArtUrl',
'boxartUrl',
'posterUrl',
'tileUrl',
'capsuleUrl',
'heroUrl',
'backgroundUrl',
'image',
'icon',
'cover',
'thumbnail',
'logo',
'headerImage',
'header',
'boxArt',
'boxart',
'poster',
'tile',
'capsule',
'hero',
'background',
'large',
'medium',
'small',
'original',
'source',
'href',
'uri',
'url',
'src',
];
@@ -1,338 +1,309 @@
import {
GAME_ENDED_EVENT,
GAME_LAUNCHED_EVENT,
GAME_STATUS_CHANNEL,
SYNTHETIC_SESSION_IDLE_EVENT,
SYNTHETIC_SESSION_RUNNING_EVENT,
TRAINER_ENDED_EVENT,
TRAINER_SNAPSHOT_CHANNEL,
} from "./constants.js"
import { isRecord, safeString, toStringId } from "./runtime.js"
GAME_ENDED_EVENT,
GAME_LAUNCHED_EVENT,
GAME_STATUS_CHANNEL,
SYNTHETIC_SESSION_IDLE_EVENT,
SYNTHETIC_SESSION_RUNNING_EVENT,
TRAINER_ENDED_EVENT,
TRAINER_SNAPSHOT_CHANNEL,
} from './constants.js';
import { invokeIpc, isRecord, safeString, toStringId } from './runtime.js';
export function createIdleGameSession() {
return {
state: "idle",
event: "snapshot",
processId: null,
gameId: null,
titleId: null,
titleName: null,
sessionDurationSeconds: null,
startedAt: null,
endedAt: null,
}
return {
state: 'idle',
event: 'snapshot',
processId: null,
gameId: null,
titleId: null,
titleName: null,
sessionDurationSeconds: null,
startedAt: null,
endedAt: null,
};
}
export function createIdleTrainerStatus() {
return {
state: "idle",
event: "snapshot",
trainerId: null,
displayName: null,
gameId: null,
titleId: null,
}
return {
state: 'idle',
event: 'snapshot',
trainerId: null,
displayName: null,
gameId: null,
titleId: null,
};
}
export function installGameStatusSubscriptions(state) {
let installed = false
let installed = false;
if (
state.gameLifecycleService &&
!state.gameLifecycleSubscriptionsInstalled
) {
installed = installLifecycleSubscriptions(state) || installed
}
if (state.gameLifecycleService && !state.gameLifecycleSubscriptionsInstalled) {
installed = installLifecycleSubscriptions(state) || installed;
}
if (
state.trainerVisibilityService &&
!state.trainerVisibilitySubscriptionInstalled
) {
state.currentRunningTrainer = normalizeRunningTrainerStatus(
state.trainerVisibilityService.runningTrainer,
"snapshot"
)
syncGameSessionFromTrainerStatus(state, state.currentRunningTrainer)
installed = installTrainerVisibilitySubscription(state) || installed
state.trainerVisibilitySubscriptionInstalled = true
}
if (state.trainerVisibilityService && !state.trainerVisibilitySubscriptionInstalled) {
state.currentRunningTrainer = normalizeRunningTrainerStatus(
state.trainerVisibilityService.runningTrainer,
'snapshot',
);
syncGameSessionFromTrainerStatus(state, state.currentRunningTrainer);
installed = installTrainerVisibilitySubscription(state) || installed;
state.trainerVisibilitySubscriptionInstalled = true;
}
if (
state.trainerService &&
!state.trainerEndedSubscriptionInstalled &&
typeof state.trainerService.onTrainerEnded === "function"
) {
state.trainerService.onTrainerEnded(() => {
clearTrainerSnapshot(state, TRAINER_ENDED_EVENT, true)
})
state.trainerEndedSubscriptionInstalled = true
installed = true
}
if (
state.trainerService &&
!state.trainerEndedSubscriptionInstalled &&
typeof state.trainerService.onTrainerEnded === 'function'
) {
state.trainerService.onTrainerEnded(() => {
clearTrainerSnapshot(state, TRAINER_ENDED_EVENT, true);
});
state.trainerEndedSubscriptionInstalled = true;
installed = true;
}
if (!installed) {
return
}
if (!installed) {
return;
}
state.log(
"info",
"Game status hooks installed.",
`lifecycle=${state.gameLifecycleSubscriptionsInstalled ? "yes" : "no"}, trainer=${state.trainerVisibilitySubscriptionInstalled ? "yes" : "no"}, trainerEnded=${state.trainerEndedSubscriptionInstalled ? "yes" : "no"}`
)
void syncGameStatus(state, true)
state.log(
'info',
'Game status hooks installed.',
`lifecycle=${state.gameLifecycleSubscriptionsInstalled ? 'yes' : 'no'}, trainer=${state.trainerVisibilitySubscriptionInstalled ? 'yes' : 'no'}, trainerEnded=${state.trainerEndedSubscriptionInstalled ? 'yes' : 'no'}`,
);
void syncGameStatus(state, true);
}
export function clearTrainerSnapshot(state, reason, clearSession = false) {
state.currentRunningTrainer = {
...createIdleTrainerStatus(),
event: reason,
}
state.currentRunningTrainer = {
...createIdleTrainerStatus(),
event: reason,
};
if (clearSession) {
clearGameSession(state, reason)
} else if (
state.currentGameSession.state === "running" &&
isSyntheticGameSessionEvent(state.currentGameSession.event)
) {
syncGameSessionFromTrainerStatus(state, state.currentRunningTrainer)
}
if (clearSession) {
clearGameSession(state, reason);
} else if (
state.currentGameSession.state === 'running' &&
isSyntheticGameSessionEvent(state.currentGameSession.event)
) {
syncGameSessionFromTrainerStatus(state, state.currentRunningTrainer);
}
void syncGameStatus(state, true)
if (!state.ipcRenderer) {
return
}
try {
void state.ipcRenderer.invoke(TRAINER_SNAPSHOT_CHANNEL, null)
} catch (error) {
state.log(
"warn",
"Trainer snapshot clear IPC failed.",
error?.stack || String(error)
)
}
void syncGameStatus(state, true);
void invokeIpc(state, TRAINER_SNAPSHOT_CHANNEL, null, 'Trainer snapshot clear');
}
export async function syncGameStatus(state, force = false) {
if (!state.ipcRenderer) {
return false
}
if (!state.ipcRenderer) {
return false;
}
const snapshot = buildGameStatusSnapshot(state)
const signature = makeGameStatusSignature(snapshot)
if (!force && signature === state.lastGameStatusSignature) {
return false
}
const snapshot = buildGameStatusSnapshot(state);
const signature = makeGameStatusSignature(snapshot);
if (!force && signature === state.lastGameStatusSignature) {
return false;
}
state.lastGameStatusSignature = signature
state.lastGameStatusSignature = signature;
try {
await state.ipcRenderer.invoke(GAME_STATUS_CHANNEL, snapshot)
state.log(
"info",
"Game status snapshot sent.",
`session=${snapshot.session.state}/${snapshot.session.event}, trainer=${snapshot.trainer.state}/${snapshot.trainer.event}`
)
return true
} catch (error) {
state.log(
"error",
"Game status snapshot IPC failed.",
error?.stack || String(error)
)
return false
}
const sent = await invokeIpc(
state,
GAME_STATUS_CHANNEL,
snapshot,
'Game status snapshot',
'error',
);
if (sent) {
state.log(
'info',
'Game status snapshot sent.',
`session=${snapshot.session.state}/${snapshot.session.event}, trainer=${snapshot.trainer.state}/${snapshot.trainer.event}`,
);
}
return sent;
}
function installLifecycleSubscriptions(state) {
let installed = false
let installed = false;
if (typeof state.gameLifecycleService.onGameLaunched === "function") {
state.gameLifecycleService.onGameLaunched((event) => {
state.currentGameSession = {
state: "running",
event: GAME_LAUNCHED_EVENT,
processId:
typeof event?.processId === "number" ? event.processId : null,
gameId: toStringId(event?.gameId),
titleId: toStringId(event?.titleId),
titleName: safeString(event?.titleName),
sessionDurationSeconds: null,
startedAt: new Date().toISOString(),
endedAt: null,
}
void syncGameStatus(state, true)
})
installed = true
}
if (typeof state.gameLifecycleService.onGameLaunched === 'function') {
state.gameLifecycleService.onGameLaunched((event) => {
state.currentGameSession = {
state: 'running',
event: GAME_LAUNCHED_EVENT,
processId: typeof event?.processId === 'number' ? event.processId : null,
gameId: toStringId(event?.gameId),
titleId: toStringId(event?.titleId),
titleName: safeString(event?.titleName),
sessionDurationSeconds: null,
startedAt: new Date().toISOString(),
endedAt: null,
};
void syncGameStatus(state, true);
});
installed = true;
}
if (typeof state.gameLifecycleService.onGameEnded === "function") {
state.gameLifecycleService.onGameEnded((event) => {
clearGameSession(
state,
GAME_ENDED_EVENT,
typeof event?.sessionDurationSeconds === "number"
? event.sessionDurationSeconds
: state.currentGameSession.sessionDurationSeconds
)
void syncGameStatus(state, true)
})
installed = true
}
if (typeof state.gameLifecycleService.onGameEnded === 'function') {
state.gameLifecycleService.onGameEnded((event) => {
clearGameSession(
state,
GAME_ENDED_EVENT,
typeof event?.sessionDurationSeconds === 'number'
? event.sessionDurationSeconds
: state.currentGameSession.sessionDurationSeconds,
);
void syncGameStatus(state, true);
});
installed = true;
}
if (installed) {
state.gameLifecycleSubscriptionsInstalled = true
}
if (installed) {
state.gameLifecycleSubscriptionsInstalled = true;
}
return installed
return installed;
}
function installTrainerVisibilitySubscription(state) {
if (
typeof state.trainerVisibilityService.onRunningTrainerChanged !== "function"
) {
return false
}
if (typeof state.trainerVisibilityService.onRunningTrainerChanged !== 'function') {
return false;
}
state.trainerVisibilityService.onRunningTrainerChanged((runningTrainer) => {
state.currentRunningTrainer = normalizeRunningTrainerStatus(
runningTrainer,
runningTrainer ? "trainer-running" : "trainer-idle"
)
syncGameSessionFromTrainerStatus(state, state.currentRunningTrainer)
void syncGameStatus(state, true)
})
state.trainerVisibilityService.onRunningTrainerChanged((runningTrainer) => {
state.currentRunningTrainer = normalizeRunningTrainerStatus(
runningTrainer,
runningTrainer ? 'trainer-running' : 'trainer-idle',
);
syncGameSessionFromTrainerStatus(state, state.currentRunningTrainer);
void syncGameStatus(state, true);
});
return true
return true;
}
function normalizeRunningTrainerStatus(runningTrainer, event = "snapshot") {
const info = isRecord(runningTrainer?.info)
? runningTrainer.info
: isRecord(runningTrainer)
? runningTrainer
: null
if (!info) {
return {
...createIdleTrainerStatus(),
event,
function normalizeRunningTrainerStatus(runningTrainer, event = 'snapshot') {
const info = isRecord(runningTrainer?.info)
? runningTrainer.info
: isRecord(runningTrainer)
? runningTrainer
: null;
if (!info) {
return {
...createIdleTrainerStatus(),
event,
};
}
}
return {
state: "running",
event,
trainerId: toStringId(info.trainerId) || toStringId(info.id),
displayName: safeString(
info.displayName,
info.gameName,
info.titleName,
info.title,
info.name
),
gameId: toStringId(info.gameId),
titleId: toStringId(info.titleId),
}
return {
state: 'running',
event,
trainerId: toStringId(info.trainerId) || toStringId(info.id),
displayName: safeString(
info.displayName,
info.gameName,
info.titleName,
info.title,
info.name,
),
gameId: toStringId(info.gameId),
titleId: toStringId(info.titleId),
};
}
function syncGameSessionFromTrainerStatus(state, trainerStatus) {
if (trainerStatus?.state === "running") {
if (trainerStatus?.state === 'running') {
if (
state.currentGameSession.state === 'running' &&
!isSyntheticGameSessionEvent(state.currentGameSession.event)
) {
return false;
}
state.currentGameSession = {
state: 'running',
event: SYNTHETIC_SESSION_RUNNING_EVENT,
processId: state.currentGameSession.processId,
gameId: trainerStatus.gameId ?? state.currentGameSession.gameId,
titleId: trainerStatus.titleId ?? state.currentGameSession.titleId,
titleName: trainerStatus.displayName ?? state.currentGameSession.titleName,
sessionDurationSeconds: null,
startedAt:
state.currentGameSession.state === 'running' &&
isSyntheticGameSessionEvent(state.currentGameSession.event)
? state.currentGameSession.startedAt
: new Date().toISOString(),
endedAt: null,
};
return true;
}
if (
state.currentGameSession.state === "running" &&
!isSyntheticGameSessionEvent(state.currentGameSession.event)
state.currentGameSession.state !== 'running' ||
!isSyntheticGameSessionEvent(state.currentGameSession.event)
) {
return false
return false;
}
state.currentGameSession = {
state: "running",
event: SYNTHETIC_SESSION_RUNNING_EVENT,
processId: state.currentGameSession.processId,
gameId: trainerStatus.gameId ?? state.currentGameSession.gameId,
titleId: trainerStatus.titleId ?? state.currentGameSession.titleId,
titleName:
trainerStatus.displayName ?? state.currentGameSession.titleName,
sessionDurationSeconds: null,
startedAt:
state.currentGameSession.state === "running" &&
isSyntheticGameSessionEvent(state.currentGameSession.event)
? state.currentGameSession.startedAt
: new Date().toISOString(),
endedAt: null,
}
const startedAt = state.currentGameSession.startedAt;
const sessionDurationSeconds = startedAt
? Math.max(0, Math.round((Date.now() - new Date(startedAt).getTime()) / 1000))
: null;
return true
}
clearGameSession(state, SYNTHETIC_SESSION_IDLE_EVENT, sessionDurationSeconds);
if (
state.currentGameSession.state !== "running" ||
!isSyntheticGameSessionEvent(state.currentGameSession.event)
) {
return false
}
const startedAt = state.currentGameSession.startedAt
const sessionDurationSeconds = startedAt
? Math.max(
0,
Math.round((Date.now() - new Date(startedAt).getTime()) / 1000)
)
: null
clearGameSession(state, SYNTHETIC_SESSION_IDLE_EVENT, sessionDurationSeconds)
return true
return true;
}
function clearGameSession(
state,
event,
sessionDurationSeconds = state.currentGameSession.sessionDurationSeconds
) {
state.currentGameSession = {
state: "idle",
state,
event,
processId: null,
gameId: null,
titleId: null,
titleName: null,
sessionDurationSeconds,
startedAt: state.currentGameSession.startedAt,
endedAt: new Date().toISOString(),
}
sessionDurationSeconds = state.currentGameSession.sessionDurationSeconds,
) {
state.currentGameSession = {
state: 'idle',
event,
processId: null,
gameId: null,
titleId: null,
titleName: null,
sessionDurationSeconds,
startedAt: state.currentGameSession.startedAt,
endedAt: new Date().toISOString(),
};
}
function isSyntheticGameSessionEvent(event) {
return (
event === SYNTHETIC_SESSION_RUNNING_EVENT ||
event === SYNTHETIC_SESSION_IDLE_EVENT
)
return event === SYNTHETIC_SESSION_RUNNING_EVENT || event === SYNTHETIC_SESSION_IDLE_EVENT;
}
function buildGameStatusSnapshot(state) {
return {
instanceId: "wand-game-status",
updatedAt: new Date().toISOString(),
session: { ...state.currentGameSession },
trainer: { ...state.currentRunningTrainer },
}
return {
instanceId: 'wand-game-status',
updatedAt: new Date().toISOString(),
session: { ...state.currentGameSession },
trainer: { ...state.currentRunningTrainer },
};
}
function makeGameStatusSignature(snapshot) {
return [
snapshot.session.state,
snapshot.session.event,
snapshot.session.processId ?? "",
snapshot.session.gameId ?? "",
snapshot.session.titleId ?? "",
snapshot.session.titleName ?? "",
snapshot.session.sessionDurationSeconds ?? "",
snapshot.session.startedAt ?? "",
snapshot.session.endedAt ?? "",
snapshot.trainer.state,
snapshot.trainer.event,
snapshot.trainer.trainerId ?? "",
snapshot.trainer.displayName ?? "",
snapshot.trainer.gameId ?? "",
snapshot.trainer.titleId ?? "",
].join("|")
return [
snapshot.session.state,
snapshot.session.event,
snapshot.session.processId ?? '',
snapshot.session.gameId ?? '',
snapshot.session.titleId ?? '',
snapshot.session.titleName ?? '',
snapshot.session.sessionDurationSeconds ?? '',
snapshot.session.startedAt ?? '',
snapshot.session.endedAt ?? '',
snapshot.trainer.state,
snapshot.trainer.event,
snapshot.trainer.trainerId ?? '',
snapshot.trainer.displayName ?? '',
snapshot.trainer.gameId ?? '',
snapshot.trainer.titleId ?? '',
].join('|');
}
+349 -334
View File
@@ -1,421 +1,436 @@
import {
BIND_CHANNEL,
BOOTSTRAP_LOG_THROTTLE_ATTEMPTS,
COMMAND_REQUEST_CHANNEL,
FOLLOW_UP_SYNC_DELAY_MS,
GLOBAL_FLAG,
MAX_BOOTSTRAP_ATTEMPTS,
OPTIONAL_SERVICES_RETRY_INTERVAL_MS,
RETRY_DELAY_MS,
SYNC_CHANNEL,
SYNC_INTERVAL_MS,
} from "./constants.js"
BIND_CHANNEL,
BOOTSTRAP_LOG_THROTTLE_ATTEMPTS,
COMMAND_REQUEST_CHANNEL,
CONTAINER_LOG_THROTTLE_ATTEMPTS,
FOLLOW_UP_SYNC_DELAY_MS,
GLOBAL_FLAG,
MAX_BOOTSTRAP_ATTEMPTS,
MAX_OPTIONAL_SERVICES_ATTEMPTS,
OPTIONAL_SERVICES_RETRY_INTERVAL_MS,
RETRY_DELAY_MS,
SYNC_CHANNEL,
SYNC_INTERVAL_MS,
} from './constants.js';
import {
createIdleGameSession,
createIdleTrainerStatus,
installGameStatusSubscriptions,
} from "./game-status.js"
createIdleGameSession,
createIdleTrainerStatus,
installGameStatusSubscriptions,
} from './game-status.js';
import {
buildSnapshot,
makeInstalledAppsSignature,
refreshUnavailableTitles,
resolveInstalledData,
} from "./installed-data.js"
import { createLogger } from "./logger.js"
import { handleRemoteCommandRequest } from "./remote-commands.js"
buildSnapshot,
makeInstalledAppsSignature,
refreshUnavailableTitles,
resolveInstalledData,
} from './installed-data.js';
import { createLogger } from './logger.js';
import { handleRemoteCommandRequest } from './remote-commands.js';
import {
getAppRoot,
getAureliaContainer,
getRequire,
getWebpackRequire,
hasAppRoot,
isRecord,
summarizeAureliaSubtree,
} from "./runtime.js"
formatError,
getAppRoot,
getAureliaContainer,
getRequire,
getWebpackRequire,
hasAppRoot,
invokeIpc,
isRecord,
summarizeAureliaSubtree,
} from './runtime.js';
import {
getInstalledAppsService,
getStoreRef,
hasMissingOptionalServices,
resolveOptionalServices,
} from "./services.js"
getInstalledAppsService,
getStoreRef,
hasMissingOptionalServices,
hasUnresolvedServices,
resolveOptionalServices,
} from './services.js';
export function installInstalledAppsSync(WandEnhancer) {
if (globalThis[GLOBAL_FLAG]) {
return
}
if (globalThis[GLOBAL_FLAG]) {
return;
}
globalThis[GLOBAL_FLAG] = true
globalThis[GLOBAL_FLAG] = true;
const state = createState(WandEnhancer)
state.resolveRemoteCommandServices = () => resolveRemoteCommandServices(state)
state.queueSync = (force = false) => queueSync(state, force)
state.queueFollowUpSync = () => queueFollowUpSync(state)
const state = createState(WandEnhancer);
state.resolveRemoteCommandServices = () => resolveRemoteCommandServices(state);
state.queueSync = (force = false) => queueSync(state, force);
state.queueFollowUpSync = () => queueFollowUpSync(state);
state.log(
"info",
"Script loaded.",
`logFile=${globalThis.__wandInstalledAppsSyncLogFile || "console-only"}`
)
retryBootstrap(state)
state.log(
'info',
'Script loaded.',
`logFile=${globalThis.__wandInstalledAppsSyncLogFile || 'console-only'}`,
);
retryBootstrap(state);
}
function createState(WandEnhancer) {
return {
WandEnhancer,
log: createLogger(WandEnhancer),
lastSignature: null,
lastGameStatusSignature: null,
refreshTimer: null,
followUpSyncTimer: null,
pollTimer: null,
optionalServicesTimer: null,
bootstrapAttempts: 0,
bridgeBound: false,
refreshPatched: false,
installedAppsService: null,
gameLifecycleService: null,
trainerVisibilityService: null,
unavailableTitlesService: null,
storeRef: null,
ipcRenderer: null,
lastBootstrapReason: null,
gameLifecycleSubscriptionsInstalled: false,
trainerVisibilitySubscriptionInstalled: false,
trainerEndedSubscriptionInstalled: false,
unavailableTitlesFetchKey: null,
unavailableTitlesFetchPromise: null,
unavailableTitlesById: {},
trainerApiService: null,
trainerService: null,
trainerLaunchRequestCtor: null,
commandListenerInstalled: false,
missingOptionalServiceWarnings: new Set(),
currentGameSession: createIdleGameSession(),
currentRunningTrainer: createIdleTrainerStatus(),
resolveRemoteCommandServices: null,
queueSync: null,
queueFollowUpSync: null,
}
return {
WandEnhancer,
log: createLogger(WandEnhancer),
lastSignature: null,
lastGameStatusSignature: null,
refreshTimer: null,
followUpSyncTimer: null,
pollTimer: null,
optionalServicesTimer: null,
bootstrapAttempts: 0,
optionalServicesAttempts: 0,
bridgeBound: false,
bridgeBinding: false,
refreshPatched: false,
installedAppsService: null,
gameLifecycleService: null,
trainerVisibilityService: null,
unavailableTitlesService: null,
storeRef: null,
ipcRenderer: null,
lastBootstrapReason: null,
gameLifecycleSubscriptionsInstalled: false,
trainerVisibilitySubscriptionInstalled: false,
trainerEndedSubscriptionInstalled: false,
unavailableTitlesFetchKey: null,
unavailableTitlesFetchPromise: null,
unavailableTitlesById: {},
trainerApiService: null,
trainerService: null,
trainerLaunchRequestCtor: null,
commandListenerInstalled: false,
missingOptionalServiceWarnings: new Set(),
currentGameSession: createIdleGameSession(),
currentRunningTrainer: createIdleTrainerStatus(),
resolveRemoteCommandServices: null,
queueSync: null,
queueFollowUpSync: null,
};
}
function setBootstrapReason(state, reason) {
if (
reason === state.lastBootstrapReason &&
state.bootstrapAttempts % BOOTSTRAP_LOG_THROTTLE_ATTEMPTS !== 0
) {
return
}
if (
reason === state.lastBootstrapReason &&
state.bootstrapAttempts % BOOTSTRAP_LOG_THROTTLE_ATTEMPTS !== 0
) {
return;
}
state.lastBootstrapReason = reason
state.log(
"info",
`Bootstrap waiting: ${reason}.`,
`attempt=${state.bootstrapAttempts + 1}/${MAX_BOOTSTRAP_ATTEMPTS}`
)
state.lastBootstrapReason = reason;
state.log(
'info',
`Bootstrap waiting: ${reason}.`,
`attempt=${state.bootstrapAttempts + 1}/${MAX_BOOTSTRAP_ATTEMPTS}`,
);
}
function bindBridge(state) {
if (state.bridgeBound || !state.ipcRenderer) {
return
}
async function bindBridge(state) {
if (state.bridgeBound || state.bridgeBinding || !state.ipcRenderer) {
return;
}
state.bridgeBound = true
if (!state.commandListenerInstalled) {
state.ipcRenderer.on(COMMAND_REQUEST_CHANNEL, (event, request) =>
handleRemoteCommandRequest(state, event, request),
);
state.commandListenerInstalled = true;
state.log('info', 'Bridge remote command handler installed.');
}
if (!state.commandListenerInstalled) {
state.ipcRenderer.on(COMMAND_REQUEST_CHANNEL, (event, request) =>
handleRemoteCommandRequest(state, event, request)
)
state.commandListenerInstalled = true
state.log("info", "Bridge remote command handler installed.")
}
try {
void state.ipcRenderer.invoke(BIND_CHANNEL)
state.log("info", "Bridge set-value handler bind requested.")
} catch (error) {
state.log("warn", "Bridge bind failed.", error?.stack || String(error))
}
// Await the bind: invoke rejects asynchronously, so marking the bridge bound up
// front left set-value permanently dead whenever the main-process handler was not
// registered yet - and the log still claimed success.
state.bridgeBinding = true;
try {
await state.ipcRenderer.invoke(BIND_CHANNEL);
state.bridgeBound = true;
state.log('info', 'Bridge set-value handler bound.');
} catch (error) {
state.log('warn', 'Bridge bind failed; will retry on the next sync.', formatError(error));
} finally {
state.bridgeBinding = false;
}
}
async function syncInstalledApps(state, force = false) {
if (!state.ipcRenderer || (!state.installedAppsService && !state.storeRef)) {
return false
}
const data = resolveInstalledData(state)
if (!data) {
if (state.installedAppsService) {
state.log(
"warn",
"Service resolved but installedApps is empty/undefined. Store fallback also unavailable."
)
if (!state.ipcRenderer || (!state.installedAppsService && !state.storeRef)) {
return false;
}
return false
}
if (Object.keys(data.rawInstalledApps).length > 0) {
await refreshUnavailableTitles(state, data.rawInstalledApps, force)
}
const data = resolveInstalledData(state);
if (!data) {
if (state.installedAppsService) {
state.log(
'warn',
'Service resolved but installedApps is empty/undefined. Store fallback also unavailable.',
);
}
return false;
}
const snapshot = buildSnapshot(state)
if (!snapshot) {
state.log("warn", "Snapshot build returned nothing.")
return false
}
if (Object.keys(data.rawInstalledApps).length > 0) {
await refreshUnavailableTitles(state, data.rawInstalledApps, force);
}
const signature = makeInstalledAppsSignature(snapshot)
if (!force && signature === state.lastSignature) {
return false
}
const snapshot = buildSnapshot(state);
if (!snapshot) {
state.log('warn', 'Snapshot build returned nothing.');
return false;
}
state.lastSignature = signature
const signature = makeInstalledAppsSignature(snapshot);
if (!force && signature === state.lastSignature) {
return false;
}
try {
await state.ipcRenderer.invoke(SYNC_CHANNEL, snapshot)
state.log(
"info",
"Installed apps snapshot sent.",
`apps=${snapshot.apps.length}, catalogGames=${snapshot.diagnostics.catalogGames}, rawInstalledApps=${snapshot.diagnostics.rawInstalledApps}`
)
return true
} catch (error) {
state.log(
"error",
"Installed apps snapshot IPC failed.",
error?.stack || String(error)
)
return false
}
state.lastSignature = signature;
const sent = await invokeIpc(state, SYNC_CHANNEL, snapshot, 'Installed apps snapshot', 'error');
if (sent) {
state.log(
'info',
'Installed apps snapshot sent.',
`apps=${snapshot.apps.length}, catalogGames=${snapshot.diagnostics.catalogGames}, rawInstalledApps=${snapshot.diagnostics.rawInstalledApps}`,
);
}
return sent;
}
function queueSync(state, force = false) {
if (state.refreshTimer) {
clearTimeout(state.refreshTimer)
}
if (state.refreshTimer) {
clearTimeout(state.refreshTimer);
}
state.refreshTimer = setTimeout(() => {
state.refreshTimer = null
void syncInstalledApps(state, force)
}, 0)
state.refreshTimer = setTimeout(() => {
state.refreshTimer = null;
void syncInstalledApps(state, force);
}, 0);
}
function queueFollowUpSync(state) {
if (state.followUpSyncTimer) {
clearTimeout(state.followUpSyncTimer)
}
if (state.followUpSyncTimer) {
clearTimeout(state.followUpSyncTimer);
}
state.followUpSyncTimer = setTimeout(() => {
state.followUpSyncTimer = null
void syncInstalledApps(state, true)
}, FOLLOW_UP_SYNC_DELAY_MS)
state.followUpSyncTimer = setTimeout(() => {
state.followUpSyncTimer = null;
void syncInstalledApps(state, true);
}, FOLLOW_UP_SYNC_DELAY_MS);
}
function patchRefreshApps(state) {
if (
!state.installedAppsService ||
state.refreshPatched ||
typeof state.installedAppsService.refreshApps !== "function"
) {
return
}
if (
!state.installedAppsService ||
state.refreshPatched ||
typeof state.installedAppsService.refreshApps !== 'function'
) {
return;
}
const originalRefreshApps = state.installedAppsService.refreshApps.bind(
state.installedAppsService
)
state.refreshPatched = true
state.log("info", "refreshApps hook installed.")
const originalRefreshApps = state.installedAppsService.refreshApps.bind(
state.installedAppsService,
);
state.refreshPatched = true;
state.log('info', 'refreshApps hook installed.');
state.installedAppsService.refreshApps = async (...args) => {
const result = await originalRefreshApps(...args)
state.log("info", "refreshApps completed; queueing installed apps sync.")
queueSync(state, true)
queueFollowUpSync(state)
return result
}
state.installedAppsService.refreshApps = async (...args) => {
const result = await originalRefreshApps(...args);
state.log('info', 'refreshApps completed; queueing installed apps sync.');
queueSync(state, true);
queueFollowUpSync(state);
return result;
};
}
function resolveRemoteCommandServices(state) {
const container = getAureliaContainer()
const webpackRequire = getWebpackRequire()
if (!container || !webpackRequire) {
return false
}
const container = getAureliaContainer();
const webpackRequire = getWebpackRequire();
if (!container || !webpackRequire) {
return false;
}
resolveRuntimeServices(state, container, webpackRequire)
return true
resolveRuntimeServices(state, container, webpackRequire);
return true;
}
function resolveRuntimeServices(state, container, webpackRequire) {
resolveOptionalServices(state, container, webpackRequire)
installGameStatusSubscriptions(state)
resolveOptionalServices(state, container, webpackRequire);
installGameStatusSubscriptions(state);
if (!hasMissingOptionalServices(state)) {
stopOptionalServicesRetry(state)
}
if (!hasMissingOptionalServices(state)) {
stopOptionalServicesRetry(state);
}
}
function stopOptionalServicesRetry(state) {
if (!state.optionalServicesTimer) {
return
}
if (!state.optionalServicesTimer) {
return;
}
clearInterval(state.optionalServicesTimer)
state.optionalServicesTimer = null
clearInterval(state.optionalServicesTimer);
state.optionalServicesTimer = null;
}
function startOptionalServicesRetry(state) {
if (state.optionalServicesTimer || !hasMissingOptionalServices(state)) {
return
}
state.optionalServicesTimer = setInterval(() => {
const container = getAureliaContainer()
const webpackRequire = getWebpackRequire()
if (container && webpackRequire) {
resolveRuntimeServices(state, container, webpackRequire)
if (state.optionalServicesTimer || !hasMissingOptionalServices(state)) {
return;
}
}, OPTIONAL_SERVICES_RETRY_INTERVAL_MS)
state.log(
"info",
"Optional service retry timer started.",
`${OPTIONAL_SERVICES_RETRY_INTERVAL_MS}ms`
)
state.optionalServicesTimer = setInterval(() => {
state.optionalServicesAttempts += 1;
const container = getAureliaContainer();
const webpackRequire = getWebpackRequire();
if (container && webpackRequire) {
resolveRuntimeServices(state, container, webpackRequire);
}
if (
state.optionalServicesTimer &&
state.optionalServicesAttempts >= MAX_OPTIONAL_SERVICES_ATTEMPTS
) {
stopOptionalServicesRetry(state);
state.log(
'warn',
'Optional service retry exhausted.',
`attempts=${state.optionalServicesAttempts}`,
);
}
}, OPTIONAL_SERVICES_RETRY_INTERVAL_MS);
state.log(
'info',
'Optional service retry timer started.',
`${OPTIONAL_SERVICES_RETRY_INTERVAL_MS}ms`,
);
}
function bootstrap(state) {
if (!hasAppRoot()) {
setBootstrapReason(state, "app root not ready")
return false
}
if (!state.ipcRenderer && !resolveIpcRenderer(state)) {
return false
}
const webpackRequire = getWebpackRequire()
if (!webpackRequire) {
setBootstrapReason(state, "webpack runtime not ready")
return false
}
const container = getAureliaContainer()
if (!container) {
logMissingContainer(state)
setBootstrapReason(state, "Aurelia container not ready")
return false
}
state.log("info", "Aurelia container resolved.")
if (!state.storeRef) {
state.storeRef = getStoreRef(state, container, webpackRequire)
if (!state.storeRef) {
state.log(
"warn",
"Store reference unavailable; unsupported installed titles will be missing."
)
if (!hasAppRoot()) {
setBootstrapReason(state, 'app root not ready');
return false;
}
}
state.installedAppsService = getInstalledAppsService(
state,
container,
webpackRequire
)
if (!state.installedAppsService) {
setBootstrapReason(state, "installed apps service not ready")
return false
}
resolveRuntimeServices(state, container, webpackRequire)
startOptionalServicesRetry(state)
if (!isRecord(state.installedAppsService.installedApps)) {
state.log(
"info",
"Service instance has no installedApps data yet; reading from store until refreshApps populates it."
)
if (!state.storeRef) {
state.log("warn", "Store fallback also unavailable; will retry on poll.")
if (!state.ipcRenderer && !resolveIpcRenderer(state)) {
return false;
}
}
bindBridge(state)
patchRefreshApps(state)
queueSync(state, true)
queueFollowUpSync(state)
startPollTimer(state)
const webpackRequire = getWebpackRequire();
if (!webpackRequire) {
setBootstrapReason(state, 'webpack runtime not ready');
return false;
}
state.log("info", "Installed apps sync ready.")
return true
const container = getAureliaContainer();
if (!container) {
logMissingContainer(state);
setBootstrapReason(state, 'Aurelia container not ready');
return false;
}
state.log('info', 'Aurelia container resolved.');
if (!state.storeRef) {
state.storeRef = getStoreRef(state, container, webpackRequire);
if (!state.storeRef) {
state.log(
'warn',
'Store reference unavailable; unsupported installed titles will be missing.',
);
}
}
state.installedAppsService = getInstalledAppsService(state, container, webpackRequire);
if (!state.installedAppsService) {
setBootstrapReason(state, 'installed apps service not ready');
return false;
}
resolveRuntimeServices(state, container, webpackRequire);
startOptionalServicesRetry(state);
if (!isRecord(state.installedAppsService.installedApps)) {
state.log(
'info',
'Service instance has no installedApps data yet; reading from store until refreshApps populates it.',
);
if (!state.storeRef) {
state.log('warn', 'Store fallback also unavailable; will retry on poll.');
}
}
void bindBridge(state);
patchRefreshApps(state);
queueSync(state, true);
queueFollowUpSync(state);
startPollTimer(state);
state.log('info', 'Installed apps sync ready.');
return true;
}
function resolveIpcRenderer(state) {
const electron = getRequire()?.("electron")
if (!electron?.ipcRenderer) {
setBootstrapReason(state, "electron ipcRenderer not ready")
return false
}
const electron = getRequire()?.('electron');
if (!electron?.ipcRenderer) {
setBootstrapReason(state, 'electron ipcRenderer not ready');
return false;
}
state.ipcRenderer = electron.ipcRenderer
state.log("info", "Electron ipcRenderer resolved.")
return true
state.ipcRenderer = electron.ipcRenderer;
state.log('info', 'Electron ipcRenderer resolved.');
return true;
}
function startPollTimer(state) {
if (state.pollTimer) {
return
}
state.pollTimer = setInterval(() => {
const container = getAureliaContainer()
const webpackRequire = getWebpackRequire()
if (container && webpackRequire) {
resolveRuntimeServices(state, container, webpackRequire)
if (state.pollTimer) {
return;
}
void syncInstalledApps(state)
}, SYNC_INTERVAL_MS)
state.log(
"info",
"Installed apps poll timer started.",
`${SYNC_INTERVAL_MS}ms`
)
state.pollTimer = setInterval(() => {
if (hasUnresolvedServices(state)) {
const container = getAureliaContainer();
const webpackRequire = getWebpackRequire();
if (container && webpackRequire) {
resolveRuntimeServices(state, container, webpackRequire);
}
}
void bindBridge(state);
void syncInstalledApps(state);
}, SYNC_INTERVAL_MS);
state.log('info', 'Installed apps poll timer started.', `${SYNC_INTERVAL_MS}ms`);
}
function logMissingContainer(state) {
if (state.bootstrapAttempts % 10 !== 0) {
return
}
if (state.bootstrapAttempts % CONTAINER_LOG_THROTTLE_ATTEMPTS !== 0) {
return;
}
const root = getAppRoot()
const aureliaKeys = root
? Object.getOwnPropertyNames(root)
.filter((key) => key.startsWith("__") || key === "au")
.join(", ")
: "root=null"
state.log(
"warn",
"Aurelia container not found.",
`rootProps=${aureliaKeys || "(none)"}, subtree=${summarizeAureliaSubtree(root)}`
)
const root = getAppRoot();
const aureliaKeys = root
? Object.getOwnPropertyNames(root)
.filter((key) => key.startsWith('__') || key === 'au')
.join(', ')
: 'root=null';
state.log(
'warn',
'Aurelia container not found.',
`rootProps=${aureliaKeys || '(none)'}, subtree=${summarizeAureliaSubtree(root)}`,
);
}
function retryBootstrap(state) {
if (bootstrap(state)) {
return
}
if (bootstrap(state)) {
return;
}
state.bootstrapAttempts += 1
if (state.bootstrapAttempts < MAX_BOOTSTRAP_ATTEMPTS) {
setTimeout(() => retryBootstrap(state), RETRY_DELAY_MS)
return
}
state.bootstrapAttempts += 1;
if (state.bootstrapAttempts < MAX_BOOTSTRAP_ATTEMPTS) {
setTimeout(() => retryBootstrap(state), RETRY_DELAY_MS);
return;
}
state.log(
"error",
"Installed apps sync bootstrap exhausted.",
state.lastBootstrapReason || "unknown reason"
)
state.log(
'error',
'Installed apps sync bootstrap exhausted.',
state.lastBootstrapReason || 'unknown reason',
);
}
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More