mirror of
https://github.com/k1tbyte/Wand-Enhancer.git
synced 2026-08-29 20:01:16 +00:00
Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 643c8f8b62 | |||
| e7c7beb621 | |||
| 710e717677 | |||
| 7e8cadff24 | |||
| 7d28eb7d52 | |||
| 413c38dbcb | |||
| 3b776c52fc | |||
| 9c88caf49b | |||
| 537608c381 | |||
| b0279ee812 | |||
| c007e11cce | |||
| a7f0eae670 | |||
| 1c9a8fb780 | |||
| ec07dc63f0 | |||
| 88556ec70f | |||
| c02bad919d | |||
| b9faf80f86 | |||
| 6395ca3a27 | |||
| 4ce47dc6d2 | |||
| 8c6d87671c | |||
| a0b3968d33 | |||
| 6906a67a2e | |||
| 37ce6b3f4a | |||
| 8756e41fb9 | |||
| 544b9f0fb0 | |||
| a4f3a57f97 | |||
| 1f5ba9fc95 | |||
| 710d014e6d | |||
| a810e5b549 | |||
| 13759b1db6 | |||
| 3b2f373946 | |||
| f78f9609b5 | |||
| 633984ed3b | |||
| fa753b4a34 | |||
| 5273930eef |
@@ -0,0 +1,4 @@
|
||||
# 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.
|
||||
web-panel/** linguist-vendored
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
repo_root=$(dirname "$script_dir")
|
||||
script_path="$repo_root/scripts/validate-release-metadata.ps1"
|
||||
|
||||
if command -v cygpath >/dev/null 2>&1; then
|
||||
script_path=$(cygpath -w "$script_path")
|
||||
fi
|
||||
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$script_path"
|
||||
+8
-2
@@ -1,2 +1,8 @@
|
||||
ko_fi: kitbyte
|
||||
custom: ["https://www.paypal.com/ncp/payment/ZP3NPDYP6A34W", "https://www.paypal.com/donate/?hosted_button_id=QGGKZTFPDKMHC"]
|
||||
patreon: kitbyte
|
||||
|
||||
custom: [
|
||||
"https://www.patreon.com/kitbyte/gift",
|
||||
"https://tronscan.org/#/address/TQdvau8pAy5Tg1Aa588tTcPCFgbcHtuoxc",
|
||||
"https://www.blockchain.com/explorer/addresses/btc/1EZKDcyU8REm9JW5xwXJqSpn5Xaq5yAWWX",
|
||||
"https://etherscan.io/address/0xd904d9d0557f88bbb1c4ab3582b4ca0d8a730e8d"
|
||||
]
|
||||
@@ -1,30 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: k1tbyte
|
||||
|
||||
---
|
||||
|
||||
**WeMod version**: X.X.X
|
||||
**Patcher version**: X.X.X
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,70 @@
|
||||
name: Bug report
|
||||
description: Create a report to help us improve
|
||||
title: '[Bug]: '
|
||||
labels: ["bug"]
|
||||
assignees:
|
||||
- k1tbyte
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**STOP BEFORE YOU POST: THIS PROJECT DOES NOT PUBLISH OFFICIAL EXECUTABLE DOWNLOADS.**
|
||||
Build WandEnhancer yourself from your own fork or local source. If you downloaded an executable from YouTube, Discord, a mirror, or any other third-party website, treat it as untrusted. Do not open issues about third-party binaries or stolen accounts here - this project is not related to those downloads.
|
||||
|
||||
- type: checkboxes
|
||||
id: build_source_check
|
||||
attributes:
|
||||
label: Build Source Confirmation (REQUIRED)
|
||||
description: You must check this box to proceed.
|
||||
options:
|
||||
- label: I confirm that I built WandEnhancer myself from my own fork or local source, and did not download an executable from YouTube, Discord, mirrors, issue comments, or any other third-party website.
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: client_version
|
||||
attributes:
|
||||
label: Client (Wand) version
|
||||
description: What version of the client are you using? (e.g., 9.0.0)
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: enhancer_version
|
||||
attributes:
|
||||
label: Enhancer version
|
||||
description: What version of this tool are you using?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: bug_description
|
||||
attributes:
|
||||
label: Describe the bug
|
||||
description: A clear and concise description of what the bug is.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: reproduce
|
||||
attributes:
|
||||
label: To Reproduce
|
||||
description: Steps to reproduce the behavior.
|
||||
value: |
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
description: A clear and concise description of what you expected to happen.
|
||||
|
||||
- type: textarea
|
||||
id: additional_context
|
||||
attributes:
|
||||
label: Screenshots & Additional context
|
||||
description: Drag and drop screenshots here, or add any other context about the problem.
|
||||
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Build executable
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 10.17.0
|
||||
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: web-panel/pnpm-lock.yaml
|
||||
|
||||
- name: Build unsigned executable
|
||||
shell: pwsh
|
||||
run: ./build.ps1 -Configuration Release
|
||||
|
||||
- name: Upload unsigned executable
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: WandEnhancer-unsigned
|
||||
path: WandEnhancer/bin/Release/WandEnhancer.exe
|
||||
if-no-files-found: error
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Mirror to GitLab
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master", "main" ]
|
||||
tags:
|
||||
- '*'
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
if: github.repository == 'k1tbyte/Wand-Enhancer'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Push to GitLab
|
||||
env:
|
||||
GITLAB_USERNAME: kitbyte
|
||||
GITLAB_REPO: Wand-Enhancer
|
||||
run: |
|
||||
git remote add gitlab https://oauth2:${{ secrets.GITLAB_TOKEN }}@gitlab.com/$GITLAB_USERNAME/$GITLAB_REPO.git
|
||||
git push gitlab --all --force
|
||||
git push gitlab --tags --force
|
||||
@@ -0,0 +1,52 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
publish-release:
|
||||
if: github.repository == 'k1tbyte/Wand-Enhancer'
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
RELEASE_VERSION: ${{ github.ref_name }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: web-panel/pnpm-lock.yaml
|
||||
|
||||
- name: Validate release metadata
|
||||
shell: pwsh
|
||||
run: ./scripts/validate-release-metadata.ps1 -ExpectedVersion $env:RELEASE_VERSION
|
||||
|
||||
- name: Extract release notes from changelog
|
||||
shell: pwsh
|
||||
run: ./scripts/get-changelog-section.ps1 -Version $env:RELEASE_VERSION -OutputPath release-notes.md
|
||||
|
||||
- name: Build release
|
||||
shell: pwsh
|
||||
run: ./build.ps1 -Configuration Release
|
||||
|
||||
- name: Publish GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
name: ${{ github.ref_name }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
body_path: release-notes.md
|
||||
files: CHANGELOG.md
|
||||
fail_on_unmatched_files: true
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Validate Release Metadata
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master", "main" ]
|
||||
pull_request:
|
||||
branches: [ "master", "main" ]
|
||||
|
||||
jobs:
|
||||
validate-release-metadata:
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Validate version and changelog sync
|
||||
shell: pwsh
|
||||
run: ./scripts/validate-release-metadata.ps1
|
||||
+6
-2
@@ -130,8 +130,8 @@ dist
|
||||
.pnp.*
|
||||
|
||||
|
||||
./WeModPatcher/obj/
|
||||
./WeModPatcher/bin/
|
||||
./WandEnhancer/obj/
|
||||
./WandEnhancer/bin/
|
||||
./AsarSharp/obj/
|
||||
./AsarSharp/bin/
|
||||
.idea
|
||||
@@ -142,3 +142,7 @@ packages
|
||||
|
||||
# App settings (user preferences)
|
||||
appsettings.json
|
||||
*DotSettings.user
|
||||
.tmp
|
||||
.source
|
||||
web-panel/bridge/wand-remote-bridge.cjs
|
||||
@@ -0,0 +1,47 @@
|
||||
INFO ./docs/*
|
||||
|
||||
# Wand Enhancer Agent Notes
|
||||
|
||||
This repository patches the Wand Electron app from a .NET Framework WPF desktop tool. Keep changes narrow and preserve the patch pipeline invariants.
|
||||
|
||||
## Remote Web Panel
|
||||
|
||||
- The default local remote port is `3223`. Keep bridge and frontend constants aligned; C# must not duplicate the presentation URL or port.
|
||||
- The embedded panel must stay small because the desktop patcher embeds it and then injects it into Wand's `app.asar`.
|
||||
- Remote tooltip links and every rendered `remote-qr-code` are redirected by `web-panel/bridge/scripts/default/remote-popup-cleanup.js`. It reuses Wand's loaded QR renderer through the webpack runtime, keeps the local URL visible as a fallback, and hides the Pro onboarding remote mobile app card. Do not reintroduce C# ASAR patches for the tooltip URL or QR component; a changed UI bundle must not make the whole remote-panel patch fail.
|
||||
- Production builds must not include mock data, debug routes, sourcemaps, local fonts, heavy icon libraries, or runtime class helper packages.
|
||||
- The Electron bridge is authored as TypeScript under `web-panel/bridge/src/`, but production runtime must be bundled/minified into `web-panel/dist/bridge.cjs` by `pnpm run build:bridge`. Do not copy bridge source into Wand or embed it as ASAR resources.
|
||||
- Mock/demo data is dev-only and must be reached through `import.meta.env.DEV` dynamic imports.
|
||||
- Source can use React-compatible imports, but production runtime resolves them to Preact aliases in `web-panel/vite.config.ts`.
|
||||
- UI uses Tailwind CSS and lightweight local primitives under `web-panel/src/shared/ui/`.
|
||||
- Default renderer script sources live in `web-panel/bridge/scripts/default/` and are bundled/minified into `web-panel/dist/renderer-scripts/` by `pnpm run build:bridge`. Custom user scripts are selected in the WPF patch modal and copied from `PatchConfig.CustomScriptPaths`; only existing `.js` files are accepted. A local `renderer-scripts/` folder next to the patcher exe is still copied as an advanced fallback.
|
||||
- `web-panel/bridge/scripts/default/installed-apps-sync.js` resolves Wand's renderer services/store and publishes `My Games` snapshots through the `wand-remote-installed-apps` IPC channel. The synced list must mirror Wand's `my_games` source criteria: catalog games come from `installedGameVersions`, and extra installed unsupported titles come from `correlatedUnavailableTitles` whose `games[].correlationIds` match `installedApps`.
|
||||
- If the injected renderer cannot read a populated `correlatedUnavailableTitles` slice from the live store, `installed-apps-sync.js` must fall back to Wand's `/v3/unavailable_titles` correlation lookup through the renderer API client instead of degrading to raw install entries or an empty `My Games` list.
|
||||
- Installed app snapshots should include game artwork in `imageUrl` when possible. `installed-apps-sync.js` must prefer Wand's own client icon CDN shape `https://api-cdn.wemod.com/steam_community/<steamAppId>/client_icon/96.webp` whenever the matched title/game/version metadata contains a Steam AppID, regardless of install platform. Do not assume `steamAppId` is a flat property; search nested `steam*` metadata before falling back to installed Steam `sku`. If metadata still does not expose the icon, fall back to the rendered Wand sidebar DOM (`.sidebar-game-row-image` background-image) keyed by `titleId` parsed from `data-tooltip-trigger-for`. The web panel `GameCover` must tolerate broken artwork URLs and fall back to its text cover.
|
||||
- The same renderer sync script also forwards lifecycle state through `wand-remote-game-status`: `game-launched` / `game-ended` come from Wand's launch monitor service, and trainer runtime comes from the running-trainer visibility service. The web panel consumes this as the `game_status` websocket message.
|
||||
- When Wand does not emit a `game-launched` event but a trainer is already active, `wand-remote-game-status` must synthesize a running session from the running-trainer visibility payload so the remote panel does not show an idle game session next to a running trainer.
|
||||
- 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).
|
||||
|
||||
## ASAR Patch Pipeline
|
||||
|
||||
- Preserve and restore both `resources/app.asar` and `resources/app.asar.unpacked` backups.
|
||||
- Inject `web-panel/dist` as `remote-panel/`; it must already contain `bridge.cjs` and generated default renderer scripts under `renderer-scripts/`. Selected/local custom renderer scripts are then copied under `remote-panel/renderer-scripts`.
|
||||
- Do not commit extracted `.source/` or `.sources/` output. Recreate it only for reverse-engineering sessions.
|
||||
- `AsarSharp.AsarExtractor.ExtractAll` must skip unpacked entries when their source path equals the destination (in-place extraction is a self-copy that fails on locked files like `TrainerLib_x64.dll`) and silently skip unpacked entries whose source is missing on disk (e.g. `auxiliary/GameLauncher.exe` removed by an installer). Do not reintroduce hard failure on either case.
|
||||
- The `DevToolsOnF12` patch anchors on the Electron main-process `<app>.whenReady().then(` site and attaches a `before-input-event` hook to every `BrowserWindow.webContents`. Do not patch the renderer keydown listener — the minified `ACTION_OPEN_DEV_TOOLS` dispatch site is not stable across Wand releases.
|
||||
- Cheats can be pinned per game in the web panel via `pinned-storage.ts` (`localStorage` key `wand-remote.pinned-cheats.v1:<gameId>`). Pinned cheats render as a virtual `pinned` category at the top of the list; their normal category placement is preserved.
|
||||
- Custom quick presets are per trainer/game and stored by `preset-storage.ts` under `localStorage` key `wand-remote.presets.v1:<gameId-or-trainerId>`. Presets capture persistent cheat values only; do not include `button` one-shot cheats in saved presets.
|
||||
- All `localStorage` access in `web-panel/src/` MUST go through `web-panel/src/shared/storage.ts` (`loadJson` / `saveJson` / `loadStringSet` / `saveStringSet`). Do not reintroduce per-capability `try/catch` + `JSON.parse` duplication. Trainer/game storage IDs are derived through the shared `getTrainerStorageId(trainer)` helper; do not re-implement the `gameId → titleId → trainerId → 'global'` precedence inline.
|
||||
- Shared web protocol version, port, and HTTP/WS paths live in `web-panel/protocol/web-contract.json`. Bridge-only IPC channels, WS opcodes, and renderer injection delays live in `web-panel/bridge/src/constants.ts`. Do not redeclare these values inline.
|
||||
- UI string-union types follow the `E*` enum convention from `.claude/rules/frontend-conventions.md` (currently `ECheatType` in `protocol/messages.ts`, `EConnectionStatus` in `remote-session/remote-session.reducer.ts`); wire string values must remain on the right-hand side of enum members. Reducer action tags stay as discriminated-union string literals.
|
||||
- Cheat input controls live one-per-file under `web-panel/src/trainer/controls/`; shared `SliderTrack` / `StepButton` / `ControlInternalProps` are in `controls/shared.tsx` and number formatting helpers in `controls/format-number.ts`. `controls/CheatControl.tsx` remains a thin dispatcher keyed by `ECheatType`.
|
||||
- Mobile drawer performance is sensitive to `backdrop-filter`. Keep drawer panels and nested glass controls blur-free under coarse pointers, and do not add per-row `backdrop-blur-*` inside drawer lists.
|
||||
|
||||
## Validation
|
||||
|
||||
- Web panel build: `cd web-panel && pnpm run build` (runs type-check, Vite build, then `build:bridge` into `dist`).
|
||||
- Bridge/script syntax checks after build: `node --check web-panel/dist/bridge.cjs` and `node --check web-panel/dist/renderer-scripts/remote-popup-cleanup.js`.
|
||||
- Production dist should contain only static assets and should not contain `mock-instance`, `Mock Adventure`, `Simulation`, `Debug session`, `mock=1`, `demo-session`, `vite.svg`, `tailwind-merge`, `class-variance-authority`, or `clsx`.
|
||||
+25
-25
@@ -1,14 +1,13 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using AsarSharp.AsarFileSystem;
|
||||
using AsarSharp.Integrity;
|
||||
using AsarSharp.Utils;
|
||||
|
||||
namespace AsarSharp
|
||||
{
|
||||
|
||||
public class CreateOptions
|
||||
{
|
||||
public Regex Unpack { get; set; }
|
||||
@@ -28,41 +27,36 @@ namespace AsarSharp
|
||||
_destPath = destPath ?? throw new ArgumentNullException(nameof(destPath));
|
||||
_options = options;
|
||||
}
|
||||
|
||||
|
||||
public void CreatePackageWithOptions()
|
||||
{
|
||||
var result = FileSystemCrawler.CrawlFileSystem(_folderPath);
|
||||
var result = FileSystemCrawler.CrawlFileSystem(_folderPath);
|
||||
_filenames = result.filenames;
|
||||
_metadata = result.metadata;
|
||||
CreatePackageFromFiles();
|
||||
}
|
||||
|
||||
|
||||
public void CreatePackageFromFiles()
|
||||
{
|
||||
var filesystem = new Filesystem(_folderPath);
|
||||
var files = new List<Disk.BasicFileInfo>();
|
||||
|
||||
var filenamesSorted = _filenames.ToList();
|
||||
|
||||
foreach (var filename in filenamesSorted)
|
||||
var files = new List<Disk.BasicFileInfo>(_filenames.Count);
|
||||
|
||||
foreach (var filename in _filenames)
|
||||
{
|
||||
HandleFile(filesystem, filename, files);
|
||||
}
|
||||
|
||||
InsertsDone(filesystem, files);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
private void HandleFile(Filesystem filesystem, string filename, List<Disk.BasicFileInfo> files)
|
||||
{
|
||||
if (!_metadata.ContainsKey(filename))
|
||||
if (!_metadata.TryGetValue(filename, out var file))
|
||||
{
|
||||
var fileType = FileSystemCrawler.DetermineFileType(filename);
|
||||
_metadata[filename] = fileType ?? throw new Exception("Unknown file type for file: " + filename);
|
||||
file = FileSystemCrawler.DetermineFileType(filename)
|
||||
?? throw new Exception("Unknown file type for file: " + filename);
|
||||
_metadata[filename] = file;
|
||||
}
|
||||
var file = _metadata[filename];
|
||||
|
||||
switch (file.Type)
|
||||
{
|
||||
@@ -70,9 +64,13 @@ namespace AsarSharp
|
||||
filesystem.InsertDirectory(filename, false);
|
||||
break;
|
||||
case FileType.File:
|
||||
var shouldUnpack = ShouldUnpackPath(Extensions.GetRelativePath(_folderPath, Path.GetDirectoryName(filename)));
|
||||
string parentDir = Path.GetDirectoryName(filename) ?? string.Empty;
|
||||
string relParent = Extensions.GetRelativePath(_folderPath, parentDir);
|
||||
bool shouldUnpack = ShouldUnpackPath(relParent);
|
||||
long fileSize = file.Stat is FileInfo fi ? fi.Length : 0;
|
||||
var placeholder = IntegrityHelper.CreatePlaceholder(fileSize);
|
||||
files.Add(new Disk.BasicFileInfo { Filename = filename, Unpack = shouldUnpack });
|
||||
filesystem.InsertFile(filename, shouldUnpack, file);
|
||||
filesystem.InsertFile(filename, shouldUnpack, file, placeholder);
|
||||
break;
|
||||
case FileType.Link:
|
||||
throw new NotImplementedException();
|
||||
@@ -81,14 +79,16 @@ namespace AsarSharp
|
||||
|
||||
private bool ShouldUnpackPath(string relativePath)
|
||||
{
|
||||
return _options.Unpack?.IsMatch(relativePath) == true;
|
||||
return _options?.Unpack?.IsMatch(relativePath) == true;
|
||||
}
|
||||
|
||||
private void InsertsDone(Filesystem filesystem, List<Disk.BasicFileInfo> files)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_destPath) ?? throw new InvalidOperationException());
|
||||
Disk.WriteFileSystem(_destPath, filesystem, new Disk.FilesystemFilesAndLinks { Files = files, Links = null }, _metadata);
|
||||
Directory.CreateDirectory(
|
||||
Path.GetDirectoryName(_destPath)
|
||||
?? throw new InvalidOperationException());
|
||||
Disk.WriteFileSystem(_destPath, filesystem,
|
||||
new Disk.FilesystemFilesAndLinks { Files = files, Links = null }, _metadata);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+140
-74
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
@@ -10,98 +10,66 @@ namespace AsarSharp
|
||||
{
|
||||
public class AsarExtractor
|
||||
{
|
||||
private const int IO_BUFFER_SIZE = 1024 * 1024;
|
||||
private const int FS_INTERNAL_BUFFER = 4096;
|
||||
|
||||
public static void ExtractAll(string archivePath, string dest)
|
||||
{
|
||||
var filesystem = Disk.ReadFilesystemSync(archivePath);
|
||||
var filenames = filesystem.ListFiles();
|
||||
|
||||
// under windows just extract links as regular files
|
||||
// On Windows, links are extracted as plain files.
|
||||
bool followLinks = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
|
||||
|
||||
// create destination directory
|
||||
Directory.CreateDirectory(dest);
|
||||
|
||||
byte[] ioBuffer = new byte[IO_BUFFER_SIZE];
|
||||
var dirCache = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Path.GetFullPath(dest) };
|
||||
var extractionErrors = new List<Exception>();
|
||||
foreach (var fullPath in filenames)
|
||||
string rootPath = filesystem.GetRootPath();
|
||||
long dataOffset = 8 + filesystem.GetHeaderSize();
|
||||
|
||||
// One archive handle for all reads — old code opened it per file.
|
||||
using (var archive = new FileStream(rootPath, FileMode.Open, FileAccess.Read, FileShare.Read,
|
||||
FS_INTERNAL_BUFFER, FileOptions.RandomAccess))
|
||||
{
|
||||
try
|
||||
foreach (var fullPath in filenames)
|
||||
{
|
||||
// Remove leading slash
|
||||
var filename = fullPath.Substring(1);
|
||||
var destFilename = Path.Combine(dest, filename);
|
||||
var file = filesystem.GetFile(filename, followLinks);
|
||||
|
||||
// Check that the file is not written outside the specified destination folder
|
||||
string relativePath = Extensions.GetRelativePath(dest, destFilename);
|
||||
if (relativePath.StartsWith(".."))
|
||||
try
|
||||
{
|
||||
throw new InvalidOperationException($"{fullPath}: file \"{destFilename}\" writes out of the package");
|
||||
}
|
||||
var filename = fullPath.Substring(1);
|
||||
var destFilename = Path.Combine(dest, filename);
|
||||
var file = filesystem.GetFile(filename, followLinks);
|
||||
|
||||
if (file.IsDirectory)
|
||||
{
|
||||
// it's a directory, create it and continue with the next entry
|
||||
Directory.CreateDirectory(destFilename);
|
||||
}
|
||||
// TODO (LINK NOT SUPPORTED)
|
||||
else if (file.IsLink)
|
||||
{
|
||||
// it's a symlink, create a symlink
|
||||
var linkSrcPath = Extensions.GetDirectoryName(Path.Combine(dest, file.Link));
|
||||
var linkDestPath = Extensions.GetDirectoryName(destFilename);
|
||||
var relativeLinkPath = Extensions.GetRelativePath(linkDestPath, linkSrcPath);
|
||||
|
||||
// try to delete output file, because we can't overwrite a link
|
||||
try
|
||||
{
|
||||
File.Delete(destFilename);
|
||||
}
|
||||
catch {
|
||||
// Ignore errors during file link deletion
|
||||
}
|
||||
|
||||
var linkTo = Path.Combine(relativeLinkPath, Path.GetFileName(file.Link));
|
||||
|
||||
if (Extensions.GetRelativePath(dest, linkSrcPath).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 \"{file.Link}\" links out of the package to \"{linkSrcPath}\"");
|
||||
$"{fullPath}: file \"{destFilename}\" writes out of the package");
|
||||
}
|
||||
|
||||
// On Windows, creating symlinks requires additional permissions or enabling Developer Mode,
|
||||
// so just copy the contents of the file
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
if (file.IsDirectory)
|
||||
{
|
||||
var targetPath = Path.Combine(linkSrcPath, Path.GetFileName(file.Link));
|
||||
if (Directory.Exists(targetPath))
|
||||
{
|
||||
Directory.CreateDirectory(destFilename);
|
||||
Extensions.CopyDirectory(targetPath, destFilename);
|
||||
}
|
||||
else if (File.Exists(targetPath))
|
||||
{
|
||||
Directory.CreateDirectory(Extensions.GetDirectoryName(destFilename));
|
||||
File.Copy(targetPath, destFilename, true);
|
||||
}
|
||||
EnsureDirectory(destFilename, dirCache);
|
||||
continue;
|
||||
}
|
||||
else
|
||||
|
||||
if (file.IsLink)
|
||||
{
|
||||
// On Unix systems we use symlinks
|
||||
Directory.CreateDirectory(Extensions.GetDirectoryName(destFilename));
|
||||
Extensions.CreateSymbolicLink(linkTo, destFilename);
|
||||
ExtractLink(dest, fullPath, destFilename, file, dirCache);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (file.IsFile)
|
||||
{
|
||||
// it's a file, try to extract it
|
||||
|
||||
if (!file.IsFile) continue;
|
||||
|
||||
try
|
||||
{
|
||||
byte[] content;
|
||||
|
||||
content = Disk.ReadFileSync(filesystem, filename, file);
|
||||
|
||||
File.WriteAllBytes(destFilename, content);
|
||||
|
||||
ExtractFile(archive, dataOffset, rootPath, filename, destFilename, file, ioBuffer, dirCache);
|
||||
|
||||
if (file.Executable == true && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
Extensions.SetUnixFilePermission(destFilename, "755");
|
||||
@@ -112,10 +80,10 @@ namespace AsarSharp
|
||||
extractionErrors.Add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
extractionErrors.Add(ex);
|
||||
catch (Exception ex)
|
||||
{
|
||||
extractionErrors.Add(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,5 +95,103 @@ namespace AsarSharp
|
||||
extractionErrors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureDirectory(string path, HashSet<string> cache)
|
||||
{
|
||||
string full = Path.GetFullPath(path);
|
||||
if (cache.Contains(full)) return;
|
||||
Directory.CreateDirectory(full);
|
||||
// Mark every ancestor too so siblings skip the syscall.
|
||||
string p = full;
|
||||
while (!string.IsNullOrEmpty(p) && cache.Add(p))
|
||||
{
|
||||
p = Path.GetDirectoryName(p);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureParentDir(string filePath, HashSet<string> cache)
|
||||
{
|
||||
string parent = Path.GetDirectoryName(filePath);
|
||||
if (string.IsNullOrEmpty(parent)) return;
|
||||
EnsureDirectory(parent, cache);
|
||||
}
|
||||
|
||||
private static void ExtractFile(FileStream archive, long dataOffset, string rootPath,
|
||||
string filename, string destFilename, FilesystemEntry file, byte[] buffer,
|
||||
HashSet<string> dirCache)
|
||||
{
|
||||
EnsureParentDir(destFilename, dirCache);
|
||||
|
||||
if (file.Unpacked == true)
|
||||
{
|
||||
string unpackedSourcePath = Path.GetFullPath(Path.Combine($"{rootPath}.unpacked", filename));
|
||||
string unpackedDestPath = Path.GetFullPath(destFilename);
|
||||
|
||||
if (string.Equals(unpackedSourcePath, unpackedDestPath, StringComparison.OrdinalIgnoreCase))
|
||||
return; // self-copy
|
||||
if (!File.Exists(unpackedSourcePath))
|
||||
return; // header references a missing unpacked file — skip rather than abort
|
||||
|
||||
File.Copy(unpackedSourcePath, destFilename, true);
|
||||
return;
|
||||
}
|
||||
|
||||
long size = file.Size ?? 0;
|
||||
using (var dst = new FileStream(destFilename, FileMode.Create, FileAccess.Write, FileShare.None,
|
||||
FS_INTERNAL_BUFFER, FileOptions.SequentialScan))
|
||||
{
|
||||
if (size <= 0) return;
|
||||
|
||||
archive.Position = dataOffset + long.Parse(file.Offset);
|
||||
long remaining = size;
|
||||
while (remaining > 0)
|
||||
{
|
||||
int toRead = remaining > buffer.Length ? buffer.Length : (int)remaining;
|
||||
int got = archive.Read(buffer, 0, toRead);
|
||||
if (got <= 0) throw new EndOfStreamException("Archive truncated");
|
||||
dst.Write(buffer, 0, got);
|
||||
remaining -= got;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ExtractLink(string dest, string fullPath, string destFilename,
|
||||
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.IsPathInside(dest, linkSrcPath))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{fullPath}: file \"{file.Link}\" links out of the package to \"{linkSrcPath}\"");
|
||||
}
|
||||
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
var targetPath = Path.Combine(linkSrcPath, Path.GetFileName(file.Link));
|
||||
if (Directory.Exists(targetPath))
|
||||
{
|
||||
EnsureDirectory(destFilename, dirCache);
|
||||
Extensions.CopyDirectory(targetPath, destFilename);
|
||||
}
|
||||
else if (File.Exists(targetPath))
|
||||
{
|
||||
EnsureParentDir(destFilename, dirCache);
|
||||
File.Copy(targetPath, destFilename, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
EnsureParentDir(destFilename, dirCache);
|
||||
Extensions.CreateSymbolicLink(linkTo, destFilename);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using AsarSharp.Integrity;
|
||||
using AsarSharp.PickleTools;
|
||||
using AsarSharp.Utils;
|
||||
using Newtonsoft.Json;
|
||||
@@ -9,7 +11,9 @@ namespace AsarSharp.AsarFileSystem
|
||||
{
|
||||
public static class Disk
|
||||
{
|
||||
private static Dictionary<string, Filesystem> _filesystemCache = new Dictionary<string, Filesystem>();
|
||||
private const int StreamBufferSize = 1024 * 1024;
|
||||
private static readonly ConcurrentDictionary<string, Filesystem> _filesystemCache =
|
||||
new ConcurrentDictionary<string, Filesystem>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public class ArchiveHeader
|
||||
{
|
||||
@@ -29,36 +33,29 @@ namespace AsarSharp.AsarFileSystem
|
||||
public string Filename { get; set; }
|
||||
public bool Unpack { get; set; }
|
||||
}
|
||||
|
||||
|
||||
|
||||
#region Reading
|
||||
|
||||
|
||||
public static ArchiveHeader ReadArchiveHeaderSync(string archivePath)
|
||||
{
|
||||
using (FileStream fs = File.OpenRead(archivePath))
|
||||
{
|
||||
// read the size of the header (8 bytes)
|
||||
using (var fs = new FileStream(archivePath, FileMode.Open, FileAccess.Read, FileShare.Read,
|
||||
65536, FileOptions.SequentialScan))
|
||||
{
|
||||
byte[] sizeBuf = new byte[8];
|
||||
if (fs.Read(sizeBuf, 0, 8) != 8)
|
||||
{
|
||||
throw new Exception("Unable to read header size");
|
||||
}
|
||||
|
||||
|
||||
var sizePickle = Pickle.CreateFromBuffer(sizeBuf);
|
||||
var size = sizePickle.CreateIterator().ReadUInt32();
|
||||
|
||||
// Read the header of the specified size
|
||||
|
||||
var headerBuf = new byte[size];
|
||||
if(fs.Read(headerBuf, 0, (int)size) != size)
|
||||
{
|
||||
if (fs.Read(headerBuf, 0, (int)size) != size)
|
||||
throw new Exception("Unable to read header");
|
||||
}
|
||||
|
||||
|
||||
var headerPickle = Pickle.CreateFromBuffer(headerBuf);
|
||||
var header = headerPickle.CreateIterator().ReadString();
|
||||
|
||||
var headerObj = JsonConvert.DeserializeObject<FilesystemEntry>(header);
|
||||
|
||||
|
||||
return new ArchiveHeader
|
||||
{
|
||||
Header = headerObj,
|
||||
@@ -67,137 +64,161 @@ namespace AsarSharp.AsarFileSystem
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static Filesystem ReadFilesystemSync(string archivePath)
|
||||
{
|
||||
if (!_filesystemCache.ContainsKey(archivePath) || _filesystemCache[archivePath] == null)
|
||||
return _filesystemCache.GetOrAdd(archivePath, key =>
|
||||
{
|
||||
ArchiveHeader header = ReadArchiveHeaderSync(archivePath);
|
||||
Filesystem filesystem = new Filesystem(archivePath);
|
||||
var header = ReadArchiveHeaderSync(key);
|
||||
var filesystem = new Filesystem(key);
|
||||
filesystem.SetHeader(header.Header, header.HeaderSize);
|
||||
_filesystemCache[archivePath] = filesystem;
|
||||
}
|
||||
|
||||
return _filesystemCache[archivePath];
|
||||
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 (size <= 0) return buffer;
|
||||
|
||||
if (info.Unpacked == true)
|
||||
{
|
||||
// It's an unpacked file, read it directly
|
||||
string filePath = Path.Combine($"{filesystem.GetRootPath()}.unpacked", filename);
|
||||
return File.ReadAllBytes(filePath);
|
||||
}
|
||||
|
||||
// Read from the ASAR archive
|
||||
using (FileStream fs = File.OpenRead(filesystem.GetRootPath()))
|
||||
using (var fs = new FileStream(filesystem.GetRootPath(), FileMode.Open, FileAccess.Read,
|
||||
FileShare.Read, 65536, FileOptions.RandomAccess))
|
||||
{
|
||||
// Important: the offset must take into account the size of the Pickle header (8 bytes)
|
||||
// and the size of the header itself
|
||||
long offset = 8 + filesystem.GetHeaderSize() + long.Parse(info.Offset);
|
||||
fs.Position = offset;
|
||||
|
||||
// Read the whole file at once
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
public static bool UncacheFilesystem(string archivePath)
|
||||
{
|
||||
if (_filesystemCache.ContainsKey(archivePath))
|
||||
{
|
||||
_filesystemCache.Remove(archivePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
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)
|
||||
if (dest == null || rootPath == null || filename == null)
|
||||
throw new ArgumentNullException();
|
||||
|
||||
if (dest == rootPath)
|
||||
{
|
||||
string normalizedDestRoot = Path.GetFullPath(dest)
|
||||
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
string normalizedRootPath = Path.GetFullPath(rootPath)
|
||||
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
|
||||
if (string.Equals(normalizedDestRoot, normalizedRootPath, StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
|
||||
string sourcePath = Path.GetFullPath(Path.Combine(rootPath, filename));
|
||||
string destPath = Path.GetFullPath(Path.Combine(dest, filename));
|
||||
|
||||
if (string.Equals(sourcePath, destPath, StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
}
|
||||
|
||||
string sourcePath = Path.Combine(rootPath, filename);
|
||||
string destPath = Path.Combine(dest, filename);
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destPath) ?? throw new InvalidOperationException());
|
||||
using (var sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
|
||||
using (var destinationStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
|
||||
using (var src = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamBufferSize, FileOptions.SequentialScan))
|
||||
using (var dst = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.None, StreamBufferSize, FileOptions.SequentialScan))
|
||||
{
|
||||
sourceStream.CopyTo(destinationStream);
|
||||
src.CopyTo(dst, StreamBufferSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void WriteFileSystem(string dest, Filesystem fileSystem,
|
||||
FilesystemFilesAndLinks lists,
|
||||
Dictionary<string, CrawledFileType> metadata)
|
||||
FilesystemFilesAndLinks lists, Dictionary<string, CrawledFileType> metadata)
|
||||
{
|
||||
var fsHeader = fileSystem.GetHeader();
|
||||
var headerPickle = Pickle.CreateEmpty();
|
||||
var serializerSettings = new JsonSerializerSettings()
|
||||
{ NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore } ;
|
||||
|
||||
var headerJson = JsonConvert.SerializeObject(fsHeader,serializerSettings);
|
||||
headerPickle.WriteString(headerJson);
|
||||
var headerBuf = headerPickle.ToBuffer();
|
||||
|
||||
var sizePickle = Pickle.CreateEmpty();
|
||||
sizePickle.WriteUInt32((uint)headerBuf.Length);
|
||||
var sizeBuf = sizePickle.ToBuffer();
|
||||
|
||||
using (FileStream fs = File.Create(dest))
|
||||
var serializerSettings = new JsonSerializerSettings
|
||||
{
|
||||
fs.Write(sizeBuf, 0, sizeBuf.Length);
|
||||
fs.Write(headerBuf, 0, headerBuf.Length);
|
||||
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
DefaultValueHandling = DefaultValueHandling.Ignore
|
||||
};
|
||||
|
||||
// --- Phase 1: write placeholder header ---
|
||||
string headerJson = JsonConvert.SerializeObject(fileSystem.GetHeader(), serializerSettings);
|
||||
var headerPickle = Pickle.CreateEmpty();
|
||||
headerPickle.WriteString(headerJson);
|
||||
|
||||
var sizePickle = Pickle.CreateEmpty();
|
||||
sizePickle.WriteUInt32((uint)headerPickle.GetTotalSize());
|
||||
int sizePickleSize = sizePickle.GetTotalSize();
|
||||
|
||||
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))
|
||||
{
|
||||
sizePickle.WriteTo(fs);
|
||||
headerPickle.WriteTo(fs);
|
||||
|
||||
// --- Phase 2: stream files, hash in one pass, patch nodes in-memory ---
|
||||
foreach (var file in lists.Files)
|
||||
{
|
||||
if (file.Unpack)
|
||||
{
|
||||
var filename = Extensions.GetRelativePath(fileSystem.GetRootPath(), file.Filename);
|
||||
CopyFile($"{dest}.unpacked", fileSystem.GetRootPath(), filename);
|
||||
var relName = Extensions.GetRelativePath(fileSystem.GetRootPath(), file.Filename);
|
||||
CopyFile($"{dest}.unpacked", fileSystem.GetRootPath(), relName);
|
||||
CopyAndHash(file.Filename, null, buf, blockBuf, fileSystem);
|
||||
continue;
|
||||
}
|
||||
using (var transformedFileStream = new FileStream(file.Filename, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
transformedFileStream.CopyTo(fs);
|
||||
}
|
||||
|
||||
CopyAndHash(file.Filename, fs, buf, blockBuf, fileSystem);
|
||||
}
|
||||
|
||||
// --- Phase 3: re-serialize header with real hashes, seek back, overwrite ---
|
||||
string patchedJson = JsonConvert.SerializeObject(fileSystem.GetHeader(), serializerSettings);
|
||||
var patchedPickle = Pickle.CreateEmpty();
|
||||
patchedPickle.WriteString(patchedJson);
|
||||
|
||||
var patchedSizePickle = Pickle.CreateEmpty();
|
||||
patchedSizePickle.WriteUInt32((uint)patchedPickle.GetTotalSize());
|
||||
|
||||
fs.Position = 0;
|
||||
patchedSizePickle.WriteTo(fs);
|
||||
patchedPickle.WriteTo(fs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyAndHash(string srcPath, Stream dest, byte[] buf, byte[] blockBuf, Filesystem fs)
|
||||
{
|
||||
string relPath = Extensions.GetRelativePath(fs.GetRootPath(), srcPath);
|
||||
var node = fs.GetNode(relPath, followLinks: false);
|
||||
|
||||
long fileSize = node?.Size ?? 0;
|
||||
int estimatedBlocks = fileSize > 0 ? (int)((fileSize + 4 * 1024 * 1024 - 1) / (4 * 1024 * 1024)) : 0;
|
||||
|
||||
using (var hasher = new IntegrityHelper.StreamingHasher(estimatedBlocks, blockBuf))
|
||||
using (var src = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamBufferSize, FileOptions.SequentialScan))
|
||||
{
|
||||
int read;
|
||||
while ((read = src.Read(buf, 0, buf.Length)) > 0)
|
||||
{
|
||||
hasher.Append(buf, 0, read);
|
||||
dest?.Write(buf, 0, read);
|
||||
}
|
||||
|
||||
if (node != null)
|
||||
node.Integrity = hasher.Finalise();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using AsarSharp.Integrity;
|
||||
@@ -13,7 +13,7 @@ namespace AsarSharp.AsarFileSystem
|
||||
private int _headerSize;
|
||||
private long _offset;
|
||||
|
||||
private const uint UINT32_MAX = 0xFFFFFFFF; // 2^32 - 1
|
||||
private const uint UINT32_MAX = 0xFFFFFFFF;
|
||||
|
||||
public Filesystem(string src)
|
||||
{
|
||||
@@ -23,20 +23,9 @@ namespace AsarSharp.AsarFileSystem
|
||||
_offset = 0;
|
||||
}
|
||||
|
||||
public string GetRootPath()
|
||||
{
|
||||
return _src;
|
||||
}
|
||||
|
||||
public FilesystemEntry GetHeader()
|
||||
{
|
||||
return _header;
|
||||
}
|
||||
|
||||
public int GetHeaderSize()
|
||||
{
|
||||
return _headerSize;
|
||||
}
|
||||
public string GetRootPath() => _src;
|
||||
public FilesystemEntry GetHeader() => _header;
|
||||
public int GetHeaderSize() => _headerSize;
|
||||
|
||||
public void SetHeader(FilesystemEntry header, int headerSize)
|
||||
{
|
||||
@@ -47,82 +36,94 @@ namespace AsarSharp.AsarFileSystem
|
||||
public FilesystemEntry SearchNodeFromDirectory(string p)
|
||||
{
|
||||
FilesystemEntry json = _header;
|
||||
|
||||
// Normalize path delimiters to system delimiters
|
||||
p = p.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
|
||||
|
||||
string[] dirs = p.Split(Path.DirectorySeparatorChar);
|
||||
|
||||
foreach (string dir in dirs)
|
||||
|
||||
int len = p.Length;
|
||||
int start = 0;
|
||||
|
||||
// skip leading separators
|
||||
while (start < len && (p[start] == '/' || p[start] == '\\')) start++;
|
||||
|
||||
while (start < len)
|
||||
{
|
||||
if (dir == "." || string.IsNullOrEmpty(dir)) continue;
|
||||
|
||||
if (json.IsDirectory)
|
||||
// find next separator
|
||||
int end = start;
|
||||
while (end < len && p[end] != '/' && p[end] != '\\') end++;
|
||||
|
||||
int segLen = end - start;
|
||||
if (segLen == 0 || (segLen == 1 && p[start] == '.'))
|
||||
{
|
||||
if (!json.Files.ContainsKey(dir))
|
||||
{
|
||||
json.Files[dir] = new FilesystemEntry { Files = new Dictionary<string, FilesystemEntry>(StringComparer.Ordinal) };
|
||||
}
|
||||
json = json.Files[dir];
|
||||
start = end + 1;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
string seg = p.Substring(start, segLen);
|
||||
|
||||
if (!json.IsDirectory)
|
||||
throw new Exception($"Unexpected directory state while traversing: {p}");
|
||||
|
||||
if (!json.Files.TryGetValue(seg, out var child))
|
||||
{
|
||||
child = new FilesystemEntry { Files = new Dictionary<string, FilesystemEntry>(StringComparer.Ordinal) };
|
||||
json.Files[seg] = child;
|
||||
}
|
||||
json = child;
|
||||
start = end + 1;
|
||||
}
|
||||
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
|
||||
public (FilesystemEntry parent, string name) SearchNodeFromPathWithParent(string p)
|
||||
{
|
||||
string rel = Extensions.GetRelativePath(_src, p);
|
||||
if (string.IsNullOrEmpty(rel))
|
||||
return (_header, string.Empty);
|
||||
|
||||
string name = Path.GetFileName(rel);
|
||||
string dir = Extensions.GetDirectoryName(rel);
|
||||
var parent = SearchNodeFromDirectory(dir);
|
||||
|
||||
if (parent.Files == null)
|
||||
parent.Files = new Dictionary<string, FilesystemEntry>(StringComparer.Ordinal);
|
||||
|
||||
if (!parent.Files.ContainsKey(name))
|
||||
parent.Files[name] = new FilesystemEntry();
|
||||
|
||||
return (parent, name);
|
||||
}
|
||||
|
||||
public List<string> ListFiles(bool isPack = false)
|
||||
{
|
||||
var files = new List<string>();
|
||||
|
||||
FillFilesFromMetadata("/", _header);
|
||||
return files;
|
||||
|
||||
void FillFilesFromMetadata(string basePath, FilesystemEntry metadata)
|
||||
{
|
||||
if (!metadata.IsDirectory)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!metadata.IsDirectory) return;
|
||||
foreach (var entry in metadata.Files)
|
||||
{
|
||||
string childPath = entry.Key;
|
||||
FilesystemEntry childMetadata = entry.Value;
|
||||
string fullPath = Path.Combine(basePath, childPath).Replace('\\', '/');
|
||||
|
||||
string packState =
|
||||
childMetadata.Unpacked == true ? "unpack" : "pack ";
|
||||
|
||||
string fullPath = Path.Combine(basePath, entry.Key).Replace('\\', '/');
|
||||
string packState = entry.Value.Unpacked == true ? "unpack" : "pack ";
|
||||
files.Add(isPack ? $"{packState} : {fullPath}" : fullPath);
|
||||
FillFilesFromMetadata(fullPath, childMetadata);
|
||||
FillFilesFromMetadata(fullPath, entry.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public FilesystemEntry GetNode(string p, bool followLinks = true)
|
||||
{
|
||||
// Normalize path delimiters
|
||||
p = p.Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar);
|
||||
|
||||
FilesystemEntry node = SearchNodeFromDirectory(Extensions.GetDirectoryName(p));
|
||||
string name = Path.GetFileName(p);
|
||||
|
||||
// Process symbolic links
|
||||
|
||||
if (node.IsLink && followLinks)
|
||||
{
|
||||
return GetNode(Path.Combine(node.Link, name));
|
||||
}
|
||||
|
||||
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
{
|
||||
if (node.IsDirectory && node.Files.TryGetValue(name, out var entry))
|
||||
{
|
||||
return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -132,104 +133,62 @@ namespace AsarSharp.AsarFileSystem
|
||||
public FilesystemEntry GetFile(string p, bool followLinks = true)
|
||||
{
|
||||
FilesystemEntry info = GetNode(p, followLinks);
|
||||
|
||||
if (info == null)
|
||||
{
|
||||
throw new Exception($"\"{p}\" was not found in this archive");
|
||||
}
|
||||
|
||||
// If followLinks=false, do not allow symbolic links (TODO)
|
||||
if (info.IsLink && followLinks)
|
||||
{
|
||||
return GetFile(info.Link, followLinks);
|
||||
}
|
||||
|
||||
if (info == null) throw new Exception($"\"{p}\" was not found in this archive");
|
||||
if (info.IsLink && followLinks) return GetFile(info.Link, followLinks);
|
||||
return info;
|
||||
}
|
||||
|
||||
public static string ReadLink(string path)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
return Path.GetFileName(path);
|
||||
// TODO , NOT IMPLEMENTED
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static string ReadLink(string path) => throw new NotImplementedException();
|
||||
|
||||
#region Writing
|
||||
|
||||
|
||||
public FilesystemEntry SearchNodeFromPath(string p)
|
||||
{
|
||||
p = Extensions.GetRelativePath(_src, p);
|
||||
|
||||
if (string.IsNullOrEmpty(p))
|
||||
{
|
||||
return _header;
|
||||
}
|
||||
|
||||
var name = Path.GetFileName(p);
|
||||
var node = SearchNodeFromDirectory(Extensions.GetDirectoryName(p));
|
||||
|
||||
if (node.Files == null)
|
||||
{
|
||||
node.Files = new Dictionary<string, FilesystemEntry>();
|
||||
}
|
||||
|
||||
if (!node.Files.ContainsKey(name))
|
||||
{
|
||||
node.Files[name] = new FilesystemEntry();
|
||||
}
|
||||
|
||||
return node.Files[name];
|
||||
var (parent, name) = SearchNodeFromPathWithParent(p);
|
||||
if (string.IsNullOrEmpty(name)) return _header;
|
||||
return parent.Files[name];
|
||||
}
|
||||
|
||||
|
||||
public void InsertDirectory(string p, bool unpack)
|
||||
{
|
||||
FilesystemEntry node = SearchNodeFromPath(p);
|
||||
node.Files = node.Files ?? new Dictionary<string, FilesystemEntry>();
|
||||
node.Files = node.Files ?? new Dictionary<string, FilesystemEntry>(StringComparer.Ordinal);
|
||||
node.Unpacked = unpack;
|
||||
}
|
||||
|
||||
public void InsertFile(string path, bool shouldUnpack, CrawledFileType file)
|
||||
|
||||
public void InsertFile(string path, bool shouldUnpack, CrawledFileType file,
|
||||
IntegrityHelper.FileIntegrity precomputedIntegrity = null)
|
||||
{
|
||||
var dirName = Path.GetDirectoryName(path);
|
||||
var dirNode = SearchNodeFromPath(dirName);
|
||||
var (dirNode, _) = SearchNodeFromPathWithParent(Path.GetDirectoryName(path) ?? path);
|
||||
var node = SearchNodeFromPath(path);
|
||||
|
||||
long size = 0;
|
||||
if (file.Stat is FileInfo fileInfo)
|
||||
{
|
||||
size = fileInfo.Length;
|
||||
}
|
||||
long size;
|
||||
if (file.Stat is FileInfo fi)
|
||||
size = fi.Length;
|
||||
else
|
||||
{
|
||||
throw new Exception($"{path}: stat is not a file");
|
||||
}
|
||||
|
||||
|
||||
if (shouldUnpack || dirNode.Unpacked == true)
|
||||
{
|
||||
node.Size = size;
|
||||
node.Unpacked = true;
|
||||
node.Integrity = IntegrityHelper.GetFileIntegrity(path);
|
||||
node.Integrity = precomputedIntegrity ?? IntegrityHelper.GetFileIntegrity(path);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check that the file size does not exceed UINT32_MAX
|
||||
if (size > UINT32_MAX)
|
||||
{
|
||||
throw new Exception($"{path}: file size cannot be larger than 4.2GB");
|
||||
}
|
||||
|
||||
node.Size = size;
|
||||
node.Offset = _offset.ToString();
|
||||
node.Integrity = IntegrityHelper.GetFileIntegrity(path);
|
||||
node.Integrity = precomputedIntegrity ?? IntegrityHelper.GetFileIntegrity(path);
|
||||
|
||||
if (!Extensions.IsWindowsPlatform() && (file.Stat.Attributes & FileAttributes.Hidden) != 0)
|
||||
{
|
||||
node.Executable = true;
|
||||
}
|
||||
|
||||
_offset += size;
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using AsarSharp.Utils;
|
||||
|
||||
namespace AsarSharp.AsarFileSystem
|
||||
@@ -25,136 +24,108 @@ namespace AsarSharp.AsarFileSystem
|
||||
Directory,
|
||||
Link
|
||||
}
|
||||
|
||||
|
||||
public static class FileSystemCrawler
|
||||
{
|
||||
|
||||
|
||||
public static CrawledFileType DetermineFileType(string filename)
|
||||
{
|
||||
var fileInfo = new FileInfo(filename);
|
||||
if (fileInfo.Exists)
|
||||
FileAttributes attributes;
|
||||
try
|
||||
{
|
||||
return new CrawledFileType { Type = FileType.File, Stat = fileInfo };
|
||||
attributes = File.GetAttributes(filename);
|
||||
}
|
||||
|
||||
var directoryInfo = new DirectoryInfo(filename);
|
||||
if (directoryInfo.Exists)
|
||||
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
|
||||
{
|
||||
return new CrawledFileType { Type = FileType.Directory, Stat = directoryInfo };
|
||||
return null;
|
||||
}
|
||||
|
||||
var linkInfo = new FileInfo(filename);
|
||||
if (linkInfo.Exists && (linkInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
|
||||
{
|
||||
return new CrawledFileType { Type = FileType.Link, Stat = linkInfo };
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
bool isDirectory = (attributes & FileAttributes.Directory) == FileAttributes.Directory;
|
||||
bool isLink = (attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
|
||||
FileSystemInfo info = isDirectory
|
||||
? (FileSystemInfo)new DirectoryInfo(filename)
|
||||
: new FileInfo(filename);
|
||||
|
||||
if (isLink) return new CrawledFileType { Type = FileType.Link, Stat = info };
|
||||
if (isDirectory) return new CrawledFileType { Type = FileType.Directory, Stat = info };
|
||||
return new CrawledFileType { Type = FileType.File, Stat = info };
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static (List<string> filenames, Dictionary<string, CrawledFileType> metadata) CrawlFileSystem(string dir)
|
||||
{
|
||||
var metadata = new Dictionary<string, CrawledFileType>();
|
||||
var crawled = CrawlIterative(dir);
|
||||
var results = crawled.Select(filename => new { filename, type = DetermineFileType(filename) }).ToList();
|
||||
|
||||
var links = new List<string>();
|
||||
var filenames = new List<string>();
|
||||
var links = new List<string>();
|
||||
|
||||
foreach (var result in results.Where(result => result.type != null))
|
||||
foreach (var fullPath in CrawlIterative(dir))
|
||||
{
|
||||
metadata[result.filename] = result.type;
|
||||
if (result.type.Type == FileType.Link)
|
||||
{
|
||||
links.Add(result.filename);
|
||||
}
|
||||
filenames.Add(result.filename);
|
||||
var type = DetermineFileType(fullPath);
|
||||
if (type == null) continue;
|
||||
metadata[fullPath] = type;
|
||||
if (type.Type == FileType.Link) links.Add(fullPath);
|
||||
filenames.Add(fullPath);
|
||||
}
|
||||
|
||||
var filteredFilenames = new List<string>();
|
||||
if (links.Count == 0) return (filenames, metadata);
|
||||
|
||||
var filtered = new List<string>(filenames.Count);
|
||||
foreach (var filename in filenames)
|
||||
{
|
||||
var exactLinkIndex = links.FindIndex(link => filename == link);
|
||||
var isValid = true;
|
||||
bool isValid = true;
|
||||
string fileDir = Path.GetDirectoryName(filename) ?? string.Empty;
|
||||
|
||||
for (var i = 0; i < links.Count; i++)
|
||||
foreach (var link in links)
|
||||
{
|
||||
if (i == exactLinkIndex)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (string.Equals(filename, link, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
var link = links[i];
|
||||
var isFileWithinSymlinkDir = filename.StartsWith(link, StringComparison.OrdinalIgnoreCase);
|
||||
var relativePath = Extensions.GetRelativePath(link, Path.GetDirectoryName(filename) ?? string.Empty);
|
||||
|
||||
if (isFileWithinSymlinkDir && !relativePath.StartsWith("..", StringComparison.Ordinal))
|
||||
if (filename.StartsWith(link, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
isValid = false;
|
||||
break;
|
||||
string rel = Extensions.GetRelativePath(link, fileDir);
|
||||
if (!rel.StartsWith("..", StringComparison.Ordinal))
|
||||
{
|
||||
isValid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isValid)
|
||||
{
|
||||
filteredFilenames.Add(filename);
|
||||
}
|
||||
if (isValid) filtered.Add(filename);
|
||||
}
|
||||
|
||||
return (filteredFilenames, metadata);
|
||||
return (filtered, metadata);
|
||||
}
|
||||
|
||||
|
||||
// (File order is not important!!!)
|
||||
public static List<string> CrawlIterative(string dir)
|
||||
{
|
||||
var result = new List<string>();
|
||||
var stack = new Stack<string>();
|
||||
var stack = new Stack<DirectoryInfo>();
|
||||
|
||||
|
||||
string basePath = Extensions.GetBasePath(dir);
|
||||
if (!Directory.Exists(basePath)) return result;
|
||||
|
||||
if (!Directory.Exists(basePath))
|
||||
return result;
|
||||
|
||||
// Add only the base directory to the stack, but not to the result
|
||||
stack.Push(basePath);
|
||||
stack.Push(new DirectoryInfo(basePath));
|
||||
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
string currentDir = stack.Pop();
|
||||
|
||||
var current = stack.Pop();
|
||||
FileSystemInfo[] entries;
|
||||
try
|
||||
{
|
||||
// Add all files from the current directory
|
||||
result.AddRange(Directory.GetFiles(currentDir, "*", SearchOption.TopDirectoryOnly));
|
||||
|
||||
// Add subdirectories to the results and to the stack
|
||||
foreach (var directory in Directory.GetDirectories(currentDir, "*",
|
||||
SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
// Add subdirectories to the result
|
||||
if (directory != basePath) // Do not add a base directory
|
||||
{
|
||||
result.Add(directory);
|
||||
}
|
||||
|
||||
// Add to the stack for processing
|
||||
stack.Push(directory);
|
||||
}
|
||||
entries = current.GetFileSystemInfos();
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// Skip directories to which there is no access
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
result.Add(entry.FullName);
|
||||
if (entry is DirectoryInfo subDir)
|
||||
stack.Push(subDir);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
@@ -9,61 +9,148 @@ namespace AsarSharp.Integrity
|
||||
public static class IntegrityHelper
|
||||
{
|
||||
private const string ALGORITHM = "SHA256";
|
||||
// 4MB default block size
|
||||
private const int BLOCK_SIZE = 4 * 1024 * 1024;
|
||||
public const string PLACEHOLDER_HASH = "0000000000000000000000000000000000000000000000000000000000000000";
|
||||
private static readonly char[] HexDigits = "0123456789abcdef".ToCharArray();
|
||||
|
||||
public class FileIntegrity
|
||||
{
|
||||
[JsonProperty("algorithm")]
|
||||
public string Algorithm { get; set; }
|
||||
|
||||
|
||||
[JsonProperty("hash")]
|
||||
public string Hash { get; set; }
|
||||
|
||||
|
||||
[JsonProperty("blockSize")]
|
||||
public int BlockSize { get; set; }
|
||||
|
||||
|
||||
[JsonProperty("blocks")]
|
||||
public List<string> Blocks { get; set; }
|
||||
}
|
||||
|
||||
public static FileIntegrity GetFileIntegrity(string path)
|
||||
public static FileIntegrity CreatePlaceholder(long fileSize)
|
||||
{
|
||||
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
using(var fileHash = SHA256.Create())
|
||||
{
|
||||
int blockCount = fileSize > 0 ? (int)((fileSize + BLOCK_SIZE - 1) / BLOCK_SIZE) : 0;
|
||||
var blocks = new List<string>(blockCount);
|
||||
for (int i = 0; i < blockCount; i++)
|
||||
blocks.Add(PLACEHOLDER_HASH);
|
||||
|
||||
var blockHashes = new List<string>();
|
||||
var buffer = new byte[BLOCK_SIZE];
|
||||
return new FileIntegrity
|
||||
{
|
||||
Algorithm = ALGORITHM,
|
||||
Hash = PLACEHOLDER_HASH,
|
||||
BlockSize = BLOCK_SIZE,
|
||||
Blocks = blocks,
|
||||
};
|
||||
}
|
||||
|
||||
public static FileIntegrity GetFileIntegrity(string path, byte[] reusableBuffer = null)
|
||||
{
|
||||
bool ownBuffer = reusableBuffer == null;
|
||||
if (ownBuffer) reusableBuffer = new byte[BLOCK_SIZE];
|
||||
|
||||
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
|
||||
65536, FileOptions.SequentialScan))
|
||||
using (var fileHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
|
||||
using (var blockHash = SHA256.Create())
|
||||
{
|
||||
int estimatedBlockCount = fileStream.Length > 0
|
||||
? (int)((fileStream.Length + BLOCK_SIZE - 1) / BLOCK_SIZE)
|
||||
: 0;
|
||||
var blockHashes = new List<string>(estimatedBlockCount);
|
||||
int bytesRead;
|
||||
|
||||
while ((bytesRead = fileStream.Read(buffer, 0, BLOCK_SIZE)) > 0)
|
||||
while ((bytesRead = fileStream.Read(reusableBuffer, 0, reusableBuffer.Length)) > 0)
|
||||
{
|
||||
var block = new byte[bytesRead];
|
||||
Array.Copy(buffer, block, bytesRead);
|
||||
blockHashes.Add(HashBlock(block));
|
||||
fileHash.TransformBlock(block, 0, block.Length, null, 0);
|
||||
blockHashes.Add(ToLowerHex(blockHash.ComputeHash(reusableBuffer, 0, bytesRead)));
|
||||
fileHash.AppendData(reusableBuffer, 0, bytesRead);
|
||||
}
|
||||
|
||||
fileHash.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
|
||||
|
||||
return new FileIntegrity
|
||||
{
|
||||
Algorithm = ALGORITHM,
|
||||
Hash = BitConverter.ToString(fileHash.Hash).Replace("-", "").ToLowerInvariant(),
|
||||
Hash = ToLowerHex(fileHash.GetHashAndReset()),
|
||||
BlockSize = BLOCK_SIZE,
|
||||
Blocks = blockHashes,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static string HashBlock(byte[] block)
|
||||
public sealed class StreamingHasher : IDisposable
|
||||
{
|
||||
using (var sha256 = SHA256.Create())
|
||||
private readonly IncrementalHash _fileHash;
|
||||
private readonly SHA256 _blockHash;
|
||||
private readonly byte[] _blockBuf;
|
||||
private int _blockFill;
|
||||
private readonly List<string> _blockHashes;
|
||||
|
||||
public StreamingHasher(int estimatedBlocks = 0, byte[] sharedBlockBuffer = null)
|
||||
{
|
||||
var hash = sha256.ComputeHash(block);
|
||||
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
|
||||
_fileHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
_blockHash = SHA256.Create();
|
||||
_blockBuf = sharedBlockBuffer ?? new byte[BLOCK_SIZE];
|
||||
_blockFill = 0;
|
||||
_blockHashes = new List<string>(estimatedBlocks);
|
||||
}
|
||||
|
||||
public void Append(byte[] data, int offset, int count)
|
||||
{
|
||||
_fileHash.AppendData(data, offset, count);
|
||||
|
||||
int remaining = count;
|
||||
int src = offset;
|
||||
while (remaining > 0)
|
||||
{
|
||||
int space = BLOCK_SIZE - _blockFill;
|
||||
int copy = Math.Min(space, remaining);
|
||||
Buffer.BlockCopy(data, src, _blockBuf, _blockFill, copy);
|
||||
_blockFill += copy;
|
||||
src += copy;
|
||||
remaining -= copy;
|
||||
|
||||
if (_blockFill == BLOCK_SIZE)
|
||||
{
|
||||
_blockHashes.Add(ToLowerHex(_blockHash.ComputeHash(_blockBuf, 0, BLOCK_SIZE)));
|
||||
_blockFill = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public FileIntegrity Finalise()
|
||||
{
|
||||
if (_blockFill > 0)
|
||||
{
|
||||
_blockHashes.Add(ToLowerHex(_blockHash.ComputeHash(_blockBuf, 0, _blockFill)));
|
||||
_blockFill = 0;
|
||||
}
|
||||
|
||||
return new FileIntegrity
|
||||
{
|
||||
Algorithm = ALGORITHM,
|
||||
Hash = ToLowerHex(_fileHash.GetHashAndReset()),
|
||||
BlockSize = BLOCK_SIZE,
|
||||
Blocks = _blockHashes,
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_fileHash.Dispose();
|
||||
_blockHash.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public static string ToLowerHex(byte[] bytes)
|
||||
{
|
||||
if (bytes == null || bytes.Length == 0) return string.Empty;
|
||||
var chars = new char[bytes.Length * 2];
|
||||
for (int i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
byte v = bytes[i];
|
||||
chars[i * 2] = HexDigits[v >> 4];
|
||||
chars[i * 2 + 1] = HexDigits[v & 0x0F];
|
||||
}
|
||||
return new string(chars);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+100
-220
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace AsarSharp.PickleTools
|
||||
@@ -12,10 +13,10 @@ namespace AsarSharp.PickleTools
|
||||
public const int SIZE_FLOAT = 4;
|
||||
public const int SIZE_DOUBLE = 8;
|
||||
|
||||
// Size of memory allocation unit for payload
|
||||
public const int PAYLOAD_UNIT = 64;
|
||||
// Initial payload allocation. Bumped from 64 — large headers used to
|
||||
// realloc many times when growing geometrically from 64.
|
||||
public const int PAYLOAD_UNIT = 4096;
|
||||
|
||||
// Maximum value for read-only
|
||||
public const long CAPACITY_READ_ONLY = 9007199254740992;
|
||||
|
||||
private byte[] _header;
|
||||
@@ -57,55 +58,40 @@ namespace AsarSharp.PickleTools
|
||||
SetPayloadSize(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static Pickle CreateEmpty()
|
||||
{
|
||||
return new Pickle();
|
||||
}
|
||||
|
||||
public static Pickle CreateFromBuffer(byte[] buffer)
|
||||
{
|
||||
return new Pickle(buffer);
|
||||
}
|
||||
|
||||
public byte[] GetHeader()
|
||||
{
|
||||
return _header;
|
||||
}
|
||||
public static Pickle CreateEmpty() => new Pickle();
|
||||
public static Pickle CreateFromBuffer(byte[] buffer) => new Pickle(buffer);
|
||||
|
||||
public int GetHeaderSize()
|
||||
{
|
||||
return _headerSize;
|
||||
}
|
||||
|
||||
public PickleIterator CreateIterator()
|
||||
{
|
||||
return new PickleIterator(this);
|
||||
}
|
||||
public byte[] GetHeader() => _header;
|
||||
public int GetHeaderSize() => _headerSize;
|
||||
|
||||
/// <summary>
|
||||
/// Converts Pickle to a byte array
|
||||
/// </summary>
|
||||
public PickleIterator CreateIterator() => new PickleIterator(this);
|
||||
|
||||
/// <summary>Total byte length of the serialised pickle (header + payload).</summary>
|
||||
public int GetTotalSize() => _headerSize + GetPayloadSize();
|
||||
|
||||
/// <summary>Materialise the pickle into a fresh byte array (allocates).</summary>
|
||||
public byte[] ToBuffer()
|
||||
{
|
||||
int resultSize = _headerSize + GetPayloadSize();
|
||||
int resultSize = GetTotalSize();
|
||||
byte[] result = new byte[resultSize];
|
||||
Array.Copy(_header, 0, result, 0, resultSize);
|
||||
Buffer.BlockCopy(_header, 0, result, 0, resultSize);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public bool WriteBool(bool value)
|
||||
/// <summary>Write the serialised pickle straight to <paramref name="stream"/> — no extra copy.</summary>
|
||||
public void WriteTo(Stream stream)
|
||||
{
|
||||
return WriteInt(value ? 1 : 0);
|
||||
stream.Write(_header, 0, GetTotalSize());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public bool WriteBool(bool value) => WriteInt(value ? 1 : 0);
|
||||
|
||||
public bool WriteInt(int value)
|
||||
{
|
||||
EnsureCapacity(SIZE_INT32);
|
||||
|
||||
var dataLength = AlignInt(SIZE_INT32, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
const int dataLength = SIZE_INT32; // already 4-byte aligned
|
||||
int newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
@@ -113,13 +99,6 @@ namespace AsarSharp.PickleTools
|
||||
}
|
||||
|
||||
WriteInt32LE(value, _headerSize + _writeOffset);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + SIZE_INT32;
|
||||
for (int i = endOffset; i < endOffset + dataLength - SIZE_INT32; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
|
||||
SetPayloadSize(newSize);
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
@@ -128,10 +107,8 @@ namespace AsarSharp.PickleTools
|
||||
|
||||
public bool WriteUInt32(uint value)
|
||||
{
|
||||
EnsureCapacity(SIZE_UINT32);
|
||||
|
||||
var dataLength = AlignInt(SIZE_UINT32, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
const int dataLength = SIZE_UINT32;
|
||||
int newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
@@ -139,24 +116,15 @@ namespace AsarSharp.PickleTools
|
||||
}
|
||||
|
||||
WriteUInt32LE(value, _headerSize + _writeOffset);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + SIZE_UINT32;
|
||||
for (int i = endOffset; i < endOffset + dataLength - SIZE_UINT32; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
|
||||
SetPayloadSize(newSize);
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public bool WriteInt64(long value)
|
||||
{
|
||||
EnsureCapacity(SIZE_INT64);
|
||||
|
||||
var dataLength = AlignInt(SIZE_INT64, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
const int dataLength = SIZE_INT64;
|
||||
int newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
@@ -164,13 +132,6 @@ namespace AsarSharp.PickleTools
|
||||
}
|
||||
|
||||
WriteInt64LE(value, _headerSize + _writeOffset);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + SIZE_INT64;
|
||||
for (int i = endOffset; i < endOffset + dataLength - SIZE_INT64; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
|
||||
SetPayloadSize(newSize);
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
@@ -179,10 +140,8 @@ namespace AsarSharp.PickleTools
|
||||
|
||||
public bool WriteUInt64(ulong value)
|
||||
{
|
||||
EnsureCapacity(SIZE_UINT64);
|
||||
|
||||
var dataLength = AlignInt(SIZE_UINT64, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
const int dataLength = SIZE_UINT64;
|
||||
int newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
@@ -190,102 +149,69 @@ namespace AsarSharp.PickleTools
|
||||
}
|
||||
|
||||
WriteUInt64LE(value, _headerSize + _writeOffset);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + SIZE_UINT64;
|
||||
for (int i = endOffset; i < endOffset + dataLength - SIZE_UINT64; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
|
||||
SetPayloadSize(newSize);
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public bool WriteFloat(float value)
|
||||
{
|
||||
EnsureCapacity(SIZE_FLOAT);
|
||||
|
||||
var dataLength = AlignInt(SIZE_FLOAT, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
const int dataLength = SIZE_FLOAT;
|
||||
int newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
Resize(Math.Max((int)_capacityAfterHeader * 2, newSize));
|
||||
}
|
||||
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
if (!BitConverter.IsLittleEndian)
|
||||
{
|
||||
Array.Reverse(bytes);
|
||||
}
|
||||
|
||||
Array.Copy(bytes, 0, _header, _headerSize + _writeOffset, SIZE_FLOAT);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + SIZE_FLOAT;
|
||||
for (int i = endOffset; i < endOffset + dataLength - SIZE_FLOAT; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
int bits = BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
|
||||
WriteInt32LE(bits, _headerSize + _writeOffset);
|
||||
|
||||
SetPayloadSize(newSize);
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public bool WriteDouble(double value)
|
||||
{
|
||||
EnsureCapacity(SIZE_DOUBLE);
|
||||
|
||||
var dataLength = AlignInt(SIZE_DOUBLE, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
const int dataLength = SIZE_DOUBLE;
|
||||
int newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
Resize(Math.Max((int)_capacityAfterHeader * 2, newSize));
|
||||
}
|
||||
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
if (!BitConverter.IsLittleEndian)
|
||||
{
|
||||
Array.Reverse(bytes);
|
||||
}
|
||||
|
||||
Array.Copy(bytes, 0, _header, _headerSize + _writeOffset, SIZE_DOUBLE);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + SIZE_DOUBLE;
|
||||
for (int i = endOffset; i < endOffset + dataLength - SIZE_DOUBLE; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
long bits = BitConverter.DoubleToInt64Bits(value);
|
||||
WriteInt64LE(bits, _headerSize + _writeOffset);
|
||||
|
||||
SetPayloadSize(newSize);
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public bool WriteString(string value)
|
||||
{
|
||||
byte[] strBytes = Encoding.UTF8.GetBytes(value);
|
||||
int length = strBytes.Length;
|
||||
int byteLen = Encoding.UTF8.GetByteCount(value);
|
||||
|
||||
if (!WriteInt(length))
|
||||
if (!WriteInt(byteLen))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var dataLength = AlignInt(length, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
int aligned = AlignInt(byteLen, SIZE_UINT32);
|
||||
int newSize = _writeOffset + aligned;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
Resize(Math.Max((int)_capacityAfterHeader * 2, newSize));
|
||||
}
|
||||
|
||||
Array.Copy(strBytes, 0, _header, _headerSize + _writeOffset, length);
|
||||
int writeStart = _headerSize + _writeOffset;
|
||||
Encoding.UTF8.GetBytes(value, 0, value.Length, _header, writeStart);
|
||||
|
||||
var endOffset = _headerSize + _writeOffset + length;
|
||||
for (int i = endOffset; i < endOffset + dataLength - length; i++)
|
||||
// zero alignment padding
|
||||
for (int i = writeStart + byteLen; i < writeStart + aligned; i++)
|
||||
{
|
||||
_header[i] = 0;
|
||||
}
|
||||
@@ -294,132 +220,86 @@ namespace AsarSharp.PickleTools
|
||||
_writeOffset = newSize;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public void SetPayloadSize(int payloadSize)
|
||||
{
|
||||
WriteUInt32LE((uint)payloadSize, 0);
|
||||
}
|
||||
|
||||
public int GetPayloadSize()
|
||||
{
|
||||
return (int)ReadUInt32LE(0);
|
||||
}
|
||||
|
||||
|
||||
public int GetPayloadSize() => (int)ReadUInt32LE(0);
|
||||
|
||||
private void Resize(int newCapacity)
|
||||
{
|
||||
newCapacity = AlignInt(newCapacity, PAYLOAD_UNIT);
|
||||
byte[] newHeader = new byte[_header.Length + newCapacity];
|
||||
Array.Copy(_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;
|
||||
}
|
||||
|
||||
|
||||
public static int AlignInt(int i, int alignment)
|
||||
{
|
||||
return i + ((alignment - (i % alignment)) % alignment);
|
||||
}
|
||||
|
||||
private void EnsureCapacity(int additionalSize)
|
||||
{
|
||||
var dataLength = AlignInt(additionalSize, SIZE_UINT32);
|
||||
var newSize = _writeOffset + dataLength;
|
||||
|
||||
if (newSize > _capacityAfterHeader)
|
||||
{
|
||||
Resize(Math.Max((int)_capacityAfterHeader * 2, newSize));
|
||||
}
|
||||
}
|
||||
|
||||
#region Auxiliary methods for reading/writing values in Little Endian
|
||||
|
||||
private uint ReadUInt32LE(int offset)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
return BitConverter.ToUInt32(_header, offset);
|
||||
}
|
||||
else
|
||||
{
|
||||
return (uint)(_header[offset] |
|
||||
(_header[offset + 1] << 8) |
|
||||
(_header[offset + 2] << 16) |
|
||||
(_header[offset + 3] << 24));
|
||||
}
|
||||
// _header is allocated by us so always little-endian-friendly when on LE host.
|
||||
return (uint)(_header[offset] |
|
||||
(_header[offset + 1] << 8) |
|
||||
(_header[offset + 2] << 16) |
|
||||
(_header[offset + 3] << 24));
|
||||
}
|
||||
|
||||
private void WriteInt32LE(int value, int offset)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
Array.Copy(bytes, 0, _header, offset, 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
_header[offset] = (byte)value;
|
||||
_header[offset + 1] = (byte)(value >> 8);
|
||||
_header[offset + 2] = (byte)(value >> 16);
|
||||
_header[offset + 3] = (byte)(value >> 24);
|
||||
}
|
||||
_header[offset] = (byte)value;
|
||||
_header[offset + 1] = (byte)(value >> 8);
|
||||
_header[offset + 2] = (byte)(value >> 16);
|
||||
_header[offset + 3] = (byte)(value >> 24);
|
||||
}
|
||||
|
||||
private void WriteUInt32LE(uint value, int offset)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
Array.Copy(bytes, 0, _header, offset, 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
_header[offset] = (byte)value;
|
||||
_header[offset + 1] = (byte)(value >> 8);
|
||||
_header[offset + 2] = (byte)(value >> 16);
|
||||
_header[offset + 3] = (byte)(value >> 24);
|
||||
}
|
||||
_header[offset] = (byte)value;
|
||||
_header[offset + 1] = (byte)(value >> 8);
|
||||
_header[offset + 2] = (byte)(value >> 16);
|
||||
_header[offset + 3] = (byte)(value >> 24);
|
||||
}
|
||||
|
||||
private void WriteInt64LE(long value, int offset)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
Array.Copy(bytes, 0, _header, offset, 8);
|
||||
}
|
||||
else
|
||||
{
|
||||
_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)
|
||||
{
|
||||
if (BitConverter.IsLittleEndian)
|
||||
{
|
||||
byte[] bytes = BitConverter.GetBytes(value);
|
||||
Array.Copy(bytes, 0, _header, offset, 8);
|
||||
}
|
||||
else
|
||||
{
|
||||
_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);
|
||||
}
|
||||
_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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+114
-38
@@ -1,11 +1,19 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace AsarSharp.Utils
|
||||
{
|
||||
internal static class Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Compute path relative to <paramref name="relativeTo"/>.
|
||||
/// Fast common-case (path is inside relativeTo): plain prefix-strip.
|
||||
/// Falls back to <see cref="Path.GetFullPath"/> + manual relativisation
|
||||
/// when paths must be normalised or '..' segments are required.
|
||||
/// Replaces previous URI-based implementation which was a large hot-path cost.
|
||||
/// </summary>
|
||||
public static string GetRelativePath(string relativeTo, string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(relativeTo))
|
||||
@@ -13,84 +21,155 @@ namespace AsarSharp.Utils
|
||||
if (string.IsNullOrEmpty(path))
|
||||
throw new ArgumentNullException(nameof(path));
|
||||
|
||||
var fullRelativeTo = Path.GetFullPath(relativeTo);
|
||||
var fullPath = Path.GetFullPath(path);
|
||||
// Fast path: literal prefix match (no normalisation). Covers ~all
|
||||
// intra-archive callers where both inputs already come from the
|
||||
// same crawl pass.
|
||||
string baseFast = TrimTrailingSeparators(relativeTo);
|
||||
string pathFast = TrimTrailingSeparators(path);
|
||||
|
||||
if (string.Equals(fullRelativeTo, fullPath, StringComparison.OrdinalIgnoreCase))
|
||||
return "";
|
||||
if (string.Equals(baseFast, pathFast, StringComparison.OrdinalIgnoreCase))
|
||||
return string.Empty;
|
||||
|
||||
var relativeToUri = new Uri(fullRelativeTo.EndsWith(Path.DirectorySeparatorChar.ToString())
|
||||
? fullRelativeTo
|
||||
: fullRelativeTo + Path.DirectorySeparatorChar);
|
||||
var pathUri = new Uri(fullPath.EndsWith(Path.DirectorySeparatorChar.ToString()) && !File.Exists(fullPath)
|
||||
? fullPath
|
||||
: fullPath + (Directory.Exists(fullPath) ? Path.DirectorySeparatorChar.ToString() : ""));
|
||||
if (pathFast.Length > baseFast.Length &&
|
||||
pathFast.StartsWith(baseFast, StringComparison.OrdinalIgnoreCase) &&
|
||||
IsSeparator(pathFast[baseFast.Length]))
|
||||
{
|
||||
return pathFast.Substring(baseFast.Length + 1);
|
||||
}
|
||||
|
||||
var relativeUri = relativeToUri.MakeRelativeUri(pathUri);
|
||||
var relativePath = Uri.UnescapeDataString(relativeUri.ToString())
|
||||
.Replace('/', Path.DirectorySeparatorChar);
|
||||
|
||||
return relativePath.TrimEnd(Path.DirectorySeparatorChar);
|
||||
// Slow path: normalise both sides and compute relative — used for
|
||||
// security checks (out-of-tree symlink/destination guards) and the
|
||||
// rare "go up" case.
|
||||
return GetRelativePathNormalised(relativeTo, path);
|
||||
}
|
||||
|
||||
|
||||
private static string GetRelativePathNormalised(string relativeTo, string path)
|
||||
{
|
||||
string fullBase = Path.GetFullPath(relativeTo);
|
||||
string fullPath = Path.GetFullPath(path);
|
||||
|
||||
fullBase = TrimTrailingSeparators(fullBase);
|
||||
fullPath = TrimTrailingSeparators(fullPath);
|
||||
|
||||
if (string.Equals(fullBase, fullPath, StringComparison.OrdinalIgnoreCase))
|
||||
return string.Empty;
|
||||
|
||||
if (fullPath.Length > fullBase.Length &&
|
||||
fullPath.StartsWith(fullBase, StringComparison.OrdinalIgnoreCase) &&
|
||||
IsSeparator(fullPath[fullBase.Length]))
|
||||
{
|
||||
return fullPath.Substring(fullBase.Length + 1);
|
||||
}
|
||||
|
||||
// Need to walk up the common ancestor.
|
||||
char sep = Path.DirectorySeparatorChar;
|
||||
string[] baseParts = fullBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] pathParts = fullPath.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
int common = 0;
|
||||
int max = Math.Min(baseParts.Length, pathParts.Length);
|
||||
while (common < max &&
|
||||
string.Equals(baseParts[common], pathParts[common], StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
common++;
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
for (int i = common; i < baseParts.Length; i++)
|
||||
{
|
||||
if (sb.Length > 0) sb.Append(sep);
|
||||
sb.Append("..");
|
||||
}
|
||||
for (int i = common; i < pathParts.Length; i++)
|
||||
{
|
||||
if (sb.Length > 0) sb.Append(sep);
|
||||
sb.Append(pathParts[i]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string TrimTrailingSeparators(string s)
|
||||
{
|
||||
int end = s.Length;
|
||||
while (end > 0 && IsSeparator(s[end - 1])) end--;
|
||||
return end == s.Length ? s : s.Substring(0, end);
|
||||
}
|
||||
|
||||
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))
|
||||
return ".";
|
||||
|
||||
string result = Path.GetDirectoryName(path);
|
||||
|
||||
// If the result is an empty string, return “.” as in Node.js
|
||||
|
||||
if (string.IsNullOrEmpty(result))
|
||||
return ".";
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static void CopyDirectory(string sourceDir, string destinationDir)
|
||||
{
|
||||
// Create the destination directory
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
|
||||
// Get all files in the source directory
|
||||
foreach (var file in Directory.GetFiles(sourceDir))
|
||||
{
|
||||
var destFile = Path.Combine(destinationDir, Path.GetFileName(file));
|
||||
File.Copy(file, destFile, true);
|
||||
}
|
||||
|
||||
// Recursively copy all subdirectories
|
||||
foreach (var dir in Directory.GetDirectories(sourceDir))
|
||||
{
|
||||
var destDir = Path.Combine(destinationDir, Path.GetFileName(dir));
|
||||
CopyDirectory(dir, destDir);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static string GetBasePath(string dir)
|
||||
{
|
||||
// Look for the last path delimiter before any pattern
|
||||
int wildcardIndex = dir.IndexOfAny(new[] { '*', '?' });
|
||||
if (wildcardIndex == -1)
|
||||
{
|
||||
return dir;
|
||||
}
|
||||
|
||||
|
||||
int lastSeparatorIndex = dir.LastIndexOf(Path.DirectorySeparatorChar, wildcardIndex);
|
||||
if (lastSeparatorIndex == -1)
|
||||
{
|
||||
return ".";
|
||||
}
|
||||
|
||||
|
||||
return dir.Substring(0, lastSeparatorIndex);
|
||||
}
|
||||
|
||||
|
||||
public static void SetUnixFilePermission(string filePath, string permission)
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
return;
|
||||
|
||||
// Use chmod
|
||||
var process = new System.Diagnostics.Process
|
||||
{
|
||||
StartInfo = new System.Diagnostics.ProcessStartInfo
|
||||
@@ -105,14 +184,12 @@ namespace AsarSharp.Utils
|
||||
process.Start();
|
||||
process.WaitForExit();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static void CreateSymbolicLink(string linkTarget, string linkPath)
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
// On Windows, creating symlinks requires special privileges,
|
||||
// so on many systems it simply won't work without administrator privileges
|
||||
NativeMethods.CreateSymbolicLink(linkPath, linkTarget,
|
||||
Directory.Exists(linkTarget)
|
||||
? NativeMethods.SymLinkFlag.Directory
|
||||
@@ -120,7 +197,6 @@ namespace AsarSharp.Utils
|
||||
return;
|
||||
}
|
||||
|
||||
// In Unix systems we use the corresponding system call
|
||||
var process = new System.Diagnostics.Process
|
||||
{
|
||||
StartInfo = new System.Diagnostics.ProcessStartInfo
|
||||
@@ -135,11 +211,11 @@ namespace AsarSharp.Utils
|
||||
process.Start();
|
||||
process.WaitForExit();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static bool IsWindowsPlatform()
|
||||
{
|
||||
return Environment.OSVersion.Platform == PlatformID.Win32NT;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
# Changelog
|
||||
|
||||
This file is the source of truth for release notes.
|
||||
The newest entry must match the version in `WandEnhancer/Properties/AssemblyInfo.cs`.
|
||||
|
||||
## [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. [Discussion #140](https://github.com/k1tbyte/Wand-Enhancer/discussions/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](https://github.com/k1tbyte/Wand-Enhancer/pull/145). Related issue: [#136](https://github.com/k1tbyte/Wand-Enhancer/issues/136)
|
||||
- Fixed ASAR extraction path traversal and corrupt Pickle payload allocation by @divya0795 in [#143](https://github.com/k1tbyte/Wand-Enhancer/pull/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](https://github.com/k1tbyte/Wand-Enhancer/issues/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
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed Pro features disappearing after a day or two when Wand refreshed account data in the background; account store updates now preserve the patched active subscription by @Kava-4 in #110. Related issue #106
|
||||
- Fixed the new Pro account reducer guard so normal account updates do not fail while keeping Pro active.
|
||||
|
||||
## [1.0.9.0] - 2026-06-15
|
||||
|
||||
### Features
|
||||
|
||||
- The Remote Web Panel now shows mod names, descriptions, and instructions translated to your WeMod account language by @YifePlayte in #98. Related issue: #85
|
||||
- Added a language selector to the Remote Web Panel (English, Russian, German, French, Spanish, Simplified Chinese) with automatic detection from the browser language.
|
||||
|
||||
### Improvements
|
||||
|
||||
- Release builds are now code-signed, which reduces false-positive antivirus and VirusTotal detections.
|
||||
- Reworked the Remote Web Panel internals around feature capabilities for easier maintenance, with no change to existing behavior.
|
||||
|
||||
## [1.0.8.4] - 2026-06-10
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed QR code issues on the latest Wand version.
|
||||
- Fixed application hang that occurred after Wand updates with pending patches.
|
||||
|
||||
## [1.0.8.3] - 2026-06-06
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed the Remote Web Panel patches so they reliably apply on newer Wand builds by making the remote bridge patch anchors version-resilient.
|
||||
- Fixed Pro activation being lost after changing the app language; the account language endpoint now keeps the patched subscription.
|
||||
- Fixed "WeMod directory not found" when Wand/WeMod is installed outside the default location or only one brand folder exists. The patcher now also resolves the install directory from a running Wand/WeMod process. #82
|
||||
- Hid the Pro "Remote" onboarding card in the Explore Pro benefits dialog. #86
|
||||
|
||||
## [1.0.8.2] - 2026-05-15
|
||||
|
||||
### Fixes
|
||||
|
||||
- Rolled back an incorrect Disable Updates patch fix that introduced a `SyntaxError` preventing Wand from launching.
|
||||
|
||||
## [1.0.8.1] - 2026-05-15
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed a syntax error in the Disable Updates patch that prevented Wand from launching. #70
|
||||
- Fixed an issue where the Remote Web Panel WebSocket connection wouldn't automatically reconnect when turning returning to the app or turning on the screen.
|
||||
- Reduced battery consumption and device heating on mobile device by optimizing heavy UI blur effects and eliminating unnecessary React re-renders in the Remote Web Panel. #67
|
||||
|
||||
## [1.0.8.0] - 2026-05-06
|
||||
|
||||
### Features
|
||||
|
||||
- Added the My Games list to the Remote Panel with remote start and stop actions.
|
||||
- Improved the Remote Panel with new UI and overall UX.
|
||||
- Added an update dialog with release notes and access to full patch notes.
|
||||
|
||||
### Improvements
|
||||
|
||||
- Optimized and sped up patching and ASAR unpack/pack operations.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed in-place handling of unpacked `app.asar.unpacked` assets during packing to avoid locked-file failures.
|
||||
- Fixed local network IP detection for QR-based Remote Panel pairing, so the app no longer picks Cloudflare, VMware, and similar non-LAN adapters by mistake.
|
||||
|
||||
## [1.0.7.0] - 2026-05-01
|
||||
|
||||
### Features
|
||||
|
||||
- New Remote Web Panel: control local app features from a phone or another PC over the local network via QR code connection. #37
|
||||
- Custom Script Loader: inject and execute custom user `.js` scripts directly into the Wand renderer process via the patch modal.
|
||||
- Added the ability to export and copy application logs from the UI.
|
||||
- Stabilized the DevTools on `F12` patch.
|
||||
- Added a repository mirror on GitLab. #47
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed ASAR unpacking failures on locked files or missing entries. #63 #57
|
||||
|
||||
## [1.0.6.0] - 2025-12-14
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed issues related to Wand `12.5.1`. #35
|
||||
- Fixed a bug where the patch could not be reapplied after restoring without restarting the patcher.
|
||||
- Removed the redundant telemetry removal option from patch settings.
|
||||
|
||||
### Features
|
||||
|
||||
- Added localization support.
|
||||
- Added the patch option to open Wand DevTools with `F12`.
|
||||
|
||||
## [1.0.5.0] - 2025-11-30
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed the issue where games detected the debugger. #33 #23 #19 #13
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Removed patch methods.
|
||||
- Removed shortcut launch.
|
||||
- Removed automatic patching for new versions because it is not compatible with the current patch method.
|
||||
|
||||
### Notes
|
||||
|
||||
- This version is incompatible with previous versions of the patcher. Before updating, previous patches must be rolled back.
|
||||
- With the current method, the patcher only needs to be run once to apply the patch.
|
||||
- Thanks to issue #12 for sharing the patching method used here.
|
||||
|
||||
## [1.0.4.0] - 2025-11-05
|
||||
|
||||
### Features
|
||||
|
||||
- Added backward compatibility for older WeMod versions so both legacy WeMod and the newer Wand builds can be patched.
|
||||
- Added manual version management for patches, including separate patches and shortcuts for individual WeMod or Wand versions.
|
||||
|
||||
## [1.0.3.0] - 2025-11-03
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed issues related to the WeMod to Wand rebrand. #24
|
||||
|
||||
## [1.0.2.0] - 2025-04-09
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed a performance issue when a process with an applied patch was scanned again.
|
||||
- Fixed exception propagation into the WeMod process. #11
|
||||
|
||||
## [1.0.1.0] - 2025-04-01
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed WeMod overlay breakage when using the runtime patch.
|
||||
|
||||
## [1.0.0.0] - 2025-03-24
|
||||
|
||||
### Changes
|
||||
|
||||
- Replaced Electron with WPF.
|
||||
- Reduced the `.exe` size by more than 70x.
|
||||
- Updated the UI.
|
||||
- Added two types of patching.
|
||||
- Fixed hotkeys breaking after patching.
|
||||
- Added patch recovery.
|
||||
- Removed external dependencies such as Electron and ASAR tooling from runtime.
|
||||
- Added a patch option to disable WeMod updates.
|
||||
|
||||
### Notes
|
||||
|
||||
- VirusTotal detection increased with the new patching method.
|
||||
|
||||
## [0.0.1] - 2025-01-04
|
||||
|
||||
### Changes
|
||||
|
||||
- Basic ElectronJS wrapper over the original script.
|
||||
+25
-8
@@ -1,6 +1,6 @@
|
||||
# Contributing to WeMod Patcher
|
||||
# Contributing to WandEnhancer
|
||||
|
||||
Thank you for your interest in the WeMod Patcher project! This document provides guidelines for contributing to the project.
|
||||
Thank you for your interest in the WandEnhancer project! This document provides guidelines for contributing to the project.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -8,6 +8,7 @@ Thank you for your interest in the WeMod Patcher project! This document provides
|
||||
- [Bug Reports](#bug-reports)
|
||||
- [Feature Suggestions](#feature-suggestions)
|
||||
- [Creating a Pull Request](#creating-a-pull-request)
|
||||
- [Release Process](#release-process)
|
||||
- [Code Style](#code-style)
|
||||
- [Testing](#testing)
|
||||
- [License](#license)
|
||||
@@ -20,9 +21,9 @@ By participating in this project, you commit to maintaining respectful interacti
|
||||
|
||||
The project consists of the following main components:
|
||||
|
||||
- **WeModPatcher** - Main project containing the patcher logic and user interface
|
||||
- **WandEnhancer** - Main project containing the enhancement logic and user interface
|
||||
- **AsarSharp** - Library for working with ASAR archives (used for unpacking and modifying WeMod files)
|
||||
- **Core** - Core of the patcher, including static and dynamic patching
|
||||
- **Core** - Core of the enhancement flow, including static and dynamic modifications
|
||||
- **Models** - Data models used in the project
|
||||
- **View** - User interface components
|
||||
|
||||
@@ -30,10 +31,10 @@ The project consists of the following main components:
|
||||
|
||||
1. Clone the repository:
|
||||
```
|
||||
git clone https://github.com/k1tbyte/Wemod-Patcher.git
|
||||
git clone https://github.com/k1tbyte/Wand-Enhancer.git
|
||||
```
|
||||
|
||||
2. Open the solution `Wemod-Patcher.sln` in Visual Studio or JetBrains Rider.
|
||||
2. Open the solution `Wand-Enhancer.sln` in Visual Studio or JetBrains Rider.
|
||||
|
||||
3. Restore NuGet packages.
|
||||
|
||||
@@ -43,7 +44,7 @@ The project consists of the following main components:
|
||||
|
||||
If you've found a bug, please create an Issue with a detailed description:
|
||||
|
||||
- WeMod Patcher version
|
||||
- WandEnhancer version
|
||||
- WeMod version where the problem occurred
|
||||
- Detailed steps to reproduce the bug
|
||||
- Expected and actual behavior
|
||||
@@ -82,6 +83,22 @@ Suggestions for new features or improvements are welcome! Create an Issue descri
|
||||
|
||||
7. In the Pull Request description, explain the changes made and why they're necessary.
|
||||
|
||||
## Release Process
|
||||
|
||||
1. Update `WandEnhancer/Properties/AssemblyInfo.cs`.
|
||||
2. Add a new top section with the same version to `CHANGELOG.md`.
|
||||
3. Configure local hooks once:
|
||||
```
|
||||
git config core.hooksPath .githooks
|
||||
```
|
||||
4. Commit and push the version/changelog changes.
|
||||
5. Create and push a tag matching the same version exactly, for example:
|
||||
```
|
||||
git tag 1.0.8.0
|
||||
git push origin 1.0.8.0
|
||||
```
|
||||
6. GitHub Actions will validate the version, build the project, extract the matching changelog section, and publish a notes-only release automatically. Official releases do not attach compiled binaries.
|
||||
|
||||
## Code Style
|
||||
|
||||
- Use C# naming conventions:
|
||||
@@ -108,4 +125,4 @@ By contributing, you agree that your contributions will be licensed under the [A
|
||||
|
||||
---
|
||||
|
||||
Thank you for contributing to the WeMod Patcher project!
|
||||
Thank you for contributing to the WandEnhancer project!
|
||||
|
||||
@@ -2,58 +2,145 @@
|
||||
|
||||

|
||||
|
||||
---
|
||||
<h1>WeMod Patcher</h1>
|
||||
# WandEnhancer
|
||||
|
||||
[](https://gitlab.com/kitbyte/wand-enhancer)
|
||||
|
||||
</div>
|
||||
|
||||
<h4>WeMod patcher allows you to get some WeMod Pro features absolutely free. This script patches WeMod, thereby removing the daily usage limit (2h), etc.</h4>
|
||||
<h4>An open-source interoperability tool designed to extend local client-side configurations and improve the UX of the Wand application.</h4>
|
||||
|
||||
## 👾 No malware? Is it safe for me?
|
||||
**🚨 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.**
|
||||
|
||||
Yes, this is safe. This script is open-source, and you can check the code yourself. I have no intention of harming you or your computer. The script does absolutely nothing with your computer and does not require Internet access. It only affects WeMod files.
|
||||
## 👾 What does it access?
|
||||
|
||||
## 💻 Does this script only work with older versions of WeMod like other unlockers?
|
||||
The .NET patcher modifies files in the selected local Wand installation and does not contact an update or telemetry service. The bundled `version.dll` proxy is loaded by Wand and changes Electron's ASAR-integrity fuse byte inside Wand's own process; it does not inject into another process. Wand itself remains an online application, build tools restore declared dependencies, and the optional Remote Web Panel deliberately starts a LAN HTTP/WebSocket server and uses Wand API/CDN data. Review the source and build the executable from your own fork; unsigned patching tools can trigger generic antivirus heuristics.
|
||||
|
||||
With this patch you will be able to use the latest version together with Pro.
|
||||
## 💫 What features are improved?
|
||||
|
||||
## 💫 What features will be available?
|
||||
✅ Local environment configuration management <br/>
|
||||
✅ Automated compatibility adjustments for new client versions <br/>
|
||||
✅ Advanced layout and theme customization (Client-side only) <br/>
|
||||
✅ AI Features <br/>
|
||||
✅ Remote web panel (Remote Connect on mobile) <br/>
|
||||
|
||||
✅ Unlimited usage time <br/>
|
||||
✅ Disabling automatic updates (optional) <br/>
|
||||
✅ Automatic patching of new WeMod versions <br/>
|
||||
✅ AI Game guides <br/>
|
||||
✅ Saving mods <br/>
|
||||
✅ Exclusive to pro subscription customization for hacks <br/>
|
||||
✅ Hotkeys (hotkey functionality is broken after static patching for unknown reason) <br/>
|
||||
❌ Connect phone <br/>
|
||||
## 🌐 Remote Web Panel
|
||||
WandEnhancer includes a built-in **Remote Web Panel** allowing you to control app features directly from your phone.
|
||||
|
||||
### Quick Start:
|
||||
1. Ensure both your PC and phone are on the **same Wi-Fi network**.
|
||||
2. Hover over the **Connect** button in the top bar of WandEnhancer.
|
||||
3. Scan the displayed **QR code** with your phone's camera.
|
||||
|
||||
### 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?
|
||||
|
||||
1. Go to [Releases](https://github.com/k1tbyte/Wemod-Patcher/releases) page.
|
||||
2. Download latest version
|
||||
3. Run and click the patch
|
||||
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. 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/7966cabe-0aa6-424d-8c2f-981ad91e0f91
|
||||
|
||||
|
||||
|
||||
## 🧩 Custom scripts
|
||||
|
||||
You can inject your own JavaScript into Wand at patch time to tweak or fix things in the client UI. This reuses the same renderer injection the Remote Web Panel uses, so it requires the **Remote Web Panel** patch to be enabled.
|
||||
|
||||
**How to add a script**
|
||||
|
||||
- In the patch dialog, add one or more `.js` files (only existing `.js` files are accepted), **or**
|
||||
- Drop `.js` files into a `renderer-scripts/` folder placed next to the patcher executable.
|
||||
|
||||
Then patch as usual — your scripts are bundled into the client and run inside Wand's window.
|
||||
|
||||
**How it runs**
|
||||
|
||||
- Each script runs inside Wand's renderer (full DOM access, plus Node `require`).
|
||||
- It is wrapped so a thrown error is logged and never crashes Wand.
|
||||
- It may run **more than once** per launch (on load and again shortly after), so guard one‑time work behind a global flag.
|
||||
- A small `WandEnhancer` helper is available: `WandEnhancer.log(...)`, `WandEnhancer.remoteUrl`, `WandEnhancer.apiVersion`.
|
||||
|
||||
**Minimal example** (`hello.js`)
|
||||
|
||||
```js
|
||||
// Injected scripts can run multiple times — guard one-time setup.
|
||||
if (!globalThis.__helloScriptInstalled) {
|
||||
globalThis.__helloScriptInstalled = true;
|
||||
|
||||
WandEnhancer.log("Hello from my custom script!", WandEnhancer.remoteUrl);
|
||||
|
||||
new MutationObserver(() => {
|
||||
const dialog = document.querySelector("ux-dialog:not([data-seen])");
|
||||
if (dialog) {
|
||||
dialog.setAttribute("data-seen", "1");
|
||||
WandEnhancer.log("A dialog opened.");
|
||||
}
|
||||
}).observe(document.documentElement, { childList: true, subtree: true });
|
||||
}
|
||||
```
|
||||
|
||||
> Scripts run with the same privileges as the Wand client. Only add scripts you trust and understand.
|
||||
|
||||
## 🛠️ How to build from source
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## ❓ Q&A
|
||||
|
||||
- I applied the patch but when I inject I get stuck on 'Loading mods...'.
|
||||
- Just close WeMod and try again
|
||||
- During the game, some hacks are enabled without my input
|
||||
- This is a bug after the static patch, you have to turn off hotkeys in WeMod settings
|
||||
- VirusTotal claims that this program is a malware/trojan.
|
||||
- Perhaps the patcher does have the same signatures as malware (virtual memory patching). But this is a false positive, you can look at the source code or even build the patcher yourself.
|
||||
- Does this application transfer any data to the Internet from my computer?
|
||||
- The short answer is NO. This application does not need access to the Internet. The most it does is download updates if you want it to.
|
||||
- What makes this application better than other patchers?
|
||||
- All actions related to patches are performed on your computer. No files of unknown origin will be downloaded.
|
||||
- **Why is there no `.exe` in GitHub Releases?**
|
||||
- Official releases are notes-only on purpose. The project no longer distributes prebuilt executables because unsigned or self-built patching tools are repeatedly reuploaded, mislabeled, and flagged by third-party scanners. Build the executable from your own fork using GitHub Actions instead.
|
||||
- **Where do I download the executable?**
|
||||
- From your own fork's **Actions** artifact after running the **Build executable** workflow. Do not download `.exe` files from YouTube descriptions, random mirrors, Discord attachments, or issue comments.
|
||||
- **Why does Windows Defender or SmartScreen warn about my build?**
|
||||
- The GitHub Actions artifact is unsigned and uncommon, so Windows may warn even when the code was built directly from your fork. Review the source, verify the workflow logs, and only run binaries you built yourself.
|
||||
- **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 .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
|
||||

|
||||
<div align='center'>
|
||||
|
||||

|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 📜 License
|
||||
@@ -61,8 +148,20 @@ This project is licensed under the Apache-2.0 - see the [LICENSE](LICENSE.md) fi
|
||||
|
||||
---
|
||||
## ❤️ Support
|
||||
[](https://ko-fi.com/kitbyte)
|
||||
|
||||
If you find this project useful, you can support its development using any of the options below 🙌
|
||||
|
||||
[](https://www.patreon.com/kitbyte/gift)
|
||||
[](https://tronscan.org/#/address/TQdvau8pAy5Tg1Aa588tTcPCFgbcHtuoxc)
|
||||
[](https://www.blockchain.com/explorer/addresses/btc/1EZKDcyU8REm9JW5xwXJqSpn5Xaq5yAWWX)
|
||||
[](https://etherscan.io/address/0xd904d9d0557f88bbb1c4ab3582b4ca0d8a730e8d)
|
||||
|
||||
|
||||
---
|
||||
|
||||
[](https://www.star-history.com/#k1tbyte/Wemod-Patcher&Date)
|
||||
> **Legal Disclaimer:**
|
||||
> 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.
|
||||
|
||||
---
|
||||
|
||||
[](https://www.star-history.com/#k1tbyte/Wand-Enhancer&Date)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WeModPatcher", "WeModPatcher\WeModPatcher.csproj", "{106D3E44-ECBB-4EF3-84B2-5FC6BCF77727}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WandEnhancer", "WandEnhancer\WandEnhancer.csproj", "{106D3E44-ECBB-4EF3-84B2-5FC6BCF77727}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AsarSharp", "AsarSharp\AsarSharp.csproj", "{BEAA604A-402A-4387-8903-A53FC913A26E}"
|
||||
EndProject
|
||||
@@ -1,8 +1,8 @@
|
||||
<Application x:Class="WeModPatcher.App"
|
||||
<Application x:Class="WandEnhancer.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:WeModPatcher"
|
||||
xmlns:converters="clr-namespace:WeModPatcher.Converters">
|
||||
xmlns:local="clr-namespace:WandEnhancer"
|
||||
xmlns:converters="clr-namespace:WandEnhancer.Converters">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
@@ -1,12 +1,12 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using WeModPatcher.Core;
|
||||
using WeModPatcher.Core.Services;
|
||||
using WeModPatcher.View.MainWindow;
|
||||
using WandEnhancer.Core;
|
||||
using WandEnhancer.Core.Services;
|
||||
using WandEnhancer.View.MainWindow;
|
||||
using MessageBox = System.Windows.Forms.MessageBox;
|
||||
|
||||
namespace WeModPatcher
|
||||
namespace WandEnhancer
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
@@ -1,12 +1,12 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using WeModPatcher.Models;
|
||||
using WandEnhancer.Models;
|
||||
|
||||
namespace WeModPatcher
|
||||
namespace WandEnhancer
|
||||
{
|
||||
public static class Constants
|
||||
{
|
||||
public const string RepoName = "Wemod-Patcher";
|
||||
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}";
|
||||
+1
-1
@@ -3,7 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace WeModPatcher.Converters
|
||||
namespace WandEnhancer.Converters
|
||||
{
|
||||
public abstract class BaseBooleanConverter<T> : IValueConverter
|
||||
{
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace WeModPatcher.Converters
|
||||
namespace WandEnhancer.Converters
|
||||
{
|
||||
internal sealed class ToVisibilityConverter : BaseBooleanConverter<Visibility>
|
||||
{
|
||||
@@ -0,0 +1,506 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using AsarSharp;
|
||||
using WandEnhancer.Models;
|
||||
using WandEnhancer.Utils;
|
||||
using WandEnhancer.View.MainWindow;
|
||||
|
||||
namespace WandEnhancer.Core
|
||||
{
|
||||
public class Enhancer
|
||||
{
|
||||
private const string ResourcesDirectoryName = "resources";
|
||||
private const string AppAsarFileName = "app.asar";
|
||||
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 WebPanelDirectoryName = "web-panel";
|
||||
private const string WebPanelDistDirectoryName = "dist";
|
||||
private const string LocalCustomScriptsDirectoryName = "renderer-scripts";
|
||||
private const string RemotePanelDirectoryName = "remote-panel";
|
||||
private const string RemoteBridgeTargetFileName = "bridge.cjs";
|
||||
private const string RemoteRendererScriptsDirectoryName = "renderer-scripts";
|
||||
private const string EmbeddedRemotePanelDistPrefix = "remote-panel/dist/";
|
||||
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;
|
||||
|
||||
private readonly WeModConfig _weModConfig;
|
||||
private readonly Action<string, ELogType> _logger;
|
||||
private readonly PatchConfig _config;
|
||||
private readonly string _asarPath;
|
||||
private readonly string _backupPath;
|
||||
private readonly string _unpackedPath;
|
||||
private readonly string _unpackedBackupPath;
|
||||
|
||||
public Enhancer(WeModConfig weModConfig, Action<string, ELogType> logger, PatchConfig config)
|
||||
{
|
||||
_weModConfig = weModConfig;
|
||||
_logger = logger;
|
||||
_config = config;
|
||||
|
||||
_asarPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarFileName);
|
||||
_unpackedPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarUnpackedDirectoryName);
|
||||
_backupPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarBackupFileName);
|
||||
_unpackedBackupPath = Path.Combine(weModConfig.RootDirectory, ResourcesDirectoryName, AppAsarUnpackedBackupDirectoryName);
|
||||
}
|
||||
|
||||
private string ApplyJsPatch(string fileName, string js, EnhancerConfig.PatchEntry patch, EPatchType patchType, out bool patchApplied)
|
||||
{
|
||||
patchApplied = false;
|
||||
|
||||
if (patch.Applied)
|
||||
{
|
||||
return js;
|
||||
}
|
||||
|
||||
if (!CanSearchPatchInFile(fileName, patch) || !ContainsSearchHint(js, patch.SearchHints))
|
||||
{
|
||||
return js;
|
||||
}
|
||||
|
||||
var match = patch.Target.Match(js);
|
||||
if (!match.Success)
|
||||
{
|
||||
return js;
|
||||
}
|
||||
|
||||
var prefix = $"[ENHANCER] [{patchType} -> {patch.Name}]";
|
||||
|
||||
if(patch.SingleMatch && match.NextMatch().Success)
|
||||
{
|
||||
throw new Exception(
|
||||
$"{prefix} Patch failed. Multiple target functions found. Looks like the version is not supported");
|
||||
}
|
||||
|
||||
string patchSource = patch.PatchFactory != null
|
||||
? patch.PatchFactory(match)
|
||||
: patch.Patch;
|
||||
|
||||
if (patch.Resolver != null)
|
||||
{
|
||||
string resolvedField = patch.Resolver.Handler(match.Value);
|
||||
if (string.IsNullOrEmpty(resolvedField))
|
||||
{
|
||||
throw new Exception($"{prefix} Resolver failed to find field name");
|
||||
}
|
||||
|
||||
patchSource = patchSource.Replace(patch.Resolver.Placeholder, resolvedField);
|
||||
}
|
||||
|
||||
_logger($"{prefix} Found target function in: " + Path.GetFileName(fileName), ELogType.Info);
|
||||
|
||||
string newJs;
|
||||
if (patch.PatchFactory != null)
|
||||
{
|
||||
newJs = patch.SingleMatch
|
||||
? patch.Target.Replace(js, _ => patchSource, 1)
|
||||
: patch.Target.Replace(js, _ => patchSource);
|
||||
}
|
||||
else
|
||||
{
|
||||
newJs = patch.SingleMatch
|
||||
? patch.Target.Replace(js, patchSource, 1)
|
||||
: patch.Target.Replace(js, patchSource);
|
||||
}
|
||||
|
||||
_logger($"{prefix} Patch applied", ELogType.Success);
|
||||
patch.Applied = true;
|
||||
patchApplied = true;
|
||||
|
||||
return newJs;
|
||||
}
|
||||
|
||||
private void PatchAsar()
|
||||
{
|
||||
var items = Directory.EnumerateFiles(_unpackedPath, $"*{JavaScriptFileExtension}", SearchOption.TopDirectoryOnly)
|
||||
.Where(IsCandidateBundleFile)
|
||||
.ToList();
|
||||
|
||||
if (!items.Any())
|
||||
{
|
||||
throw new Exception("[ENHANCER] No app bundle found");
|
||||
}
|
||||
|
||||
var remainingPatches = new HashSet<EPatchType>(_config.PatchTypes);
|
||||
var enhancerConfig = EnhancerConfig.GetInstance();
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (remainingPatches.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (!CouldFileContainRemainingPatch(item, remainingPatches, enhancerConfig))
|
||||
{
|
||||
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);
|
||||
fileChanged = fileChanged || patchApplied;
|
||||
}
|
||||
|
||||
if (entries.All(x => x.Applied))
|
||||
{
|
||||
remainingPatches.Remove(entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (fileChanged)
|
||||
{
|
||||
File.WriteAllText(item, data);
|
||||
}
|
||||
}
|
||||
|
||||
if(remainingPatches.Count > 0)
|
||||
{
|
||||
var failedPatches = string.Join(", ", remainingPatches.Select(p => p.ToString()));
|
||||
throw new Exception($"[ENHANCER] Failed to apply patches: {failedPatches}. The version may not be supported.");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsCandidateBundleFile(string filePath)
|
||||
{
|
||||
string fileName = Path.GetFileName(filePath);
|
||||
return fileName.Equals(IndexBundleFileName, StringComparison.OrdinalIgnoreCase)
|
||||
|| (fileName.StartsWith(AppBundleFilePrefix, StringComparison.OrdinalIgnoreCase)
|
||||
&& fileName.EndsWith(AppBundleFileSuffix, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static string FindWorkspacePath(params string[] segments)
|
||||
{
|
||||
string current = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
while (!string.IsNullOrEmpty(current))
|
||||
{
|
||||
string candidate = Path.Combine(new[] { current }.Concat(segments).ToArray());
|
||||
if (Directory.Exists(candidate) || File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
current = Directory.GetParent(current)?.FullName;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Required workspace artifact not found: {Path.Combine(segments)}");
|
||||
}
|
||||
|
||||
internal static void CopyDirectory(string sourceDir, string destinationDir)
|
||||
{
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
|
||||
foreach (var directory in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relativePath = directory.Substring(sourceDir.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
Directory.CreateDirectory(Path.Combine(destinationDir, relativePath));
|
||||
}
|
||||
|
||||
foreach (var file in Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relativePath = file.Substring(sourceDir.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
var destinationPath = Path.Combine(destinationDir, relativePath);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath) ?? destinationDir);
|
||||
File.Copy(file, destinationPath, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static int CopyJavaScriptFiles(string sourceDir, string destinationDir)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sourceDir) || !Directory.Exists(sourceDir))
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
private static string GetAvailableScriptPath(string destinationDir, string fileName)
|
||||
{
|
||||
string destinationPath = Path.Combine(destinationDir, fileName);
|
||||
if (!File.Exists(destinationPath))
|
||||
{
|
||||
return destinationPath;
|
||||
}
|
||||
|
||||
string name = Path.GetFileNameWithoutExtension(fileName);
|
||||
string extension = Path.GetExtension(fileName);
|
||||
for (int index = FirstDuplicateScriptIndex; ; index++)
|
||||
{
|
||||
destinationPath = Path.Combine(destinationDir, $"{name}{DuplicateScriptSuffix}{index}{extension}");
|
||||
if (!File.Exists(destinationPath))
|
||||
{
|
||||
return destinationPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int CopyEmbeddedDirectory(string resourcePrefix, string destinationDir)
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
var resourceNames = assembly.GetManifestResourceNames()
|
||||
.Where(name => name.StartsWith(resourcePrefix, StringComparison.Ordinal))
|
||||
.ToList();
|
||||
|
||||
if (resourceNames.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
|
||||
foreach (var resourceName in resourceNames)
|
||||
{
|
||||
var relativePath = resourceName.Substring(resourcePrefix.Length)
|
||||
.Replace('/', Path.DirectorySeparatorChar)
|
||||
.Replace('\\', Path.DirectorySeparatorChar);
|
||||
var destinationPath = Path.Combine(destinationDir, relativePath);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath) ?? destinationDir);
|
||||
|
||||
using (var resource = assembly.GetManifestResourceStream(resourceName))
|
||||
{
|
||||
if (resource == null)
|
||||
{
|
||||
throw new FileNotFoundException($"Embedded resource not found: {resourceName}");
|
||||
}
|
||||
|
||||
using (var output = File.Create(destinationPath))
|
||||
{
|
||||
resource.CopyTo(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resourceNames.Count;
|
||||
}
|
||||
|
||||
private static string FindLocalCustomScriptsPath()
|
||||
{
|
||||
string executableDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
if (string.IsNullOrEmpty(executableDirectory))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string localScripts = Path.Combine(executableDirectory, LocalCustomScriptsDirectoryName);
|
||||
return Directory.Exists(localScripts) ? localScripts : null;
|
||||
}
|
||||
|
||||
private static int CopySelectedJavaScriptFiles(IEnumerable<string> files, string destinationDir)
|
||||
{
|
||||
if (files == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
|
||||
int copied = 0;
|
||||
foreach (var file in files.Where(IsJavaScriptFile).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
File.Copy(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))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string localCustomScriptsRoot = FindLocalCustomScriptsPath();
|
||||
string targetRoot = Path.Combine(_unpackedPath, RemotePanelDirectoryName);
|
||||
string targetScriptsRoot = Path.Combine(targetRoot, RemoteRendererScriptsDirectoryName);
|
||||
string targetBridgePath = Path.Combine(targetRoot, RemoteBridgeTargetFileName);
|
||||
|
||||
if (Directory.Exists(targetRoot))
|
||||
{
|
||||
Directory.Delete(targetRoot, true);
|
||||
}
|
||||
|
||||
if (CopyEmbeddedDirectory(EmbeddedRemotePanelDistPrefix, targetRoot) == 0)
|
||||
{
|
||||
CopyDirectory(FindWorkspacePath(WebPanelDirectoryName, WebPanelDistDirectoryName), targetRoot);
|
||||
}
|
||||
|
||||
if (!File.Exists(targetBridgePath))
|
||||
{
|
||||
throw new FileNotFoundException("[ENHANCER] Remote bridge artifact is missing. Run `cd web-panel && pnpm run build` before patching.", targetBridgePath);
|
||||
}
|
||||
|
||||
int defaultScriptCount = Directory.Exists(targetScriptsRoot)
|
||||
? Directory.GetFiles(targetScriptsRoot, JavaScriptFileSearchPattern, SearchOption.TopDirectoryOnly).Length
|
||||
: 0;
|
||||
if (defaultScriptCount == 0)
|
||||
{
|
||||
throw new FileNotFoundException("[ENHANCER] Remote renderer script artifacts are missing. Run `cd web-panel && pnpm run build` before patching.", targetScriptsRoot);
|
||||
}
|
||||
|
||||
int selectedScriptCount = CopySelectedJavaScriptFiles(_config.CustomScriptPaths, targetScriptsRoot);
|
||||
int localScriptCount = CopyJavaScriptFiles(localCustomScriptsRoot, targetScriptsRoot);
|
||||
|
||||
_logger($"[ENHANCER] Injected remote panel assets and renderer scripts into app.asar (default: {defaultScriptCount}, selected: {selectedScriptCount}, local: {localScriptCount})", ELogType.Info);
|
||||
}
|
||||
|
||||
private void AttachProxyDll()
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
var dll = assembly.GetManifestResourceStream(Constants.ProxyDllResouceName);
|
||||
if (dll == null)
|
||||
{
|
||||
throw new Exception("[ENHANCER] Proxy DLL resource not found");
|
||||
}
|
||||
var destPath = Path.Combine(_weModConfig.RootDirectory, "version.dll");
|
||||
using (var fileStream = File.Create(destPath))
|
||||
{
|
||||
dll.CopyTo(fileStream);
|
||||
}
|
||||
_logger("[ENHANCER] Proxy DLL attached", ELogType.Info);
|
||||
}
|
||||
|
||||
public void Patch()
|
||||
{
|
||||
Common.TryKillProcess(_weModConfig.BrandName);
|
||||
if (!File.Exists(_backupPath))
|
||||
{
|
||||
_logger("[ENHANCER] Creating backup...", ELogType.Info);
|
||||
File.Copy(_asarPath, _backupPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger("[ENHANCER] Backup found, restoring pristine app.asar before patching...", ELogType.Info);
|
||||
File.Copy(_backupPath, _asarPath, true);
|
||||
}
|
||||
|
||||
if (!Directory.Exists(_unpackedBackupPath) && Directory.Exists(_unpackedPath))
|
||||
{
|
||||
_logger("[ENHANCER] Creating backup of app.asar.unpacked...", ELogType.Info);
|
||||
CopyDirectory(_unpackedPath, _unpackedBackupPath);
|
||||
}
|
||||
else if (Directory.Exists(_unpackedBackupPath))
|
||||
{
|
||||
_logger("[ENHANCER] Restoring pristine app.asar.unpacked before patching...", ELogType.Info);
|
||||
if (Directory.Exists(_unpackedPath))
|
||||
{
|
||||
Directory.Delete(_unpackedPath, true);
|
||||
}
|
||||
|
||||
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))
|
||||
{
|
||||
throw new Exception("app.asar not found");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_logger("[ENHANCER] Extracting app.asar...", ELogType.Info);
|
||||
AsarExtractor.ExtractAll(_asarPath, _unpackedPath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception($"[ENHANCER] Failed to unpack app.asar: {e.Message}");
|
||||
}
|
||||
|
||||
PatchAsar();
|
||||
InjectRemotePanelFiles();
|
||||
|
||||
try
|
||||
{
|
||||
new AsarCreator(_unpackedPath, _asarPath, new CreateOptions
|
||||
{
|
||||
Unpack = new Regex(@"^static\\unpacked.*$")
|
||||
}).CreatePackageWithOptions();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception($"[ENHANCER] Failed to pack app.asar: {e.Message}");
|
||||
}
|
||||
|
||||
AttachProxyDll();
|
||||
|
||||
_logger("[ENHANCER] Done!", ELogType.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using WandEnhancer.Models;
|
||||
|
||||
namespace WandEnhancer.Core
|
||||
{
|
||||
public static class EnhancerConfig
|
||||
{
|
||||
public class ResolveContext
|
||||
{
|
||||
public string Placeholder { get; set; }
|
||||
public Func<string, string> Handler { get; set; }
|
||||
}
|
||||
|
||||
public 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 string[] CandidateFileNames { get; set; }
|
||||
public string[] SearchHints { get; set; }
|
||||
public ResolveContext Resolver { get; set; }
|
||||
}
|
||||
|
||||
private static string RequireGroup(Match match, string groupName, string patchName)
|
||||
{
|
||||
var group = match.Groups[groupName];
|
||||
if (!group.Success || string.IsNullOrEmpty(group.Value))
|
||||
{
|
||||
throw new Exception($"{patchName} failed to resolve {groupName}");
|
||||
}
|
||||
|
||||
return group.Value;
|
||||
}
|
||||
|
||||
private static string RequirePattern(string source, string pattern, string groupName, string patchName)
|
||||
{
|
||||
var match = Regex.Match(source, pattern, RegexOptions.Singleline);
|
||||
return RequireGroup(match, groupName, patchName);
|
||||
}
|
||||
|
||||
private static string BuildSetAccountLanguagePatch(Match match)
|
||||
{
|
||||
var parameters = RequireGroup(match, "params", "setAccountLanguage");
|
||||
var expr = RequireGroup(match, "expr", "setAccountLanguage");
|
||||
return $"setAccountLanguage({parameters}){{return ({expr}).then(response=>{{response&&\"object\"==typeof response&&(response.subscription={{period:\"yearly\",state:\"active\"}});return response;}})}}";
|
||||
}
|
||||
|
||||
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}()}})}}";
|
||||
}
|
||||
|
||||
public static Dictionary<EPatchType, PatchEntry[]> GetInstance()
|
||||
{
|
||||
return new Dictionary<EPatchType, PatchEntry[]>()
|
||||
{
|
||||
{
|
||||
EPatchType.ActivatePro,
|
||||
new[]
|
||||
{
|
||||
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;})}"
|
||||
},
|
||||
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;})}"
|
||||
},
|
||||
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.
|
||||
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
|
||||
},
|
||||
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.
|
||||
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
|
||||
},
|
||||
new PatchEntry
|
||||
{
|
||||
// Wand's native "connect phone" pairing (POST /v3/auth/remote_code)
|
||||
// triggers a server-side device handoff that deauthorizes this desktop
|
||||
// session - the reported "entered the mobile activation key and got
|
||||
// signed out" bug. Neutralize the code issuer so native pairing can
|
||||
// never start. The injected remote panel is independent of this flow
|
||||
// (IPC bridge, not Wand's Pusher pairing) and keeps working. The
|
||||
// rejection is swallowed by the caller's try/catch (renders no code).
|
||||
Name = "disableNativeRemotePairing",
|
||||
SearchHints = new[] { "requestRemoteAuthCode", "/v3/auth/remote_code" },
|
||||
Target = new Regex(@"requestRemoteAuthCode\(\)\{return this\.#[\w$]+\.post\(""/v3/auth/remote_code""\)\}"),
|
||||
Patch = "requestRemoteAuthCode(){return Promise.reject(new Error(\"wand-enhancer: native mobile pairing disabled\"))}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
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
|
||||
{
|
||||
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)))"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
EPatchType.DevToolsOnF12,
|
||||
new[]
|
||||
{
|
||||
new PatchEntry
|
||||
{
|
||||
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("
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
EPatchType.RemoteWebPanelPreview,
|
||||
new[]
|
||||
{
|
||||
new PatchEntry
|
||||
{
|
||||
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()})"
|
||||
},
|
||||
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
|
||||
},
|
||||
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
|
||||
},
|
||||
new PatchEntry
|
||||
{
|
||||
// Inject the bridge init + setHandler right after the method's opening
|
||||
// brace; the rest of setCurrentTrainer is left untouched. Only `${trainer}`
|
||||
// (active-trainer field) and `${remoteSource}` (value-source enum, taken
|
||||
// via lookahead from the sole `e.source!==` site) vary between builds and
|
||||
// are resolved from the match — nothing is hardcoded.
|
||||
Name = "remoteBridgeBindHandler",
|
||||
SearchHints = new[] { "client-state" },
|
||||
Target = new Regex(@"(?<head>setCurrentTrainer\(e,t=null\)\{)(?=const s=e\?\.trainerId\|\|null,i=\(s\?e\?\.gameId:null\)\|\|null,n=\(s\?e\?\.supportedVersions:null\)\|\|\[\];if\(s===this\.#[\w$]+&&t===this\.(?<trainer>#[\w$]+)\)return;)(?=.*?e\.source!==(?<remoteSource>[\w$]+\.[\w$]+\.Remote))",
|
||||
RegexOptions.Singleline),
|
||||
Patch = "${head}this.__wandRemoteBridge||(this.__wandRemoteBridge=(()=>{try{const r=globalThis.require||require;const{ipcRenderer:c}=r(\"electron\");try{c.invoke(\"wand-remote-url\").then((u=>{u&&(globalThis.__wandRemoteBridgeUrl=u)}))}catch(e){}const send=(ch,p)=>{try{return c.invoke(ch,p&&JSON.parse(JSON.stringify(p)))}catch(e){}};return{sync:(s)=>send(\"wand-remote-sync\",s),valueChanged:(s)=>send(\"wand-remote-value-changed\",s),setHandler:(h)=>{if(this.__wandRemoteBridgeBound)return;this.__wandRemoteBridgeBound=true;try{c.invoke(\"wand-remote-set-handler-bind\")}catch(e){}c.on(\"wand-remote-set-value\",(_e,req)=>{try{h(req)}catch(e){}})}}}catch(e){try{const r=globalThis.require||require,fs=r(\"node:fs\"),os=r(\"node:os\"),p=r(\"node:path\");fs.appendFileSync(p.join(os.tmpdir(),\"wand-remote-bridge.log\"),\"[\"+new Date().toISOString()+\"] [renderer-bind-error] \"+(e&&e.stack||e)+\"\\n\");}catch(_){}return null}})());this.__wandRemoteBridge?.setHandler((e=>{if(!this.${trainer}||!e?.target)return!1;return this.${trainer}.isActive()?this.${trainer}.setValue(e.target,e.value,${remoteSource},e.cheatId):!1}));this.__wandRemoteTrainerInfo=e??null;"
|
||||
},
|
||||
new PatchEntry
|
||||
{
|
||||
// Pure insertion: splice one `valueChanged` bridge call in after the
|
||||
// existing `client-value-changed` send, before the onValueSet callback
|
||||
// closes. Resolves no private names — `${head}`/`${tail}` carry the
|
||||
// original text verbatim. trainerId is omitted from the payload;
|
||||
// bridge-state falls back to the active snapshot trainer.
|
||||
Name = "remoteBridgeValueDelta",
|
||||
SearchHints = new[] { "client-value-changed" },
|
||||
Target = new Regex(@"(?<head>#[\w$]+\(e,t\)\{t\.push\(e\.onValueSet\(e=>\{this\.status===[\w$]+\.Connected&&e\.source!==[\w$]+\.[\w$]+\.Remote&&this\.#[\w$]+\?\.send\(""client-value-changed"",\{instanceId:this\.#[\w$]+,name:e\.name,value:e\.value,cheatId:e\.cheatId\}\))(?<tail>\}\)\),this\.#[\w$]+\(\)\})"),
|
||||
Patch = "${head},this.__wandRemoteBridge?.valueChanged({target:e.name,value:e.value,oldValue:e.oldValue,source:String(e.source??\"desktop\"),cheatId:e.cheatId})${tail}"
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
|
||||
namespace WeModPatcher.Core.Services
|
||||
namespace WandEnhancer.Core.Services
|
||||
{
|
||||
public static class LocalizationManager
|
||||
{
|
||||
+1
-1
@@ -2,7 +2,7 @@ using System;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace WeModPatcher.Core.Services
|
||||
namespace WandEnhancer.Core.Services
|
||||
{
|
||||
public class AppSettings
|
||||
{
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Eine neue Version ist verfügbar</s:String>
|
||||
<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">Patch</s:String>
|
||||
<s:String x:Key="mw_patch">Anwenden</s:String>
|
||||
<s:String x:Key="mw_restore">Wiederherstellen</s:String>
|
||||
<s:String x:Key="mw_source_code">Quellcode</s:String>
|
||||
<s:String x:Key="mw_made_by">Mit ❤️ von k1tbyte erstellt</s:String>
|
||||
<s:String x:Key="mw_star_hint">Gib einen Stern, wenn dir das geholfen hat ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Logs in die Zwischenablage kopieren</s:String>
|
||||
<s:String x:Key="mw_export_logs">Logs in Datei exportieren</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Speichern</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">WeMod Pro aktivieren</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools mit F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Updates deaktivieren</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Remote-Zugriff aktivieren (Beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Benutzerdefinierte Skripte</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">.js hinzufügen</s:String>
|
||||
<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_popup_title">Was werden wir patchen?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Vor dem Update wird dringend empfohlen, Patches rückgängig zu machen, falls sie angewendet wurden</s:String>
|
||||
<s:String x:Key="up_update_now">Jetzt aktualisieren</s:String>
|
||||
<s:String x:Key="up_popup_title">Update verfügbar!</s:String>
|
||||
<s:String x:Key="pv_popup_title">Was werden wir verbessern?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">A new version is available</s:String>
|
||||
<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">Patch</s:String>
|
||||
<s:String x:Key="mw_patch">Enhance</s:String>
|
||||
<s:String x:Key="mw_restore">Restore</s:String>
|
||||
<s:String x:Key="mw_source_code">Source code</s:String>
|
||||
<s:String x:Key="mw_made_by">Made with ❤️ by k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Put a star if you found this helpful ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Copy logs to clipboard</s:String>
|
||||
<s:String x:Key="mw_export_logs">Export logs to file</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Save</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Activate WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools on F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Disable updates</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Enable remote access (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Custom scripts</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Add .js</s:String>
|
||||
<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_popup_title">What are we gonna patch?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Before updating, it is strongly recommended to roll back patches if they have been applied</s:String>
|
||||
<s:String x:Key="up_update_now">Update now</s:String>
|
||||
<s:String x:Key="up_popup_title">Update available!</s:String>
|
||||
<s:String x:Key="pv_popup_title">What are we gonna enhance?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Una nueva versión está disponible</s:String>
|
||||
<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">Parchear</s:String>
|
||||
<s:String x:Key="mw_patch">Aplicar</s:String>
|
||||
<s:String x:Key="mw_restore">Restaurar</s:String>
|
||||
<s:String x:Key="mw_source_code">Código fuente</s:String>
|
||||
<s:String x:Key="mw_made_by">Hecho con ❤️ por k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Pon una estrella si te fue útil ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Copiar registros al portapapeles</s:String>
|
||||
<s:String x:Key="mw_export_logs">Exportar registros a un archivo</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Guardar</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Activar WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools en F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Desactivar actualizaciones</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Habilitar acceso remoto (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Scripts personalizados</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Agregar .js</s:String>
|
||||
<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_popup_title">¿Qué vamos a parchear?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Antes de actualizar, se recomienda encarecidamente revertir los parches si se han aplicado</s:String>
|
||||
<s:String x:Key="up_update_now">Actualizar ahora</s:String>
|
||||
<s:String x:Key="up_popup_title">¡Actualización disponible!</s:String>
|
||||
<s:String x:Key="pv_popup_title">¿Qué vamos a mejorar?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Une nouvelle version est disponible</s:String>
|
||||
<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">Patcher</s:String>
|
||||
<s:String x:Key="mw_patch">Appliquer</s:String>
|
||||
<s:String x:Key="mw_restore">Restaurer</s:String>
|
||||
<s:String x:Key="mw_source_code">Code source</s:String>
|
||||
<s:String x:Key="mw_made_by">Fait avec ❤️ par k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Mettez une étoile si cela vous a aidé ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Copier les logs dans le presse-papiers</s:String>
|
||||
<s:String x:Key="mw_export_logs">Exporter les logs dans un fichier</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Enregistrer</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Activer WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools sur F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Désactiver les mises à jour</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Activer l'accès à distance (bêta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Scripts personnalisés</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Ajouter .js</s:String>
|
||||
<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_popup_title">Qu'allons-nous patcher ?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Avant la mise à jour, il est fortement recommandé d'annuler les patchs s'ils ont été appliqués</s:String>
|
||||
<s:String x:Key="up_update_now">Mettre à jour maintenant</s:String>
|
||||
<s:String x:Key="up_popup_title">Mise à jour disponible !</s:String>
|
||||
<s:String x:Key="pv_popup_title">Qu'allons-nous modifier ?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">È disponibile una nuova versione</s:String>
|
||||
<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">Patch</s:String>
|
||||
<s:String x:Key="mw_patch">Applica</s:String>
|
||||
<s:String x:Key="mw_restore">Ripristina</s:String>
|
||||
<s:String x:Key="mw_source_code">Codice sorgente</s:String>
|
||||
<s:String x:Key="mw_made_by">Creato con ❤️ da k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Metti una stella se ti è stato utile ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Copia i log negli appunti</s:String>
|
||||
<s:String x:Key="mw_export_logs">Esporta i log su file</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Salva</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Attiva WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools su F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Disattiva aggiornamenti</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Abilita accesso remoto (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Script personalizzati</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Aggiungi .js</s:String>
|
||||
<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_popup_title">Cosa patcheremo?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Prima dell'aggiornamento, si consiglia vivamente di annullare le patch se sono state applicate</s:String>
|
||||
<s:String x:Key="up_update_now">Aggiorna ora</s:String>
|
||||
<s:String x:Key="up_popup_title">Aggiornamento disponibile!</s:String>
|
||||
<s:String x:Key="pv_popup_title">Cosa modificheremo?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">新しいバージョンが利用可能です</s:String>
|
||||
<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>
|
||||
<s:String x:Key="mw_patch">適用</s:String>
|
||||
<s:String x:Key="mw_restore">復元</s:String>
|
||||
<s:String x:Key="mw_source_code">ソースコード</s:String>
|
||||
<s:String x:Key="mw_made_by">k1tbyte が ❤️ を込めて作成</s:String>
|
||||
<s:String x:Key="mw_star_hint">役に立ったらスターをつけてください ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">ログをクリップボードにコピー</s:String>
|
||||
<s:String x:Key="mw_export_logs">ログをファイルにエクスポート</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">保存</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">WeMod Pro を有効化</s:String>
|
||||
<s:String x:Key="pv_devtools">F12でDevTools</s:String>
|
||||
<s:String x:Key="pv_disable_updates">アップデートを無効化</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">リモートアクセスを有効化(ベータ)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">カスタムスクリプト</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">.js を追加</s:String>
|
||||
<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_popup_title">何をパッチしますか?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">アップデート前に、パッチが適用されている場合はロールバックすることを強くお勧めします</s:String>
|
||||
<s:String x:Key="up_update_now">今すぐ更新</s:String>
|
||||
<s:String x:Key="up_popup_title">アップデート利用可能!</s:String>
|
||||
<s:String x:Key="pv_popup_title">何を改善しますか?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Dostępna jest nowa wersja</s:String>
|
||||
<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">Patchuj</s:String>
|
||||
<s:String x:Key="mw_patch">Zastosuj</s:String>
|
||||
<s:String x:Key="mw_restore">Przywróć</s:String>
|
||||
<s:String x:Key="mw_source_code">Kod źródłowy</s:String>
|
||||
<s:String x:Key="mw_made_by">Wykonane z ❤️ przez k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Daj gwiazdkę, jeśli ci pomogło ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Skopiuj logi do schowka</s:String>
|
||||
<s:String x:Key="mw_export_logs">Eksportuj logi do pliku</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Zapisz</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Aktywuj WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools na F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Wyłącz aktualizacje</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Włącz zdalny dostęp (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Skrypty niestandardowe</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Dodaj .js</s:String>
|
||||
<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_popup_title">Co będziemy patchować?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Przed aktualizacją zdecydowanie zaleca się cofnięcie patchów, jeśli zostały zastosowane</s:String>
|
||||
<s:String x:Key="up_update_now">Aktualizuj teraz</s:String>
|
||||
<s:String x:Key="up_popup_title">Dostępna aktualizacja!</s:String>
|
||||
<s:String x:Key="pv_popup_title">Co będziemy ulepszać?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Uma nova versão está disponível</s:String>
|
||||
<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">Patch</s:String>
|
||||
<s:String x:Key="mw_patch">Aplicar</s:String>
|
||||
<s:String x:Key="mw_restore">Restaurar</s:String>
|
||||
<s:String x:Key="mw_source_code">Código fonte</s:String>
|
||||
<s:String x:Key="mw_made_by">Feito com ❤️ por k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Dê uma estrela se isso te ajudou ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Copiar logs para a área de transferência</s:String>
|
||||
<s:String x:Key="mw_export_logs">Exportar logs para arquivo</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Salvar</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Ativar WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools no F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Desativar atualizações</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Ativar acesso remoto (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Scripts personalizados</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Adicionar .js</s:String>
|
||||
<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_popup_title">O que vamos patchear?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Antes de atualizar, é altamente recomendável reverter os patches se eles foram aplicados</s:String>
|
||||
<s:String x:Key="up_update_now">Atualizar agora</s:String>
|
||||
<s:String x:Key="up_popup_title">Atualização disponível!</s:String>
|
||||
<s:String x:Key="pv_popup_title">O que vamos melhorar?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Доступна новая версия</s:String>
|
||||
<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>
|
||||
<s:String x:Key="mw_patch">Применить</s:String>
|
||||
<s:String x:Key="mw_restore">Восстановить</s:String>
|
||||
<s:String x:Key="mw_source_code">Исходный код</s:String>
|
||||
<s:String x:Key="mw_made_by">Сделано с ❤️ by k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Поставьте звезду, если это было полезно ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Скопировать логи в буфер обмена</s:String>
|
||||
<s:String x:Key="mw_export_logs">Экспортировать логи в файл</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Сохранить</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Активировать WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools на F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Отключить обновления</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Remote-доступ (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Свои скрипты</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Добавить .js</s:String>
|
||||
<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_popup_title">Что будем патчить?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Перед обновлением настоятельно рекомендуется откатить патчи, если они были применены</s:String>
|
||||
<s:String x:Key="up_update_now">Обновить сейчас</s:String>
|
||||
<s:String x:Key="up_popup_title">Доступно обновление!</s:String>
|
||||
<s:String x:Key="pv_popup_title">Что будем улучшать?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Yeni bir sürüm mevcut</s:String>
|
||||
<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">Yama</s:String>
|
||||
<s:String x:Key="mw_patch">Uygula</s:String>
|
||||
<s:String x:Key="mw_restore">Geri Yükle</s:String>
|
||||
<s:String x:Key="mw_source_code">Kaynak kodu</s:String>
|
||||
<s:String x:Key="mw_made_by">k1tbyte tarafından ❤️ ile yapıldı</s:String>
|
||||
<s:String x:Key="mw_star_hint">Yardımcı olduysa yıldız verin ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Günlükleri panoya kopyala</s:String>
|
||||
<s:String x:Key="mw_export_logs">Günlükleri dosyaya aktar</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Kaydet</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">WeMod Pro'yu Etkinleştir</s:String>
|
||||
<s:String x:Key="pv_devtools">F12 ile DevTools</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Güncellemeleri devre dışı bırak</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Uzaktan erişimi etkinleştir (beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Özel betikler</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">.js ekle</s:String>
|
||||
<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_popup_title">Ne yamalayacağız?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Güncellemeden önce, yamalar uygulandıysa geri almak şiddetle tavsiye edilir</s:String>
|
||||
<s:String x:Key="up_update_now">Şimdi güncelle</s:String>
|
||||
<s:String x:Key="up_popup_title">Güncelleme mevcut!</s:String>
|
||||
<s:String x:Key="pv_popup_title">Neyi geliştireceğiz?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">Доступна нова версія</s:String>
|
||||
<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>
|
||||
<s:String x:Key="mw_patch">Застосувати</s:String>
|
||||
<s:String x:Key="mw_restore">Відновити</s:String>
|
||||
<s:String x:Key="mw_source_code">Вихідний код</s:String>
|
||||
<s:String x:Key="mw_made_by">Зроблено з ❤️ by k1tbyte</s:String>
|
||||
<s:String x:Key="mw_star_hint">Поставте зірку, якщо це було корисно ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">Скопіювати логи до буфера обміну</s:String>
|
||||
<s:String x:Key="mw_export_logs">Експортувати логи у файл</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">Зберегти</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">Активувати WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">DevTools на F12</s:String>
|
||||
<s:String x:Key="pv_disable_updates">Вимкнути оновлення</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">Увімкнути віддалений доступ (бета)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">Користувацькі скрипти</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">Додати .js</s:String>
|
||||
<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_popup_title">Що будемо патчити?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">Перед оновленням наполегливо рекомендується відкотити патчі, якщо вони були застосовані</s:String>
|
||||
<s:String x:Key="up_update_now">Оновити зараз</s:String>
|
||||
<s:String x:Key="up_popup_title">Доступне оновлення!</s:String>
|
||||
<s:String x:Key="pv_popup_title">Що будемо покращувати?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -7,15 +7,16 @@
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region MainWindow -->
|
||||
<s:String x:Key="mw_title">WeMod Patcher</s:String>
|
||||
<s:String x:Key="mw_update_available">有新版本可用</s:String>
|
||||
<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>
|
||||
<s:String x:Key="mw_patch">增强</s:String>
|
||||
<s:String x:Key="mw_restore">恢复</s:String>
|
||||
<s:String x:Key="mw_source_code">源代码</s:String>
|
||||
<s:String x:Key="mw_made_by">由 k1tbyte 用 ❤️ 制作</s:String>
|
||||
<s:String x:Key="mw_star_hint">如果这对您有帮助,请给个星标 ;)</s:String>
|
||||
<s:String x:Key="mw_copy_logs">复制日志到剪贴板</s:String>
|
||||
<s:String x:Key="mw_export_logs">将日志导出到文件</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region Settings -->
|
||||
@@ -24,18 +25,17 @@
|
||||
<s:String x:Key="settings_save">保存</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region PatchVectorsPopup -->
|
||||
<!--#region EnhanceVectorsPopup -->
|
||||
<s:String x:Key="pv_activate_pro">激活 WeMod Pro</s:String>
|
||||
<s:String x:Key="pv_devtools">按 F12 打开开发者工具</s:String>
|
||||
<s:String x:Key="pv_disable_updates">禁用更新</s:String>
|
||||
<s:String x:Key="pv_remote_web_panel_preview">启用远程访问(beta)</s:String>
|
||||
<s:String x:Key="pv_custom_scripts">自定义脚本</s:String>
|
||||
<s:String x:Key="pv_add_js_scripts">添加 .js</s:String>
|
||||
<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_popup_title">我们要打什么补丁?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
<!--#region UpdatePopup -->
|
||||
<s:String x:Key="up_warning">在更新之前,强烈建议回滚已应用的补丁</s:String>
|
||||
<s:String x:Key="up_update_now">立即更新</s:String>
|
||||
<s:String x:Key="up_popup_title">有更新可用!</s:String>
|
||||
<s:String x:Key="pv_popup_title">我们要增强什么?</s:String>
|
||||
<!--#endregion -->
|
||||
|
||||
</ResourceDictionary>
|
||||
@@ -1,10 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
using WeModPatcher.Utils;
|
||||
using WandEnhancer.Utils;
|
||||
|
||||
namespace WeModPatcher.Models
|
||||
namespace WandEnhancer.Models
|
||||
{
|
||||
|
||||
public enum EPatchType
|
||||
@@ -12,13 +11,16 @@ namespace WeModPatcher.Models
|
||||
ActivatePro = 1,
|
||||
DisableUpdates = 2,
|
||||
DisableTelemetry = 4,
|
||||
DevToolsOnF12 = 8
|
||||
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; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace WeModPatcher.Models
|
||||
namespace WandEnhancer.Models
|
||||
{
|
||||
public sealed class Signature
|
||||
{
|
||||
@@ -1,6 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace WeModPatcher.Models
|
||||
namespace WandEnhancer.Models
|
||||
{
|
||||
public class WeModConfig
|
||||
{
|
||||
@@ -2,9 +2,9 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using WeModPatcher.View.MainWindow;
|
||||
using WandEnhancer.View.MainWindow;
|
||||
|
||||
namespace WeModPatcher
|
||||
namespace WandEnhancer
|
||||
{
|
||||
public static class Program
|
||||
{
|
||||
@@ -7,11 +7,11 @@ using System.Windows;
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("WeModPatcher")]
|
||||
[assembly: AssemblyTitle("WandEnhancer")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("WeModPatcher")]
|
||||
[assembly: AssemblyProduct("WandEnhancer")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2025")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
@@ -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.6.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.6.0")]
|
||||
[assembly: AssemblyVersion("1.0.9.4")]
|
||||
[assembly: AssemblyFileVersion("1.0.9.4")]
|
||||
Generated
+2
-2
@@ -8,7 +8,7 @@
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace WeModPatcher.Properties
|
||||
namespace WandEnhancer.Properties
|
||||
{
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
@@ -45,7 +45,7 @@ namespace WeModPatcher.Properties
|
||||
if ((resourceMan == null))
|
||||
{
|
||||
global::System.Resources.ResourceManager temp =
|
||||
new global::System.Resources.ResourceManager("WeModPatcher.Properties.Resources",
|
||||
new global::System.Resources.ResourceManager("WandEnhancer.Properties.Resources",
|
||||
typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace WeModPatcher.ReactiveUICore
|
||||
namespace WandEnhancer.ReactiveUICore
|
||||
{
|
||||
public sealed class AsyncRelayCommand : ICommand
|
||||
{
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace WeModPatcher.ReactiveUICore
|
||||
namespace WandEnhancer.ReactiveUICore
|
||||
{
|
||||
public class ObservableObject : INotifyPropertyChanged
|
||||
{
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace WeModPatcher.ReactiveUICore
|
||||
namespace WandEnhancer.ReactiveUICore
|
||||
{
|
||||
public sealed class RelayCommand : ICommand
|
||||
{
|
||||
@@ -27,6 +27,14 @@
|
||||
<Geometry x:Key="ArrowLeft">
|
||||
M5.05 11.94l5-5v3.99H19l-.03 2.01H10.05v4Z
|
||||
</Geometry>
|
||||
|
||||
<Geometry x:Key="CopyIcon">
|
||||
M19 21H8V7h11m0-2H8a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2m-3-4H4a2 2 0 0 0-2 2v14h2V3h12V1Z
|
||||
</Geometry>
|
||||
|
||||
<Geometry x:Key="ExportIcon">
|
||||
M14 13h-3v3H9v-3H6v-2h3V8h2v3h3m-1-9H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9l-7-7M5 4h7v5h5v11H5V4Z
|
||||
</Geometry>
|
||||
|
||||
<!--<Geometry x:Key="">
|
||||
|
||||
@@ -4,14 +4,19 @@ using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
|
||||
namespace WeModPatcher.Utils
|
||||
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++)
|
||||
// Retry while any target process is still alive, capped at 5 attempts.
|
||||
// The previous condition (processes.Length > i || i < 5) compared the
|
||||
// process count to the loop index and, because of the "|| i < 5", always
|
||||
// ran at least 5 iterations — sleeping ~1.25s even when the process was
|
||||
// never running.
|
||||
for (int i = 0; processes.Length > 0 && i < 5; i++)
|
||||
{
|
||||
foreach (var process in processes)
|
||||
{
|
||||
@@ -0,0 +1,148 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using WandEnhancer.Models;
|
||||
|
||||
namespace WandEnhancer.Utils
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static WeModConfig CheckWeModPath(string versionRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
foreach (var name in Constants.WeModBrandNames)
|
||||
{
|
||||
var exeName = $"{name}.exe";
|
||||
var path = Path.Combine(versionRoot, exeName);
|
||||
if (File.Exists(path) && File.Exists(Path.Combine(versionRoot, "resources", "app.asar")))
|
||||
{
|
||||
return new WeModConfig
|
||||
{
|
||||
BrandName = name,
|
||||
ExecutableName = exeName,
|
||||
RootDirectory = versionRoot
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static WeModConfig FindWeMod()
|
||||
{
|
||||
string localAppDataPath = Environment.GetEnvironmentVariable("LOCALAPPDATA");
|
||||
|
||||
if (!string.IsNullOrEmpty(localAppDataPath))
|
||||
{
|
||||
foreach (var folder in Constants.WeModBrandNames)
|
||||
{
|
||||
var weModDir = Path.Combine(localAppDataPath, folder);
|
||||
if (!Directory.Exists(weModDir))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Keep scanning the other brand folders if this one has no valid
|
||||
// install instead of giving up on the first folder that exists.
|
||||
var config = FindLatestWeMod(weModDir);
|
||||
if (config != null)
|
||||
{
|
||||
return config;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: a running Wand/WeMod process reveals the install directory
|
||||
// wherever it lives (non-default LOCALAPPDATA, moved install, other drive).
|
||||
return FindWeModFromRunningProcess();
|
||||
}
|
||||
|
||||
private static WeModConfig FindWeModFromRunningProcess()
|
||||
{
|
||||
foreach (var name in Constants.WeModBrandNames)
|
||||
{
|
||||
Process[] processes;
|
||||
try
|
||||
{
|
||||
processes = Process.GetProcessesByName(name);
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var process in processes)
|
||||
{
|
||||
try
|
||||
{
|
||||
var exePath = process.MainModule?.FileName;
|
||||
if (string.IsNullOrEmpty(exePath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process may be the versioned exe (dir is the install root) or
|
||||
// the launcher stub at the parent (dir holds `app-*` subfolders).
|
||||
var processDir = Path.GetDirectoryName(exePath);
|
||||
var config = CheckWeModPath(processDir) ?? FindLatestWeMod(processDir);
|
||||
if (config != null)
|
||||
{
|
||||
return config;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// MainModule throws on access-denied / bitness mismatch; skip.
|
||||
}
|
||||
finally
|
||||
{
|
||||
process.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string Base64Decode(string base64EncodedData)
|
||||
{
|
||||
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
|
||||
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
|
||||
}
|
||||
|
||||
public static string Base64Encode(string plainText)
|
||||
{
|
||||
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
|
||||
return System.Convert.ToBase64String(plainTextBytes);
|
||||
}
|
||||
|
||||
public static WeModConfig FindLatestWeMod(string root)
|
||||
{
|
||||
var appFolders = Directory.EnumerateDirectories(root)
|
||||
.Select(folderPath => new DirectoryInfo(folderPath))
|
||||
.Where(dirInfo => Regex.IsMatch(dirInfo.Name, @"^app-\w+"))
|
||||
.Select(dirInfo => new
|
||||
{
|
||||
Name = dirInfo.Name,
|
||||
Path = dirInfo.FullName,
|
||||
LastModified = dirInfo.LastWriteTime
|
||||
})
|
||||
.OrderByDescending(item => item.LastModified)
|
||||
.ToList();
|
||||
|
||||
|
||||
return appFolders
|
||||
.Select(folder => CheckWeModPath(folder.Path))
|
||||
.FirstOrDefault(config => config != null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace WeModPatcher.Utils.Win32
|
||||
namespace WandEnhancer.Utils.Win32
|
||||
{
|
||||
public class Shortcut
|
||||
{
|
||||
@@ -1,9 +1,9 @@
|
||||
<UserControl x:Class="WeModPatcher.View.Controls.InfoItem"
|
||||
<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:WeModPatcher.View.Controls"
|
||||
xmlns:local="clr-namespace:WandEnhancer.View.Controls"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="300" d:DesignWidth="300">
|
||||
<Grid>
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace WeModPatcher.View.Controls
|
||||
namespace WandEnhancer.View.Controls
|
||||
{
|
||||
public partial class InfoItem : UserControl
|
||||
{
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
<Grid x:Class="WeModPatcher.View.Controls.PopupHost"
|
||||
<Grid x:Class="WandEnhancer.View.Controls.PopupHost"
|
||||
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:WeModPatcher.View.Controls"
|
||||
xmlns:local="clr-namespace:WandEnhancer.View.Controls"
|
||||
mc:Ignorable="d"
|
||||
Visibility="Collapsed">
|
||||
<Border x:Name="Splash" Background="Black" CornerRadius="7"
|
||||
+1
-1
@@ -5,7 +5,7 @@ using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media.Animation;
|
||||
|
||||
namespace WeModPatcher.View.Controls
|
||||
namespace WandEnhancer.View.Controls
|
||||
{
|
||||
public partial class PopupHost : Grid
|
||||
{
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace WeModPatcher.View.MainWindow
|
||||
namespace WandEnhancer.View.MainWindow
|
||||
{
|
||||
public enum ELogType
|
||||
{
|
||||
+22
-13
@@ -1,13 +1,13 @@
|
||||
<Window x:Class="WeModPatcher.View.MainWindow.MainWindow"
|
||||
<Window x:Class="WandEnhancer.View.MainWindow.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:WeModPatcher.View.MainWindow"
|
||||
xmlns:controls="clr-namespace:WeModPatcher.View.Controls"
|
||||
xmlns:local="clr-namespace:WandEnhancer.View.MainWindow"
|
||||
xmlns:controls="clr-namespace:WandEnhancer.View.Controls"
|
||||
mc:Ignorable="d"
|
||||
d:DataContext="{d:DesignInstance local:MainWindowVm}"
|
||||
Title="WeMod Patcher"
|
||||
Title="WandEnhancer"
|
||||
Height="510" MaxHeight="510"
|
||||
Width="780" MaxWidth="780"
|
||||
Opacity="0.97"
|
||||
@@ -36,7 +36,7 @@
|
||||
VerticalAlignment="Center"
|
||||
FontSize="18" Margin="10 0 0 0">
|
||||
<Bold>
|
||||
WeMod Patcher
|
||||
WandEnhancer
|
||||
</Bold>
|
||||
</TextBlock>
|
||||
<TextBlock x:Name="VersionLabel" VerticalAlignment="Bottom"
|
||||
@@ -45,12 +45,6 @@
|
||||
v 1.0.0
|
||||
</TextBlock>
|
||||
|
||||
<Button Background="SpringGreen" Foreground="{DynamicResource Muted}"
|
||||
FontWeight="Medium" Padding="20 0" Margin="10 5 20 5"
|
||||
ToolTip="Click to update"
|
||||
Command="{Binding UpdateCommand}"
|
||||
Visibility="{Binding IsUpdateAvailable, Converter={StaticResource ToVisibilityConverter}}"
|
||||
Content="{DynamicResource mw_update_available}"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
|
||||
@@ -109,7 +103,8 @@
|
||||
<Border Grid.Row="1" BorderBrush="{DynamicResource Border}" BorderThickness="1"
|
||||
Margin="10 0 10 10"
|
||||
CornerRadius="5">
|
||||
<ListBox ItemsSource="{Binding LogList}" SelectionMode="Single"
|
||||
<Grid>
|
||||
<ListBox ItemsSource="{Binding LogList}" SelectionMode="Single"
|
||||
BorderBrush="Transparent" BorderThickness="0"
|
||||
Background="Transparent"
|
||||
x:Name="LogList"
|
||||
@@ -152,6 +147,20 @@
|
||||
</Style>
|
||||
</ListBox.ItemContainerStyle>
|
||||
</ListBox>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top"
|
||||
Margin="0 4 4 0">
|
||||
<Button Width="22" Height="22" Padding="4"
|
||||
Style="{StaticResource IconButton}"
|
||||
Tag="{StaticResource CopyIcon}"
|
||||
ToolTip="{DynamicResource mw_copy_logs}"
|
||||
Command="{Binding CopyLogsCommand}"/>
|
||||
<Button Width="22" Height="22" Padding="4" Margin="4 0 0 0"
|
||||
Style="{StaticResource IconButton}"
|
||||
Tag="{StaticResource ExportIcon}"
|
||||
ToolTip="{DynamicResource mw_export_logs}"
|
||||
Command="{Binding ExportLogsCommand}"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
|
||||
@@ -212,4 +221,4 @@
|
||||
<controls:PopupHost x:Name="PopupHost"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
</Window>
|
||||
+1
-1
@@ -3,7 +3,7 @@ using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace WeModPatcher.View.MainWindow
|
||||
namespace WandEnhancer.View.MainWindow
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
+93
-56
@@ -1,24 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using WeModPatcher.Core;
|
||||
using WeModPatcher.Models;
|
||||
using WeModPatcher.ReactiveUICore;
|
||||
using WeModPatcher.Utils;
|
||||
using WeModPatcher.View.Popups;
|
||||
using WandEnhancer.Core;
|
||||
using WandEnhancer.Models;
|
||||
using WandEnhancer.ReactiveUICore;
|
||||
using WandEnhancer.Utils;
|
||||
using WandEnhancer.View.Popups;
|
||||
using Application = System.Windows.Application;
|
||||
|
||||
namespace WeModPatcher.View.MainWindow
|
||||
namespace WandEnhancer.View.MainWindow
|
||||
{
|
||||
public class MainWindowVm : ObservableObject
|
||||
{
|
||||
private readonly MainWindow _view;
|
||||
public ObservableCollection<LogEntry> LogList { get; set; } = new ObservableCollection<LogEntry>();
|
||||
private static Updater _updater = new Updater();
|
||||
|
||||
private WeModConfig _weModConfig;
|
||||
|
||||
public WeModConfig WeModInfo
|
||||
@@ -30,7 +28,9 @@ namespace WeModPatcher.View.MainWindow
|
||||
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")))
|
||||
var resourcesPath = Path.Combine(_weModConfig.RootDirectory, "resources");
|
||||
if (File.Exists(Path.Combine(resourcesPath, "app.asar.backup")) ||
|
||||
Directory.Exists(Path.Combine(resourcesPath, "app.asar.unpacked.backup")))
|
||||
{
|
||||
Log("WeMod already patched. If you want to patch again, please restore the backup first.",
|
||||
ELogType.Warn);
|
||||
@@ -60,19 +60,12 @@ namespace WeModPatcher.View.MainWindow
|
||||
set => SetProperty(ref _alreadyPatched, value);
|
||||
}
|
||||
|
||||
private bool _isUpdateAvailable;
|
||||
|
||||
public bool IsUpdateAvailable
|
||||
{
|
||||
get => _isUpdateAvailable;
|
||||
set => SetProperty(ref _isUpdateAvailable, value);
|
||||
}
|
||||
|
||||
public RelayCommand SetFolderPathCommand { get; }
|
||||
public RelayCommand ApplyPatchCommand { get; }
|
||||
public RelayCommand RestoreBackupCommand { get; }
|
||||
public RelayCommand UpdateCommand { get; }
|
||||
public RelayCommand OpenSettingsCommand { get; }
|
||||
public RelayCommand CopyLogsCommand { get; }
|
||||
public RelayCommand ExportLogsCommand { get; }
|
||||
|
||||
private void OnFolderPathSelection(object obj)
|
||||
{
|
||||
@@ -104,35 +97,42 @@ namespace WeModPatcher.View.MainWindow
|
||||
|
||||
private void OnBackupRestoring(object param)
|
||||
{
|
||||
var backupPath = Path.Combine(WeModInfo.RootDirectory, "resources", "app.asar.backup");
|
||||
if (!File.Exists(backupPath))
|
||||
var resourcesPath = Path.Combine(WeModInfo.RootDirectory, "resources");
|
||||
var backupPath = Path.Combine(resourcesPath, "app.asar.backup");
|
||||
var unpackedBackupPath = Path.Combine(resourcesPath, "app.asar.unpacked.backup");
|
||||
if (!File.Exists(backupPath) || !Directory.Exists(unpackedBackupPath))
|
||||
{
|
||||
Log("Backup not found. Please dont delete it manually", ELogType.Error);
|
||||
Log("Backup is incomplete. Restore the original Wand installation files or reinstall Wand.", ELogType.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Try to lock the file to see if it's in use
|
||||
using (File.Open(backupPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
var asarPath = Path.Combine(resourcesPath, "app.asar");
|
||||
var unpackedPath = Path.Combine(resourcesPath, "app.asar.unpacked");
|
||||
File.Copy(backupPath, asarPath, true);
|
||||
|
||||
if (Directory.Exists(unpackedPath))
|
||||
{
|
||||
Directory.Delete(unpackedPath, true);
|
||||
}
|
||||
|
||||
Enhancer.CopyDirectory(unpackedBackupPath, unpackedPath);
|
||||
|
||||
var proxyDllPath = Path.Combine(WeModInfo.RootDirectory, "version.dll");
|
||||
|
||||
if(File.Exists(proxyDllPath))
|
||||
if (File.Exists(proxyDllPath))
|
||||
{
|
||||
File.Delete(proxyDllPath);
|
||||
}
|
||||
|
||||
File.Delete(backupPath);
|
||||
Directory.Delete(unpackedBackupPath, true);
|
||||
}
|
||||
catch
|
||||
catch (Exception e)
|
||||
{
|
||||
Log("Backup file is locked. Please close the WeMod and try again.", ELogType.Error);
|
||||
Log($"Failed to restore backup: {e.Message}", 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;
|
||||
@@ -154,7 +154,7 @@ namespace WeModPatcher.View.MainWindow
|
||||
{
|
||||
try
|
||||
{
|
||||
new Patcher(WeModInfo, Log, config).Patch();
|
||||
new Enhancer(WeModInfo, Log, config).Patch();
|
||||
AlreadyPatched = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -182,41 +182,78 @@ namespace WeModPatcher.View.MainWindow
|
||||
});
|
||||
}
|
||||
|
||||
private void OnUpdate(object param)
|
||||
{
|
||||
MainWindow.Instance.OpenPopup(new UpdatePopup(() =>
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await _updater.Update();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log($"Failed to update: {e.Message}", ELogType.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
Log("WeModPatcher updated successfully. Restarting...", ELogType.Success);
|
||||
});
|
||||
}), Application.Current.FindResource("up_popup_title") as string);
|
||||
}
|
||||
|
||||
private void OnOpenSettings(object param)
|
||||
{
|
||||
MainWindow.Instance.OpenPopup(new SettingsPopup(), Application.Current.FindResource("settings_title") as string);
|
||||
}
|
||||
|
||||
private string BuildLogReport()
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var entry in LogList)
|
||||
{
|
||||
builder.AppendLine(entry.Message);
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private void OnCopyLogs(object param)
|
||||
{
|
||||
if (LogList.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
System.Windows.Clipboard.SetText(BuildLogReport());
|
||||
Log("Logs copied to clipboard.", ELogType.Success);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log($"Failed to copy logs: {e.Message}", ELogType.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnExportLogs(object param)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public MainWindowVm(MainWindow view)
|
||||
{
|
||||
Task.Run(async () => IsUpdateAvailable = await _updater.CheckForUpdates());
|
||||
_view = view;
|
||||
SetFolderPathCommand = new RelayCommand(OnFolderPathSelection);
|
||||
ApplyPatchCommand = new RelayCommand(OnPatching);
|
||||
RestoreBackupCommand = new RelayCommand(OnBackupRestoring);
|
||||
UpdateCommand = new RelayCommand(OnUpdate);
|
||||
OpenSettingsCommand = new RelayCommand(OnOpenSettings);
|
||||
CopyLogsCommand = new RelayCommand(OnCopyLogs);
|
||||
ExportLogsCommand = new RelayCommand(OnExportLogs);
|
||||
|
||||
WeModInfo = Extensions.FindWeMod();
|
||||
if (WeModInfo == null)
|
||||
@@ -225,4 +262,4 @@ namespace WeModPatcher.View.MainWindow
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<UserControl x:Class="WandEnhancer.View.Popups.PatchVectorsPopup"
|
||||
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.Popups"
|
||||
xmlns:controls="clr-namespace:WandEnhancer.View.Controls"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="Auto" d:DesignWidth="Auto"
|
||||
Background="{DynamicResource Background}"
|
||||
Foreground="{DynamicResource MutedForeground}"
|
||||
FontWeight="Medium"
|
||||
FontSize="13">
|
||||
<Grid MinWidth="430">
|
||||
<Grid Visibility="Visible" Margin="0 0 5 0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" Text="{DynamicResource pv_activate_pro}" />
|
||||
<CheckBox Grid.Row="0" Grid.Column="1" x:Name="ActivateProBox" HorizontalAlignment="Right" VerticalAlignment="Center"
|
||||
IsChecked="True" />
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" Text="{DynamicResource pv_devtools}" />
|
||||
<CheckBox Grid.Row="1" Grid.Column="1" x:Name="DevToolsHotkeyBox" HorizontalAlignment="Right" VerticalAlignment="Center" />
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" VerticalAlignment="Center" Text="{DynamicResource pv_disable_updates}" />
|
||||
<CheckBox Grid.Row="2" Grid.Column="1" x:Name="DisableUpdateBox" HorizontalAlignment="Right" VerticalAlignment="Center" />
|
||||
|
||||
<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"
|
||||
BorderBrush="{DynamicResource Border}" BorderThickness="1" CornerRadius="4"
|
||||
Background="{DynamicResource Muted}">
|
||||
<StackPanel>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0" VerticalAlignment="Center"
|
||||
Foreground="{DynamicResource Foreground}"
|
||||
Text="{DynamicResource pv_custom_scripts}" />
|
||||
<Button Grid.Column="1" Padding="10 4" Content="{DynamicResource pv_add_js_scripts}"
|
||||
Click="OnAddScriptClick" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Margin="0 7 0 0" FontSize="11" TextWrapping="Wrap"
|
||||
Opacity="0.8"
|
||||
Text="{DynamicResource pv_custom_scripts_hint}" />
|
||||
|
||||
<ItemsControl x:Name="ScriptList" Margin="0 2 0 0">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Margin="0 6 6 0" Padding="8 3"
|
||||
Background="{DynamicResource Card}"
|
||||
BorderBrush="{DynamicResource Border}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="3">
|
||||
<DockPanel LastChildFill="True">
|
||||
<Button DockPanel.Dock="Right" Tag="{Binding}" Content="x"
|
||||
BorderThickness="0" Padding="6 0" Margin="6 0 0 0"
|
||||
Click="OnRemoveScriptClick" />
|
||||
<TextBlock VerticalAlignment="Center"
|
||||
Foreground="{DynamicResource Foreground}"
|
||||
Text="{Binding FileName}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
<TextBlock x:Name="NoScriptsText" Margin="0 7 0 0" FontSize="11"
|
||||
Opacity="0.7"
|
||||
Text="{DynamicResource pv_no_custom_scripts}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Button Grid.Row="5" Grid.ColumnSpan="2" Padding="0 5 0 5" Margin="0 15 0 0" Content="{DynamicResource pv_start}"
|
||||
Click="OnPatchButtonClick" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
</UserControl>
|
||||
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using Microsoft.Win32;
|
||||
using WandEnhancer.Models;
|
||||
|
||||
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>();
|
||||
|
||||
public PatchVectorsPopup(Action<PatchConfig> onApply)
|
||||
{
|
||||
_onApply = onApply;
|
||||
InitializeComponent();
|
||||
ScriptList.ItemsSource = _selectedScripts;
|
||||
UpdateScriptsEmptyState();
|
||||
}
|
||||
|
||||
private void OnAddScriptClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dialog = new OpenFileDialog
|
||||
{
|
||||
Filter = JavaScriptDialogFilter,
|
||||
Multiselect = true,
|
||||
CheckFileExists = true
|
||||
};
|
||||
|
||||
if (dialog.ShowDialog() != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var path in dialog.FileNames.Where(IsJavaScriptFile))
|
||||
{
|
||||
AddScript(path);
|
||||
}
|
||||
|
||||
if (_selectedScripts.Count > 0)
|
||||
{
|
||||
RemoteWebPanelPreviewBox.IsChecked = true;
|
||||
}
|
||||
|
||||
UpdateScriptsEmptyState();
|
||||
}
|
||||
|
||||
private void OnRemoveScriptClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var button = sender as Button;
|
||||
var script = button?.Tag as SelectedScript;
|
||||
if (script == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_selectedScripts.Remove(script);
|
||||
UpdateScriptsEmptyState();
|
||||
}
|
||||
|
||||
private void OnPatchButtonClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ActivateProBox.IsChecked != true && DisableUpdateBox.IsChecked != true &&
|
||||
DevToolsHotkeyBox.IsChecked != true && RemoteWebPanelPreviewBox.IsChecked != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var result = new HashSet<EPatchType>();
|
||||
if (ActivateProBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.ActivatePro);
|
||||
}
|
||||
|
||||
if (DisableUpdateBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.DisableUpdates);
|
||||
}
|
||||
|
||||
if (DevToolsHotkeyBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.DevToolsOnF12);
|
||||
}
|
||||
|
||||
if (RemoteWebPanelPreviewBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.RemoteWebPanelPreview);
|
||||
}
|
||||
|
||||
_onApply(new PatchConfig
|
||||
{
|
||||
PatchTypes = result,
|
||||
CustomScriptPaths = _selectedScripts.Select(script => script.FullPath).ToList(),
|
||||
AutoApplyPatches = false
|
||||
});
|
||||
}
|
||||
|
||||
private void AddScript(string path)
|
||||
{
|
||||
var fullPath = Path.GetFullPath(path);
|
||||
if (_selectedScripts.Any(script => string.Equals(script.FullPath, fullPath, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_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;
|
||||
}
|
||||
|
||||
private sealed class SelectedScript
|
||||
{
|
||||
public SelectedScript(string fullPath)
|
||||
{
|
||||
FullPath = fullPath;
|
||||
FileName = Path.GetFileName(fullPath);
|
||||
}
|
||||
|
||||
public string FullPath { get; }
|
||||
|
||||
public string FileName { get; }
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
<UserControl x:Class="WeModPatcher.View.Popups.SettingsPopup"
|
||||
<UserControl x:Class="WandEnhancer.View.Popups.SettingsPopup"
|
||||
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"
|
||||
+4
-4
@@ -2,11 +2,11 @@ using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using WeModPatcher.Core;
|
||||
using WeModPatcher.Core.Services;
|
||||
using WeModPatcher.View.MainWindow;
|
||||
using WandEnhancer.Core;
|
||||
using WandEnhancer.Core.Services;
|
||||
using WandEnhancer.View.MainWindow;
|
||||
|
||||
namespace WeModPatcher.View.Popups
|
||||
namespace WandEnhancer.View.Popups
|
||||
{
|
||||
public partial class SettingsPopup : UserControl
|
||||
{
|
||||
@@ -7,8 +7,8 @@
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{106D3E44-ECBB-4EF3-84B2-5FC6BCF77727}</ProjectGuid>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<RootNamespace>WeModPatcher</RootNamespace>
|
||||
<AssemblyName>WeModPatcher</AssemblyName>
|
||||
<RootNamespace>WandEnhancer</RootNamespace>
|
||||
<AssemblyName>WandEnhancer</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
@@ -38,10 +38,13 @@
|
||||
<Prefer32bit>false</Prefer32bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<StartupObject>WeModPatcher.Program</StartupObject>
|
||||
<StartupObject>WandEnhancer.Program</StartupObject>
|
||||
<CMakeSourceDir>..\tools\asar-fuses-bypass</CMakeSourceDir>
|
||||
<CMakeBuildDir>$(CMakeSourceDir)\cmake-build-release</CMakeBuildDir>
|
||||
<ProxyDllPath>$(CMakeBuildDir)\version.dll</ProxyDllPath>
|
||||
<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">
|
||||
@@ -52,7 +55,6 @@
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xaml">
|
||||
<RequiredTargetFramework>4.0</RequiredTargetFramework>
|
||||
</Reference>
|
||||
@@ -68,8 +70,8 @@
|
||||
<Compile Include="Constants.cs" />
|
||||
<Compile Include="Converters\BaseBooleanConverter.cs" />
|
||||
<Compile Include="Converters\ToVisibilityConverter.cs" />
|
||||
<Compile Include="Core\Patcher.cs" />
|
||||
<Compile Include="Core\PatcherConfig.cs" />
|
||||
<Compile Include="Core\Enhancer.cs" />
|
||||
<Compile Include="Core\EnhancerConfig.cs" />
|
||||
<Compile Include="Core\Services\LocalizationManager.cs" />
|
||||
<Compile Include="Core\Services\SettingsManager.cs" />
|
||||
<Compile Include="Models\WeModConfig.cs" />
|
||||
@@ -81,7 +83,6 @@
|
||||
<Compile Include="ReactiveUICore\RelayCommand.cs" />
|
||||
<Compile Include="Utils\Common.cs" />
|
||||
<Compile Include="Utils\Extensions.cs" />
|
||||
<Compile Include="Utils\Updater.cs" />
|
||||
<Compile Include="Utils\Win32\Shortcut.cs" />
|
||||
<Compile Include="View\Controls\InfoItem.xaml.cs">
|
||||
<DependentUpon>InfoItem.xaml</DependentUpon>
|
||||
@@ -100,9 +101,6 @@
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="View\Popups\UpdatePopup.xaml.cs">
|
||||
<DependentUpon>UpdatePopup.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Page Include="Locale\lang.en-US.xaml" />
|
||||
<Page Include="Locale\lang.zh-CN.xaml" />
|
||||
<Page Include="Locale\lang.de-DE.xaml" />
|
||||
@@ -123,7 +121,6 @@
|
||||
<Page Include="View\MainWindow\MainWindow.xaml" />
|
||||
<Page Include="View\Popups\PatchVectorsPopup.xaml" />
|
||||
<Page Include="View\Popups\SettingsPopup.xaml" />
|
||||
<Page Include="View\Popups\UpdatePopup.xaml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Properties\AssemblyInfo.cs">
|
||||
@@ -151,15 +148,20 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AsarSharp\AsarSharp.csproj">
|
||||
<Project>{beaa604a-402a-4387-8903-a53fc913a26e}</Project>
|
||||
<Project>{BEAA604A-402A-4387-8903-A53FC913A26E}</Project>
|
||||
<Name>AsarSharp</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
</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>
|
||||
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
@@ -169,7 +171,7 @@
|
||||
<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="EmbedProxyDll" BeforeTargets="BeforeBuild">
|
||||
<Target Name="ValidateNativeArtifacts" BeforeTargets="BeforeBuild">
|
||||
<Error Text="Proxy DLL not found: $(ProxyDllPath)"
|
||||
Condition="!Exists('$(ProxyDllPath)')" />
|
||||
|
||||
@@ -184,13 +186,15 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyList Include="$(OutputPath)*.dll" />
|
||||
<AssemblyList Include="$(OutputPath)*.dll" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<DllList>@(AssemblyList->'%(FullPath)', ' ')</DllList>
|
||||
</PropertyGroup>
|
||||
|
||||
<Delete Files="$(OutputPath)$(AssemblyName).pdb" ContinueOnError="true" />
|
||||
<Exec Command=""$(ILRepackExe)" /allowMultiple /copyattrs /out:"$(OutputPath)$(AssemblyName).exe" "$(MainAssembly)" $(DllList)" />
|
||||
<Delete Files="@(AssemblyList)" ContinueOnError="true" />
|
||||
</Target>
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -1,194 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Windows.Forms;
|
||||
using AsarSharp;
|
||||
using Newtonsoft.Json;
|
||||
using WeModPatcher.Models;
|
||||
using WeModPatcher.Utils;
|
||||
using WeModPatcher.View.MainWindow;
|
||||
using Application = System.Windows.Application;
|
||||
|
||||
namespace WeModPatcher.Core
|
||||
{
|
||||
public class Patcher
|
||||
{
|
||||
|
||||
|
||||
|
||||
private readonly WeModConfig _weModConfig;
|
||||
private readonly Action<string, ELogType> _logger;
|
||||
private readonly PatchConfig _config;
|
||||
private readonly string _asarPath;
|
||||
private readonly string _backupPath;
|
||||
private readonly string _unpackedPath;
|
||||
|
||||
public Patcher(WeModConfig weModConfig, Action<string, ELogType> logger, PatchConfig config)
|
||||
{
|
||||
_weModConfig = weModConfig;
|
||||
_logger = logger;
|
||||
_config = config;
|
||||
|
||||
_asarPath = Path.Combine(weModConfig.RootDirectory, "resources", "app.asar");
|
||||
_unpackedPath = Path.Combine(weModConfig.RootDirectory, "resources", "app.asar.unpacked");
|
||||
_backupPath = Path.Combine(weModConfig.RootDirectory, "resources", "app.asar.backup");
|
||||
}
|
||||
|
||||
private string ApplyJsPatch(string fileName, string js, PatcherConfig.PatchEntry patch, EPatchType patchType)
|
||||
{
|
||||
if (patch.Applied)
|
||||
{
|
||||
return js;
|
||||
}
|
||||
|
||||
var matches = patch.Target.Matches(js);
|
||||
if (matches.Count == 0)
|
||||
{
|
||||
return js;
|
||||
}
|
||||
|
||||
var prefix = $"[PATCHER] [{patchType} -> {patch.Name}]";
|
||||
|
||||
if(matches.Count > 1 && patch.SingleMatch)
|
||||
{
|
||||
throw new Exception(
|
||||
$"{prefix} Patch failed. Multiple target functions found. Looks like the version is not supported");
|
||||
}
|
||||
|
||||
if (patch.Resolver != null)
|
||||
{
|
||||
string resolvedField = patch.Resolver.Handler(matches[0].Value);
|
||||
if (string.IsNullOrEmpty(resolvedField))
|
||||
{
|
||||
throw new Exception($"{prefix} Resolver failed to find field name");
|
||||
}
|
||||
|
||||
patch.Patch = patch.Patch.Replace(patch.Resolver.Placeholder, resolvedField);
|
||||
}
|
||||
|
||||
_logger($"{prefix} Found target function in: " + Path.GetFileName(fileName), ELogType.Info);
|
||||
|
||||
string newJs = patch.Target.Replace(js, patch.Patch);
|
||||
File.WriteAllText(fileName, newJs);
|
||||
_logger($"{prefix} Patch applied", ELogType.Success);
|
||||
patch.Applied = true;
|
||||
|
||||
return newJs;
|
||||
}
|
||||
|
||||
private void PatchAsar()
|
||||
{
|
||||
var items = Directory.EnumerateFiles(_unpackedPath)
|
||||
.Where(file => !Directory.Exists(file) && Regex.IsMatch(Path.GetFileName(file), @"^app-\w+|index\.js"))
|
||||
.ToList();
|
||||
|
||||
if (!items.Any())
|
||||
{
|
||||
throw new Exception("[PATCHER] No app bundle found");
|
||||
}
|
||||
|
||||
// Track patches that still need to be completed
|
||||
var remainingPatches = new HashSet<EPatchType>(_config.PatchTypes);
|
||||
var patcherConfig = PatcherConfig.GetInstance();
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (remainingPatches.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
string data = File.ReadAllText(item);
|
||||
|
||||
// Iterate over a copy of the list so we can modify the HashSet
|
||||
foreach (var entry in remainingPatches.ToList())
|
||||
{
|
||||
var entries = patcherConfig[entry];
|
||||
foreach (var patchEntry in entries)
|
||||
{
|
||||
// Update data in memory so subsequent patches in the same file work on latest content
|
||||
data = ApplyJsPatch(item, data, patchEntry, entry);
|
||||
}
|
||||
|
||||
// Check if all entries for this patch type are applied
|
||||
if (entries.All(x => x.Applied))
|
||||
{
|
||||
remainingPatches.Remove(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(remainingPatches.Count > 0)
|
||||
{
|
||||
var failedPatches = string.Join(", ", remainingPatches.Select(p => p.ToString()));
|
||||
throw new Exception($"[PATCHER] Failed to apply patches: {failedPatches}. The version may not be supported.");
|
||||
}
|
||||
}
|
||||
|
||||
private void AttachProxyDll()
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
var dll = assembly.GetManifestResourceStream(Constants.ProxyDllResouceName);
|
||||
if (dll == null)
|
||||
{
|
||||
throw new Exception("[PATCHER] Proxy DLL resource not found");
|
||||
}
|
||||
var destPath = Path.Combine(_weModConfig.RootDirectory, "version.dll");
|
||||
using (var fileStream = File.Create(destPath))
|
||||
{
|
||||
dll.CopyTo(fileStream);
|
||||
}
|
||||
_logger("[PATCHER] Proxy DLL attached", ELogType.Info);
|
||||
}
|
||||
|
||||
public void Patch()
|
||||
{
|
||||
Common.TryKillProcess(_weModConfig.BrandName);
|
||||
if (!File.Exists(_backupPath))
|
||||
{
|
||||
_logger("[PATCHER] Creating backup...", ELogType.Info);
|
||||
File.Copy(_asarPath, _backupPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger("[PATCHER] Backup already exists", ELogType.Warn);
|
||||
}
|
||||
|
||||
if(!File.Exists(_asarPath))
|
||||
{
|
||||
throw new Exception("app.asar not found");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_logger("[PATCHER] Extracting app.asar...", ELogType.Info);
|
||||
AsarExtractor.ExtractAll(_asarPath, _unpackedPath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception($"[PATCHER] Failed to unpack app.asar: {e.Message}");
|
||||
}
|
||||
|
||||
PatchAsar();
|
||||
|
||||
try
|
||||
{
|
||||
new AsarCreator(_unpackedPath, _asarPath, new CreateOptions
|
||||
{
|
||||
Unpack = new Regex(@"^static\\unpacked.*$")
|
||||
}).CreatePackageWithOptions();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception($"[PATCHER] Failed to pack app.asar: {e.Message}");
|
||||
}
|
||||
|
||||
AttachProxyDll();
|
||||
|
||||
_logger("[PATCHER] Done!", ELogType.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using WeModPatcher.Models;
|
||||
|
||||
namespace WeModPatcher.Core
|
||||
{
|
||||
public static class PatcherConfig
|
||||
{
|
||||
public class ResolveContext
|
||||
{
|
||||
public string Placeholder { get; set; }
|
||||
public Func<string, string> Handler { get; set; }
|
||||
}
|
||||
|
||||
public class PatchEntry
|
||||
{
|
||||
public Regex Target { get; set; }
|
||||
public string Patch { get; set; }
|
||||
public string Name { get; set; }
|
||||
public bool Applied { get; set; }
|
||||
public bool SingleMatch { get; set; } = true;
|
||||
public ResolveContext Resolver { get; set; }
|
||||
}
|
||||
|
||||
public static Dictionary<EPatchType, PatchEntry[]> GetInstance()
|
||||
{
|
||||
return new Dictionary<EPatchType, PatchEntry[]>()
|
||||
{
|
||||
{
|
||||
EPatchType.ActivatePro,
|
||||
new[]
|
||||
{
|
||||
new PatchEntry
|
||||
{
|
||||
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;})}"
|
||||
},
|
||||
new PatchEntry
|
||||
{
|
||||
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;})}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
EPatchType.DisableUpdates,
|
||||
new[]
|
||||
{
|
||||
new PatchEntry
|
||||
{
|
||||
Target = new Regex(@"registerHandler\(""ACTION_CHECK_FOR_UPDATE"".*?\)\)\)\)",
|
||||
RegexOptions.Singleline),
|
||||
Patch = "registerHandler(\"ACTION_CHECK_FOR_UPDATE\",(e=>expectUpdateFeedUrl(e,(e=>null)))"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
EPatchType.DevToolsOnF12,
|
||||
new[]
|
||||
{
|
||||
new PatchEntry
|
||||
{
|
||||
Resolver = new ResolveContext
|
||||
{
|
||||
Handler = (matchContent) => {
|
||||
var match = Regex.Match(matchContent, @"this\.#(\w+)\(""ACTION_OPEN_DEV_TOOLS""\)");
|
||||
return match.Success ? match.Groups[1].Value : null;
|
||||
},
|
||||
Placeholder = "<dispatch_method>"
|
||||
},
|
||||
Target = new Regex(@"document\.addEventListener\(""keydown"",\s*\((?<arg>\w+)\s*=>\s*\{[^}]*?""ACTION_OPEN_DEV_TOOLS""[^}]*?\}\)\)", RegexOptions.Singleline),
|
||||
Patch = "document.addEventListener(\"keydown\",(${arg}=>{\"F12\"!==${arg}.key||this.#<dispatch_method>(\"ACTION_OPEN_DEV_TOOLS\")}))"
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using WeModPatcher.Models;
|
||||
|
||||
namespace WeModPatcher.Utils
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static WeModConfig CheckWeModPath(string versionRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
foreach (var name in Constants.WeModBrandNames)
|
||||
{
|
||||
var exeName = $"{name}.exe";
|
||||
var path = Path.Combine(versionRoot, exeName);
|
||||
if (File.Exists(path) && File.Exists(Path.Combine(versionRoot, "resources", "app.asar")))
|
||||
{
|
||||
return new WeModConfig
|
||||
{
|
||||
BrandName = name,
|
||||
ExecutableName = exeName,
|
||||
RootDirectory = versionRoot
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static WeModConfig FindWeMod()
|
||||
{
|
||||
string localAppDataPath = Environment.GetEnvironmentVariable("LOCALAPPDATA");
|
||||
|
||||
foreach (var folder in Constants.WeModBrandNames)
|
||||
{
|
||||
var weModDir = Path.Combine(localAppDataPath ?? "", folder);
|
||||
if(Directory.Exists(weModDir))
|
||||
{
|
||||
return FindLatestWeMod(weModDir);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string Base64Decode(string base64EncodedData)
|
||||
{
|
||||
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
|
||||
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
|
||||
}
|
||||
|
||||
public static string Base64Encode(string plainText)
|
||||
{
|
||||
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
|
||||
return System.Convert.ToBase64String(plainTextBytes);
|
||||
}
|
||||
|
||||
public static WeModConfig FindLatestWeMod(string root)
|
||||
{
|
||||
var appFolders = Directory.EnumerateDirectories(root)
|
||||
.Select(folderPath => new DirectoryInfo(folderPath))
|
||||
.Where(dirInfo => Regex.IsMatch(dirInfo.Name, @"^app-\w+"))
|
||||
.Select(dirInfo => new
|
||||
{
|
||||
Name = dirInfo.Name,
|
||||
Path = dirInfo.FullName,
|
||||
LastModified = dirInfo.LastWriteTime
|
||||
})
|
||||
.OrderByDescending(item => item.LastModified)
|
||||
.ToList();
|
||||
|
||||
|
||||
return appFolders
|
||||
.Select(folder => CheckWeModPath(folder.Path))
|
||||
.FirstOrDefault(config => config != null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using System.Net.Http;
|
||||
using System.Windows;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace WeModPatcher.Utils
|
||||
{
|
||||
public class GitHubRelease
|
||||
{
|
||||
public class AssetsType
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonProperty("browser_download_url")]
|
||||
public string Url { get; set; }
|
||||
}
|
||||
|
||||
[JsonProperty("tag_name")]
|
||||
public string TagName { get; set; }
|
||||
|
||||
[JsonProperty("assets")]
|
||||
public AssetsType[] Assets { get; set; }
|
||||
|
||||
}
|
||||
|
||||
public class Updater
|
||||
{
|
||||
private GitHubRelease _release = null;
|
||||
private static readonly HttpClient _httpClient = new HttpClient()
|
||||
{
|
||||
DefaultRequestHeaders =
|
||||
{
|
||||
{ "User-Agent", "GitHub-Updater" }
|
||||
}
|
||||
};
|
||||
|
||||
private static readonly string ApiUrl = $"https://api.github.com/repos/{Constants.Owner}/{Constants.RepoName}/releases/latest";
|
||||
public async Task<bool> CheckForUpdates()
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
|
||||
var response = await _httpClient.GetAsync(ApiUrl);
|
||||
response.EnsureSuccessStatusCode();
|
||||
_release = JsonConvert.DeserializeObject<GitHubRelease>(await response.Content.ReadAsStringAsync());
|
||||
|
||||
if (_release == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var latestVersion = new Version(_release.TagName);
|
||||
|
||||
return latestVersion > currentVersion;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Update()
|
||||
{
|
||||
if (_release == null)
|
||||
{
|
||||
throw new Exception("No release found");
|
||||
}
|
||||
|
||||
var asset = _release.Assets.FirstOrDefault(o => o.Name.EndsWith(".exe"));
|
||||
if(asset == null)
|
||||
{
|
||||
throw new Exception("No asset found");
|
||||
}
|
||||
|
||||
// download to temp
|
||||
var downloadPath = Path.Combine(Path.GetTempPath(), asset.Name);
|
||||
|
||||
using(var response = await _httpClient.GetAsync(asset.Url))
|
||||
using(var fileStream = File.Create(downloadPath))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
await response.Content.CopyToAsync(fileStream);
|
||||
}
|
||||
|
||||
ApplyUpdate(downloadPath);
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static void ApplyUpdate(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentExecutable = Assembly.GetExecutingAssembly().Location;
|
||||
|
||||
var psCommand = $"Start-Sleep -Seconds 2; " +
|
||||
$"Copy-Item -Path '{filePath}' -Destination '{currentExecutable}' -Force; " +
|
||||
$"Remove-Item -Path '{filePath}' -Force; " +
|
||||
$"Start-Sleep -Seconds 1; " +
|
||||
$"Start-Process -FilePath '{currentExecutable}';";
|
||||
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = "powershell.exe",
|
||||
Arguments = $"-WindowStyle Hidden -ExecutionPolicy Bypass -Command \"{psCommand}\"",
|
||||
UseShellExecute = true,
|
||||
CreateNoWindow = true,
|
||||
WindowStyle = ProcessWindowStyle.Hidden
|
||||
};
|
||||
|
||||
Process.Start(startInfo);
|
||||
|
||||
Task.Delay(500).ContinueWith(_ =>
|
||||
{
|
||||
App.Shutdown();
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Update failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
<UserControl x:Class="WeModPatcher.View.Popups.PatchVectorsPopup"
|
||||
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:WeModPatcher.View.Popups"
|
||||
xmlns:controls="clr-namespace:WeModPatcher.View.Controls"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="Auto" d:DesignWidth="Auto"
|
||||
Background="{DynamicResource Background}"
|
||||
Foreground="{DynamicResource MutedForeground}"
|
||||
FontWeight="Medium"
|
||||
FontSize="13">
|
||||
<Grid>
|
||||
<Grid Visibility="Visible" Margin="0 0 5 0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="27" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" VerticalAlignment="Center" Text="{DynamicResource pv_activate_pro}" />
|
||||
<CheckBox Grid.Row="0" x:Name="ActivateProBox" HorizontalAlignment="Right" VerticalAlignment="Center"
|
||||
IsChecked="True" />
|
||||
|
||||
<TextBlock Grid.Row="1" VerticalAlignment="Center" Text="{DynamicResource pv_devtools}" />
|
||||
<CheckBox Grid.Row="1" x:Name="DevToolsHotkeyBox" HorizontalAlignment="Right" VerticalAlignment="Center" />
|
||||
|
||||
<TextBlock Grid.Row="2" VerticalAlignment="Center" Text="{DynamicResource pv_disable_updates}" />
|
||||
<CheckBox Grid.Row="2" x:Name="DisableUpdateBox" HorizontalAlignment="Right" VerticalAlignment="Center" />
|
||||
|
||||
<!--<TextBlock
|
||||
ToolTip="Disable if you want to use older versions separately and manage versions manually via different shortcuts"
|
||||
ToolTipService.InitialShowDelay="300"
|
||||
Grid.Row="3" VerticalAlignment="Center">
|
||||
Apply the patch to new versions <LineBreak /> automatically (hover to see more)
|
||||
</TextBlock>
|
||||
<CheckBox Grid.Row="3" x:Name="AutoUpdates" HorizontalAlignment="Right" VerticalAlignment="Center"
|
||||
IsChecked="True" />-->
|
||||
|
||||
<Button Grid.Row="3" Padding="0 5 0 5" Margin="0 15 0 0" Content="{DynamicResource pv_start}"
|
||||
Click="OnPatchButtonClick" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
</UserControl>
|
||||
@@ -1,51 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using WeModPatcher.Models;
|
||||
using WeModPatcher.View.Controls;
|
||||
|
||||
namespace WeModPatcher.View.Popups
|
||||
{
|
||||
public partial class PatchVectorsPopup : UserControl
|
||||
{
|
||||
private readonly Action<PatchConfig> _onApply;
|
||||
|
||||
public PatchVectorsPopup(Action<PatchConfig> onApply)
|
||||
{
|
||||
_onApply = onApply;
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void OnPatchButtonClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (ActivateProBox.IsChecked != true && DisableUpdateBox.IsChecked != true &&
|
||||
DevToolsHotkeyBox.IsChecked != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var result = new HashSet<EPatchType>();
|
||||
if (ActivateProBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.ActivatePro);
|
||||
}
|
||||
|
||||
if (DisableUpdateBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.DisableUpdates);
|
||||
}
|
||||
|
||||
if (DevToolsHotkeyBox.IsChecked == true)
|
||||
{
|
||||
result.Add(EPatchType.DevToolsOnF12);
|
||||
}
|
||||
|
||||
_onApply(new PatchConfig
|
||||
{
|
||||
PatchTypes = result,
|
||||
AutoApplyPatches =/* AutoUpdates.IsChecked == true*/ false
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<UserControl x:Class="WeModPatcher.View.Popups.UpdatePopup"
|
||||
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:WeModPatcher.View.Popups"
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="Auto" d:DesignWidth="Auto"
|
||||
Background="{DynamicResource Background}"
|
||||
Foreground="{DynamicResource MutedForeground}"
|
||||
FontWeight="Medium"
|
||||
FontSize="13">
|
||||
<StackPanel>
|
||||
|
||||
<TextBlock Foreground="Red" MaxWidth="320" TextAlignment="Center" Text="{DynamicResource up_warning}" TextWrapping="Wrap" />
|
||||
|
||||
<Button Padding="0 5 0 5" Margin="0 15 0 0" Content="{DynamicResource up_update_now}"
|
||||
Click="OnUpdateClick" />
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace WeModPatcher.View.Popups
|
||||
{
|
||||
public partial class UpdatePopup : UserControl
|
||||
{
|
||||
private readonly Action _onUpdate;
|
||||
|
||||
public UpdatePopup(Action onUpdate)
|
||||
{
|
||||
_onUpdate = onUpdate;
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void OnUpdateClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
_onUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 177 KiB |
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0build.ps1" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,121 @@
|
||||
param(
|
||||
[ValidateSet('Debug', 'Release')]
|
||||
[string]$Configuration = 'Release'
|
||||
)
|
||||
|
||||
$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 {
|
||||
param([string]$Name)
|
||||
|
||||
$command = Get-Command $Name -ErrorAction SilentlyContinue
|
||||
if (-not $command) {
|
||||
throw "Required command not found in PATH: $Name"
|
||||
}
|
||||
|
||||
return $command.Source
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
$installationPath = & $vswhere -latest -prerelease -products '*' -requires Microsoft.Component.MSBuild -property installationPath
|
||||
if ([string]::IsNullOrWhiteSpace($installationPath)) {
|
||||
throw 'Visual Studio with MSBuild was not found.'
|
||||
}
|
||||
|
||||
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"
|
||||
}
|
||||
|
||||
return $msbuildPath
|
||||
}
|
||||
|
||||
function Resolve-DumpBinPath {
|
||||
param([string]$VisualStudioPath)
|
||||
|
||||
$versionFile = Join-Path $VisualStudioPath 'VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt'
|
||||
if (-not (Test-Path $versionFile)) {
|
||||
throw "MSVC tools version file not found: $versionFile"
|
||||
}
|
||||
|
||||
$toolsVersion = (Get-Content $versionFile -Raw).Trim()
|
||||
$dumpBinPath = Join-Path $VisualStudioPath "VC\Tools\MSVC\$toolsVersion\bin\Hostx64\x64\dumpbin.exe"
|
||||
if (-not (Test-Path $dumpBinPath)) {
|
||||
throw "dumpbin.exe not found: $dumpBinPath"
|
||||
}
|
||||
|
||||
return $dumpBinPath
|
||||
}
|
||||
|
||||
function Invoke-Step {
|
||||
param(
|
||||
[string]$Label,
|
||||
[scriptblock]$Action
|
||||
)
|
||||
|
||||
Write-Host "==> $Label" -ForegroundColor Cyan
|
||||
& $Action
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Step failed: $Label"
|
||||
}
|
||||
}
|
||||
|
||||
$cmake = Resolve-CommandPath 'cmake'
|
||||
$pnpm = Resolve-CommandPath 'pnpm'
|
||||
$visualStudio = Resolve-VisualStudioPath
|
||||
$msbuild = Resolve-MSBuildPath $visualStudio
|
||||
$dumpBin = Resolve-DumpBinPath $visualStudio
|
||||
|
||||
Invoke-Step 'Install web-panel dependencies' {
|
||||
& $pnpm --dir $webPanelDir install --frozen-lockfile
|
||||
}
|
||||
|
||||
Invoke-Step 'Build web-panel' {
|
||||
& $pnpm --dir $webPanelDir run build
|
||||
}
|
||||
|
||||
Invoke-Step 'Configure asar-fuses-bypass' {
|
||||
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 'Verify native runtime dependencies' {
|
||||
$nativeDll = Join-Path $asarFusesBuildDir "$Configuration\version.dll"
|
||||
$dependencies = & $dumpBin /dependents $nativeDll
|
||||
if ($dependencies -match '(?im)^\s*(VCRUNTIME|MSVCP|api-ms-win-crt-)[^\s]*\.dll\s*$') {
|
||||
throw 'version.dll depends on the dynamic Visual C++ runtime.'
|
||||
}
|
||||
}
|
||||
|
||||
Invoke-Step 'Restore NuGet packages' {
|
||||
& $msbuild $solutionPath /m /t:Restore /p:RestorePackagesConfig=true
|
||||
}
|
||||
|
||||
Invoke-Step 'Build solution' {
|
||||
& $msbuild $solutionPath /m /p:Configuration=$Configuration '/p:Platform=Any CPU' /t:Build
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host "Build completed successfully ($Configuration)." -ForegroundColor Green
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
script_path="$script_dir/build.ps1"
|
||||
|
||||
if command -v cygpath >/dev/null 2>&1; then
|
||||
script_path="$(cygpath -w "$script_path")"
|
||||
fi
|
||||
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "$script_path" "$@"
|
||||
@@ -0,0 +1,81 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Version,
|
||||
|
||||
[string]$OutputPath
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$changelogPath = Join-Path $repoRoot 'CHANGELOG.md'
|
||||
|
||||
function Normalize-Version {
|
||||
param([string]$Value)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Value)) {
|
||||
throw 'Version value cannot be empty.'
|
||||
}
|
||||
|
||||
return $Value.Trim().TrimStart('v', 'V')
|
||||
}
|
||||
|
||||
function Get-ChangelogSection {
|
||||
param(
|
||||
[string]$Content,
|
||||
[string]$TargetVersion
|
||||
)
|
||||
|
||||
$normalizedTargetVersion = Normalize-Version $TargetVersion
|
||||
$normalizedContent = $Content -replace "`r`n", "`n" -replace "`r", "`n"
|
||||
$lines = $normalizedContent -split "`n"
|
||||
$builder = New-Object System.Text.StringBuilder
|
||||
$isInsideSection = $false
|
||||
|
||||
foreach ($line in $lines) {
|
||||
$match = [regex]::Match($line, '^##\s+\[(?<version>[^\]]+)\]')
|
||||
if ($match.Success) {
|
||||
if ($isInsideSection) {
|
||||
break
|
||||
}
|
||||
|
||||
$isInsideSection = (Normalize-Version $match.Groups['version'].Value) -eq $normalizedTargetVersion
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $isInsideSection) {
|
||||
continue
|
||||
}
|
||||
|
||||
[void]$builder.AppendLine($line)
|
||||
}
|
||||
|
||||
return $builder.ToString().Trim()
|
||||
}
|
||||
|
||||
if (-not (Test-Path $changelogPath)) {
|
||||
throw "CHANGELOG.md not found: $changelogPath"
|
||||
}
|
||||
|
||||
$changelogContent = Get-Content -Path $changelogPath -Raw
|
||||
$section = Get-ChangelogSection -Content $changelogContent -TargetVersion $Version
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($section)) {
|
||||
throw "Changelog section for version '$(Normalize-Version $Version)' was not found in CHANGELOG.md."
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
|
||||
Write-Output $section
|
||||
exit 0
|
||||
}
|
||||
|
||||
$resolvedOutputPath = if ([System.IO.Path]::IsPathRooted($OutputPath)) {
|
||||
$OutputPath
|
||||
}
|
||||
else {
|
||||
Join-Path $repoRoot $OutputPath
|
||||
}
|
||||
|
||||
Set-Content -Path $resolvedOutputPath -Value $section -Encoding utf8
|
||||
Write-Host "Wrote changelog section to $resolvedOutputPath"
|
||||
@@ -0,0 +1,111 @@
|
||||
param(
|
||||
[string]$ExpectedVersion
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$assemblyInfoPath = Join-Path $repoRoot 'WandEnhancer\Properties\AssemblyInfo.cs'
|
||||
$changelogPath = Join-Path $repoRoot 'CHANGELOG.md'
|
||||
|
||||
function Normalize-Version {
|
||||
param([string]$Value)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Value)) {
|
||||
throw 'Version value cannot be empty.'
|
||||
}
|
||||
|
||||
return $Value.Trim().TrimStart('v', 'V')
|
||||
}
|
||||
|
||||
function Get-ChangelogSection {
|
||||
param(
|
||||
[string]$Content,
|
||||
[string]$TargetVersion
|
||||
)
|
||||
|
||||
$normalizedTargetVersion = Normalize-Version $TargetVersion
|
||||
$normalizedContent = $Content -replace "`r`n", "`n" -replace "`r", "`n"
|
||||
$lines = $normalizedContent -split "`n"
|
||||
$builder = New-Object System.Text.StringBuilder
|
||||
$isInsideSection = $false
|
||||
|
||||
foreach ($line in $lines) {
|
||||
$match = [regex]::Match($line, '^##\s+\[(?<version>[^\]]+)\]')
|
||||
if ($match.Success) {
|
||||
if ($isInsideSection) {
|
||||
break
|
||||
}
|
||||
|
||||
$isInsideSection = (Normalize-Version $match.Groups['version'].Value) -eq $normalizedTargetVersion
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $isInsideSection) {
|
||||
continue
|
||||
}
|
||||
|
||||
[void]$builder.AppendLine($line)
|
||||
}
|
||||
|
||||
return $builder.ToString().Trim()
|
||||
}
|
||||
|
||||
if (-not (Test-Path $assemblyInfoPath)) {
|
||||
throw "AssemblyInfo.cs not found: $assemblyInfoPath"
|
||||
}
|
||||
|
||||
if (-not (Test-Path $changelogPath)) {
|
||||
throw "CHANGELOG.md not found: $changelogPath"
|
||||
}
|
||||
|
||||
$assemblyInfoContent = Get-Content -Path $assemblyInfoPath -Raw
|
||||
$changelogContent = Get-Content -Path $changelogPath -Raw
|
||||
|
||||
$assemblyVersionMatch = [regex]::Match($assemblyInfoContent, '(?m)^\s*\[assembly:\s*AssemblyVersion\("(?<version>[^"]+)"\)\]')
|
||||
$fileVersionMatch = [regex]::Match($assemblyInfoContent, '(?m)^\s*\[assembly:\s*AssemblyFileVersion\("(?<version>[^"]+)"\)\]')
|
||||
|
||||
if (-not $assemblyVersionMatch.Success) {
|
||||
throw 'AssemblyVersion was not found in AssemblyInfo.cs.'
|
||||
}
|
||||
|
||||
if (-not $fileVersionMatch.Success) {
|
||||
throw 'AssemblyFileVersion was not found in AssemblyInfo.cs.'
|
||||
}
|
||||
|
||||
$assemblyVersion = Normalize-Version $assemblyVersionMatch.Groups['version'].Value
|
||||
$fileVersion = Normalize-Version $fileVersionMatch.Groups['version'].Value
|
||||
|
||||
if ($assemblyVersion -ne $fileVersion) {
|
||||
throw "AssemblyVersion ($assemblyVersion) and AssemblyFileVersion ($fileVersion) must match."
|
||||
}
|
||||
|
||||
$changelogVersionMatches = [regex]::Matches($changelogContent, '(?m)^##\s+\[(?<version>[^\]]+)\]')
|
||||
if ($changelogVersionMatches.Count -eq 0) {
|
||||
throw 'CHANGELOG.md must contain at least one version section.'
|
||||
}
|
||||
|
||||
$latestChangelogVersion = Normalize-Version $changelogVersionMatches[0].Groups['version'].Value
|
||||
if ($latestChangelogVersion -ne $assemblyVersion) {
|
||||
throw "The first CHANGELOG.md section ($latestChangelogVersion) must match AssemblyInfo.cs version ($assemblyVersion)."
|
||||
}
|
||||
|
||||
$latestSection = Get-ChangelogSection -Content $changelogContent -TargetVersion $assemblyVersion
|
||||
if ([string]::IsNullOrWhiteSpace($latestSection)) {
|
||||
throw "CHANGELOG.md section '$assemblyVersion' is empty."
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($ExpectedVersion)) {
|
||||
$normalizedExpectedVersion = Normalize-Version $ExpectedVersion
|
||||
if ($normalizedExpectedVersion -ne $assemblyVersion) {
|
||||
throw "Release tag version ($normalizedExpectedVersion) must match AssemblyInfo.cs version ($assemblyVersion)."
|
||||
}
|
||||
|
||||
$expectedSection = Get-ChangelogSection -Content $changelogContent -TargetVersion $normalizedExpectedVersion
|
||||
if ([string]::IsNullOrWhiteSpace($expectedSection)) {
|
||||
throw "CHANGELOG.md section '$normalizedExpectedVersion' is missing or empty."
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Validated release metadata for version $assemblyVersion"
|
||||
@@ -1,4 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
cmake_policy(SET CMP0091 NEW)
|
||||
project(asar_fuses_bypass C)
|
||||
|
||||
set(CMAKE_C_STANDARD 11)
|
||||
@@ -10,6 +11,11 @@ add_executable(asar_fuses_bypass main.c)
|
||||
set(CMAKE_SHARED_LIBRARY_PREFIX "")
|
||||
set(CMAKE_STATIC_LIBRARY_PREFIX "")
|
||||
|
||||
add_link_options(-static -static-libgcc -static-libstdc++)
|
||||
add_library(version SHARED library.c library.def fuses.c)
|
||||
|
||||
add_library(version SHARED library.c library.def fuses.c)
|
||||
if(MSVC)
|
||||
set_property(TARGET version PROPERTY
|
||||
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
|
||||
target_link_options(version PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
|
||||
@@ -2,87 +2,146 @@
|
||||
// Created by kitbyte on 30.11.2025.
|
||||
//
|
||||
#include <Windows.h>
|
||||
#include <winver.h>
|
||||
|
||||
extern BOOL disable_asar_integrity(void);
|
||||
|
||||
#ifdef _WIN64
|
||||
#define WRAPPER_GENFUNC(name) \
|
||||
FARPROC orig_##name; \
|
||||
void _##name(); \
|
||||
__asm__( \
|
||||
".global _" #name "\n" \
|
||||
"_" #name ":\n" \
|
||||
" movq orig_" #name "(%rip), %rax\n" \
|
||||
" jmp *%rax\n" \
|
||||
);
|
||||
#else
|
||||
#define WRAPPER_GENFUNC(name) \
|
||||
FARPROC orig_##name; \
|
||||
__declspec(naked) void _##name() \
|
||||
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 \
|
||||
{ \
|
||||
asm("jmp *_orig_"#name); \
|
||||
}
|
||||
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
|
||||
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoA)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoByHandle)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoExW)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoExA)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoSizeA)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoSizeExA)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoSizeExW)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoSizeW)
|
||||
WRAPPER_GENFUNC(GetFileVersionInfoW)
|
||||
WRAPPER_GENFUNC(VerFindFileA)
|
||||
WRAPPER_GENFUNC(VerFindFileW)
|
||||
WRAPPER_GENFUNC(VerInstallFileA)
|
||||
WRAPPER_GENFUNC(VerInstallFileW)
|
||||
WRAPPER_GENFUNC(VerLanguageNameA)
|
||||
WRAPPER_GENFUNC(VerLanguageNameW)
|
||||
WRAPPER_GENFUNC(VerQueryValueA)
|
||||
WRAPPER_GENFUNC(VerQueryValueW)
|
||||
FOR_EACH_VERSION_FORWARDER(DECLARE_FORWARDER)
|
||||
|
||||
#define WRAPPER_FUNC(name) orig_##name = GetProcAddress(hOriginalDll, #name);
|
||||
|
||||
void SourceInit()
|
||||
BOOL WINAPI GetFileVersionInfoByHandle(void)
|
||||
{
|
||||
TCHAR source[MAX_PATH];
|
||||
GetSystemDirectory(source, MAX_PATH);
|
||||
strcat_s(source, sizeof source, "\\version.dll");
|
||||
HMODULE hOriginalDll = LoadLibrary(source);
|
||||
|
||||
WRAPPER_FUNC(GetFileVersionInfoA);
|
||||
WRAPPER_FUNC(GetFileVersionInfoByHandle);
|
||||
WRAPPER_FUNC(GetFileVersionInfoExW);
|
||||
WRAPPER_FUNC(GetFileVersionInfoExA);
|
||||
WRAPPER_FUNC(GetFileVersionInfoSizeA);
|
||||
WRAPPER_FUNC(GetFileVersionInfoSizeExW);
|
||||
WRAPPER_FUNC(GetFileVersionInfoSizeExA);
|
||||
WRAPPER_FUNC(GetFileVersionInfoSizeW);
|
||||
WRAPPER_FUNC(GetFileVersionInfoW);
|
||||
WRAPPER_FUNC(VerFindFileA);
|
||||
WRAPPER_FUNC(VerFindFileW);
|
||||
WRAPPER_FUNC(VerInstallFileA);
|
||||
WRAPPER_FUNC(VerInstallFileW);
|
||||
WRAPPER_FUNC(VerLanguageNameA);
|
||||
WRAPPER_FUNC(VerLanguageNameW);
|
||||
WRAPPER_FUNC(VerQueryValueA);
|
||||
WRAPPER_FUNC(VerQueryValueW);
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
|
||||
void Payload()
|
||||
static BOOL SourceInit(void)
|
||||
{
|
||||
disable_asar_integrity();
|
||||
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);
|
||||
SourceInit();
|
||||
Payload();
|
||||
|
||||
if (!SourceInit())
|
||||
{
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
disable_asar_integrity();
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
@@ -1,20 +1,20 @@
|
||||
LIBRARY "VERSION"
|
||||
EXPORTS
|
||||
|
||||
GetFileVersionInfoA = _GetFileVersionInfoA
|
||||
GetFileVersionInfoByHandle = _GetFileVersionInfoByHandle
|
||||
GetFileVersionInfoExA = _GetFileVersionInfoExA
|
||||
GetFileVersionInfoExW = _GetFileVersionInfoExW
|
||||
GetFileVersionInfoSizeA = _GetFileVersionInfoSizeA
|
||||
GetFileVersionInfoSizeExA = _GetFileVersionInfoSizeExA
|
||||
GetFileVersionInfoSizeExW = _GetFileVersionInfoSizeExW
|
||||
GetFileVersionInfoSizeW = _GetFileVersionInfoSizeW
|
||||
GetFileVersionInfoW = _GetFileVersionInfoW
|
||||
VerFindFileA = _VerFindFileA
|
||||
VerFindFileW = _VerFindFileW
|
||||
VerInstallFileA = _VerInstallFileA
|
||||
VerInstallFileW = _VerInstallFileW
|
||||
VerLanguageNameA = _VerLanguageNameA
|
||||
VerLanguageNameW = _VerLanguageNameW
|
||||
VerQueryValueA = _VerQueryValueA
|
||||
VerQueryValueW = _VerQueryValueW
|
||||
GetFileVersionInfoA
|
||||
GetFileVersionInfoByHandle
|
||||
GetFileVersionInfoExA
|
||||
GetFileVersionInfoExW
|
||||
GetFileVersionInfoSizeA
|
||||
GetFileVersionInfoSizeExA
|
||||
GetFileVersionInfoSizeExW
|
||||
GetFileVersionInfoSizeW
|
||||
GetFileVersionInfoW
|
||||
VerFindFileA
|
||||
VerFindFileW
|
||||
VerInstallFileA
|
||||
VerInstallFileW
|
||||
VerLanguageNameA
|
||||
VerLanguageNameW
|
||||
VerQueryValueA
|
||||
VerQueryValueW
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Compiled lingui catalogs — generated from .po by `lingui compile`; the app
|
||||
# loads .po directly via @lingui/vite-plugin, so these are build artifacts.
|
||||
src/locales/**/*.js
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
coverage/
|
||||
.pnpm-store/
|
||||
pnpm-lock.yaml
|
||||
package-lock.json
|
||||
pnpm-lock.yaml
|
||||
yarn.lock
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"endOfLine": "lf",
|
||||
"semi": false,
|
||||
"singleQuote": false,
|
||||
"tabWidth": 2,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 80,
|
||||
"plugins": ["prettier-plugin-tailwindcss"],
|
||||
"tailwindStylesheet": "src/index.css",
|
||||
"tailwindFunctions": ["cn", "cva"]
|
||||
}
|
||||
Vendored
+254
@@ -0,0 +1,254 @@
|
||||
Use these rules as defaults, not as a reason to add ceremonial folders or wrapper layers.
|
||||
|
||||
## Core Principles
|
||||
|
||||
- Organize code around product capabilities, not framework vocabulary.
|
||||
- Keep related UI, state, rules, and data access close until a real boundary justifies moving
|
||||
them apart.
|
||||
- Dependencies point from composition and UI toward stable rules and narrow capabilities.
|
||||
- Protect rendering code from business, state-management, and infrastructure complexity.
|
||||
- Keep one source of truth and derive everything else.
|
||||
- Apply KISS, YAGNI, and DRY together. Remove duplicated knowledge, not merely similar syntax.
|
||||
- Prefer explicit, readable flow over clever abstractions and hidden behavior.
|
||||
|
||||
## Screaming Architecture
|
||||
|
||||
The repository structure and public APIs should reveal what the product does.
|
||||
|
||||
Prefer:
|
||||
|
||||
```text
|
||||
features/
|
||||
checkout/
|
||||
search/
|
||||
account-security/
|
||||
```
|
||||
|
||||
Avoid making the application read primarily as:
|
||||
|
||||
```text
|
||||
components/
|
||||
hooks/
|
||||
services/
|
||||
stores/
|
||||
utils/
|
||||
```
|
||||
|
||||
Technical folders are useful inside a capability, where their owner is clear. Generic top-level
|
||||
folders easily become dependency magnets with unclear ownership.
|
||||
|
||||
Names should use product language. Prefer `useCheckoutSummary`, `reserveStock`, and
|
||||
`AccountSecurityPanel` over `useData`, `processItems`, and `GenericPanel`.
|
||||
|
||||
## Suggested Structure
|
||||
|
||||
Start with the smallest structure that makes ownership obvious:
|
||||
|
||||
```text
|
||||
src/
|
||||
app/ startup, providers, router, global composition
|
||||
pages/ route-level composition
|
||||
features/
|
||||
<capability>/
|
||||
index.ts optional public API
|
||||
ui/ optional rendering components
|
||||
model/ optional state, view models, decisions
|
||||
api/ optional external data access
|
||||
lib/ optional feature-local pure helpers
|
||||
domains/ optional shared product rules and types
|
||||
shared/
|
||||
ui/ domain-free visual primitives
|
||||
api/ generic transport/query infrastructure
|
||||
lib/ genuinely generic pure helpers
|
||||
```
|
||||
|
||||
Folders are created when they contain a real responsibility. A small feature may be one cohesive
|
||||
file. Do not create empty layers in anticipation of future complexity.
|
||||
|
||||
## Dependency Direction
|
||||
|
||||
- `app` installs providers, constructs dependencies, and composes the application.
|
||||
- `pages` compose capabilities for a route. They do not own business rules or data protocols.
|
||||
- A feature owns one user-recognizable capability end to end.
|
||||
- Feature UI consumes its own model/view-model API, not raw infrastructure.
|
||||
- Shared domain code contains reusable product rules and stays independent of React and I/O.
|
||||
- `shared` contains only domain-free code. Product-specific code is not shared merely because
|
||||
two files use it.
|
||||
- Avoid feature-to-feature imports. Compose features in a page, promote truly shared rules to a
|
||||
domain module, or introduce a named workflow when coordination is the actual responsibility.
|
||||
- Cyclic imports are an architecture problem, not something to solve with a tooling workaround.
|
||||
|
||||
For a simple feature, direct `ui -> model -> api` dependencies are sufficient. Introduce ports,
|
||||
facades, dependency injection, or workflows only when they hide real complexity, enable
|
||||
important tests, or separate unstable infrastructure.
|
||||
|
||||
## Make Composition Read Like The Product
|
||||
|
||||
Pages and other composition boundaries should use capability-level APIs.
|
||||
|
||||
Prefer:
|
||||
|
||||
```tsx
|
||||
<CheckoutSummary />
|
||||
<PlaceOrderButton />
|
||||
```
|
||||
|
||||
Over:
|
||||
|
||||
```tsx
|
||||
<Card>
|
||||
<Select options={paymentOptions} onChange={handlePaymentChange} />
|
||||
<Button onClick={handleSubmit}>Submit</Button>
|
||||
</Card>
|
||||
```
|
||||
|
||||
The second version makes the page understand checkout behavior and low-level UI configuration.
|
||||
That knowledge belongs to the checkout capability.
|
||||
|
||||
This does not mean wrapping every native element or design-system primitive. Semantic HTML and
|
||||
visual primitives are correct inside feature UI. Create a capability component when it hides
|
||||
product behavior or gives composition code a clearer product-level API.
|
||||
|
||||
Avoid "raw components" whose consumers must know internal options, state transitions, query
|
||||
shapes, or protocol details. Avoid generic configuration-driven components that combine
|
||||
unrelated product modes behind dozens of props.
|
||||
|
||||
## UI Boundary
|
||||
|
||||
- Components render data and translate DOM events into named user intents.
|
||||
- Keep business decisions, data mapping, persistence, protocol handling, and multi-step async
|
||||
flows outside rendering components.
|
||||
- UI receives render-ready values. It should not reconstruct domain meaning from raw DTOs.
|
||||
- Prefer intent props and commands such as `onApprove`, `renameProject`, or `submitOrder` over
|
||||
generic `onChange`, `setState`, or `patch` APIs at capability boundaries.
|
||||
- Keep ephemeral visual state local: focus, hover, open/closed, and uncommitted input usually
|
||||
belong in the component.
|
||||
- Split components by responsibility and API clarity, not by arbitrary line limits.
|
||||
- Prefer slots and composition over components with many layout modes and boolean props.
|
||||
- Use semantic HTML and preserve accessibility behavior.
|
||||
|
||||
A view-model hook is useful when it protects UI from state shape, async coordination, or business
|
||||
decisions. Do not create a pass-through hook that only renames one value to satisfy a diagram.
|
||||
|
||||
## State Ownership
|
||||
|
||||
Choose the smallest correct owner:
|
||||
|
||||
| State | Preferred owner |
|
||||
| --- | --- |
|
||||
| Ephemeral visual state | local component state |
|
||||
| Uncommitted form state | the form or feature |
|
||||
| URL/shareable navigation state | the router/URL |
|
||||
| Remote server resource and cache | a query/cache layer |
|
||||
| Shared capability state | that feature's model/store |
|
||||
| Cross-capability process | a named workflow or app-level model |
|
||||
|
||||
- A store is not a bucket for every value used by several components.
|
||||
- Split state by capability and lifecycle, not by data type.
|
||||
- Expose narrow selectors, hooks, or commands. Do not expose a complete mutable store to all UI.
|
||||
- Store transitions should express user or domain intent, not generic object mutation.
|
||||
- Derive values instead of storing synchronized copies.
|
||||
- Do not use effects to keep two pieces of application state synchronized.
|
||||
- React Context is suitable for dependency injection or stable scoped state. Avoid one broad
|
||||
app context whose every update rerenders unrelated consumers.
|
||||
|
||||
State-library choice is an implementation detail. Architecture should survive replacing it
|
||||
without rewriting pages and rendering components.
|
||||
|
||||
## Effects And Async Work
|
||||
|
||||
- Use effects to synchronize with external systems, not to calculate render data or handle user
|
||||
events.
|
||||
- Start event-driven work from the event or model command that owns it.
|
||||
- Every subscription, timer, listener, or in-flight operation must have a clear owner and
|
||||
cleanup path.
|
||||
- The owning feature/model defines pending, success, empty, error, retry, and cancellation
|
||||
semantics.
|
||||
- Prevent stale async results and race conditions where users can trigger overlapping work.
|
||||
- Do not hide failures with broad `catch` blocks or silently convert errors into empty data.
|
||||
|
||||
## Data And Infrastructure
|
||||
|
||||
- Treat network responses, storage, URL input, files, and third-party SDK output as untrusted.
|
||||
- Validate and normalize data at the boundary where it enters the application.
|
||||
- Map transport DTOs and external errors into product-oriented values before they reach UI.
|
||||
- Keep raw `fetch`, storage APIs, SDK calls, and protocol details out of rendering components.
|
||||
- Keep a feature-specific API adapter inside the feature until it has a real shared consumer.
|
||||
- Introduce a client, repository, gateway, service, or facade only when its responsibility is
|
||||
distinct and useful.
|
||||
- Avoid wrapper chains that only forward calls. One clear adapter is better than
|
||||
`Client -> Service -> Facade` without separate responsibilities.
|
||||
- Inject infrastructure when tests, multiple implementations, lifecycle, or unstable external
|
||||
APIs justify it. Do not introduce dependency injection for every pure helper.
|
||||
|
||||
## Component And Hook APIs
|
||||
|
||||
- Component and hook APIs describe product intent, not internal implementation.
|
||||
- Avoid boolean prop combinations that create unclear or invalid modes. Prefer explicit variants
|
||||
or separate components.
|
||||
- Avoid passing raw query results, stores, SDK clients, or large configuration objects through
|
||||
component trees.
|
||||
- Keep public props small and cohesive. A component that needs unrelated groups of props likely
|
||||
owns too many responsibilities.
|
||||
- Custom hooks encapsulate React state, lifecycle, or reusable reactive behavior. Pure
|
||||
calculations remain plain functions.
|
||||
- Do not use `useEffect`, `useMemo`, `useCallback`, or `memo` by habit. Use them for correctness
|
||||
or measured performance needs.
|
||||
- Do not duplicate server or domain state into component state merely to make it editable.
|
||||
Create an explicit draft only when the UX requires commit/cancel semantics.
|
||||
|
||||
## Public Boundaries
|
||||
|
||||
- Export the smallest useful public surface of a feature.
|
||||
- Consumers should use a feature's public components, hooks, commands, and types, not deep
|
||||
internal paths.
|
||||
- Keep implementation-only state, DTOs, adapters, and helpers private.
|
||||
- Do not create barrel files everywhere. Use a public entry point only where a real boundary
|
||||
exists.
|
||||
- A reusable abstraction should have a clear owner and at least one current reason to exist.
|
||||
- Avoid generic `core`, `common`, `helpers`, `services`, or `utils` modules that collect
|
||||
unrelated responsibilities.
|
||||
|
||||
## Growing The Architecture
|
||||
|
||||
Start local and promote code only after pressure appears:
|
||||
|
||||
- A second consumer may justify shared domain code, but similar code is not automatically the
|
||||
same knowledge.
|
||||
- Repeated external integration logic may justify a shared adapter.
|
||||
- A process coordinating several capabilities may justify a named workflow.
|
||||
- A large feature may split into smaller capabilities when they have distinct responsibilities
|
||||
and lifecycles.
|
||||
- Separate packages are useful when an enforceable boundary, independent reuse, or independent
|
||||
lifecycle outweighs their maintenance cost.
|
||||
|
||||
Do not begin a small application with every possible layer, package, provider, repository,
|
||||
facade, and design pattern. Strong architecture makes growth cheaper; it does not predict every
|
||||
future requirement.
|
||||
|
||||
## Testing
|
||||
|
||||
- Test product behavior and public contracts, not implementation trivia.
|
||||
- Test pure rules with unit tests.
|
||||
- Test feature models and async transitions without rendering where practical.
|
||||
- Test components through accessible user behavior.
|
||||
- Test infrastructure mapping and validation at external boundaries.
|
||||
- Keep end-to-end tests for critical user journeys.
|
||||
- Mock external systems and unstable boundaries, not every internal function.
|
||||
- Add tests proportional to risk, especially for validation, permissions, races, retries,
|
||||
cancellation, and regressions.
|
||||
|
||||
## Review Checklist
|
||||
|
||||
Before finishing a change, ask:
|
||||
|
||||
- Does the file location make its owner obvious?
|
||||
- Does composition code read in product language?
|
||||
- Is UI protected from raw state, DTOs, infrastructure, and business decisions?
|
||||
- Is there one source of truth?
|
||||
- Are effects only synchronizing external systems?
|
||||
- Is new shared code genuinely domain-free or genuinely shared?
|
||||
- Does every abstraction remove current complexity?
|
||||
- Can important behavior be tested without rendering the whole app?
|
||||
- Did the change preserve accessibility, error handling, and cleanup?
|
||||
- Is this the least code that clearly solves the current problem?
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user