fix: isolate personal wechat wcf host

This commit is contained in:
Codex
2026-06-13 16:17:25 +00:00
parent 5d484d1ac4
commit 3b6d22d817
5 changed files with 359 additions and 106 deletions
+172 -73
View File
@@ -2,6 +2,9 @@ $ErrorActionPreference = "Stop"
$Root = "C:\UniDesk\personal-wechat"
$WechatRoot = Join-Path $Root "wechat-3.9.12.51"
$ExtractRoot = Join-Path $Root "wechat-3.9.12.51-extracted"
$VersionRoot = Join-Path $ExtractRoot "[3.9.12.51]"
$DataRoot = Join-Path $Root "data\profile"
$WcfRoot = Join-Path $Root "wcf\v39.5.2"
$StateRoot = Join-Path $Root "wcf-state"
$DownloadRoot = Join-Path $Root "downloads"
@@ -10,8 +13,9 @@ $ProgressLog = Join-Path $StateRoot "prepare-progress.log"
$Python = "C:\ProgramData\miniconda3\python.exe"
$PipIndex = "http://mirrors.aliyun.com/pypi/simple/"
$ReleaseBase = "https://github.com/lich0821/WeChatFerry/releases/download/v39.5.2"
$RegistryPath = "HKCU:\Software\Tencent\WeChat"
New-Item -ItemType Directory -Force $WechatRoot,$WcfRoot,$StateRoot,$DownloadRoot | Out-Null
New-Item -ItemType Directory -Force $WechatRoot,$ExtractRoot,$VersionRoot,$DataRoot,$WcfRoot,$StateRoot,$DownloadRoot | Out-Null
$StartedAt = (Get-Date).ToUniversalTime().ToString("o")
function Write-PrepareProgress {
@@ -32,13 +36,13 @@ trap {
error = $message
valuesPrinted = $false
}
$failed | ConvertTo-Json -Depth 6 | Set-Content -Encoding utf8 $PrepareResult
$failed | ConvertTo-Json -Depth 8 | Set-Content -Encoding utf8 $PrepareResult
exit 1
}
function Download-IfMissing {
param([string]$Url, [string]$Path)
if (Test-Path $Path) { return }
if (Test-Path -LiteralPath $Path) { return }
Write-PrepareProgress "download-start $Url"
$tmp = "$Path.part"
Invoke-WebRequest -Uri $Url -OutFile $tmp -UseBasicParsing
@@ -46,18 +50,155 @@ function Download-IfMissing {
Write-PrepareProgress "download-done $Path"
}
function Find-WeChatExe {
function Get-SevenZipPath {
$candidates = @(
(Join-Path $WechatRoot "WeChat.exe"),
"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe",
"C:\Program Files\Tencent\WeChat\WeChat.exe"
"C:\Program Files\7-Zip\7z.exe",
"C:\Program Files (x86)\7-Zip\7z.exe",
"7z.exe"
)
foreach ($candidate in $candidates) {
if (Test-Path $candidate) { return $candidate }
$cmd = Get-Command $candidate -ErrorAction SilentlyContinue
if ($cmd) { return $cmd.Source }
if (Test-Path -LiteralPath $candidate) { return $candidate }
}
return $null
}
function Find-DedicatedWeChatExe {
$candidates = @(
(Join-Path $VersionRoot "WeChat.exe"),
(Join-Path $ExtractRoot "WeChat.exe"),
(Join-Path $WechatRoot "WeChat.exe")
)
foreach ($candidate in $candidates) {
if (!(Test-Path -LiteralPath $candidate)) { continue }
$dir = Split-Path -Parent $candidate
if (Test-Path -LiteralPath (Join-Path $dir "WeChatWin.dll")) { return $candidate }
}
return $null
}
function Ensure-WeChatExtracted {
param([string]$Installer)
$wechatExe = Find-DedicatedWeChatExe
if ($wechatExe) { return [ordered]@{ mode = "dedicated-existing"; wechatExe = $wechatExe } }
$sevenZip = Get-SevenZipPath
if (!$sevenZip) { throw "7-Zip is required to extract the WeChat installer without administrator elevation" }
$extractLog = Join-Path $StateRoot "7z-extract.log"
Write-PrepareProgress "wechat-extract-start $Installer"
& $sevenZip x -y "-o$ExtractRoot" $Installer > $extractLog 2>&1
if ($LASTEXITCODE -ne 0) { throw "7-Zip extract failed; see $extractLog" }
$wechatExe = Find-DedicatedWeChatExe
if (!$wechatExe) { throw "Extracted installer did not produce dedicated WeChat.exe with WeChatWin.dll" }
Write-PrepareProgress "wechat-extract-done $wechatExe"
return [ordered]@{ mode = "nsis-extracted-hkcu-registry-shim"; wechatExe = $wechatExe; extractLog = $extractLog }
}
function Ensure-IsolatedProfile {
$appData = Join-Path $DataRoot "AppData\Roaming"
$localAppData = Join-Path $DataRoot "AppData\Local"
$documents = Join-Path $DataRoot "Documents"
$temp = Join-Path $localAppData "Temp"
New-Item -ItemType Directory -Force $appData,$localAppData,$documents,$temp | Out-Null
return [ordered]@{
dataRoot = $DataRoot
appData = $appData
localAppData = $localAppData
documents = $documents
temp = $temp
}
}
function Ensure-WeChatRegistryShim {
param([string]$WechatExe)
$installPath = Split-Path -Parent $WechatExe
New-Item -Path $RegistryPath -Force | Out-Null
Set-ItemProperty -Path $RegistryPath -Name InstallPath -Value ($installPath + "\")
Set-ItemProperty -Path $RegistryPath -Name Version -Value 0x03090c33 -Type DWord
return $installPath + "\"
}
function Install-Wcferry {
if (!(Test-Path -LiteralPath $Python)) { throw "Expected Python not found: $Python" }
$pipOut = Join-Path $StateRoot "prepare-pip.stdout.log"
$pipErr = Join-Path $StateRoot "prepare-pip.stderr.log"
Write-PrepareProgress "pip-install-start"
& $Python -m pip install --trusted-host mirrors.aliyun.com --index-url $PipIndex --timeout 120 --retries 8 "wcferry==39.5.2.0" > $pipOut 2> $pipErr
if ($LASTEXITCODE -ne 0) { throw "pip install wcferry failed; see $pipErr" }
Write-PrepareProgress "pip-install-done"
$probePy = Join-Path $StateRoot "prepare-probe.py"
@'
import importlib.metadata
import json
import os
import wcferry
payload = {
"ok": True,
"wcferryVersion": importlib.metadata.version("wcferry"),
"packageRoot": os.path.abspath(os.path.dirname(wcferry.__file__)),
}
print(json.dumps(payload, ensure_ascii=False))
'@ | Set-Content -Encoding utf8 $probePy
$pyProbe = (& $Python $probePy) | ConvertFrom-Json
return [ordered]@{
ok = [bool]$pyProbe.ok
version = $pyProbe.wcferryVersion
packageRoot = $pyProbe.packageRoot
stdout = $pipOut
stderr = $pipErr
}
}
function Sync-WcfDlls {
param([string]$PackageRoot)
$dlls = @()
foreach ($name in @("sdk.dll","spy.dll","spy_debug.dll")) {
$src = Join-Path $WcfRoot $name
$dst = Join-Path $PackageRoot $name
if (!(Test-Path -LiteralPath $src)) { throw "Missing WCF release asset: $src" }
if (!(Test-Path -LiteralPath $dst)) { throw "Missing wcferry package dll target: $dst" }
$backup = "$dst.unidesk-bak"
if (!(Test-Path -LiteralPath $backup)) {
Copy-Item -LiteralPath $dst -Destination $backup -Force
}
Copy-Item -LiteralPath $src -Destination $dst -Force
$srcItem = Get-Item -LiteralPath $src
$dstItem = Get-Item -LiteralPath $dst
$dlls += [ordered]@{
name = $name
sourceBytes = $srcItem.Length
targetBytes = $dstItem.Length
targetVersion = $dstItem.VersionInfo.FileVersion
backup = $backup
}
}
return $dlls
}
function Ensure-Firewall {
try {
if (-not (Get-NetFirewallRule -DisplayName "UniDesk Personal WeChat WCF 10086" -ErrorAction SilentlyContinue)) {
New-NetFirewallRule `
-DisplayName "UniDesk Personal WeChat WCF 10086" `
-Direction Inbound `
-Action Allow `
-Protocol TCP `
-LocalPort 10086,10087 `
-RemoteAddress 172.26.0.0/16,10.42.0.0/16,127.0.0.1 `
-Profile Any `
-ErrorAction Stop | Out-Null
return [ordered]@{ ok = $true; applied = $true }
}
return [ordered]@{ ok = $true; applied = $false; alreadyPresent = $true }
} catch {
Write-PrepareProgress "firewall-skip $($_.Exception.Message)"
return [ordered]@{ ok = $false; skipped = $true; reason = $_.Exception.Message }
}
}
Write-PrepareProgress "prepare-start"
$installer = Join-Path $DownloadRoot "WeChatSetup-3.9.12.51.exe"
Download-IfMissing "$ReleaseBase/WeChatSetup-3.9.12.51.exe" $installer
@@ -65,82 +206,40 @@ Download-IfMissing "$ReleaseBase/sdk.dll" (Join-Path $WcfRoot "sdk.dll")
Download-IfMissing "$ReleaseBase/spy.dll" (Join-Path $WcfRoot "spy.dll")
Download-IfMissing "$ReleaseBase/spy_debug.dll" (Join-Path $WcfRoot "spy_debug.dll")
if (!(Test-Path $Python)) {
throw "Expected Python not found: $Python"
}
$pipOut = Join-Path $StateRoot "prepare-pip.stdout.log"
$pipErr = Join-Path $StateRoot "prepare-pip.stderr.log"
Write-PrepareProgress "pip-install-start"
& $Python -m pip install --trusted-host mirrors.aliyun.com --index-url $PipIndex "wcferry==39.5.2.0" > $pipOut 2> $pipErr
if ($LASTEXITCODE -ne 0) { throw "pip install wcferry failed" }
Write-PrepareProgress "pip-install-done"
Copy-Item -Force "$PSScriptRoot\wcf_host.py" (Join-Path $WcfRoot "wcf_host.py")
if (-not (Get-NetFirewallRule -DisplayName "UniDesk Personal WeChat WCF 10086" -ErrorAction SilentlyContinue)) {
New-NetFirewallRule `
-DisplayName "UniDesk Personal WeChat WCF 10086" `
-Direction Inbound `
-Action Allow `
-Protocol TCP `
-LocalPort 10086,10087 `
-RemoteAddress 172.26.0.0/16,10.42.0.0/16,127.0.0.1 `
-Profile Any `
-ErrorAction SilentlyContinue | Out-Null
}
$wechatExe = Find-WeChatExe
$installAttempted = $false
$installExitCode = $null
$installStdout = Join-Path $StateRoot "prepare-wechat-installer.stdout.log"
$installStderr = Join-Path $StateRoot "prepare-wechat-installer.stderr.log"
if (-not $wechatExe) {
$installAttempted = $true
$args = @("/S", "/D=$WechatRoot")
Write-PrepareProgress "wechat-install-start $installer"
$proc = Start-Process -FilePath $installer -ArgumentList $args -Wait -PassThru -RedirectStandardOutput $installStdout -RedirectStandardError $installStderr -WindowStyle Hidden
$installExitCode = $proc.ExitCode
Write-PrepareProgress "wechat-install-exit $installExitCode"
Start-Sleep -Seconds 5
$wechatExe = Find-WeChatExe
}
$probePy = Join-Path $StateRoot "prepare-probe.py"
@'
import importlib.metadata
import json
payload = {"ok": True}
try:
payload["wcferryVersion"] = importlib.metadata.version("wcferry")
except Exception as exc:
payload = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
print(json.dumps(payload, ensure_ascii=False))
'@ | Set-Content -Encoding utf8 $probePy
$pyProbeJson = & $Python $probePy
$pyProbe = $pyProbeJson | ConvertFrom-Json
$wechat = Ensure-WeChatExtracted $installer
$profile = Ensure-IsolatedProfile
$installPath = Ensure-WeChatRegistryShim $wechat.wechatExe
$wcferry = Install-Wcferry
$dlls = Sync-WcfDlls $wcferry.packageRoot
$firewall = Ensure-Firewall
$summary = [ordered]@{
ok = [bool]($pyProbe.ok -and $wechatExe)
ok = [bool]($wechat.wechatExe -and $wcferry.ok)
startedAt = $StartedAt
finishedAt = (Get-Date).ToUniversalTime().ToString("o")
root = $Root
mode = $wechat.mode
wechatInstaller = $installer
wechatRoot = $WechatRoot
wechatExe = $wechatExe
installAttempted = $installAttempted
installExitCode = $installExitCode
installLogs = [ordered]@{
stdout = $installStdout
stderr = $installStderr
}
extractRoot = $ExtractRoot
versionRoot = $VersionRoot
wechatExe = $wechat.wechatExe
installPath = $installPath
registryKey = $RegistryPath
requiredVersion = "3.9.12.51"
profile = $profile
wcfRoot = $WcfRoot
stateRoot = $StateRoot
python = $Python
wcferryVersion = $pyProbe.wcferryVersion
next = if ($wechatExe) { "Run start.ps1 and scan the WeChat login QR." } else { "WeChat silent install did not produce WeChat.exe; run the installer UI from the interactive Windows session, then re-run prepare.ps1." }
wcferryVersion = $wcferry.version
wcferryPackageRoot = $wcferry.packageRoot
dllOverride = $dlls
firewall = $firewall
valuesPrinted = $false
next = "Run start.ps1 and scan the isolated WeChat login QR."
}
Write-PrepareProgress "prepare-done ok=$($summary.ok)"
$summary | ConvertTo-Json -Depth 6 | Set-Content -Encoding utf8 $PrepareResult
$summary | ConvertTo-Json -Depth 6
$summary | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 $PrepareResult
$summary | ConvertTo-Json -Depth 10