mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
fix: 增加@所有人 完善mac发送清理与端口回退
This commit is contained in:
1 parent
c50f8861a4
commit
aca103cb96
9 files changed
+737
-173
No files matched your search
@@ -3524,6 +3524,7 @@ app.whenReady().then(async () => {
|
||||
targets.some(
|
||||
(target) =>
|
||||
target.targets.includes('host') ||
|
||||
target.targets.includes('frida_helper') ||
|
||||
(macWechatRuntimeManager.getPort() === 4290 &&
|
||||
target.targets.includes('port_4290'))
|
||||
)
|
||||
|
||||
@@ -14,13 +14,93 @@ export interface MacWechatResidualCleanupDependencies {
|
||||
platform: NodeJS.Platform
|
||||
listWechatPids: () => Promise<number[]>
|
||||
listHostPids: () => Promise<number[]>
|
||||
listFridaHelperPids: () => Promise<number[]>
|
||||
listPortPids: () => Promise<number[]>
|
||||
processName: (pid: number) => Promise<string>
|
||||
processCommand: (pid: number) => Promise<string>
|
||||
processCwd: (pid: number) => Promise<string>
|
||||
processState: (pid: number) => Promise<string>
|
||||
processIdentity: (pid: number) => Promise<string>
|
||||
signal: (pid: number, signal: NodeJS.Signals) => void
|
||||
wait: (milliseconds: number) => Promise<void>
|
||||
}
|
||||
|
||||
const SEND_HOST_PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
|
||||
function isTraceMemoRuntimePath(value: string): boolean {
|
||||
const normalized = value.replace(/\\/g, '/').toLowerCase()
|
||||
return /\/tracememo(?:\.app\/contents)?\/resources\/runtime\/darwin-arm64(?:\/|$)/.test(
|
||||
normalized
|
||||
)
|
||||
}
|
||||
|
||||
export function isTraceMemoFridaHelper(command: string, cwd: string): boolean {
|
||||
return isTraceMemoRuntimePath(command) || isTraceMemoRuntimePath(cwd)
|
||||
}
|
||||
|
||||
/* 不要把进程信息不可读当作进程已退出:TCC 限制下仍可能有存活进程。 */
|
||||
function resolveProcessName(
|
||||
name: string,
|
||||
command: string,
|
||||
cwd: string,
|
||||
isFridaHelper: boolean
|
||||
): string {
|
||||
const trimmed = name.trim()
|
||||
if (/^frida-hel/.test(trimmed)) return 'frida-helper'
|
||||
if (/^tm-wechat/.test(trimmed)) return 'tm-wechat-host'
|
||||
if (trimmed && trimmed !== 'unknown') return trimmed
|
||||
if (/tm-wechat-host/.test(command)) return 'tm-wechat-host'
|
||||
if (/frida-helper/.test(command)) return 'frida-helper'
|
||||
if (isFridaHelper) return 'frida-helper'
|
||||
if (isTraceMemoRuntimePath(cwd)) return 'tm-wechat-host'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
async function readShortProcessName(pid: number): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/sbin/lsof',
|
||||
['-a', '-p', String(pid), '-d', 'cwd'],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
/* lsof 可能忽略失效的 -p 参数,因此必须核对返回行的 PID。 */
|
||||
for (const line of stdout.split('\n')) {
|
||||
const columns = line.trim().split(/\s+/)
|
||||
if (columns[1] === String(pid)) return columns[0] || ''
|
||||
}
|
||||
return ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function readProcessField(pid: number, field: string): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', `${field}=`], {
|
||||
timeout: 2_000
|
||||
})
|
||||
return stdout.trim()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function readProcessCwd(pid: number): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/sbin/lsof',
|
||||
['-a', '-p', String(pid), '-d', 'cwd', '-Fn'],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
const lines = stdout.split('\n')
|
||||
/* lsof 可能忽略失效的 -p 参数,因此必须核对记录的 PID。 */
|
||||
if (lines.find((line) => line.startsWith('p')) !== `p${pid}`) return ''
|
||||
return lines.find((line) => line.startsWith('n'))?.slice(1) || ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function readPids(
|
||||
executable: string,
|
||||
args: string[],
|
||||
@@ -49,26 +129,58 @@ const defaultDependencies: MacWechatResidualCleanupDependencies = {
|
||||
])
|
||||
return [...new Set(results.flat())]
|
||||
},
|
||||
listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']),
|
||||
listHostPids: () => readPids('/usr/bin/pgrep', ['-x', 'tm-wechat-host']),
|
||||
listPortPids: () =>
|
||||
readPids('/usr/sbin/lsof', [
|
||||
'-nP',
|
||||
'-t',
|
||||
`-iTCP:${SEND_HOST_PORT}`,
|
||||
'-sTCP:LISTEN'
|
||||
]),
|
||||
listHostPids: async () => {
|
||||
const pids = await readPids('/usr/bin/pgrep', ['-x', 'tm-wechat-host'])
|
||||
const [commands, directories] = await Promise.all([
|
||||
Promise.all(pids.map((pid) => readProcessField(pid, 'command'))),
|
||||
Promise.all(pids.map(readProcessCwd))
|
||||
])
|
||||
return pids.filter(
|
||||
(_, index) =>
|
||||
isTraceMemoRuntimePath(commands[index]) || isTraceMemoRuntimePath(directories[index])
|
||||
)
|
||||
},
|
||||
listFridaHelperPids: async () => {
|
||||
const pids = await readPids('/usr/bin/pgrep', ['-f', 'frida-helper'])
|
||||
const [commands, directories] = await Promise.all([
|
||||
Promise.all(pids.map((pid) => readProcessField(pid, 'command'))),
|
||||
Promise.all(pids.map(readProcessCwd))
|
||||
])
|
||||
return pids.filter((_, index) => isTraceMemoFridaHelper(commands[index], directories[index]))
|
||||
},
|
||||
processName: async (pid) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], {
|
||||
timeout: 2_000
|
||||
})
|
||||
return stdout.trim().split('/').pop() || 'unknown'
|
||||
const name = stdout.trim().split('/').pop() || ''
|
||||
if (name) return name
|
||||
} catch {
|
||||
return 'unknown'
|
||||
/* ps 对同用户外部进程可能整体不可用,落到 lsof。 */
|
||||
}
|
||||
return readShortProcessName(pid) || 'unknown'
|
||||
},
|
||||
processCommand: (pid) => readProcessField(pid, 'command'),
|
||||
processCwd: readProcessCwd,
|
||||
processState: (pid) => readProcessField(pid, 'state'),
|
||||
processIdentity: async (pid) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/bin/ps',
|
||||
['-p', String(pid), '-o', 'lstart=', '-o', 'comm='],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
return createHash('sha256').update(stdout.trim()).digest('hex')
|
||||
const [startTime, command, cwd] = await Promise.all([
|
||||
readProcessField(pid, 'lstart'),
|
||||
readProcessField(pid, 'command'),
|
||||
readProcessCwd(pid)
|
||||
])
|
||||
/* 纳入 PID,避免进程退出后复用同一工作目录导致身份碰撞。 */
|
||||
return createHash('sha256')
|
||||
.update([String(pid), startTime, command, cwd].join('\0'))
|
||||
.digest('hex')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
@@ -86,60 +198,129 @@ function mergeTargets(
|
||||
hostPids: number[],
|
||||
portPids: number[],
|
||||
processNames: Map<number, string>,
|
||||
processIdentities: Map<number, string>
|
||||
processIdentities: Map<number, string>,
|
||||
processStates: Map<number, string>,
|
||||
fridaHelperPids: number[]
|
||||
): ObservedTarget[] {
|
||||
const targets = new Map<number, Set<'wechat' | 'host' | 'port_4290'>>()
|
||||
const targets = new Map<number, Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>>()
|
||||
for (const pid of wechatPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>()
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('wechat')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of hostPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>()
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('host')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of portPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>()
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('port_4290')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of fridaHelperPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('frida_helper')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
return [...targets.entries()]
|
||||
.sort(([first], [second]) => first - second)
|
||||
.map(([pid, reasons]) => ({
|
||||
pid,
|
||||
name: processNames.get(pid) || 'unknown',
|
||||
targets: [...reasons].sort(),
|
||||
confirmationToken: processIdentities.get(pid) || ''
|
||||
}))
|
||||
.map(([pid, reasons]) => {
|
||||
const state = processStates.get(pid) || ''
|
||||
return {
|
||||
pid,
|
||||
name: processNames.get(pid) || 'unknown',
|
||||
...(state ? { state } : {}),
|
||||
/* 只有明确的 U 状态才标记为不可中断;状态未知不做推断。 */
|
||||
...(/U/.test(state) ? { uninterruptible: true } : {}),
|
||||
targets: [...reasons].sort(),
|
||||
confirmationToken: processIdentities.get(pid) || ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function inspectObservedTargets(
|
||||
dependencies: MacWechatResidualCleanupDependencies
|
||||
): Promise<ObservedTarget[]> {
|
||||
if (dependencies.platform !== 'darwin') return []
|
||||
const [rawWechatPids, rawHostPids, rawPortPids] = await Promise.all([
|
||||
const [rawWechatPids, rawHostPids, rawPortPids, rawFridaHelperPids] = await Promise.all([
|
||||
dependencies.listWechatPids(),
|
||||
dependencies.listHostPids(),
|
||||
dependencies.listPortPids()
|
||||
dependencies.listPortPids(),
|
||||
dependencies.listFridaHelperPids()
|
||||
])
|
||||
const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid)
|
||||
const hostPids = rawHostPids.filter((pid) => pid !== process.pid)
|
||||
const portPids = rawPortPids.filter((pid) => pid !== process.pid)
|
||||
const pids = [...new Set([...wechatPids, ...portPids])].filter(
|
||||
const fridaHelperPids = rawFridaHelperPids.filter((pid) => pid !== process.pid)
|
||||
const pids = [...new Set([...wechatPids, ...portPids, ...fridaHelperPids])].filter(
|
||||
(pid) => Number.isSafeInteger(pid) && pid > 0
|
||||
)
|
||||
for (const pid of hostPids) {
|
||||
if (Number.isSafeInteger(pid) && pid > 0 && !pids.includes(pid)) pids.push(pid)
|
||||
}
|
||||
const [names, identities] = await Promise.all([
|
||||
const [names, identities, states] = await Promise.all([
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const))
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processState(pid)] as const))
|
||||
])
|
||||
return mergeTargets(wechatPids, hostPids, portPids, new Map(names), new Map(identities))
|
||||
const [commands, directories] = await Promise.all([
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processCommand(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processCwd(pid)] as const))
|
||||
])
|
||||
const commandByPid = new Map(commands)
|
||||
const cwdByPid = new Map(directories)
|
||||
const nameByPid = new Map(names)
|
||||
const filteredFridaHelpers = fridaHelperPids.filter((pid) =>
|
||||
isTraceMemoFridaHelper(commandByPid.get(pid) || '', cwdByPid.get(pid) || '')
|
||||
)
|
||||
const fridaHelperSet = new Set(filteredFridaHelpers)
|
||||
const resolvedNames = new Map<number, string>()
|
||||
for (const pid of pids) {
|
||||
resolvedNames.set(
|
||||
pid,
|
||||
resolveProcessName(
|
||||
nameByPid.get(pid) || '',
|
||||
commandByPid.get(pid) || '',
|
||||
cwdByPid.get(pid) || '',
|
||||
fridaHelperSet.has(pid)
|
||||
)
|
||||
)
|
||||
}
|
||||
return mergeTargets(
|
||||
wechatPids,
|
||||
hostPids,
|
||||
portPids,
|
||||
resolvedNames,
|
||||
new Map(identities),
|
||||
new Map(states),
|
||||
filteredFridaHelpers
|
||||
)
|
||||
}
|
||||
|
||||
async function waitForConfirmedTargets(
|
||||
dependencies: MacWechatResidualCleanupDependencies,
|
||||
selected: ObservedTarget[],
|
||||
attempts: number,
|
||||
intervalMs: number
|
||||
): Promise<ObservedTarget[]> {
|
||||
const expected = new Map(selected.map((target) => [target.pid, target.confirmationToken]))
|
||||
let remaining = selected.filter((target) => !/U/.test(target.state || ''))
|
||||
if (remaining.length === 0) return selected
|
||||
for (let attempt = 0; attempt < attempts && remaining.length > 0; attempt++) {
|
||||
await dependencies.wait(intervalMs)
|
||||
const current = await inspectObservedTargets(dependencies)
|
||||
remaining = current.filter(
|
||||
(target) =>
|
||||
expected.get(target.pid) === target.confirmationToken && !/U/.test(target.state || '')
|
||||
)
|
||||
}
|
||||
const blocked = selected.filter((target) => /U/.test(target.state || ''))
|
||||
return [...remaining, ...blocked]
|
||||
}
|
||||
|
||||
export async function inspectMacWechatResidualProcesses(
|
||||
@@ -170,10 +351,11 @@ export async function cleanupMacWechatResidualProcesses(
|
||||
const selected = current.filter(
|
||||
(target) => confirmed.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
const selectedIdentities = new Map(selected.map((target) => [target.pid, target.confirmationToken]))
|
||||
if (selected.length === 0) {
|
||||
return {
|
||||
stopped: [],
|
||||
remaining: current.filter((target) => confirmed.has(target.pid))
|
||||
remaining: current
|
||||
}
|
||||
}
|
||||
let cleanupTargetsNotified = false
|
||||
@@ -185,7 +367,9 @@ export async function cleanupMacWechatResidualProcesses(
|
||||
const identity = await dependencies.processIdentity(target.pid)
|
||||
if (!expectedIdentity || identity !== expectedIdentity) return
|
||||
if (
|
||||
(target.targets.includes('host') || target.targets.includes('port_4290')) &&
|
||||
(target.targets.includes('host') ||
|
||||
target.targets.includes('port_4290') ||
|
||||
target.targets.includes('frida_helper')) &&
|
||||
!cleanupTargetsNotified
|
||||
) {
|
||||
cleanupTargetsNotified = true
|
||||
@@ -198,33 +382,73 @@ export async function cleanupMacWechatResidualProcesses(
|
||||
}
|
||||
}
|
||||
|
||||
for (const target of selected.filter((item) => item.targets.includes('wechat'))) {
|
||||
await signalMatchingTarget(target, confirmed.get(target.pid) || '', 'SIGTERM')
|
||||
}
|
||||
if (selected.some((item) => item.targets.includes('wechat'))) await dependencies.wait(1_000)
|
||||
|
||||
let remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
let activeTargets = (await inspectObservedTargets(dependencies)).filter(
|
||||
(target) =>
|
||||
confirmed.has(target.pid) &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of remaining) {
|
||||
const selectedTarget = selected.find((item) => item.pid === target.pid)
|
||||
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
|
||||
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGTERM')
|
||||
const hostTargets = activeTargets.filter((target) => target.targets.includes('host'))
|
||||
for (const target of hostTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
if (hostTargets.some((target) => !/U/.test(target.state || ''))) {
|
||||
await dependencies.wait(1_000)
|
||||
await waitForConfirmedTargets(dependencies, hostTargets, 8, 250)
|
||||
}
|
||||
if (remaining.length > 0) await dependencies.wait(1_000)
|
||||
|
||||
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
activeTargets = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid) && selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of remaining) {
|
||||
const helperTargets = activeTargets.filter(
|
||||
(target) =>
|
||||
!target.targets.includes('host') &&
|
||||
target.targets.includes('frida_helper') &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
const unrelatedPortTargets = activeTargets.filter(
|
||||
(target) =>
|
||||
!target.targets.includes('host') &&
|
||||
!target.targets.includes('frida_helper') &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of helperTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
for (const target of unrelatedPortTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
await waitForConfirmedTargets(dependencies, helperTargets, 4, 250)
|
||||
await waitForConfirmedTargets(dependencies, unrelatedPortTargets, 4, 250)
|
||||
|
||||
activeTargets = (await inspectObservedTargets(dependencies)).filter(
|
||||
(target) =>
|
||||
confirmed.has(target.pid) &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
const wechatTargets = activeTargets.filter((target) => target.targets.includes('wechat'))
|
||||
for (const target of wechatTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
await waitForConfirmedTargets(dependencies, wechatTargets, 8, 250)
|
||||
const remainingTargets = activeTargets.filter(
|
||||
(target) =>
|
||||
!target.targets.includes('host') &&
|
||||
!target.targets.includes('frida_helper') &&
|
||||
!target.targets.includes('wechat') &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
await waitForConfirmedTargets(dependencies, remainingTargets, 10, 500)
|
||||
|
||||
activeTargets = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid) && selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of activeTargets) {
|
||||
const selectedTarget = selected.find((item) => item.pid === target.pid)
|
||||
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
|
||||
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGKILL')
|
||||
}
|
||||
if (remaining.length > 0) await dependencies.wait(250)
|
||||
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
)
|
||||
await waitForConfirmedTargets(dependencies, activeTargets, 8, 250)
|
||||
const remaining = await inspectObservedTargets(dependencies)
|
||||
return {
|
||||
stopped: selected
|
||||
.filter((target) => !remaining.some((item) => item.pid === target.pid))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from 'child_process'
|
||||
import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { chmodSync, existsSync } from 'fs'
|
||||
import { get, request as httpRequest } from 'http'
|
||||
import { join } from 'path'
|
||||
@@ -30,6 +31,8 @@ import {
|
||||
MacWechatRuntimeManifestCache
|
||||
} from './mac-wechat-runtime-artifact'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/*
|
||||
* MacWechatRuntimeManager — lifecycle owner of the built-in macOS native
|
||||
* WeChat runtime (tm-wechat-host + libtmwechat.dylib).
|
||||
@@ -48,10 +51,10 @@ import {
|
||||
* auto-binding, that path dead-ends in a 20s attach timeout every time.
|
||||
*/
|
||||
|
||||
/* 默认 4290。进程会 fork 继承监听 fd(CLOEXEC 只挡 exec),
|
||||
* host 崩溃后孤儿进程仍扣着端口,新 host bind 失败会返回 1 无限重启。
|
||||
* 被占用时用 TM_WECHAT_HOST_PORT 指到备用端口。 */
|
||||
const PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
/* Helper 会继承监听 fd,并在 Host 退出后继续持有;它卡在内核不可中断态时
|
||||
* SIGKILL 也不回收,重试同一端口永远失败,所以启动必须允许备用端口。 */
|
||||
const DEFAULT_PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
const PORT_FALLBACK_SPAN = 3
|
||||
const HOST = '127.0.0.1'
|
||||
const START_TIMEOUT_MS = 15_000
|
||||
const REQUEST_TIMEOUT_MS = 30_000
|
||||
@@ -61,6 +64,36 @@ const CRASH_RESTART_DELAY_MS = 1_500
|
||||
const LICENSE_STATUS_TIMEOUT_MS = 8_000
|
||||
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
|
||||
|
||||
/* 仅地址占用可以通过切换端口恢复。 */
|
||||
function isPortConflictDiagnostic(diagnostic: string): boolean {
|
||||
return /address already in use|EADDRINUSE|bind .*failed/i.test(diagnostic)
|
||||
}
|
||||
|
||||
async function describePortHolder(port: number): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/sbin/lsof',
|
||||
['-nP', '-t', `-iTCP:${port}`, '-sTCP:LISTEN'],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
const pid = Number(stdout.trim().split(/\s+/)[0])
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) return ''
|
||||
try {
|
||||
const { stdout: command } = await execFileAsync(
|
||||
'/bin/ps',
|
||||
['-p', String(pid), '-o', 'comm='],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
const name = command.trim().split('/').pop() || 'unknown'
|
||||
return `${name}(PID ${pid})`
|
||||
} catch {
|
||||
return `PID ${pid}(进程信息不可读,可能卡在退出中)`
|
||||
}
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
interface MacWechatSenderStatusInput {
|
||||
snapshot: MacWechatRuntimeSnapshot
|
||||
binding: MacWechatBindingStatus | null
|
||||
@@ -75,6 +108,15 @@ export function shouldClearWechatRestartRequired(
|
||||
return orphanWechatPid > 0 && currentWechatPid > 0 && orphanWechatPid !== currentWechatPid
|
||||
}
|
||||
|
||||
export function formatMacWechatHostStartupFailure(code: number | null, diagnostic: string): string {
|
||||
const lines = diagnostic.trim().split('\n').filter(Boolean)
|
||||
const detail = lines[lines.length - 1]
|
||||
if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}`
|
||||
return code === null
|
||||
? '发送运行时在启动过程中退出'
|
||||
: `发送运行时启动失败(进程退出码 ${code})`
|
||||
}
|
||||
|
||||
export function resolveMacWechatSendMechanism(
|
||||
binding: MacWechatBindingStatus | null,
|
||||
manifest: MacWechatRuntimeManifest | null
|
||||
@@ -226,17 +268,20 @@ export class MacWechatRuntimeManager {
|
||||
private lastError: string | null = null
|
||||
private restartTimer: NodeJS.Timeout | null = null
|
||||
private manuallyStopped = false
|
||||
private activePort = DEFAULT_PORT
|
||||
private portFallbackFrom: number | null = null
|
||||
|
||||
getPort(): number {
|
||||
return PORT
|
||||
return this.activePort
|
||||
}
|
||||
|
||||
getSnapshot(): MacWechatRuntimeSnapshot {
|
||||
return {
|
||||
lifecycle: this.lifecycle,
|
||||
wechatRestartRequired: this.wechatRestartRequired,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
port: PORT,
|
||||
endpoint: `http://${HOST}:${this.activePort}`,
|
||||
port: this.activePort,
|
||||
...(this.portFallbackFrom === null ? {} : { portFallbackFrom: this.portFallbackFrom }),
|
||||
runtimeDir: this.resolveRuntimeDir() ?? undefined,
|
||||
error: this.lastError ?? undefined,
|
||||
binding: this.lastBinding ?? undefined
|
||||
@@ -394,7 +439,7 @@ export class MacWechatRuntimeManager {
|
||||
* frida session, so the app is immediately ready with NO re-bind, exactly
|
||||
* the "keep the send capability process" behaviour the user asked to carry over.
|
||||
*/
|
||||
if (await this.ping()) {
|
||||
if (await this.adoptRunningHost()) {
|
||||
this.lifecycle = 'online'
|
||||
this.child = null
|
||||
this.wechatRestartRequired = false
|
||||
@@ -458,46 +503,151 @@ export class MacWechatRuntimeManager {
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
this.lifecycle = 'starting'
|
||||
this.lastError = null
|
||||
const manifestPath = join(runtimeDir, 'runtime-manifest.json')
|
||||
/* stderr 保持管道以便启动失败时取诊断;运行日志走 hostLogFile。 */
|
||||
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
|
||||
const candidates = this.candidatePorts()
|
||||
const failures: Array<{ port: number; detail: string; portConflict: boolean }> = []
|
||||
|
||||
try {
|
||||
/* Host stderr goes to /dev/null (stdio ignored, see note above), so the
|
||||
* host writes its own log file via TM_WECHAT_LOG_FILE. Without this the
|
||||
* agent's stage beacons (send-enter / cdn-enter / …) are invisible and a
|
||||
* media/CDN stall is undiagnosable. info level so stage beacons show. */
|
||||
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
|
||||
this.child = spawn(
|
||||
hostPath,
|
||||
[
|
||||
'--port',
|
||||
String(PORT),
|
||||
'--manifest',
|
||||
join(runtimeDir, 'runtime-manifest.json'),
|
||||
'--log-level',
|
||||
'info'
|
||||
],
|
||||
{
|
||||
cwd: runtimeDir,
|
||||
stdio: 'ignore',
|
||||
detached: false,
|
||||
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
|
||||
for (const port of candidates) {
|
||||
this.activePort = port
|
||||
this.lifecycle = 'starting'
|
||||
this.lastError = null
|
||||
|
||||
let child: ChildProcess
|
||||
try {
|
||||
child = spawn(
|
||||
hostPath,
|
||||
['--port', String(port), '--manifest', manifestPath, '--log-level', 'info'],
|
||||
{
|
||||
cwd: runtimeDir,
|
||||
stdio: ['ignore', 'ignore', 'pipe'],
|
||||
detached: false,
|
||||
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = String(error)
|
||||
return this.getSnapshot()
|
||||
}
|
||||
this.child = child
|
||||
|
||||
let startupDiagnostic = ''
|
||||
let exitedDuringStartup = false
|
||||
child.stderr?.setEncoding('utf8')
|
||||
child.stderr?.on('data', (chunk: string) => {
|
||||
startupDiagnostic = (startupDiagnostic + chunk).slice(-2_000)
|
||||
})
|
||||
child.on('exit', () => {
|
||||
exitedDuringStartup = true
|
||||
if (this.child === child) this.child = null
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
exitedDuringStartup = true
|
||||
startupDiagnostic += `\nspawn error: ${error.message}`
|
||||
if (this.child === child) this.child = null
|
||||
})
|
||||
|
||||
/* Host 退出就结束等待,不必耗满 healthz 超时。 */
|
||||
let reachable = false
|
||||
const deadline = Date.now() + START_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (await this.ping()) {
|
||||
reachable = true
|
||||
break
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = String(error)
|
||||
return this.getSnapshot()
|
||||
if (exitedDuringStartup) break
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
}
|
||||
|
||||
if (reachable) {
|
||||
this.lifecycle = 'online'
|
||||
this.portFallbackFrom = port === DEFAULT_PORT ? null : DEFAULT_PORT
|
||||
this.attachChildLifecycleHandlers(child, startupDiagnostic)
|
||||
if (this.portFallbackFrom !== null) {
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_port_fallback',
|
||||
details: { preferredPort: DEFAULT_PORT, activePort: port }
|
||||
})
|
||||
}
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
!this.lastBinding ||
|
||||
!this.manifest ||
|
||||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '运行中的 host 与 runtime manifest 不一致'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
const portConflict = isPortConflictDiagnostic(startupDiagnostic)
|
||||
failures.push({
|
||||
port,
|
||||
detail: exitedDuringStartup
|
||||
? formatMacWechatHostStartupFailure(child.exitCode, startupDiagnostic)
|
||||
: '发送运行时未在超时内响应 /healthz',
|
||||
portConflict
|
||||
})
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_port_attempt_failed',
|
||||
details: { port, portConflict }
|
||||
})
|
||||
/* 其他启动失败换端口也不会好,直接停。 */
|
||||
if (!portConflict) break
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
try {
|
||||
child.kill('SIGKILL')
|
||||
} catch {
|
||||
/* 进程可能已在状态检查后退出。 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.child.on('exit', (code) => {
|
||||
const exitedDuringStartup = this.lifecycle === 'starting' && this.startInFlight !== null
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = await this.formatPortRotationFailure(failures)
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
/* Always retry the preferred port first so it is reused once available. */
|
||||
private candidatePorts(): number[] {
|
||||
const ports = [DEFAULT_PORT, this.activePort]
|
||||
for (let offset = 1; offset <= PORT_FALLBACK_SPAN; offset++) ports.push(DEFAULT_PORT + offset)
|
||||
return ports.filter(
|
||||
(port, index) =>
|
||||
Number.isSafeInteger(port) && port > 0 && port < 65_536 && ports.indexOf(port) === index
|
||||
)
|
||||
}
|
||||
|
||||
/* Reuse an existing Host on any supported port before spawning another one. */
|
||||
private async adoptRunningHost(): Promise<boolean> {
|
||||
for (const port of this.candidatePorts()) {
|
||||
const previous = this.activePort
|
||||
this.activePort = port
|
||||
if (await this.ping()) {
|
||||
this.portFallbackFrom = port === DEFAULT_PORT ? null : DEFAULT_PORT
|
||||
return true
|
||||
}
|
||||
this.activePort = previous
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private attachChildLifecycleHandlers(child: ChildProcess, startupDiagnostic: string): void {
|
||||
child.on('exit', (code) => {
|
||||
const wasBound =
|
||||
this.lastBinding?.bound === true ||
|
||||
this.lastBinding?.sessionAttached === true ||
|
||||
this.lastBinding?.bindingState === 'binding'
|
||||
const orphanPid = this.lastBinding?.boundWechatPid || this.lastBinding?.wechatPid || 0
|
||||
this.child = null
|
||||
if (this.child === child) this.child = null
|
||||
this.lastBinding = null
|
||||
if (this.lifecycle === 'stopped') return // deliberate shutdown
|
||||
|
||||
@@ -511,31 +661,24 @@ export class MacWechatRuntimeManager {
|
||||
message: 'host_died_while_bound',
|
||||
details: { code: code ?? null, orphanWechatPid: orphanPid }
|
||||
})
|
||||
} else {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
if (exitedDuringStartup) {
|
||||
this.lastError =
|
||||
code === null
|
||||
? '发送运行时在启动过程中退出'
|
||||
: `发送运行时启动失败(进程退出码 ${code})`
|
||||
}
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_died_while_unbound_auto_restart',
|
||||
details: { code: code ?? null }
|
||||
})
|
||||
if (!exitedDuringStartup) {
|
||||
if (this.restartTimer) clearTimeout(this.restartTimer)
|
||||
this.restartTimer = setTimeout(() => {
|
||||
void this.ensureStarted()
|
||||
}, CRASH_RESTART_DELAY_MS)
|
||||
}
|
||||
return
|
||||
}
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = formatMacWechatHostStartupFailure(code, startupDiagnostic)
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_died_while_unbound_auto_restart',
|
||||
details: { code: code ?? null }
|
||||
})
|
||||
if (this.restartTimer) clearTimeout(this.restartTimer)
|
||||
this.restartTimer = setTimeout(() => {
|
||||
void this.ensureStarted()
|
||||
}, CRASH_RESTART_DELAY_MS)
|
||||
})
|
||||
this.child.on('error', (error) => {
|
||||
child.on('error', (error) => {
|
||||
if (this.lifecycle === 'stopped') return
|
||||
this.child = null
|
||||
if (this.child === child) this.child = null
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '无法启动发送 Host:' + error.message
|
||||
appLogger.write({
|
||||
@@ -545,33 +688,18 @@ export class MacWechatRuntimeManager {
|
||||
details: { detail: error.message }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Wait for /healthz
|
||||
const deadline = Date.now() + START_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (await this.ping()) {
|
||||
this.lifecycle = 'online'
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
!this.lastBinding ||
|
||||
!this.manifest ||
|
||||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '运行中的 host 与 runtime manifest 不一致'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
if (this.child === null) break // died during startup
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
}
|
||||
|
||||
if (this.lifecycle === 'starting') {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = 'host did not answer /healthz in time'
|
||||
}
|
||||
return this.getSnapshot()
|
||||
private async formatPortRotationFailure(
|
||||
failures: Array<{ port: number; detail: string; portConflict: boolean }>
|
||||
): Promise<string> {
|
||||
const last = failures[failures.length - 1]
|
||||
if (!last) return '发送运行时启动失败'
|
||||
if (!failures.some((failure) => failure.portConflict)) return last.detail
|
||||
const holder = await describePortHolder(last.port)
|
||||
const holderText = holder ? `,占用者 ${holder}` : ''
|
||||
if (failures.length === 1) return `${last.detail}${holderText}`
|
||||
return `端口 ${failures.map((failure) => failure.port).join('、')} 均被占用${holderText}。请重启系统释放端口,或用 TM_WECHAT_HOST_PORT 指定其他端口。`
|
||||
}
|
||||
|
||||
private request(
|
||||
@@ -588,7 +716,7 @@ export class MacWechatRuntimeManager {
|
||||
const req = transport(
|
||||
{
|
||||
host: HOST,
|
||||
port: PORT,
|
||||
port: this.activePort,
|
||||
path,
|
||||
method,
|
||||
timeout: timeoutMs,
|
||||
@@ -836,7 +964,7 @@ export class MacWechatRuntimeManager {
|
||||
arch: process.arch,
|
||||
sipDisabled: true,
|
||||
wechatRunning: false,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
endpoint: `http://${HOST}:${this.activePort}`,
|
||||
endpointReady: false,
|
||||
runtimeReady: false,
|
||||
attachReady: false,
|
||||
@@ -891,7 +1019,7 @@ export class MacWechatRuntimeManager {
|
||||
arch: process.arch,
|
||||
sipDisabled: true,
|
||||
wechatRunning: false,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
endpoint: `http://${HOST}:${this.activePort}`,
|
||||
endpointReady: false,
|
||||
runtimeReady: false,
|
||||
attachReady: false,
|
||||
|
||||
@@ -526,37 +526,18 @@ export function PersonalWechatSendPage({
|
||||
if (result.stopped.some((target) => target.targets.includes('wechat'))) {
|
||||
setMacWechatRebindRequired(true)
|
||||
}
|
||||
if (result.stopped.length === 0) {
|
||||
if (result.remaining.length > 0) {
|
||||
setMacResidualProcesses(result.remaining)
|
||||
onNotice('进程状态已变化,请核对更新后的清理目标。')
|
||||
return
|
||||
}
|
||||
setMacResidualDialogOpen(false)
|
||||
setMacResidualProcesses([])
|
||||
await refreshMac4290PortStatus()
|
||||
await restartMacSendRuntime()
|
||||
return
|
||||
}
|
||||
if (result.remaining.length > 0) {
|
||||
setMacResidualProcesses(result.remaining)
|
||||
onNotice(
|
||||
'已结束 ' +
|
||||
result.stopped.length +
|
||||
' 个进程,仍有 ' +
|
||||
result.remaining.length +
|
||||
' 个;请核对后重试。'
|
||||
)
|
||||
} else {
|
||||
setMacResidualDialogOpen(false)
|
||||
setMacResidualProcesses([])
|
||||
}
|
||||
const stillAlive = result.remaining
|
||||
setMacResidualProcesses([])
|
||||
setMacResidualDialogOpen(false)
|
||||
await refreshMac4290PortStatus()
|
||||
if (result.remaining.length === 0) {
|
||||
await restartMacSendRuntime()
|
||||
} else {
|
||||
await refresh()
|
||||
if (stillAlive.length > 0) {
|
||||
onNotice(
|
||||
`${result.stopped.length} 个进程已退出,${stillAlive.length} 个系统无法结束(${stillAlive
|
||||
.map((target) => target.name)
|
||||
.join('、')});正在改用可用端口启动发送组件…`
|
||||
)
|
||||
}
|
||||
await restartMacSendRuntime()
|
||||
} catch (reason) {
|
||||
onNotice(reason instanceof Error ? reason.message : '清理残留进程失败')
|
||||
} finally {
|
||||
@@ -571,9 +552,21 @@ export function PersonalWechatSendPage({
|
||||
if (snapshot.lifecycle !== 'online') {
|
||||
throw new Error(snapshot.error || '发送组件启动失败')
|
||||
}
|
||||
if (snapshot.binding?.runtimeState === 'ready' && snapshot.binding.bound) {
|
||||
onNotice('发送 Host 已启动并连接到已有微信会话。')
|
||||
}
|
||||
await refresh()
|
||||
await refreshMac4290PortStatus()
|
||||
onNotice('已清理并重启发送 Host;如刚才关闭了微信,请重新打开微信并绑定。')
|
||||
if (!snapshot.binding?.bound) {
|
||||
const fallback = snapshot.portFallbackFrom
|
||||
? `${snapshot.portFallbackFrom} 已被占用,已改用 ${snapshot.port} 端口。`
|
||||
: ''
|
||||
onNotice(
|
||||
fallback
|
||||
? `发送 Host 已在 ${snapshot.port} 端口启动。${fallback}`
|
||||
: '已清理并重启发送 Host;如刚才关闭了微信,请重新打开微信并绑定。'
|
||||
)
|
||||
}
|
||||
} catch (reason) {
|
||||
onNotice(reason instanceof Error ? reason.message : '发送组件启动失败')
|
||||
} finally {
|
||||
@@ -1033,8 +1026,8 @@ export function PersonalWechatSendPage({
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>清理微信残留进程?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
将结束下面列出的微信进程,以及所有 TraceMemo 发送 Host(包括未占用 4290 的 Host)。
|
||||
完成清理后会自动重启发送 Host;若列表包含微信,微信会关闭,之后需要重新打开微信并绑定。
|
||||
将结束下面列出的微信进程、TraceMemo 发送 Host 和由 TraceMemo Runtime 启动的 Frida Helper。
|
||||
所有目标都退出后才会自动重启发送 Host;若列表包含微信,微信会关闭,之后需要重新打开微信并绑定。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<ul className="grid gap-2 rounded-md border border-border-subtle p-3 text-sm">
|
||||
@@ -1045,9 +1038,20 @@ export function PersonalWechatSendPage({
|
||||
PID {item.pid} ·{' '}
|
||||
{item.targets
|
||||
.map((target) =>
|
||||
target === 'wechat' ? '微信进程' : target === 'host' ? '发送 Host' : '4290 端口'
|
||||
target === 'wechat'
|
||||
? '微信进程'
|
||||
: target === 'host'
|
||||
? '发送 Host'
|
||||
: target === 'frida_helper'
|
||||
? 'Frida Helper'
|
||||
: '4290 端口'
|
||||
)
|
||||
.join('、')}
|
||||
{item.uninterruptible
|
||||
? ` · 内核不可中断${item.state ? `(${item.state})` : ''}`
|
||||
: item.state
|
||||
? ` · 状态 ${item.state}`
|
||||
: ''}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@@ -25,7 +25,10 @@ export interface MacWechatSendRuntimeAvailabilityResult {
|
||||
export interface MacWechatResidualProcess {
|
||||
pid: number
|
||||
name: string
|
||||
targets: Array<'wechat' | 'host' | 'port_4290'>
|
||||
state?: string
|
||||
/** 明确处于内核不可中断等待状态。 */
|
||||
uninterruptible?: boolean
|
||||
targets: Array<'wechat' | 'host' | 'port_4290' | 'frida_helper'>
|
||||
confirmationToken: string
|
||||
}
|
||||
|
||||
@@ -110,6 +113,8 @@ export interface MacWechatRuntimeSnapshot {
|
||||
wechatRestartRequired: boolean
|
||||
endpoint: string
|
||||
port: number
|
||||
/** 自动切换端口时记录首选端口。 */
|
||||
portFallbackFrom?: number
|
||||
runtimeDir?: string
|
||||
error?: string
|
||||
binding?: MacWechatBindingStatus
|
||||
|
||||
@@ -173,6 +173,53 @@ describe('PersonalWechatSendPage on macOS', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('still starts the runtime when a target survives cleanup, and names it', async () => {
|
||||
const onNotice = vi.fn()
|
||||
cleanupResidualProcesses.mockResolvedValueOnce({
|
||||
stopped: [],
|
||||
remaining: [
|
||||
{
|
||||
pid: 404,
|
||||
name: 'frida-helper',
|
||||
state: 'UE',
|
||||
uninterruptible: true,
|
||||
targets: ['frida_helper', 'port_4290'],
|
||||
confirmationToken: 'process-identity-404'
|
||||
}
|
||||
],
|
||||
runtimeStopped: false
|
||||
})
|
||||
render(<PersonalWechatSendPage onNotice={onNotice} />)
|
||||
|
||||
await screen.findByText('运行环境已就绪')
|
||||
fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' }))
|
||||
fireEvent.click(await screen.findByRole('button', { name: '确认结束进程' }))
|
||||
|
||||
await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce())
|
||||
expect(onNotice).toHaveBeenCalledWith(
|
||||
'0 个进程已退出,1 个系统无法结束(frida-helper);正在改用可用端口启动发送组件…'
|
||||
)
|
||||
})
|
||||
|
||||
it('reports the fallback port when the runtime comes up on a spare one', async () => {
|
||||
listResidualProcesses.mockResolvedValue([])
|
||||
startMacRuntime.mockResolvedValueOnce({
|
||||
lifecycle: 'online',
|
||||
port: 4291,
|
||||
portFallbackFrom: 4290
|
||||
})
|
||||
const onNotice = vi.fn()
|
||||
render(<PersonalWechatSendPage onNotice={onNotice} />)
|
||||
|
||||
await screen.findByText('运行环境已就绪')
|
||||
fireEvent.click(screen.getByRole('button', { name: '清理残留以及微信进程' }))
|
||||
|
||||
await waitFor(() => expect(startMacRuntime).toHaveBeenCalledOnce())
|
||||
expect(onNotice).toHaveBeenCalledWith(
|
||||
'发送 Host 已在 4291 端口启动。4290 已被占用,已改用 4291 端口。'
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the same cleanup button to start the runtime when no residual process exists', async () => {
|
||||
listResidualProcesses.mockResolvedValue([])
|
||||
const onNotice = vi.fn()
|
||||
|
||||
@@ -225,6 +225,23 @@ describe('POST /api/v1/wechat/send', () => {
|
||||
expect(invalid.status).toBe(400)
|
||||
})
|
||||
|
||||
it('透传群聊 @ 全体目标', async () => {
|
||||
const response = await post({
|
||||
to: 'fixture-room@chatroom',
|
||||
isGroup: true,
|
||||
type: 'text',
|
||||
text: '@所有人 请查看这条测试消息',
|
||||
at: { 'notify@all': '所有人' }
|
||||
})
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(lastAction().content).toEqual({
|
||||
type: 'text',
|
||||
text: '@所有人 请查看这条测试消息',
|
||||
at: { 'notify@all': '所有人' }
|
||||
})
|
||||
})
|
||||
|
||||
it('拒绝格式错误的群聊 @ 成员映射', async () => {
|
||||
const response = await post({
|
||||
to: 'fixture-room@chatroom',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
cleanupMacWechatResidualProcesses,
|
||||
isTraceMemoFridaHelper,
|
||||
inspectMacWechatResidualProcesses,
|
||||
readPids,
|
||||
type MacWechatResidualCleanupDependencies
|
||||
@@ -13,8 +14,12 @@ function createDependencies(
|
||||
platform: 'darwin',
|
||||
listWechatPids: vi.fn(async () => [101]),
|
||||
listHostPids: vi.fn(async () => []),
|
||||
listFridaHelperPids: vi.fn(async () => []),
|
||||
listPortPids: vi.fn(async () => [202]),
|
||||
processName: vi.fn(async (pid) => (pid === 101 ? 'WeChat' : 'tm-wechat-host')),
|
||||
processCommand: vi.fn(async () => ''),
|
||||
processState: vi.fn(async () => ''),
|
||||
processCwd: vi.fn(async () => ''),
|
||||
processIdentity: vi.fn(async (pid) => 'identity-' + pid),
|
||||
signal: vi.fn(),
|
||||
wait: vi.fn(async () => undefined),
|
||||
@@ -64,6 +69,98 @@ describe('macOS WeChat residual cleanup', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('lists Frida helpers that retain the configured listener', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
listHostPids: vi.fn(async () => []),
|
||||
listFridaHelperPids: vi.fn(async () => [404]),
|
||||
listPortPids: vi.fn(async () => [404]),
|
||||
processName: vi.fn(async () => '(frida-helper)'),
|
||||
processCommand: vi.fn(async () => '(frida-helper)'),
|
||||
processCwd: vi.fn(async () => '/Applications/TraceMemo.app/Contents/Resources/runtime/darwin-arm64'),
|
||||
processState: vi.fn(async () => 'UE')
|
||||
})
|
||||
|
||||
await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([
|
||||
{
|
||||
pid: 404,
|
||||
name: '(frida-helper)',
|
||||
state: 'UE',
|
||||
uninterruptible: true,
|
||||
targets: ['frida_helper', 'port_4290'],
|
||||
confirmationToken: 'identity-404'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('escalates a helper in kernel wait state and reports it while the system retains it', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
listHostPids: vi.fn(async () => []),
|
||||
listFridaHelperPids: vi.fn(async () => [404]),
|
||||
listPortPids: vi.fn(async () => [404]),
|
||||
processName: vi.fn(async () => '(frida-helper)'),
|
||||
processCommand: vi.fn(async () => '(frida-helper)'),
|
||||
processCwd: vi.fn(async () => '/Applications/TraceMemo.app/Contents/Resources/runtime/darwin-arm64'),
|
||||
processState: vi.fn(async () => 'UE')
|
||||
})
|
||||
const targets = await inspectMacWechatResidualProcesses(dependencies)
|
||||
|
||||
const result = await cleanupMacWechatResidualProcesses(
|
||||
targets.map(({ pid, confirmationToken }) => ({ pid, confirmationToken })),
|
||||
dependencies
|
||||
)
|
||||
|
||||
expect(dependencies.signal).toHaveBeenCalledWith(404, 'SIGTERM')
|
||||
expect(dependencies.signal).toHaveBeenCalledWith(404, 'SIGKILL')
|
||||
expect(dependencies.wait).not.toHaveBeenCalled()
|
||||
expect(result.stopped).toEqual([])
|
||||
expect(result.remaining).toMatchObject([{ pid: 404, state: 'UE', targets: ['frida_helper', 'port_4290'] }])
|
||||
})
|
||||
|
||||
it('uses the process working directory to associate an orphan helper with TraceMemo', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
listHostPids: vi.fn(async () => []),
|
||||
listFridaHelperPids: vi.fn(async () => [405]),
|
||||
listPortPids: vi.fn(async () => []),
|
||||
processCommand: vi.fn(async () => '(frida-helper)'),
|
||||
processCwd: vi.fn(async () => '/Applications/TraceMemo.app/Contents/Resources/runtime/darwin-arm64')
|
||||
})
|
||||
|
||||
await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([
|
||||
{
|
||||
pid: 405,
|
||||
name: 'tm-wechat-host',
|
||||
targets: ['frida_helper'],
|
||||
confirmationToken: 'identity-405'
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('does not list unrelated Frida helpers', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
listHostPids: vi.fn(async () => []),
|
||||
listFridaHelperPids: vi.fn(async () => [405]),
|
||||
listPortPids: vi.fn(async () => []),
|
||||
processCommand: vi.fn(async () => '/opt/debug-tool/frida-helper'),
|
||||
processCwd: vi.fn(async () => '/opt/debug-tool')
|
||||
})
|
||||
|
||||
await expect(inspectMacWechatResidualProcesses(dependencies)).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('identifies an orphan helper by its TraceMemo runtime path', () => {
|
||||
expect(
|
||||
isTraceMemoFridaHelper(
|
||||
'(frida-helper)',
|
||||
'/Applications/TraceMemo.app/Contents/Resources/runtime/darwin-arm64'
|
||||
)
|
||||
).toBe(true)
|
||||
expect(isTraceMemoFridaHelper('/opt/debug-tool/frida-helper', '/opt/debug-tool')).toBe(false)
|
||||
})
|
||||
|
||||
it('does not signal a PID whose process identity changed after confirmation', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
@@ -108,6 +205,39 @@ describe('macOS WeChat residual cleanup', () => {
|
||||
expect(result.remaining.map((target) => target.pid)).toEqual([202])
|
||||
})
|
||||
|
||||
it('waits for a TraceMemo Host to finish normal teardown before signaling its helper', async () => {
|
||||
const sentSignals: Array<[number, NodeJS.Signals]> = []
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
listHostPids: vi.fn(async () => [303]),
|
||||
listFridaHelperPids: vi.fn(async () => [404]),
|
||||
listPortPids: vi.fn(async () => [404]),
|
||||
processName: vi.fn(async (pid) => (pid === 303 ? 'tm-wechat-host' : '(frida-helper)')),
|
||||
processCommand: vi.fn(async (pid) =>
|
||||
pid === 303
|
||||
? '/Applications/TraceMemo.app/Contents/Resources/runtime/darwin-arm64/tm-wechat-host'
|
||||
: '(frida-helper)'
|
||||
),
|
||||
processCwd: vi.fn(async (pid) =>
|
||||
pid === 303 ? '' : '/Applications/TraceMemo.app/Contents/Resources/runtime/darwin-arm64'
|
||||
),
|
||||
processIdentity: vi.fn(async (pid) => 'identity-' + pid),
|
||||
signal: vi.fn((pid, signal) => sentSignals.push([pid, signal])),
|
||||
wait: vi.fn(async () => undefined)
|
||||
})
|
||||
const targets = await inspectMacWechatResidualProcesses(dependencies)
|
||||
|
||||
await cleanupMacWechatResidualProcesses(
|
||||
targets.map(({ pid, confirmationToken }) => ({ pid, confirmationToken })),
|
||||
dependencies
|
||||
)
|
||||
|
||||
expect(sentSignals.findIndex(([pid]) => pid === 303)).toBeLessThan(
|
||||
sentSignals.findIndex(([pid]) => pid === 404)
|
||||
)
|
||||
expect(sentSignals[0]).toEqual([303, 'SIGTERM'])
|
||||
})
|
||||
|
||||
it('reports only identity-matched targets before signaling so the caller can stop its own runtime safely', async () => {
|
||||
const dependencies = createDependencies({
|
||||
listWechatPids: vi.fn(async () => []),
|
||||
@@ -157,6 +287,8 @@ describe('macOS WeChat residual cleanup', () => {
|
||||
onTargetsConfirmed
|
||||
)
|
||||
|
||||
expect(identityReads).toBeGreaterThan(1)
|
||||
|
||||
expect(dependencies.signal).not.toHaveBeenCalled()
|
||||
expect(onTargetsConfirmed).not.toHaveBeenCalled()
|
||||
expect(result.stopped).toEqual([])
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
deriveMacWechatSenderStatus,
|
||||
formatMacWechatHostStartupFailure,
|
||||
MacWechatRuntimeManager,
|
||||
resolveMacWechatSendMechanism
|
||||
} from '../../src/main/services/mac-wechat-runtime-manager'
|
||||
@@ -96,6 +97,11 @@ class ConcurrentStartManager extends MacWechatRuntimeManager {
|
||||
}
|
||||
|
||||
describe('deriveMacWechatSenderStatus', () => {
|
||||
it('shows the Native Host startup diagnostic instead of only exit code 1', () => {
|
||||
expect(formatMacWechatHostStartupFailure(1, 'bind 127.0.0.1:4290 failed: Address already in use\n'))
|
||||
.toBe('发送运行时启动失败(进程退出码 1):bind 127.0.0.1:4290 failed: Address already in use')
|
||||
})
|
||||
|
||||
it('shares one in-flight start promise with concurrent status reads', async () => {
|
||||
const manager = new ConcurrentStartManager()
|
||||
|
||||
|
||||
Reference in new issue
Block a user