25 Commits
Author SHA1 Message Date
xenosandGitHub ba459cff40 Merge pull request #22 from tomaszk8266/master
Add macOS signing
2026-07-11 10:27:31 +08:00
Tomasz K. 8b54da6adf macOS: Sign the patched app before launching and increase timeout 2026-07-11 00:20:54 +02:00
xenosandGitHub 432f9a8e70 Merge pull request #18 from xenos1337/dependabot/npm_and_yarn/brace-expansion-5.0.5 2026-05-03 17:52:46 +02:00
xenosandGitHub 7d437d16e2 Merge pull request #20 from xenos1337/dependabot/npm_and_yarn/xmldom/xmldom-0.8.13 2026-04-26 23:04:44 +02:00
dependabot[bot]andGitHub 3ed4d62d6c chore(deps): bump @xmldom/xmldom from 0.8.11 to 0.8.13
Bumps [@xmldom/xmldom](https://github.com/xmldom/xmldom) from 0.8.11 to 0.8.13.
- [Release notes](https://github.com/xmldom/xmldom/releases)
- [Changelog](https://github.com/xmldom/xmldom/blob/master/CHANGELOG.md)
- [Commits](https://github.com/xmldom/xmldom/compare/0.8.11...0.8.13)

---
updated-dependencies:
- dependency-name: "@xmldom/xmldom"
  dependency-version: 0.8.13
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-23 03:33:12 +00:00
dependabot[bot]andGitHub 1adcd3c5cb chore(deps): bump brace-expansion from 5.0.4 to 5.0.5
Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 5.0.4 to 5.0.5.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v5.0.4...v5.0.5)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 5.0.5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-27 14:53:52 +00:00
xenosandGitHub 86c35f079a Merge pull request #16 from Shyzg/fix/macos-hash-patching 2026-03-22 01:35:45 +01:00
Al Jarreau Arman MaulanaandClaude Opus 4.6 24c8828e71 Fix macOS hash patching and update dependencies
On macOS, the integrity hash is stored in Info.plist, not embedded in
the executable binary. Added patchInfoPlistHash() and platform branching
so macOS patches Info.plist while Windows/Linux patch the binary.

Also updated dependencies for compatibility:
- @electron/asar 4.0.1 → 4.1.0 (named export change)
- chalk 4 → 5.6.2 (tagged template → function call syntax)
- @types/node 20 → 25

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 17:08:12 +07:00
xenos bbc7918678 Update package.json 2026-03-17 01:05:17 +01:00
xenos 68f7e1c1c0 update for 1.24.4 2026-03-17 00:29:26 +01:00
xenosandGitHub 0685a1e727 Merge pull request #10 from xenos1337/dependabot/npm_and_yarn/minimatch-10.2.4 2026-03-03 00:29:10 +01:00
dependabot[bot]andGitHub fa9dcf5361 chore(deps): bump minimatch from 10.2.2 to 10.2.4
Bumps [minimatch](https://github.com/isaacs/minimatch) from 10.2.2 to 10.2.4.
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v10.2.2...v10.2.4)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 10.2.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-28 13:26:35 +00:00
xenosandGitHub efcc89bab4 Merge pull request #9 from xenos1337/dependabot/npm_and_yarn/multi-4348f2d014 2026-02-24 16:49:12 +01:00
dependabot[bot]andGitHub 8215f4348b chore(deps): bump minimatch and @electron/asar
Bumps [minimatch](https://github.com/isaacs/minimatch) to 10.2.2 and updates ancestor dependency [@electron/asar](https://github.com/electron/asar). These dependencies need to be updated together.


Updates `minimatch` from 3.1.2 to 10.2.2
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v10.2.2)

Updates `@electron/asar` from 3.4.1 to 4.0.1
- [Release notes](https://github.com/electron/asar/releases)
- [Changelog](https://github.com/electron/asar/blob/main/CHANGELOG.md)
- [Commits](https://github.com/electron/asar/compare/v3.4.1...v4.0.1)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 10.2.2
  dependency-type: indirect
- dependency-name: "@electron/asar"
  dependency-version: 4.0.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-21 10:32:42 +00:00
xenos 359b707b44 Update for 1.24.2 2025-12-18 17:38:56 +01:00
xenosandGitHub 7537b33593 Merge pull request #6 from jokelbaf/master 2025-12-11 21:37:37 +01:00
JokelBafandGitHub fe97c803f5 feat: Support newer electron import name 2025-12-11 21:31:42 +02:00
xenos 61b3bdeb5e chore(version): update version to 2.0.8 and add author information in package.json; remove unused version comparison documentation in index.js
Signed-off-by: xenos <66328734+xenos1337@users.noreply.github.com>
2025-11-29 00:08:02 +01:00
xenos 91333c1a3e refactor(version): read LOCAL_VERSION from package.json dynamically 2025-11-29 00:06:55 +01:00
xenos d1a64774da feat(version): add automatic update check from GitHub tags 2025-11-29 00:06:24 +01:00
xenos fe7cae9dd9 refactor(patcher): use local inject.js and simplify injection mechanism 2025-11-29 00:04:54 +01:00
xenos cb8fd663b7 docs(readme): remove 'Can They Fix It' section 2025-11-29 00:04:09 +01:00
xenos 30ec13fbdc Refactor index.js to use function declarations instead of arrow functions for consistency and readability. Update README.md to clarify installation and usage instructions, removing the build section. Remove GitHub Actions release workflow as it is no longer needed.
Signed-off-by: xenos <66328734+xenos1337@users.noreply.github.com>
2025-11-24 05:47:59 +01:00
xenosandGitHub f139d9c2ba Merge pull request #4 from USLTD/patch-1 2025-11-24 05:06:23 +01:00
Luka MamukashviliandGitHub cde93879a2 Rename preload.js to preload.cjs in index.js 2025-11-21 14:24:32 +04:00
6 changed files with 827 additions and 2658 deletions
-120
View File
@@ -1,120 +0,0 @@
name: Release Build
on:
push:
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: write
jobs:
build:
name: Build ${{ matrix.os }}
runs-on: ${{ matrix.runner }}
strategy:
matrix:
include:
- os: linux
runner: ubuntu-latest
targets: node18-linux-x64,node18-linux-arm64
- os: macos
runner: macos-latest
targets: node18-macos-x64,node18-macos-arm64
- os: windows
runner: windows-latest
targets: node18-win-x64
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Create dist directory
run: mkdir -p dist
- name: Build for ${{ matrix.os }}
run: |
npm run build
npx pkg dist/bundle.cjs --targets ${{ matrix.targets }} --compress GZip --out-path dist/
- name: List built files (debug - Unix)
if: matrix.os != 'windows'
run: ls -lah dist/
- name: List built files (debug - Windows)
if: matrix.os == 'windows'
shell: pwsh
run: Get-ChildItem -Path dist/ | Format-Table -AutoSize
- name: Rename executables (Linux)
if: matrix.os == 'linux'
run: |
[ -f dist/bundle-x64 ] && mv dist/bundle-x64 dist/httptoolkit-patcher-linux-x64
[ -f dist/bundle-arm64 ] && mv dist/bundle-arm64 dist/httptoolkit-patcher-linux-arm64
rm -f dist/bundle dist/bundle.cjs 2>/dev/null || true
- name: Rename executables (macOS)
if: matrix.os == 'macos'
run: |
[ -f dist/bundle-x64 ] && mv dist/bundle-x64 dist/httptoolkit-patcher-macos-x64
[ -f dist/bundle-arm64 ] && mv dist/bundle-arm64 dist/httptoolkit-patcher-macos-arm64
rm -f dist/bundle dist/bundle.cjs 2>/dev/null || true
- name: Rename executables (Windows)
if: matrix.os == 'windows'
shell: pwsh
run: |
if (Test-Path dist/bundle.exe) { Move-Item -Force dist/bundle.exe dist/httptoolkit-patcher.exe }
if (Test-Path dist/bundle-x64.exe) { Move-Item -Force dist/bundle-x64.exe dist/httptoolkit-patcher-win-x64.exe }
Remove-Item -Force dist/bundle.cjs -ErrorAction SilentlyContinue
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: binaries-${{ matrix.os }}
path: dist/*
release:
name: Create Release
needs: build
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
pattern: binaries-*
path: artifacts
merge-multiple: true
- name: Prepare release files
run: |
mkdir -p release
cp artifacts/* release/ 2>/dev/null || find artifacts -type f -exec cp {} release/ \;
ls -lah release/
- name: Extract version from tag
id: get_version
run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Create Release
uses: softprops/action-gh-release@v1
with:
files: release/*
draft: false
prerelease: false
generate_release_notes: true
name: Release ${{ steps.get_version.outputs.VERSION }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+8 -67
View File
@@ -20,70 +20,32 @@ The patcher intercepts HTTP Toolkit's authentication functions:
By hooking these functions, we bypass the subscription checks entirely. By hooking these functions, we bypass the subscription checks entirely.
### Can They Fix It?
Yes, but they most likely won't. Fixing this would require changing their entire codebase architecture. And if they do? I'll just update the patcher.
## Installation ## Installation
1. Install dependencies: 1. Install Node.js (if not already installed)
2. Install dependencies:
```bash ```bash
npm install npm install
``` ```
## Building
Build standalone executables for all platforms and architectures:
```bash
npm run build
```
This creates self-contained executables in the `dist/` directory:
**Windows:**
- `httptoolkit-patcher-win-x64.exe` (64-bit)
**Linux:**
- `httptoolkit-patcher-linux-x64` (x86_64/AMD64)
- `httptoolkit-patcher-linux-arm64` (ARM64/AArch64)
**macOS:**
- `httptoolkit-patcher-macos-x64` (Intel)
- `httptoolkit-patcher-macos-arm64` (Apple Silicon M Chip)
**Note:** These are standalone executables created with `pkg` that include Node.js runtime and all dependencies. No need to install Node.js separately!
## Usage ## Usage
### From Source **Patch HTTP Toolkit:**
**Patch:**
```bash ```bash
npm start npm start
``` ```
**Unpatch:** **Unpatch/Restore:**
```bash ```bash
npm run unpatch npm run unpatch
``` ```
### Using Prebuilt Executables **Show help:**
Download the appropriate executable for your platform from [Releases](https://github.com/xenos1337/httptoolkit-patcher/releases), then:
**Windows:**
```cmd
httptoolkit-patcher-win-x64.exe
```
**Linux/macOS:**
```bash ```bash
chmod +x httptoolkit-patcher-linux-x64 # or your architecture npm start help
./httptoolkit-patcher-linux-x64
``` ```
That's it. The patcher handles everything automatically. That's it. The patcher handles everything automatically and will request elevated permissions if needed.
## Technical Details ## Technical Details
@@ -96,7 +58,7 @@ That's it. The patcher handles everything automatically.
## Troubleshooting ## Troubleshooting
**Permission errors?** Run as admin/sudo or let the patcher request elevation. **Permission errors?** The patcher will automatically request elevated permissions (admin/sudo).
**Already patched?** The patcher will ask if you want to repatch. **Already patched?** The patcher will ask if you want to repatch.
@@ -104,27 +66,6 @@ That's it. The patcher handles everything automatically.
**Anything else?** Open an issue on the [GitHub repository](https://github.com/xenos1337/httptoolkit-patcher/issues). **Anything else?** Open an issue on the [GitHub repository](https://github.com/xenos1337/httptoolkit-patcher/issues).
## GitHub Release Workflow
This project includes an automated GitHub Actions workflow that builds and releases the patcher for all platforms.
### Creating a Release
1. Create and push a version tag:
```bash
git tag v2.0.1
git push origin v2.0.1
```
2. The GitHub Actions workflow will automatically:
- Build for all platforms and architectures (Windows x64, Linux x64/ARM64, macOS Intel/Apple Silicon)
- Create standalone native executables using pkg
- Create a GitHub release with all binaries as downloadable artifacts
### Manual Workflow Trigger
You can also manually trigger the release workflow from the GitHub Actions tab.
## Disclaimer ## Disclaimer
This tool is provided as-is. Use at your own risk. For educational purposes only. This tool is provided as-is. Use at your own risk. For educational purposes only.
+496 -184
View File
@@ -1,6 +1,6 @@
// @ts-check // @ts-check
import { spawn, execSync } from "child_process"; import { spawn, execSync } from "child_process";
import asar from "@electron/asar"; import * as asar from "@electron/asar";
import chalk from "chalk"; import chalk from "chalk";
import path from "path"; import path from "path";
import fs from "fs"; import fs from "fs";
@@ -15,19 +15,28 @@ const isLinux = process.platform === "linux";
// Handle both ESM and pkg-bundled scenarios // Handle both ESM and pkg-bundled scenarios
const __filename = (() => { const __filename = (() => {
// Check if running as pkg bundle // Check if running as pkg bundle
// @ts-ignore - pkg adds this property at runtime
if (process.pkg) { if (process.pkg) {
return process.execPath; return process.execPath;
} }
// Check if import.meta.url exists (ESM) // ESM: use import.meta.url
if (typeof import.meta !== 'undefined' && import.meta.url) {
return fileURLToPath(import.meta.url); return fileURLToPath(import.meta.url);
})();
// Version info - read from package.json
const GITHUB_REPO = "xenos1337/httptoolkit-patcher";
const LOCAL_VERSION = (() => {
try {
const packageJsonPath = path.join(path.dirname(__filename), "package.json");
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
return packageJson.version || "0.0.0";
} catch {
return "0.0.0";
} }
// Fallback to __filename if in CommonJS
return typeof __filename !== 'undefined' ? __filename : process.argv[1];
})(); })();
// Check if running with elevated privileges // Check if running with elevated privileges
const isElevated = () => { function isElevated() {
if (isWin) { if (isWin) {
try { try {
execSync("net session", { stdio: "ignore" }); execSync("net session", { stdio: "ignore" });
@@ -38,10 +47,10 @@ const isElevated = () => {
} else { } else {
return process.getuid && process.getuid() === 0; return process.getuid && process.getuid() === 0;
} }
}; }
// Helper function to prompt user for input // Helper function to prompt user for input
const prompt = question => { function prompt(question) {
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
@@ -52,23 +61,83 @@ const prompt = question => {
resolve(answer); resolve(answer);
}); });
}); });
}; }
// Helper function to fetch content from URL /**
const fetchUrl = url => { * Fetch JSON from a URL
* @param {string} url
* @returns {Promise<Array<{name: string}>>}
*/
function fetchJson(url) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const options = {
headers: {
"User-Agent": "httptoolkit-patcher",
Accept: "application/vnd.github.v3+json",
},
};
https https
.get(url, res => { .get(url, options, res => {
if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}`));
return;
}
let data = ""; let data = "";
res.on("data", chunk => (data += chunk)); res.on("data", chunk => (data += chunk));
res.on("end", () => resolve(data)); res.on("end", () => {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(e);
}
});
}) })
.on("error", reject); .on("error", reject);
}); });
}; }
function compareVersions(v1, v2) {
const normalize = (/** @type {string} */ v) => v.replace(/^v/, "").split(".").map(Number);
const parts1 = normalize(v1);
const parts2 = normalize(v2);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const num1 = parts1[i] || 0;
const num2 = parts2[i] || 0;
if (num1 > num2) return 1;
if (num1 < num2) return -1;
}
return 0;
}
/**
* Check for updates from GitHub
*/
async function checkForUpdates() {
try {
const tags = await fetchJson(`https://api.github.com/repos/${GITHUB_REPO}/tags`);
if (!tags || tags.length === 0) {
return; // No tags found, skip update check
}
// Tags are returned in order, first one is the latest
const latestTag = tags[0].name;
const latestVersion = latestTag.replace(/^v/, "");
if (compareVersions(latestVersion, LOCAL_VERSION) > 0) {
console.log(chalk.yellowBright('\n╔════════════════════════════════════════════════════════════╗'));
console.log(chalk.yellowBright('║') + chalk.white(' A new version is available: ') + chalk.greenBright(`v${latestVersion}`) + chalk.white(' (current: ') + chalk.gray(`v${LOCAL_VERSION}`) + chalk.white(') ') + chalk.yellowBright(' ║'));
console.log(chalk.yellowBright('║') + chalk.white(' Update: ') + chalk.cyanBright(`https://github.com/${GITHUB_REPO}`) + chalk.white(' ') + chalk.yellowBright('║'));
console.log(chalk.yellowBright('╚════════════════════════════════════════════════════════════╝\n'));
}
} catch (e) {
// Silently ignore update check errors (network issues, etc.)
}
}
// Helper function to remove directory recursively // Helper function to remove directory recursively
const rm = dirPath => { function rm(dirPath) {
if (!fs.existsSync(dirPath)) return; if (!fs.existsSync(dirPath)) return;
if (!fs.lstatSync(dirPath).isDirectory()) return fs.rmSync(dirPath, { force: true }); if (!fs.lstatSync(dirPath).isDirectory()) return fs.rmSync(dirPath, { force: true });
for (const entry of fs.readdirSync(dirPath)) { for (const entry of fs.readdirSync(dirPath)) {
@@ -77,11 +146,15 @@ const rm = dirPath => {
else fs.rmSync(entryPath, { force: true }); else fs.rmSync(entryPath, { force: true });
} }
fs.rmdirSync(dirPath); fs.rmdirSync(dirPath);
}; }
// Find HTTP Toolkit installation path // Find HTTP Toolkit installation path
const findAppPath = async () => { async function findAppPath() {
const possiblePaths = isWin ? [path.join("C:", "Program Files", "HTTP Toolkit", "resources"), path.join("C:", "Program Files (x86)", "HTTP Toolkit", "resources")] : isMac ? ["/Applications/HTTP Toolkit.app/Contents/Resources"] : ["/opt/HTTP Toolkit/resources", "/opt/httptoolkit/resources"]; const possiblePaths = isWin
? [path.join("C:", "Program Files", "HTTP Toolkit", "resources"), path.join("C:", "Program Files (x86)", "HTTP Toolkit", "resources"), path.join(process.env.LOCALAPPDATA || path.join(process.env.USERPROFILE || "", "AppData", "Local"), "Programs", "HTTP Toolkit", "resources")]
: isMac
? ["/Applications/HTTP Toolkit.app/Contents/Resources"]
: ["/opt/HTTP Toolkit/resources", "/opt/httptoolkit/resources"];
for (const p of possiblePaths) { for (const p of possiblePaths) {
if (fs.existsSync(path.join(p, "app.asar"))) { if (fs.existsSync(path.join(p, "app.asar"))) {
@@ -89,11 +162,11 @@ const findAppPath = async () => {
} }
} }
console.log(chalk.yellowBright`[!] HTTP Toolkit not found in default locations`); console.log(chalk.yellowBright('[!] HTTP Toolkit not found in default locations'));
const userPath = await prompt("Please enter the path to HTTP Toolkit executable/app: "); const userPath = await prompt("Please enter the path to HTTP Toolkit executable/app: ");
if (!userPath) { if (!userPath) {
console.error(chalk.redBright`[-] No path provided`); console.error(chalk.redBright('[-] No path provided'));
process.exit(1); process.exit(1);
} }
@@ -104,122 +177,285 @@ const findAppPath = async () => {
if (!resourcesPath.endsWith("resources")) resourcesPath = path.join(resourcesPath, "resources"); if (!resourcesPath.endsWith("resources")) resourcesPath = path.join(resourcesPath, "resources");
if (!fs.existsSync(path.join(resourcesPath, "app.asar"))) { if (!fs.existsSync(path.join(resourcesPath, "app.asar"))) {
console.error(chalk.redBright`[-] app.asar not found at ${resourcesPath}`); console.error(chalk.redBright(`[-] app.asar not found at ${resourcesPath}`));
process.exit(1); process.exit(1);
} }
return resourcesPath; return resourcesPath;
}; }
// Request elevated permissions // Request elevated permissions
const requestElevation = async () => { async function requestElevation() {
console.log(chalk.yellowBright`[!] Requesting elevated permissions...`); console.log(chalk.yellowBright('[!] Requesting elevated permissions...'));
// @ts-ignore - pkg adds this property at runtime
const isBundled = process.pkg;
if (isWin) { if (isWin) {
// Windows: Use PowerShell to run as administrator // Windows: Use PowerShell to run as administrator
const script = `Start-Process -FilePath "node" -ArgumentList '"${__filename}"' -Verb RunAs`; let script;
if (isBundled) {
script = `Start-Process -FilePath "${__filename}" -Verb RunAs`;
} else {
script = `Start-Process -FilePath "node" -ArgumentList "${__filename}" -Verb RunAs`;
}
try { try {
spawn("powershell", ["-Command", script], { console.log(chalk.greenBright(`[+] Spawning PowerShell with script: ${script}`));
stdio: "inherit", execSync(`powershell -Command "${script}"`, { stdio: "inherit" });
shell: true, console.log(chalk.blueBright('[+] Restarting with administrator privileges...'));
});
console.log(chalk.blueBright`[+] Restarting with administrator privileges...`);
process.exit(0); process.exit(0);
} catch (e) { } catch (e) {
console.error(chalk.redBright`[-] Failed to elevate permissions: ${e.message}`); console.error(chalk.redBright(`[-] Failed to elevate permissions: ${e.message}`));
console.error(chalk.redBright`[-] Please run as administrator manually`); console.error(chalk.redBright('[-] Please run as administrator manually'));
process.exit(1); process.exit(1);
} }
} else if (isLinux) { } else if (isLinux) {
// Linux: Cannot auto-elevate with sudo, show instructions instead // Linux: Cannot auto-elevate with sudo, show instructions instead
console.log(chalk.yellowBright`[!] Elevated permissions are required for patching on Linux`); console.log(chalk.yellowBright('[!] Elevated permissions are required for patching on Linux'));
console.log(chalk.yellowBright`[!] Please re-run this script with sudo:`); console.log(chalk.yellowBright('[!] Please re-run this script with sudo:'));
console.log(chalk.blueBright` sudo node ${__filename}`); if (isBundled) {
console.log(chalk.blueBright(` sudo ${__filename}`));
} else {
console.log(chalk.blueBright(` sudo node ${__filename}`));
}
process.exit(1); process.exit(1);
} else { } else {
// macOS: Try to elevate with sudo // macOS: Try to elevate with sudo
console.log(chalk.blueBright`[+] Restarting with sudo...`); console.log(chalk.blueBright('[+] Restarting with sudo...'));
try { try {
const child = spawn("sudo", ["node", __filename], { let child;
if (isBundled) {
child = spawn("sudo", [__filename], {
stdio: "inherit", stdio: "inherit",
}); });
} else {
child = spawn("sudo", ["node", __filename], {
stdio: "inherit",
});
}
child.on("exit", code => process.exit(code || 0)); child.on("exit", code => process.exit(code || 0));
} catch (e) { } catch (e) {
console.error(chalk.redBright`[-] Failed to elevate permissions: ${e.message}`); console.error(chalk.redBright(`[-] Failed to elevate permissions: ${e.message}`));
console.error(chalk.redBright`[-] Please run with sudo manually`); console.error(chalk.redBright('[-] Please run with sudo manually'));
process.exit(1); process.exit(1);
} }
} }
}; }
// Check if we have write permissions // Check if we have write permissions
const checkPermissions = filePath => { function checkPermissions(filePath) {
try { try {
// Check write access to the file/directory
fs.accessSync(filePath, fs.constants.W_OK); fs.accessSync(filePath, fs.constants.W_OK);
return true;
} catch (e) { // Check if we can create directories
const testDirPath = path.join(path.dirname(filePath), `.test_${Date.now()}`);
try {
fs.mkdirSync(testDirPath, { recursive: true });
fs.rmdirSync(testDirPath);
} catch (dirError) {
console.error(chalk.redBright(`[-] Cannot create directories in ${path.dirname(filePath)}: ${dirError.message}`));
return false; return false;
} }
};
console.log(chalk.greenBright(`[+] Permissions check passed for ${filePath}`));
return true;
} catch (e) {
console.error(chalk.redBright(`[-] Permissions check failed for ${filePath}: ${e.message}`));
return false;
}
}
// Kill HTTP Toolkit processes // Kill HTTP Toolkit processes
const killHttpToolkit = async () => { async function killHttpToolkit() {
console.log(chalk.yellowBright`[+] Checking for running HTTP Toolkit processes...`); console.log(chalk.yellowBright('[+] Checking for running HTTP Toolkit processes...'));
try { try {
if (isWin) { if (isWin) {
// Windows: Use tasklist to find and taskkill to terminate // Windows: Use tasklist to find and taskkill to terminate
const output = execSync('tasklist /FI "IMAGENAME eq HTTP Toolkit.exe" /FO CSV /NH', { encoding: "utf-8" }); const output = execSync('tasklist /FI "IMAGENAME eq HTTP Toolkit.exe" /FO CSV /NH', { encoding: "utf-8" });
if (output.includes("HTTP Toolkit.exe")) { if (output.includes("HTTP Toolkit.exe")) {
console.log(chalk.yellowBright`[!] HTTP Toolkit is running, attempting to close it...`); console.log(chalk.yellowBright('[!] HTTP Toolkit is running, attempting to close it...'));
execSync('taskkill /F /IM "HTTP Toolkit.exe" /T', { stdio: "ignore" }); execSync('taskkill /F /IM "HTTP Toolkit.exe" /T', { stdio: "ignore" });
console.log(chalk.greenBright`[+] HTTP Toolkit processes terminated`); console.log(chalk.greenBright('[+] HTTP Toolkit processes terminated'));
// Wait a moment for the process to fully close // Wait a moment for the process to fully close
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => setTimeout(resolve, 2000));
} else { } else {
console.log(chalk.greenBright`[+] HTTP Toolkit is not running`); console.log(chalk.greenBright('[+] HTTP Toolkit is not running'));
} }
} else if (isMac) { } else if (isMac) {
// macOS: Use pgrep and pkill // macOS: Use pgrep and pkill
try { try {
execSync('pgrep -f "HTTP Toolkit"', { stdio: "ignore" }); execSync('pgrep -f "HTTP Toolkit"', { stdio: "ignore" });
console.log(chalk.yellowBright`[!] HTTP Toolkit is running, attempting to close it...`); console.log(chalk.yellowBright('[!] HTTP Toolkit is running, attempting to close it...'));
execSync('pkill -f "HTTP Toolkit"', { stdio: "ignore" }); execSync('pkill -f "HTTP Toolkit"', { stdio: "ignore" });
console.log(chalk.greenBright`[+] HTTP Toolkit processes terminated`); console.log(chalk.greenBright('[+] HTTP Toolkit processes terminated'));
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) { } catch (e) {
console.log(chalk.greenBright`[+] HTTP Toolkit is not running`); console.log(chalk.greenBright('[+] HTTP Toolkit is not running'));
} }
} else { } else {
// Linux: Use pgrep and pkill // Linux: Use pgrep and pkill
try { try {
execSync('pgrep -f "HTTP Toolkit"', { stdio: "ignore" }); execSync('pgrep -f "HTTP Toolkit"', { stdio: "ignore" });
console.log(chalk.yellowBright`[!] HTTP Toolkit is running, attempting to close it...`); console.log(chalk.yellowBright('[!] HTTP Toolkit is running, attempting to close it...'));
execSync('pkill -f "HTTP Toolkit"', { stdio: "ignore" }); execSync('pkill -f "HTTP Toolkit"', { stdio: "ignore" });
console.log(chalk.greenBright`[+] HTTP Toolkit processes terminated`); console.log(chalk.greenBright('[+] HTTP Toolkit processes terminated'));
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) { } catch (e) {
console.log(chalk.greenBright`[+] HTTP Toolkit is not running`); console.log(chalk.greenBright('[+] HTTP Toolkit is not running'));
} }
} }
} catch (e) { } catch (e) {
console.log(chalk.yellowBright`[!] Could not check/kill processes: ${e.message}`); console.log(chalk.yellowBright(`[!] Could not check/kill processes: ${e.message}`));
console.log(chalk.yellowBright`[!] If HTTP Toolkit is running, please close it manually`); console.log(chalk.yellowBright('[!] If HTTP Toolkit is running, please close it manually'));
}
}
// Resolve the base installation directory (without the trailing resources folder)
function getBinaryBasePath(resourcesPath) {
const normalized = resourcesPath.replace(/[\\/]+$/, "");
if (normalized.toLowerCase().endsWith("resources")) {
return path.dirname(normalized);
}
return normalized;
}
// Determine the executable path for HTTP Toolkit based on platform
function getExecutablePath(resourcesPath) {
const basePath = getBinaryBasePath(resourcesPath);
const candidates = isWin ? [path.join(basePath, "HTTP Toolkit.exe"), path.join(basePath, "httptoolkit.exe")] : isMac ? [path.join(basePath, "MacOS", "HTTP Toolkit"), path.join(basePath, "MacOS", "HTTP Toolkit Preview")] : [path.join(basePath, "httptoolkit"), path.join(basePath, "HTTP Toolkit")];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
throw new Error(`Could not locate HTTP Toolkit executable near ${resourcesPath}`);
}
// Extract hashes from integrity check output
function extractIntegrityHashes(output) {
const regex = /Integrity check failed for asar archive[\s\S]*?\(\s*([0-9a-f]{64})\s*vs\s*([0-9a-f]{64})\s*\)/i;
const match = output.match(regex);
if (!match) return null;
return {
originalHash: match[1],
newHash: match[2],
};
}
// Launch the app once to grab integrity hashes from its crash output
async function captureIntegrityHashes(executablePath) {
return new Promise((resolve, reject) => {
let output = "";
let finished = false;
const child = spawn(executablePath, {
cwd: path.dirname(executablePath),
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
const timeout = setTimeout(() => {
if (!finished) {
finished = true;
child.kill();
reject(new Error("Timed out waiting for integrity check output"));
}
}, 30000);
const handleData = data => {
output += data.toString();
const hashes = extractIntegrityHashes(output);
if (hashes && !finished) {
finished = true;
clearTimeout(timeout);
child.kill();
resolve(hashes);
} }
}; };
child.stdout.on("data", handleData);
child.stderr.on("data", handleData);
child.on("error", err => {
if (!finished) {
finished = true;
clearTimeout(timeout);
reject(err);
}
});
child.on("exit", () => {
if (!finished) {
clearTimeout(timeout);
const hashes = extractIntegrityHashes(output);
if (hashes) {
resolve(hashes);
} else {
reject(new Error("Could not find integrity hashes in HTTP Toolkit output"));
}
}
});
});
}
// Replace all occurrences of the original hash with the new hash inside the binary
function patchExecutableHash(executablePath, originalHash, newHash) {
if (originalHash.length !== newHash.length) {
throw new Error("Hash lengths do not match; cannot safely patch binary");
}
const binary = fs.readFileSync(executablePath);
const originalBuf = Buffer.from(originalHash, "utf-8");
const newBuf = Buffer.from(newHash, "utf-8");
let occurrences = 0;
let idx = binary.indexOf(originalBuf);
while (idx !== -1) {
newBuf.copy(binary, idx);
occurrences += 1;
idx = binary.indexOf(originalBuf, idx + originalBuf.length);
}
if (occurrences === 0) {
throw new Error("Original hash not found in binary");
}
fs.writeFileSync(executablePath, binary);
return occurrences;
}
// Replace the asar integrity hash inside the macOS Info.plist
function patchInfoPlistHash(resourcesPath, originalHash, newHash) {
const basePath = getBinaryBasePath(resourcesPath);
const plistPath = path.join(basePath, "Info.plist");
if (!fs.existsSync(plistPath)) {
throw new Error(`Info.plist not found at ${plistPath}`);
}
let content = fs.readFileSync(plistPath, "utf-8");
if (!content.includes(originalHash)) {
throw new Error("Original hash not found in Info.plist");
}
content = content.replaceAll(originalHash, newHash);
fs.writeFileSync(plistPath, content, "utf-8");
}
// Unpatch/restore function // Unpatch/restore function
const unpatchApp = async () => { async function unpatchApp() {
console.log(chalk.blueBright`[+] HTTP Toolkit Unpatcher Started`); console.log(chalk.blueBright('[+] HTTP Toolkit Unpatcher Started'));
// Step 1: Find app path
const appPath = await findAppPath(); const appPath = await findAppPath();
console.log(chalk.greenBright`[+] HTTP Toolkit found at ${appPath}`); console.log(chalk.greenBright(`[+] HTTP Toolkit found at ${appPath}`));
// Step 2: Kill HTTP Toolkit if running
await killHttpToolkit(); await killHttpToolkit();
// Step 3: Check permissions
const asarPath = path.join(appPath, "app.asar"); const asarPath = path.join(appPath, "app.asar");
const backupPath = path.join(appPath, "app.asar.bak"); const backupPath = path.join(appPath, "app.asar.bak");
const extractPath = path.join(appPath, "app.asar_extracted"); const extractPath = path.join(appPath, "app.asar_extracted");
@@ -228,241 +464,317 @@ const unpatchApp = async () => {
const hasPermissions = checkPermissions(appPath) && checkPermissions(asarPath); const hasPermissions = checkPermissions(appPath) && checkPermissions(asarPath);
if (!hasPermissions) { if (!hasPermissions) {
console.log(chalk.yellowBright`[!] No write permissions for ${appPath}`); console.log(chalk.yellowBright(`[!] No write permissions for ${appPath}`));
if (isElevated()) { if (isElevated()) {
console.error(chalk.redBright`[-] Still no permissions even with elevated privileges`); console.error(chalk.redBright('[-] Still no permissions even with elevated privileges'));
process.exit(1); process.exit(1);
} }
console.log(chalk.yellowBright`[!] Administrator/sudo privileges required for unpatching`); console.log(chalk.yellowBright('[!] Administrator/sudo privileges required for unpatching'));
const answer = await prompt("Do you want to request elevated permissions? [Y/n]: ");
if (!answer || answer.toLowerCase() === "y" || answer.toLowerCase() === "yes") {
await requestElevation(); await requestElevation();
} else {
console.log(chalk.redBright`[-] Cannot proceed without write permissions`);
process.exit(1);
}
} }
// Step 4: Check if backup exists
if (!fs.existsSync(backupPath)) { if (!fs.existsSync(backupPath)) {
console.error(chalk.redBright`[-] Backup file not found at ${backupPath}`); console.error(chalk.redBright(`[-] Backup file not found at ${backupPath}`));
console.error(chalk.redBright`[-] Cannot unpatch without backup file`); console.error(chalk.redBright('[-] Cannot unpatch without backup file'));
process.exit(1); process.exit(1);
} }
// Step 5: Restore from backup console.log(chalk.yellowBright('[+] Restoring from backup...'));
console.log(chalk.yellowBright`[+] Restoring from backup...`);
try { try {
fs.copyFileSync(backupPath, asarPath); fs.copyFileSync(backupPath, asarPath);
console.log(chalk.greenBright`[+] Restored app.asar from backup`); console.log(chalk.greenBright('[+] Restored app.asar from backup'));
} catch (e) { } catch (e) {
console.error(chalk.redBright`[-] Failed to restore backup: ${e.message}`); console.error(chalk.redBright(`[-] Failed to restore backup: ${e.message}`));
process.exit(1); process.exit(1);
} }
// Step 6: Clean up extracted files if they exist
if (fs.existsSync(extractPath)) { if (fs.existsSync(extractPath)) {
console.log(chalk.yellowBright`[+] Removing extracted files...`); console.log(chalk.yellowBright('[+] Removing extracted files...'));
rm(extractPath); rm(extractPath);
console.log(chalk.greenBright`[+] Cleaned up extracted files`); console.log(chalk.greenBright('[+] Cleaned up extracted files'));
} }
// Step 7: Optionally remove backup
const removeBackup = await prompt("Do you want to remove the backup file? (y/n): "); const removeBackup = await prompt("Do you want to remove the backup file? (y/n): ");
if (removeBackup.toLowerCase() === "y" || removeBackup.toLowerCase() === "yes") { if (removeBackup.toLowerCase() === "y" || removeBackup.toLowerCase() === "yes") {
fs.rmSync(backupPath, { force: true }); fs.rmSync(backupPath, { force: true });
console.log(chalk.greenBright`[+] Backup file removed`); console.log(chalk.greenBright('[+] Backup file removed'));
} }
console.log(chalk.greenBright`[+] Successfully unpatched!`); console.log(chalk.greenBright('[+] Successfully unpatched!'));
}; }
// Main patching function // Main patching function
const patchApp = async () => { async function patchApp() {
console.log(chalk.blueBright`[+] HTTP Toolkit Patcher Started`); console.log(chalk.blueBright('[+] HTTP Toolkit Patcher Started'));
// Step 1: Find app path
const appPath = await findAppPath(); const appPath = await findAppPath();
console.log(chalk.greenBright`[+] HTTP Toolkit found at ${appPath}`); console.log(chalk.greenBright(`[+] HTTP Toolkit found at ${appPath}`));
// Step 2: Kill HTTP Toolkit if running
await killHttpToolkit(); await killHttpToolkit();
// Step 3: Check permissions
const asarPath = path.join(appPath, "app.asar"); const asarPath = path.join(appPath, "app.asar");
// Check if we have write permissions on both the directory and the file // Check if we have write permissions on both the directory and the file
const hasPermissions = checkPermissions(appPath) && checkPermissions(asarPath); const hasPermissions = checkPermissions(appPath) && checkPermissions(asarPath);
if (!hasPermissions) { if (!hasPermissions) {
console.log(chalk.yellowBright`[!] No write permissions for ${appPath}`); console.log(chalk.yellowBright(`[!] No write permissions for ${appPath}`));
if (isElevated()) { if (isElevated()) {
console.error(chalk.redBright`[-] Still no permissions even with elevated privileges`); console.error(chalk.redBright('[-] Still no permissions even with elevated privileges'));
process.exit(1); process.exit(1);
} }
console.log(chalk.yellowBright`[!] Administrator/sudo privileges required for patching`); console.log(chalk.yellowBright('[!] Administrator/sudo privileges required for patching'));
const answer = await prompt("Do you want to request elevated permissions? [Y/n]: ");
if (!answer || answer.toLowerCase() === "y" || answer.toLowerCase() === "yes") {
await requestElevation(); await requestElevation();
} else {
console.log(chalk.redBright`[-] Cannot proceed without write permissions`);
process.exit(1);
}
} }
// Step 4: Backup app.asar
const backupPath = path.join(appPath, "app.asar.bak"); const backupPath = path.join(appPath, "app.asar.bak");
if (!fs.existsSync(backupPath)) { if (!fs.existsSync(backupPath)) {
console.log(chalk.yellowBright`[+] Creating backup...`); console.log(chalk.yellowBright('[+] Creating backup...'));
fs.copyFileSync(asarPath, backupPath); fs.copyFileSync(asarPath, backupPath);
console.log(chalk.greenBright`[+] Backup created at ${backupPath}`); console.log(chalk.greenBright(`[+] Backup created at ${backupPath}`));
} }
// Step 5: Extract app.asar
const extractPath = path.join(appPath, "app.asar_extracted"); const extractPath = path.join(appPath, "app.asar_extracted");
console.log(chalk.yellowBright`[+] Extracting app.asar...`); console.log(chalk.yellowBright('[+] Extracting app.asar...'));
rm(extractPath); rm(extractPath);
asar.extractAll(asarPath, extractPath); asar.extractAll(asarPath, extractPath);
console.log(chalk.greenBright`[+] Extracted to ${extractPath}`); console.log(chalk.greenBright(`[+] Extracted to ${extractPath}`));
// Step 6: Check if preload.js exists const preloadPath = path.join(extractPath, "build", "preload.cjs");
const preloadPath = path.join(extractPath, "build", "preload.js");
if (!fs.existsSync(preloadPath)) { if (!fs.existsSync(preloadPath)) {
console.error(chalk.redBright`[-] preload.js not found at ${preloadPath}`); console.error(chalk.redBright(`[-] preload.cjs not found in ${path.join(extractPath, "build")}`));
console.error(chalk.yellowBright('[!] Please download the latest version of HTTP Toolkit from https://httptoolkit.com/'));
rm(extractPath); rm(extractPath);
process.exit(1); process.exit(1);
} }
console.log(chalk.greenBright('[+] Found preload.cjs'));
// Step 7: Fetch inject.js from GitHub console.log(chalk.yellowBright('[+] Reading inject code from local file...'));
console.log(chalk.yellowBright`[+] Fetching inject code from GitHub...`); const injectJsPath = path.join(path.dirname(__filename), "inject.js");
const injectCode = await fetchUrl("https://raw.githubusercontent.com/xenos1337/httptoolkit-patcher/refs/heads/master/inject.js"); if (!fs.existsSync(injectJsPath)) {
if (!injectCode || !injectCode.includes("injectPageContextHooks")) { console.error(chalk.redBright(`[-] inject.js not found at ${injectJsPath}`));
console.error(chalk.redBright`[-] Failed to fetch inject.js from GitHub`);
rm(extractPath); rm(extractPath);
process.exit(1); process.exit(1);
} }
console.log(chalk.greenBright`[+] Inject code fetched successfully`); const injectCode = fs.readFileSync(injectJsPath, "utf-8");
if (!injectCode || !injectCode.includes("PAGE-INJECT")) {
console.error(chalk.redBright('[-] Invalid inject.js file'));
rm(extractPath);
process.exit(1);
}
console.log(chalk.greenBright('[+] Inject code loaded successfully'));
// Step 8: Read preload.js and check if already patched
let preloadContent = fs.readFileSync(preloadPath, "utf-8"); let preloadContent = fs.readFileSync(preloadPath, "utf-8");
const isPatched = preloadContent.includes("injectPageContextHooks");
if (isPatched) { const electronVarName = preloadContent.includes("electron_1") ? "electron_1" : "electron";
console.log(chalk.yellowBright`[!] File already patched`); console.log(chalk.greenBright(`[+] Detected electron variable: ${electronVarName}`));
const preloadPatchCode = `
(function loadInjectScript() {
const injectCode = ${JSON.stringify(injectCode)};
function injectViaWebFrame() {
try {
const { webFrame } = ${electronVarName};
if (webFrame && webFrame.executeJavaScript) {
webFrame.executeJavaScript(injectCode).then(() => console.log("[PRELOAD] Injected via webFrame.executeJavaScript")).catch(err => console.error("[PRELOAD] webFrame injection failed:", err));
return true;
}
} catch (e) {
console.error("[PRELOAD] webFrame not available:", e);
}
return false;
}
if (!injectViaWebFrame()) {
const tryInject = () => {
if (!injectViaWebFrame()) {
console.error("[PRELOAD] All injection methods failed");
}
};
if (document.readyState === 'complete' || document.readyState === 'interactive') {
tryInject();
} else {
document.addEventListener('DOMContentLoaded', tryInject, { once: true });
}
}
})();
`;
const isPreloadPatched = preloadContent.includes("loadInjectScript");
if (isPreloadPatched) {
console.log(chalk.yellowBright('[!] Files already patched'));
const answer = await prompt("Do you want to repatch? (y/n): "); const answer = await prompt("Do you want to repatch? (y/n): ");
if (answer.toLowerCase() !== "y" && answer.toLowerCase() !== "yes") { if (answer.toLowerCase() !== "y" && answer.toLowerCase() !== "yes") {
console.log(chalk.blueBright`[+] Patching cancelled`); console.log(chalk.blueBright('[+] Patching cancelled'));
rm(extractPath); rm(extractPath);
process.exit(0); process.exit(0);
} }
// Replace the existing injectPageContextHooks function // Remove existing patches
console.log(chalk.yellowBright`[+] Replacing existing patch...`); console.log(chalk.yellowBright('[+] Replacing existing patches...'));
const functionRegex = /\(function injectPageContextHooks\(\) \{[\s\S]*?\}\)\(\);/;
preloadContent = preloadContent.replace(functionRegex, injectCode);
} else {
// Find line with electron_1 and insert inject code below it
console.log(chalk.yellowBright`[+] Applying patch...`);
const lines = preloadContent.split("\n");
let insertIndex = -1;
for (let i = 0; i < lines.length; i++) { // Remove preload patch
if (lines[i].includes("electron_1")) { const preloadPatchRegex = /\n?\(function loadInjectScript\(\) \{[\s\S]*?\}\)\(\);/;
insertIndex = i + 1; preloadContent = preloadContent.replace(preloadPatchRegex, "");
}
console.log(chalk.yellowBright('[+] Applying preload patch...'));
const preloadLines = preloadContent.split("\n");
let preloadInsertIndex = -1;
for (let i = 0; i < preloadLines.length; i++) {
const line = preloadLines[i];
if (line.includes('require("electron")') || line.includes("require('electron')") || line.includes("electron_1")) {
preloadInsertIndex = i + 1;
break; break;
} }
} }
if (insertIndex === -1) { if (preloadInsertIndex === -1) {
console.error(chalk.redBright`[-] Could not find insertion point (electron_1) in preload.js`); console.error(chalk.redBright(`[-] Could not find insertion point (electron import) in ${path.basename(preloadPath)}`));
rm(extractPath); rm(extractPath);
process.exit(1); process.exit(1);
} }
lines.splice(insertIndex, 0, injectCode); preloadLines.splice(preloadInsertIndex, 0, preloadPatchCode);
preloadContent = lines.join("\n"); preloadContent = preloadLines.join("\n");
// Write patched preload file
fs.writeFileSync(preloadPath, preloadContent, "utf-8");
console.log(chalk.greenBright(`[+] ${path.basename(preloadPath)} patched successfully`));
console.log(chalk.yellowBright('[+] Repackaging app.asar...'));
await asar.createPackage(extractPath, asarPath);
console.log(chalk.greenBright('[+] app.asar repackaged successfully'));
let executablePath;
try {
executablePath = getExecutablePath(appPath);
} catch (e) {
rm(extractPath);
console.error(chalk.redBright(`[-] ${e.message}`));
process.exit(1);
} }
// Step 9: Write patched preload.js // macOS: Sign the patched app
fs.writeFileSync(preloadPath, preloadContent, "utf-8"); if (isMac) {
console.log(chalk.greenBright`[+] preload.js patched successfully`); const appBundlePath = path.resolve(appPath, '..', '..');
console.log(chalk.yellowBright('[+] Signing HTTP Toolkit with ad-hoc signature...'));
// Step 10: Repackage app.asar
console.log(chalk.yellowBright`[+] Repackaging app.asar...`);
await asar.createPackage(extractPath, asarPath);
console.log(chalk.greenBright`[+] app.asar repackaged successfully`);
// Step 11: Clean up
console.log(chalk.yellowBright`[+] Cleaning up temporary files...`);
rm(extractPath);
console.log(chalk.greenBright`[+] Successfully patched!`);
// Step 12: Open HTTP Toolkit as detached process
console.log(chalk.blueBright`[+] Opening HTTP Toolkit...`);
try { try {
if (isLinux) { execSync(`codesign --deep --force --sign - "${appBundlePath}"`, {stdio: "pipe"});
// Linux: Cannot auto-launch reliably, show manual instructions console.log(chalk.greenBright('[+] HTTP Toolkit signed successfully'));
console.log(chalk.yellowBright`[!] HTTP Toolkit has been successfully patched`); console.log(chalk.yellowBright(` Make sure to whitelist the app in privacy and security settings!`));
console.log(chalk.yellowBright`[!] Please manually launch HTTP Toolkit from your applications menu or using the command:`); } catch (e) {
console.log(chalk.blueBright` httptoolkit`); rm(extractPath);
console.error(chalk.redBright(`[!] Failed to sign HTTP Toolkit: ${e.message}`));
process.exit(1);
}
try {
execSync(`xattr -d com.apple.quarantine "${appBundlePath}" 2>/dev/null`, {stdio: 'pipe'});
} catch (e) {
console.log(chalk.redBright('[!] Failed to remove the quarantine attribute'));
}
}
console.log(chalk.yellowBright('[+] Launching HTTP Toolkit to read integrity hashes...'));
let hashes;
try {
hashes = await captureIntegrityHashes(executablePath);
} catch (e) {
rm(extractPath);
console.error(chalk.redBright(`[-] Failed to capture integrity hashes: ${e.message}`));
process.exit(1);
}
console.log(chalk.greenBright('[+] Integrity hashes captured'));
console.log(chalk.white(` Original hash: ${hashes.originalHash}`));
console.log(chalk.white(` New asar hash: ${hashes.newHash}`));
try {
if (isMac) {
patchInfoPlistHash(appPath, hashes.originalHash, hashes.newHash);
console.log(chalk.greenBright('[+] Patched Info.plist hash'));
} else { } else {
const command = isWin ? `"${path.resolve(appPath, "..", "HTTP Toolkit.exe")}"` : isMac ? 'open -a "HTTP Toolkit"' : "httptoolkit"; const replacements = patchExecutableHash(executablePath, hashes.originalHash, hashes.newHash);
const child = spawn(command, { console.log(chalk.greenBright(`[+] Patched binary hash (${replacements} replacement${replacements === 1 ? "" : "s"})`));
stdio: "ignore",
shell: true,
detached: true,
});
child.unref(); // Completely detach the child process
console.log(chalk.greenBright`[+] HTTP Toolkit launched successfully`);
} }
} catch (e) { } catch (e) {
console.error(chalk.yellowBright`[!] Could not auto-start HTTP Toolkit: ${e.message}`); rm(extractPath);
console.log(chalk.blueBright`[+] Please start HTTP Toolkit manually`); console.error(chalk.redBright(`[-] Failed to patch hash: ${e.message}`));
process.exit(1);
}
console.log(chalk.yellowBright('[+] Cleaning up temporary files...'));
rm(extractPath);
console.log(chalk.greenBright('[+] Successfully patched!'));
console.log(chalk.blueBright('[+] Opening HTTP Toolkit...'));
try {
const child = spawn(executablePath, {
stdio: "ignore",
shell: false,
detached: true,
});
child.unref();
console.log(chalk.greenBright('[+] HTTP Toolkit launched successfully'));
} catch (e) {
console.error(chalk.yellowBright(`[!] Could not auto-start HTTP Toolkit: ${e.message}`));
console.log(chalk.blueBright('[+] Please start HTTP Toolkit manually'));
}
} }
};
// Parse command line arguments
const args = process.argv.slice(2); const args = process.argv.slice(2);
const command = args[0]; const command = args[0];
// Get the command name for display const commandName = (() => {
const commandName = process.pkg ? path.basename(__filename) : 'node index.js'; // @ts-ignore - pkg adds this property at runtime
if (process.pkg) {
return path.basename(__filename);
} else {
return `node ${process.argv[1]}`;
}
})();
// Run the appropriate command // Run the appropriate command
(async () => { (async () => {
try { try {
// Check for updates from GitHub
await checkForUpdates();
if (command === "unpatch" || command === "restore") { if (command === "unpatch" || command === "restore") {
await unpatchApp(); await unpatchApp();
} else if (command === "help" || command === "-h" || command === "--help") { } else if (command === "help" || command === "-h" || command === "--help") {
console.log(chalk.blueBright`HTTP Toolkit Patcher`); console.log(chalk.blueBright('HTTP Toolkit Patcher'));
console.log(chalk.white`\nUsage:`); console.log(chalk.white('\nUsage:'));
console.log(chalk.white` ${commandName} [command]`); console.log(chalk.white(` ${commandName} [command]`));
console.log(chalk.white`\nCommands:`); console.log(chalk.white('\nCommands:'));
console.log(chalk.white` patch ${chalk.gray`- Patch HTTP Toolkit (default)`}`); console.log(chalk.white(` patch ${chalk.gray('- Patch HTTP Toolkit (default)')}`));
console.log(chalk.white` unpatch ${chalk.gray`- Restore original HTTP Toolkit from backup`}`); console.log(chalk.white(` unpatch ${chalk.gray('- Restore original HTTP Toolkit from backup')}`));
console.log(chalk.white` restore ${chalk.gray`- Alias for unpatch`}`); console.log(chalk.white(` restore ${chalk.gray('- Alias for unpatch')}`));
console.log(chalk.white` help ${chalk.gray`- Show this help message`}`); console.log(chalk.white(` help ${chalk.gray('- Show this help message')}`));
process.exit(0); process.exit(0);
} else if (!command || command === "patch") { } else if (!command || command === "patch") {
// Ask for confirmation before patching // Ask for confirmation before patching
const answer = await prompt("Do you want to patch HTTP Toolkit? [Y/n]: "); const answer = await prompt("Do you want to patch HTTP Toolkit? [Y/n]: ");
if (answer.toLowerCase() === "n" || answer.toLowerCase() === "no") { if (answer.toLowerCase() === "n" || answer.toLowerCase() === "no") {
console.log(chalk.blueBright`[+] Patching cancelled`); console.log(chalk.blueBright('[+] Patching cancelled'));
process.exit(0); process.exit(0);
} }
await patchApp(); await patchApp();
} else { } else {
console.error(chalk.redBright`[-] Unknown command: ${command}`); console.error(chalk.redBright(`[-] Unknown command: ${command}`));
console.log(chalk.yellowBright`[!] Use 'help' to see available commands`); console.log(chalk.yellowBright('[!] Use \'help\' to see available commands'));
process.exit(1); process.exit(1);
} }
} catch (error) { } catch (error) {
console.error(chalk.redBright`[-] Error: ${error.message}`); console.error(chalk.redBright(`[-] Error: ${error.message}`));
process.exit(1); process.exit(1);
} }
})(); })();
+85 -55
View File
@@ -1,36 +1,56 @@
(function injectPageContextHooks() {
const injectionCode = `
(function () { (function () {
console.log("[PAGE-INJECT] Installing hooks in page context"); console.log("[PAGE-INJECT] Installing hooks in page context");
// Properties to hook directly on accountStore (still exist as computed properties)
const propertyHooks = { const propertyHooks = {
isPaidUser: true,
isLoggedIn: true, isLoggedIn: true,
userHasSubscription: true,
userEmail: "hi@httptoolkit.com", userEmail: "hi@httptoolkit.com",
mightBePaidUser: true, mightBePaidUser: true,
isPastDueUser: false,
userSubscription: { userSubscription: {
state: "fulfilled",
status: "active", status: "active",
plan: "pro", plan: "pro",
sku: "sku", sku: "sku",
tierCode: "pro", tierCode: "pro",
interval: "monthly", interval: "monthly",
quantity: 1, quantity: 1,
expiry: new Date("2999-01-01"), expiry: new Date(new Date().setFullYear(new Date().getFullYear() + 10)),
updateBillingDetailsUrl: "https://httptoolkit.com/", updateBillingDetailsUrl: "https://httptoolkit.com/",
cancelSubscriptionUrl: "https://httptoolkit.com/", cancelSubscriptionUrl: "https://httptoolkit.com/",
lastReceiptUrl: "https://httptoolkit.com/", lastReceiptUrl: "https://httptoolkit.com/",
canManageSubscription: true canManageSubscription: true,
} },
};
// Methods to hook on the user object (moved from accountStore properties to user methods in v3.1.0)
const userMethodHooks = {
isPaidUser: true,
isPastDueUser: false,
userHasSubscription: true,
}; };
const hookedObjects = new WeakSet(); const hookedObjects = new WeakSet();
const hookedUsers = new WeakSet();
// Patch user object methods
function patchUserObject(user) {
if (!user || typeof user !== "object" || hookedUsers.has(user)) return;
for (const methodName of Object.keys(userMethodHooks)) {
if (typeof user[methodName] === "function") {
console.log("[PAGE-INJECT] Patching user." + methodName + "()");
user[methodName] = function () {
return userMethodHooks[methodName];
};
}
}
hookedUsers.add(user);
}
// Override Object.defineProperty to intercept all property definitions // Override Object.defineProperty to intercept all property definitions
const originalDefineProperty = Object.defineProperty; const originalDefineProperty = Object.defineProperty;
Object.defineProperty = function (target, prop, descriptor) { Object.defineProperty = function (target, prop, descriptor) {
// Intercept our target properties
if (prop in propertyHooks) { if (prop in propertyHooks) {
console.log("[PAGE-INJECT] Intercepting defineProperty for: " + prop); console.log("[PAGE-INJECT] Intercepting defineProperty for: " + prop);
@@ -47,6 +67,22 @@
} }
} }
// Intercept the 'user' property to patch its methods when it's set/accessed
if (prop === "user") {
console.log("[PAGE-INJECT] Intercepting defineProperty for: user");
if (descriptor && descriptor.get) {
const originalGetter = descriptor.get;
descriptor.get = function () {
const user = originalGetter.call(this);
if (user) patchUserObject(user);
return user;
};
} else if (descriptor && descriptor.value !== undefined && descriptor.value) {
patchUserObject(descriptor.value);
}
}
return originalDefineProperty.call(this, target, prop, descriptor); return originalDefineProperty.call(this, target, prop, descriptor);
}; };
@@ -67,6 +103,20 @@
props[prop].value = propertyHooks[prop]; props[prop].value = propertyHooks[prop];
} }
} }
if (prop === "user") {
console.log("[PAGE-INJECT] Intercepting defineProperties for: user");
if (props[prop].get) {
const originalGetter = props[prop].get;
props[prop].get = function () {
const user = originalGetter.call(this);
if (user) patchUserObject(user);
return user;
};
} else if (props[prop].value !== undefined && props[prop].value) {
patchUserObject(props[prop].value);
}
}
} }
return originalDefineProperties.call(this, target, props); return originalDefineProperties.call(this, target, props);
}; };
@@ -74,17 +124,13 @@
// Periodically scan and patch existing objects // Periodically scan and patch existing objects
function scanAndPatch() { function scanAndPatch() {
// Search through window and common store locations // Search through window and common store locations
const searchPaths = [ const searchPaths = [window, window.accountStore, window.stores && window.stores.accountStore, window.appState && window.appState.accountStore];
window,
window.accountStore,
window.stores && window.stores.accountStore,
window.appState && window.appState.accountStore,
];
searchPaths.forEach((obj, idx) => { searchPaths.forEach((obj, idx) => {
if (!obj || hookedObjects.has(obj)) return; if (!obj || hookedObjects.has(obj)) return;
try { try {
// Patch direct property hooks
Object.keys(propertyHooks).forEach(prop => { Object.keys(propertyHooks).forEach(prop => {
try { try {
const desc = Object.getOwnPropertyDescriptor(obj, prop); const desc = Object.getOwnPropertyDescriptor(obj, prop);
@@ -93,7 +139,7 @@
if (desc.get) { if (desc.get) {
const originalGetter = desc.get; const originalGetter = desc.get;
Object.defineProperty(obj, prop, { originalDefineProperty(obj, prop, {
get: function () { get: function () {
const originalValue = originalGetter.call(this); const originalValue = originalGetter.call(this);
console.log("[PAGE-INJECT] " + prop + " getter intercepted, original=" + originalValue + ", returning=" + JSON.stringify(propertyHooks[prop])); console.log("[PAGE-INJECT] " + prop + " getter intercepted, original=" + originalValue + ", returning=" + JSON.stringify(propertyHooks[prop]));
@@ -101,7 +147,7 @@
}, },
set: desc.set, set: desc.set,
configurable: true, configurable: true,
enumerable: desc.enumerable enumerable: desc.enumerable,
}); });
} else if (desc.writable) { } else if (desc.writable) {
obj[prop] = propertyHooks[prop]; obj[prop] = propertyHooks[prop];
@@ -113,6 +159,14 @@
} }
}); });
// Patch user object if present
try {
if (obj.user && typeof obj.user === "object") {
console.log("[PAGE-INJECT] Found user object on object #" + idx + ", patching methods...");
patchUserObject(obj.user);
}
} catch (e) {}
hookedObjects.add(obj); hookedObjects.add(obj);
} catch (e) { } catch (e) {
// Ignore object access errors // Ignore object access errors
@@ -124,7 +178,7 @@
for (let key in window) { for (let key in window) {
try { try {
const obj = window[key]; const obj = window[key];
if (obj && typeof obj === 'object' && 'accountStore' in obj) { if (obj && typeof obj === "object" && "accountStore" in obj) {
console.log("[PAGE-INJECT] Found accountStore in window." + key); console.log("[PAGE-INJECT] Found accountStore in window." + key);
const store = obj.accountStore; const store = obj.accountStore;
if (store && !hookedObjects.has(store)) { if (store && !hookedObjects.has(store)) {
@@ -133,7 +187,7 @@
const desc = Object.getOwnPropertyDescriptor(store, prop); const desc = Object.getOwnPropertyDescriptor(store, prop);
if (desc && desc.configurable && desc.get) { if (desc && desc.configurable && desc.get) {
const originalGetter = desc.get; const originalGetter = desc.get;
Object.defineProperty(store, prop, { originalDefineProperty(store, prop, {
get: function () { get: function () {
const originalValue = originalGetter.call(this); const originalValue = originalGetter.call(this);
console.log("[PAGE-INJECT] accountStore." + prop + " intercepted, original=" + originalValue + ", returning=" + JSON.stringify(propertyHooks[prop])); console.log("[PAGE-INJECT] accountStore." + prop + " intercepted, original=" + originalValue + ", returning=" + JSON.stringify(propertyHooks[prop]));
@@ -141,11 +195,20 @@
}, },
set: desc.set, set: desc.set,
configurable: true, configurable: true,
enumerable: desc.enumerable enumerable: desc.enumerable,
}); });
} }
} catch (e) {} } catch (e) {}
}); });
// Patch user methods on the store
try {
if (store.user && typeof store.user === "object") {
console.log("[PAGE-INJECT] Found user object in accountStore, patching methods...");
patchUserObject(store.user);
}
} catch (e) {}
hookedObjects.add(store); hookedObjects.add(store);
} }
} }
@@ -163,44 +226,11 @@
scanCount++; scanCount++;
scanAndPatch(); scanAndPatch();
if (scanCount >= 10) { if (scanCount >= 50) {
clearInterval(scanInterval); clearInterval(scanInterval);
console.log("[PAGE-INJECT] Stopped periodic scanning after 10 attempts"); console.log("[PAGE-INJECT] Stopped periodic scanning after 50 attempts");
} }
}, 100); }, 100);
console.log("[PAGE-INJECT] Hooks installed successfully"); console.log("[PAGE-INJECT] Hooks installed successfully");
})(); })();
`;
function injectScript() {
try {
const script = document.createElement('script');
script.textContent = injectionCode;
(document.head || document.documentElement).appendChild(script);
script.remove(); // Clean up the script tag
console.log("[PRELOAD] Injected page context hooks");
} catch (e) {
console.error("[PRELOAD] Failed to inject hooks:", e);
}
}
// Try to inject immediately if DOM is ready, otherwise wait
if (document.documentElement) {
injectScript();
} else {
// Wait for document to be created
const observer = new MutationObserver(() => {
if (document.documentElement) {
observer.disconnect();
injectScript();
}
});
observer.observe(document, { childList: true, subtree: true });
// Also try on DOMContentLoaded as backup
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', injectScript, { once: true });
}
}
})();
+173 -2155
View File
File diff suppressed because it is too large Load Diff
+6 -18
View File
@@ -1,35 +1,23 @@
{ {
"name": "httptoolkit-patcher", "name": "httptoolkit-patcher",
"version": "2.0.5", "version": "2.0.11",
"description": "HTTP Toolkit Pro Patcher", "description": "HTTP Toolkit Pro Patcher",
"main": "index.js", "main": "index.js",
"type": "module", "type": "module",
"bin": "index.js", "bin": "index.js",
"author": "xenos1337",
"scripts": { "scripts": {
"start": "node index.js", "start": "node index.js",
"patch": "node index.js patch", "patch": "node index.js patch",
"unpatch": "node index.js unpatch", "unpatch": "node index.js unpatch",
"restore": "node index.js restore", "restore": "node index.js restore"
"build": "esbuild index.js --bundle --platform=node --format=cjs --target=node18 --outfile=dist/bundle.cjs --external:@electron/asar --external:chalk"
},
"pkg": {
"targets": [
"node18-win-x64",
"node18-linux-x64",
"node18-linux-arm64",
"node18-macos-x64",
"node18-macos-arm64"
],
"outputPath": "dist"
}, },
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@electron/asar": "^3.2.9", "@electron/asar": "^4.1.0",
"chalk": "4" "chalk": "5.6.2"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^20.14.9", "@types/node": "^25.5.0"
"esbuild": "^0.25.11",
"pkg": "^5.8.1"
} }
} }