mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: windows自动化下统一逻辑
This commit is contained in:
1 parent
915ee73f95
commit
450668f5e6
14 files changed
+1907
-64
No files matched your search
+244
-26
@@ -152,6 +152,18 @@ import {
|
||||
type MsgInsertSwitchName,
|
||||
type MsgInsertSwitchesSnapshot
|
||||
} from './services/msg-insert-switch-service'
|
||||
import type { MsgInsertErrorCode, MsgInsertSwitchStatus } from '../shared/msg-insert-switch'
|
||||
import {
|
||||
msgInsertCapabilityService,
|
||||
type MessageInsertCapability
|
||||
} from './services/msg-insert-capability-service'
|
||||
import { resolveExternalComponent } from './services/external-component-locator'
|
||||
import {
|
||||
isDefinitelyBlocked,
|
||||
isEntitlementBlocked,
|
||||
resolveExitNoticeGate,
|
||||
resolveSwitchPresentation
|
||||
} from './services/exit-notice-gate'
|
||||
import { GroupStatsService } from './services/group-stats-service'
|
||||
import {
|
||||
configureWechatLocalExitNotice,
|
||||
@@ -202,7 +214,6 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
|
||||
const scope = resolveMsgInsertScopeInput()
|
||||
if (scope) {
|
||||
const snapshot = readMsgInsertSwitches(scope)
|
||||
snapshot.sendCapabilityAvailable = !isMacNativeRuntimeUnavailable()
|
||||
/* 退群提示的开关状态来自本地设置(事件驱动,不装规则),
|
||||
* 不是微信库里的 _tm_config。 */
|
||||
snapshot.switches.group_exit_notice = eventModeStatus(
|
||||
@@ -214,7 +225,6 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
sendCapabilityAvailable: !isMacNativeRuntimeUnavailable(),
|
||||
switches: {
|
||||
recall_notice: emptyMsgInsertStatus('recall_notice'),
|
||||
group_exit_notice: eventModeStatus(
|
||||
@@ -227,6 +237,126 @@ function buildMsgInsertSwitchesSnapshot(): MsgInsertSwitchesSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
/** 能力判定需要知道「微信库连没连」,但不需要知道发送是否就绪。 */
|
||||
function capabilityDatabaseReady(): boolean {
|
||||
return Boolean(chat.getChatDb()?.getWcdb4Client())
|
||||
}
|
||||
|
||||
/**
|
||||
* 退群提示与防撤回同为发送能力:授权/组件不成立时 desired 与 effective 一起压
|
||||
* (UI 读 desired),探测失败不落盘,否则正常用户会被误关。
|
||||
*/
|
||||
/** 明确不可用时把本地开关落盘关掉;只写设置文件,不动监控范围。 */
|
||||
function enforceExitNoticeGate(capability: MessageInsertCapability): void {
|
||||
if (!isDefinitelyBlocked(capability)) return
|
||||
if (!wechatLocalExitNoticeService.isEnabled()) return
|
||||
const decision = resolveExitNoticeGate(capability, true)
|
||||
if (!decision.persistDisable) return
|
||||
const disabled = wechatLocalExitNoticeService.setEnabled(false)
|
||||
syncExitNoticeScope()
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'capability-gate',
|
||||
message: '退群内提示已因发送能力不可用自动关闭',
|
||||
details: {
|
||||
reasonCode: capability.reasonCode,
|
||||
entitlementState: capability.entitlementState,
|
||||
nativeComponentState: capability.nativeComponentState,
|
||||
persisted: !disabled.error
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 把授权/组件判定挂到快照上;GET 仍是纯读,不写库不触发 DDL。 */
|
||||
async function attachCapability(
|
||||
snapshot: MsgInsertSwitchesSnapshot
|
||||
): Promise<MsgInsertSwitchesSnapshot> {
|
||||
const capability = await msgInsertCapabilityService.getCapability({
|
||||
databaseReady: capabilityDatabaseReady()
|
||||
})
|
||||
enforceExitNoticeGate(capability)
|
||||
|
||||
/* 两个开关的呈现共用同一判定:授权不成立显示关闭,库没连只压 effective。 */
|
||||
const switches = { ...snapshot.switches }
|
||||
const applyPresentation = (
|
||||
kind: 'recall_notice' | 'group_exit_notice',
|
||||
status: MsgInsertSwitchStatus | undefined
|
||||
): MsgInsertSwitchStatus | undefined => {
|
||||
if (!status) return status
|
||||
const current =
|
||||
kind === 'group_exit_notice'
|
||||
? wechatLocalExitNoticeService.isEnabled()
|
||||
: status.desiredEnabled === true
|
||||
const presentation = resolveSwitchPresentation(kind, current, capability)
|
||||
if (presentation.effectiveEnabled) {
|
||||
return {
|
||||
...status,
|
||||
desiredEnabled: true,
|
||||
effectiveEnabled: true,
|
||||
operationOk: true
|
||||
}
|
||||
}
|
||||
/*
|
||||
* 不要无脑覆盖 errorCode:授权没问题、只是暂时不生效时(库没连、分片没读到),
|
||||
* 用 CAPABILITY_READY 盖上去会把真实原因擦掉,用户看到的是「授权与组件均已就绪」
|
||||
* 配一个点不动的开关。
|
||||
*/
|
||||
const blocked = isEntitlementBlocked(capability)
|
||||
return {
|
||||
...status,
|
||||
desiredEnabled: presentation.desiredEnabled,
|
||||
effectiveEnabled: false,
|
||||
operationOk: false,
|
||||
errorCode: blocked
|
||||
? (capability.reasonCode as MsgInsertErrorCode)
|
||||
: (status.errorCode ?? (capability.reasonCode as MsgInsertErrorCode)),
|
||||
message: blocked ? capability.message : (status.message ?? capability.message)
|
||||
}
|
||||
}
|
||||
switches.recall_notice = applyPresentation('recall_notice', switches.recall_notice)!
|
||||
switches.group_exit_notice = applyPresentation(
|
||||
'group_exit_notice',
|
||||
switches.group_exit_notice
|
||||
)!
|
||||
return {
|
||||
...snapshot,
|
||||
switches,
|
||||
capability: capability,
|
||||
/* 旧字段保留一个与真实判定一致的值,避免老调用方继续读到一个恒 true */
|
||||
sendCapabilityAvailable: capability.canEnable
|
||||
}
|
||||
}
|
||||
|
||||
/** 能力原因 → 开关错误码。三种「不可用」必须能区分开。 */
|
||||
function reasonToErrorCode(capability: MessageInsertCapability): MsgInsertErrorCode {
|
||||
switch (capability.reasonCode) {
|
||||
case 'LICENSE_REQUIRED':
|
||||
return 'LICENSE_REQUIRED'
|
||||
case 'LICENSE_PENDING':
|
||||
return 'LICENSE_PENDING'
|
||||
case 'LICENSE_EXPIRED':
|
||||
return 'LICENSE_EXPIRED'
|
||||
case 'COMPONENT_MISSING':
|
||||
case 'COMPONENT_INVALID':
|
||||
return 'COMPONENT_MISSING'
|
||||
case 'DATABASE_UNAVAILABLE':
|
||||
return 'DATABASE_UNAVAILABLE'
|
||||
default:
|
||||
return 'CAPABILITY_UNAVAILABLE'
|
||||
}
|
||||
}
|
||||
|
||||
/** 开启前的统一裁决:拿最新状态,不信页面缓存。 */
|
||||
async function requireCapability(): Promise<{
|
||||
ok: boolean
|
||||
capability: MessageInsertCapability
|
||||
}> {
|
||||
const capability = await msgInsertCapabilityService.refresh({
|
||||
databaseReady: capabilityDatabaseReady()
|
||||
})
|
||||
return { ok: capability.canEnable, capability }
|
||||
}
|
||||
|
||||
/**
|
||||
* 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。
|
||||
*
|
||||
@@ -250,14 +380,14 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
|
||||
if (!scope || !client) return
|
||||
|
||||
let enabled = false
|
||||
let shardSignature = ''
|
||||
try {
|
||||
const shards = client.listMessageShardPaths()
|
||||
const shardSignature = shards.map((item) => path.basename(item)).join(',')
|
||||
shardSignature = shards.map((item) => path.basename(item)).join(',')
|
||||
if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) {
|
||||
/* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */
|
||||
console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则')
|
||||
}
|
||||
lastMsgInsertReconciledShards = shardSignature
|
||||
for (const shardPath of shards) {
|
||||
const read = client.getMsgInsertSwitches(shardPath)
|
||||
if (read.success && read.switches?.recall_notice) {
|
||||
@@ -270,15 +400,23 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
|
||||
return
|
||||
}
|
||||
if (!enabled) return
|
||||
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||||
|
||||
/*
|
||||
* 授权前置:没有有效授权时不许 spawn helper 装规则。
|
||||
* 指纹**不在这里更新** —— 没补成功就记指纹,会让「无授权跳过 → 后来激活 →
|
||||
* 分片没变 → 永远不再补」这个死循环成立。
|
||||
*/
|
||||
const gate = await requireCapability()
|
||||
if (!gate.ok) {
|
||||
console.log(
|
||||
`[MsgInsert] 启动补齐已跳过:${gate.capability.reasonCode}(${gate.capability.message})`
|
||||
)
|
||||
return
|
||||
}
|
||||
const done = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||||
if (done) lastMsgInsertReconciledShards = shardSignature
|
||||
}
|
||||
|
||||
/**
|
||||
* 防撤回的作用面 = 全部可定位会话(群聊 + 私聊)。
|
||||
*
|
||||
* native 侧有「定义漂移就 DROP + 重建」的能力,但只有显式复核时才会跑;
|
||||
* 规则定义变了不自动铺开,用户就得手动关-开一次开关。
|
||||
*/
|
||||
function recallRoomsForReconcile(scope: MsgInsertScopeInput): string[] {
|
||||
return resolveTargetRooms(scope, 'recall_notice').rooms
|
||||
}
|
||||
@@ -287,6 +425,15 @@ async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise<bo
|
||||
const scope = resolveMsgInsertScopeInput()
|
||||
const client = chat.getChatDb()?.getWcdb4Client()
|
||||
if (!scope || !client) return false
|
||||
/*
|
||||
* 底层兜底:不管从哪条路径进来(启动 / 刷新 / 清理 / 未来的新调用方),
|
||||
* 装规则前都过一次发送能力校验。上层已经判过也不亏——命中 TTL 缓存几乎零成本。
|
||||
*/
|
||||
const gate = await requireCapability()
|
||||
if (!gate.ok) {
|
||||
console.warn(`[MsgInsert] 拒绝安装规则:${gate.capability.reasonCode}`)
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const result = await reconcileMsgInsertRules({
|
||||
...scope,
|
||||
@@ -347,8 +494,21 @@ async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
|
||||
* 删除必须借 helper 的可写连接:本进程对分片只有只读连接,自己发 DROP 一定失败。
|
||||
* helper 那条链路会在装规则时顺手清掉残留,顺带把新规则铺到所有会话。
|
||||
*/
|
||||
/*
|
||||
* 清理只能借 helper 的 ensure-rules 完成(没有独立的 drop-only 动作),
|
||||
* 而 ensure-rules 会顺手把新规则铺到所有会话 —— 那属于写库动作。
|
||||
* 所以没有授权时只保留残留、不执行清理,绝不拿「清理」当借口绕开门禁。
|
||||
*/
|
||||
const scope = resolveMsgInsertScopeInput()
|
||||
const applied = scope ? await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) : false
|
||||
let applied = false
|
||||
if (scope) {
|
||||
const gate = await requireCapability()
|
||||
if (gate.ok) {
|
||||
applied = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||||
} else {
|
||||
console.log(`[RecallResidue] 无有效授权,跳过残留清理(${gate.capability.reasonCode})`)
|
||||
}
|
||||
}
|
||||
|
||||
/* 收尾结论以「重新扫描」为准,不采信 helper 的自述。 */
|
||||
const after = client.scanLegacyRecallResidue()
|
||||
@@ -392,7 +552,6 @@ import type {
|
||||
PersonalWechatSendResult,
|
||||
PersonalWechatSenderStatus
|
||||
} from '../shared/personal-wechat'
|
||||
import { isMacNativeRuntimeUnavailable } from './native-runtime-paths'
|
||||
import { isTruthyDebugFlag } from '../shared/debug-flags'
|
||||
import { TextToSpeechSettingsService } from './services/text-to-speech-settings-service'
|
||||
import type {
|
||||
@@ -1211,6 +1370,47 @@ app.whenReady().then(async () => {
|
||||
message: 'TraceMemo 启动',
|
||||
details: { build: BUILD_MARK, platform: process.platform, version: app.getVersion() }
|
||||
})
|
||||
/*
|
||||
* 发送能力组件解析结果单独落一条日志。
|
||||
* 现场排障时这是第一分界线:「组件没解析到」和「解析到了但授权不过」是两条完全不同的
|
||||
* 排查路径,用户报「装了没生效」先看这一行,不要先去怀疑授权。
|
||||
*/
|
||||
const external = resolveExternalComponent()
|
||||
console.log(
|
||||
external
|
||||
? `[Component] resolved version=${external.version} dirty=${external.dirty} dir=${external.dir}`
|
||||
: '[Component] not resolved (no current.json, or manifest size/sha256 check failed)'
|
||||
)
|
||||
appLogger.write({
|
||||
level: external ? 'info' : 'warn',
|
||||
scope: 'component-locate',
|
||||
message: external ? '已加载发送能力组件' : '未找到可用的发送能力组件',
|
||||
details: external
|
||||
? {
|
||||
version: external.version,
|
||||
dir: external.dir,
|
||||
helper: external.helperPath,
|
||||
worktreeDirty: external.dirty
|
||||
}
|
||||
: {
|
||||
platform: process.platform,
|
||||
expected: '%LOCALAPPDATA%\\TraceMemo\\Pro\\windows-x64\\current.json'
|
||||
}
|
||||
})
|
||||
/* 启动即对齐本地开关,否则 enabled=true 会潜伏,授权一恢复就自己开跑。 */
|
||||
void msgInsertCapabilityService
|
||||
.refresh({ databaseReady: capabilityDatabaseReady() })
|
||||
.then((capability) => {
|
||||
enforceExitNoticeGate(capability)
|
||||
})
|
||||
.catch((error) => {
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'capability-gate',
|
||||
message: '启动对齐退群内提示失败',
|
||||
details: { error: error instanceof Error ? error.message : String(error) }
|
||||
})
|
||||
})
|
||||
process.on('uncaughtException', (error) => {
|
||||
appLogger.write({
|
||||
level: 'error',
|
||||
@@ -2203,10 +2403,11 @@ app.whenReady().then(async () => {
|
||||
* 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能
|
||||
* 真的生效(规则可能没装齐),渲染层不能只看前者。
|
||||
*/
|
||||
ipcMain.handle('automation:getMsgInsertSwitches', () => {
|
||||
ipcMain.handle('automation:getMsgInsertSwitches', async () => {
|
||||
/* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。
|
||||
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。 */
|
||||
return buildMsgInsertSwitchesSnapshot()
|
||||
* 需要顺带补齐规则的场景走 automation:refreshMsgInsertSwitches。
|
||||
* 授权判定只走本机 HTTP + 文件 stat,同样不碰数据库。 */
|
||||
return attachCapability(buildMsgInsertSwitchesSnapshot())
|
||||
})
|
||||
/**
|
||||
* 微信消息插入开关 —— **运行期刷新**(允许在分片集合变化时补一次规则)。
|
||||
@@ -2226,16 +2427,28 @@ app.whenReady().then(async () => {
|
||||
.listMessageShardPaths()
|
||||
.map((item) => path.basename(item))
|
||||
.join(',')
|
||||
/*
|
||||
* 分片变了只在「确实有授权」时补齐。
|
||||
* 指纹必须**补齐成功之后**才更新:否则无授权跳过一次,等用户激活回来
|
||||
* 分片没变,就再也不会补了(这正是原实现的坑)。
|
||||
*/
|
||||
if (signature !== lastMsgInsertReconciledShards) {
|
||||
lastMsgInsertReconciledShards = signature
|
||||
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
|
||||
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||||
const gate = await requireCapability()
|
||||
if (gate.ok) {
|
||||
console.log('[MsgInsert] 运行期检测到消息分片变化,重新补齐规则')
|
||||
const done = await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
|
||||
if (done) lastMsgInsertReconciledShards = signature
|
||||
} else {
|
||||
console.log(
|
||||
`[MsgInsert] 跳过运行期补齐:${gate.capability.reasonCode}(授权恢复后会自动重试)`
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[MsgInsert] 运行期补齐失败:', error)
|
||||
}
|
||||
}
|
||||
return buildMsgInsertSwitchesSnapshot()
|
||||
return attachCapability(buildMsgInsertSwitchesSnapshot())
|
||||
})
|
||||
/**
|
||||
* 微信消息插入开关 —— 写入。
|
||||
@@ -2255,12 +2468,17 @@ app.whenReady().then(async () => {
|
||||
message: '未知的开关'
|
||||
}
|
||||
}
|
||||
if (isMacNativeRuntimeUnavailable()) {
|
||||
return {
|
||||
success: false,
|
||||
status: emptyMsgInsertStatus(name, 'HELPER_NOT_FOUND', '微信内消息插入仅在 TraceMemo 具备发送能力时开放'),
|
||||
errorCode: 'HELPER_NOT_FOUND',
|
||||
message: '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响'
|
||||
/* 只拦开启;关闭永远放行,否则规则会永久锁在微信库里。 */
|
||||
if (payload.enabled === true) {
|
||||
const gate = await requireCapability()
|
||||
if (!gate.ok) {
|
||||
const code = reasonToErrorCode(gate.capability)
|
||||
return {
|
||||
success: false,
|
||||
status: emptyMsgInsertStatus(name, code, gate.capability.message),
|
||||
errorCode: code,
|
||||
message: gate.capability.message
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { MessageInsertCapability } from './msg-insert-capability-service'
|
||||
|
||||
/** 退群内提示开关的判定:授权或组件不成立时必须显示关闭;库没连只压 effective。 */
|
||||
|
||||
export interface ExitNoticeGateDecision {
|
||||
/** 界面开关值 */
|
||||
desiredEnabled: boolean
|
||||
/** 是否真的在生效 */
|
||||
effectiveEnabled: boolean
|
||||
/** 只在明确否定时落盘;探测失败不落盘,避免误关正常用户的开关。 */
|
||||
persistDisable: boolean
|
||||
}
|
||||
|
||||
/** 授权维度是否成立(不含微信库连接)。 */
|
||||
export function isEntitlementBlocked(capability: MessageInsertCapability): boolean {
|
||||
return capability.entitlementState !== 'valid' || capability.nativeComponentState !== 'ready'
|
||||
}
|
||||
|
||||
/** 明确否定(不含 unavailable:那是「不知道」,不是「不行」)。 */
|
||||
export function isDefinitelyBlocked(capability: MessageInsertCapability): boolean {
|
||||
return (
|
||||
capability.entitlementState === 'invalid' ||
|
||||
capability.entitlementState === 'unsupported' ||
|
||||
capability.nativeComponentState === 'missing' ||
|
||||
capability.nativeComponentState === 'invalid' ||
|
||||
capability.nativeComponentState === 'incompatible'
|
||||
)
|
||||
}
|
||||
|
||||
export function resolveExitNoticeGate(
|
||||
capability: MessageInsertCapability,
|
||||
runtimeEnabled: boolean
|
||||
): ExitNoticeGateDecision {
|
||||
if (isEntitlementBlocked(capability)) {
|
||||
return {
|
||||
desiredEnabled: false,
|
||||
effectiveEnabled: false,
|
||||
persistDisable: isDefinitelyBlocked(capability) && runtimeEnabled
|
||||
}
|
||||
}
|
||||
/*
|
||||
* 授权与组件都就绪,只是微信库没连:用户意愿保留(连上自动恢复),
|
||||
* 但此刻没有真的在跑。
|
||||
*/
|
||||
if (runtimeEnabled && !capability.canEnable) {
|
||||
return { desiredEnabled: true, effectiveEnabled: false, persistDisable: false }
|
||||
}
|
||||
return {
|
||||
desiredEnabled: runtimeEnabled,
|
||||
effectiveEnabled: runtimeEnabled && capability.canEnable,
|
||||
persistDisable: false
|
||||
}
|
||||
}
|
||||
|
||||
/** 界面呈现结果(只有开关的两个布尔值,不含落盘决策)。 */
|
||||
export interface SwitchPresentation {
|
||||
desiredEnabled: boolean
|
||||
effectiveEnabled: boolean
|
||||
}
|
||||
|
||||
/** 两个开关共用这套呈现判定:授权不成立时都显示关闭,但关闭操作永远放行。 */
|
||||
export function resolveSwitchPresentation(
|
||||
kind: 'recall_notice' | 'group_exit_notice',
|
||||
currentDesired: boolean,
|
||||
capability: MessageInsertCapability
|
||||
): SwitchPresentation {
|
||||
if (kind === 'group_exit_notice') {
|
||||
const gate = resolveExitNoticeGate(capability, currentDesired)
|
||||
return { desiredEnabled: gate.desiredEnabled, effectiveEnabled: gate.effectiveEnabled }
|
||||
}
|
||||
if (isEntitlementBlocked(capability)) {
|
||||
return { desiredEnabled: false, effectiveEnabled: false }
|
||||
}
|
||||
return {
|
||||
desiredEnabled: currentDesired,
|
||||
effectiveEnabled: currentDesired && capability.canEnable
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
/**
|
||||
* 发送能力组件定位:读 current.json 找目录,按 manifest 校验 size/sha256,不过当没装。
|
||||
* 组件放用户目录,避免被自动更新清掉。
|
||||
*/
|
||||
|
||||
export interface ComponentLocation {
|
||||
dir: string
|
||||
helperPath: string
|
||||
version: string
|
||||
/** 打包时工作区是否 dirty(内部调试构建标识,正式发布不应出现) */
|
||||
dirty: boolean
|
||||
}
|
||||
|
||||
interface ManifestFile {
|
||||
path?: unknown
|
||||
size?: unknown
|
||||
sha256?: unknown
|
||||
}
|
||||
|
||||
const HELPER_NAME = 'tm-wcdb-config-helper.exe'
|
||||
|
||||
const verifyCache = new Map<string, { stamp: string; ok: boolean; dirty: boolean }>()
|
||||
|
||||
function sha256File(filePath: string): string | null {
|
||||
try {
|
||||
const hash = crypto.createHash('sha256')
|
||||
hash.update(fs.readFileSync(filePath))
|
||||
return hash.digest('hex')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function verifyManifest(dir: string): { ok: boolean; dirty: boolean } {
|
||||
const manifestPath = path.join(dir, 'manifest.json')
|
||||
let stat: fs.Stats
|
||||
try {
|
||||
stat = fs.statSync(manifestPath)
|
||||
} catch {
|
||||
return { ok: false, dirty: false }
|
||||
}
|
||||
const stamp = `${dir}|${stat.mtimeMs}|${stat.size}`
|
||||
const cached = verifyCache.get(dir)
|
||||
if (cached && cached.stamp === stamp) return { ok: cached.ok, dirty: cached.dirty }
|
||||
|
||||
let ok = false
|
||||
let dirty = false
|
||||
try {
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as {
|
||||
worktreeDirty?: unknown
|
||||
files?: ManifestFile[]
|
||||
}
|
||||
dirty = manifest.worktreeDirty === true
|
||||
const files = Array.isArray(manifest.files) ? manifest.files : []
|
||||
if (files.length === 0) {
|
||||
ok = false
|
||||
} else {
|
||||
ok = files.every((entry) => {
|
||||
const name = typeof entry.path === 'string' ? entry.path : ''
|
||||
if (!name) return false
|
||||
const target = path.join(dir, name)
|
||||
let size = -1
|
||||
try {
|
||||
size = fs.statSync(target).size
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (typeof entry.size === 'number' && size !== entry.size) return false
|
||||
if (typeof entry.sha256 === 'string' && entry.sha256.length === 64) {
|
||||
return sha256File(target) === entry.sha256
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
ok = false
|
||||
}
|
||||
verifyCache.set(dir, { stamp, ok, dirty })
|
||||
return { ok, dirty }
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回发送能力组件位置;不存在、校验失败、非 Windows 一律返回 null。
|
||||
* 调用方拿到 null 时应当把它当作「组件没装」,而不是「没授权」。
|
||||
*/
|
||||
export function resolveExternalComponent(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
platform: NodeJS.Platform = process.platform
|
||||
): ComponentLocation | null {
|
||||
if (platform !== 'win32') return null
|
||||
const localAppData = env.LOCALAPPDATA
|
||||
if (!localAppData) return null
|
||||
|
||||
const root = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64')
|
||||
const pointerPath = path.join(root, 'current.json')
|
||||
if (!fs.existsSync(pointerPath)) return null
|
||||
|
||||
let version = ''
|
||||
let dir = ''
|
||||
try {
|
||||
const pointer = JSON.parse(fs.readFileSync(pointerPath, 'utf8')) as {
|
||||
version?: unknown
|
||||
dir?: unknown
|
||||
}
|
||||
version = typeof pointer.version === 'string' ? pointer.version : ''
|
||||
dir = typeof pointer.dir === 'string' ? pointer.dir : ''
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!version || !dir) return null
|
||||
try {
|
||||
if (!fs.statSync(dir).isDirectory()) return null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
const helperPath = path.join(dir, HELPER_NAME)
|
||||
if (!fs.existsSync(helperPath)) return null
|
||||
|
||||
const verified = verifyManifest(dir)
|
||||
if (!verified.ok) return null
|
||||
|
||||
return { dir, helperPath, version, dirty: verified.dirty }
|
||||
}
|
||||
|
||||
/** 测试用:清掉校验缓存 */
|
||||
export function resetComponentCache(): void {
|
||||
verifyCache.clear()
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
import fs from 'node:fs'
|
||||
import http from 'node:http'
|
||||
|
||||
import type { CapabilityReasonCode } from '../../shared/msg-insert-switch'
|
||||
import { hasMacNativeBundle, isMacNativeRuntimeUnavailable } from '../native-runtime-paths'
|
||||
import { resolveHelperPath } from './msg-insert-switch-service'
|
||||
|
||||
/**
|
||||
* 发送能力的唯一判定入口:授权、原生组件、库连接分开算,任一项不确定都不许开启。
|
||||
* 4290 的 JSON 本机可伪造,这里只是应用层门禁,真正的校验在原生 helper。
|
||||
*/
|
||||
|
||||
export type { CapabilityReasonCode }
|
||||
|
||||
export type EntitlementState = 'valid' | 'invalid' | 'pending' | 'unavailable' | 'unsupported'
|
||||
|
||||
export type NativeComponentState = 'ready' | 'missing' | 'invalid' | 'incompatible'
|
||||
|
||||
export interface MessageInsertCapability {
|
||||
/** 授权 */
|
||||
entitlementState: EntitlementState
|
||||
/** 发送能力组件 */
|
||||
nativeComponentState: NativeComponentState
|
||||
/** 微信数据库是否已连接(不代表发送能力) */
|
||||
databaseReady: boolean
|
||||
/** 是否允许「开启」发送能力 */
|
||||
canEnable: boolean
|
||||
/** 关闭永远不因授权被拒,否则用户没法把自己开过的功能关掉。 */
|
||||
canDisable: boolean
|
||||
reasonCode: CapabilityReasonCode
|
||||
/** 给人看的一句话 */
|
||||
message: string
|
||||
/** Hook 原始状态名,仅用于诊断展示 */
|
||||
licenseStatus?: string
|
||||
/** 判定时间戳 */
|
||||
checkedAt: number
|
||||
}
|
||||
|
||||
export interface CapabilityInput {
|
||||
/** 微信库是否已连接(由主进程按 chat 状态传入) */
|
||||
databaseReady: boolean
|
||||
}
|
||||
|
||||
export interface LicenseProbeResult {
|
||||
ok: boolean
|
||||
status?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface CapabilityDeps {
|
||||
platform: NodeJS.Platform
|
||||
/** mac:是否 native 包 */
|
||||
hasMacNativeBundle: () => boolean
|
||||
/** mac:是否 public 包(拿不到 native 运行时) */
|
||||
isMacRuntimeUnavailable: () => boolean
|
||||
/** 发送能力组件路径;null = 缺失 */
|
||||
resolveNativeComponent: () => string | null
|
||||
/** 授权探测(Windows) */
|
||||
probeLicense: (timeoutMs: number) => Promise<LicenseProbeResult>
|
||||
/** 组件文件探测(便于测试注入) */
|
||||
statFile?: (filePath: string) => { size: number } | null
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
const DEFAULT_TTL_MS = 30_000
|
||||
const PROBE_TIMEOUT_MS = 1_200
|
||||
|
||||
/** Hook 的 LicenseStatus → 授权状态。只有明确可接受的结果才算 valid。 */
|
||||
export function mapLicenseStatus(status: string | undefined): {
|
||||
entitlement: EntitlementState
|
||||
reasonCode: CapabilityReasonCode
|
||||
message: string
|
||||
} {
|
||||
switch (status) {
|
||||
case 'LICENSE_OK':
|
||||
return { entitlement: 'valid', reasonCode: 'CAPABILITY_READY', message: '授权有效' }
|
||||
case 'LICENSE_CHECKING':
|
||||
return {
|
||||
entitlement: 'pending',
|
||||
reasonCode: 'LICENSE_PENDING',
|
||||
message: '授权正在验证,请稍候'
|
||||
}
|
||||
case 'LICENSE_EXPIRED':
|
||||
return {
|
||||
entitlement: 'invalid',
|
||||
reasonCode: 'LICENSE_EXPIRED',
|
||||
message: '授权已过期,请重新激活后再开启'
|
||||
}
|
||||
case 'LICENSE_MACHINE_MISMATCH':
|
||||
return {
|
||||
entitlement: 'invalid',
|
||||
reasonCode: 'LICENSE_MACHINE_MISMATCH',
|
||||
message: '这份授权不属于本机'
|
||||
}
|
||||
case 'LICENSE_REVOKED':
|
||||
return {
|
||||
entitlement: 'invalid',
|
||||
reasonCode: 'LICENSE_REVOKED',
|
||||
message: '授权已被吊销'
|
||||
}
|
||||
case 'LICENSE_INVALID':
|
||||
case 'LICENSE_TAMPERED':
|
||||
return {
|
||||
entitlement: 'invalid',
|
||||
reasonCode: 'LICENSE_INVALID',
|
||||
message: '授权无效,请重新激活'
|
||||
}
|
||||
case 'LICENSE_NOT_FOUND':
|
||||
return {
|
||||
entitlement: 'invalid',
|
||||
reasonCode: 'LICENSE_REQUIRED',
|
||||
message: '未检测到有效授权'
|
||||
}
|
||||
case 'LICENSE_NETWORK_ERROR':
|
||||
case 'LICENSE_SERVER_ERROR':
|
||||
return {
|
||||
entitlement: 'unavailable',
|
||||
reasonCode: 'LICENSE_UNAVAILABLE',
|
||||
message: '授权服务暂时不可用,稍后再试'
|
||||
}
|
||||
default:
|
||||
// 未知状态一律 fail-closed,但要说清「是未知」而不是「你没买」
|
||||
return {
|
||||
entitlement: 'unavailable',
|
||||
reasonCode: 'LICENSE_UNAVAILABLE',
|
||||
message: '暂时无法确认授权状态'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测本机 Hook 的授权接口。失败只报失败,不臆测状态。 */
|
||||
export function probeLicenseStatus(timeoutMs = PROBE_TIMEOUT_MS): Promise<LicenseProbeResult> {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false
|
||||
const done = (result: LicenseProbeResult): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve(result)
|
||||
}
|
||||
let req: http.ClientRequest
|
||||
try {
|
||||
req = http.get(
|
||||
{ host: '127.0.0.1', port: 4290, path: '/license/status', timeout: timeoutMs },
|
||||
(res) => {
|
||||
const chunks: Buffer[] = []
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as {
|
||||
status?: unknown
|
||||
}
|
||||
done({ ok: true, status: typeof body.status === 'string' ? body.status : '' })
|
||||
} catch {
|
||||
done({ ok: false, error: 'BAD_JSON' })
|
||||
}
|
||||
})
|
||||
res.on('error', () => done({ ok: false, error: 'RESPONSE_ERROR' }))
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
done({ ok: false, error: error instanceof Error ? error.message : String(error) })
|
||||
return
|
||||
}
|
||||
req.on('timeout', () => {
|
||||
req.destroy()
|
||||
done({ ok: false, error: 'TIMEOUT' })
|
||||
})
|
||||
req.on('error', (error: Error) => done({ ok: false, error: error.message }))
|
||||
})
|
||||
}
|
||||
|
||||
/** 粗检组件:非 PE 或架构不符判 invalid,不做哈希白名单。 */
|
||||
export function inspectNativeComponent(
|
||||
filePath: string | null,
|
||||
arch: string,
|
||||
statFile: (p: string) => { size: number } | null
|
||||
): NativeComponentState {
|
||||
if (!filePath) return 'missing'
|
||||
const stat = statFile(filePath)
|
||||
if (!stat || stat.size < 1024) return 'missing'
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r')
|
||||
try {
|
||||
const head = Buffer.alloc(0x40)
|
||||
fs.readSync(fd, head, 0, 0x40, 0)
|
||||
if (head[0] !== 0x4d || head[1] !== 0x5a) return 'invalid' // "MZ"
|
||||
const peOffset = head.readUInt32LE(0x3c)
|
||||
const pe = Buffer.alloc(6)
|
||||
fs.readSync(fd, pe, 0, 6, peOffset)
|
||||
if (pe[0] !== 0x50 || pe[1] !== 0x45) return 'invalid' // "PE"
|
||||
const machine = pe.readUInt16LE(4)
|
||||
const expected = arch === 'arm64' ? 0xaa64 : 0x8664
|
||||
return machine === expected ? 'ready' : 'incompatible'
|
||||
} finally {
|
||||
fs.closeSync(fd)
|
||||
}
|
||||
} catch {
|
||||
return 'invalid'
|
||||
}
|
||||
}
|
||||
|
||||
export class MessageInsertCapabilityService {
|
||||
private cached: MessageInsertCapability | null = null
|
||||
private inflight: Promise<MessageInsertCapability> | null = null
|
||||
private readonly now: () => number
|
||||
|
||||
constructor(private readonly deps: CapabilityDeps) {
|
||||
this.now = deps.now || (() => Date.now())
|
||||
}
|
||||
|
||||
/** 读缓存(页面刷新用);过期或从未算过就重新评估。 */
|
||||
async getCapability(input: CapabilityInput): Promise<MessageInsertCapability> {
|
||||
const now = this.now()
|
||||
if (this.cached && now - this.cached.checkedAt < DEFAULT_TTL_MS) {
|
||||
/* 数据库连接状态可能瞬间变化,缓存命中时也要用最新入参重算这一项 */
|
||||
const merged = this.compose(input, this.cached.entitlementState, this.cached.licenseStatus)
|
||||
this.cached = merged
|
||||
return merged
|
||||
}
|
||||
return this.refresh(input)
|
||||
}
|
||||
|
||||
/** 强制重新评估(写库前必须调用,不能相信页面上那份缓存)。 */
|
||||
async refresh(input: CapabilityInput): Promise<MessageInsertCapability> {
|
||||
if (this.inflight) return this.inflight
|
||||
this.inflight = this.evaluate(input).finally(() => {
|
||||
this.inflight = null
|
||||
})
|
||||
const result = await this.inflight
|
||||
this.cached = result
|
||||
return result
|
||||
}
|
||||
|
||||
/** 供主进程做「开启」前的最终裁决。 */
|
||||
async ensureCanEnable(input: CapabilityInput): Promise<MessageInsertCapability> {
|
||||
return this.refresh(input)
|
||||
}
|
||||
|
||||
/** 测试与设置变化时清缓存。 */
|
||||
invalidate(): void {
|
||||
this.cached = null
|
||||
}
|
||||
|
||||
private async evaluate(input: CapabilityInput): Promise<MessageInsertCapability> {
|
||||
const platform = this.deps.platform
|
||||
|
||||
if (platform !== 'win32' && platform !== 'darwin') {
|
||||
return this.build({
|
||||
input,
|
||||
entitlement: 'unsupported',
|
||||
licenseStatus: undefined,
|
||||
reasonCode: 'UNSUPPORTED_PLATFORM',
|
||||
message: '微信内消息写入目前仅支持 Windows 与 macOS'
|
||||
})
|
||||
}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
if (!this.deps.hasMacNativeBundle()) {
|
||||
// OSS 包:如实说不提供,不假装「未授权」
|
||||
return this.build({
|
||||
input,
|
||||
entitlement: 'unsupported',
|
||||
licenseStatus: undefined,
|
||||
reasonCode: 'UNSUPPORTED_PLATFORM',
|
||||
message: '当前版本不包含微信内消息发送能力'
|
||||
})
|
||||
}
|
||||
return this.build({
|
||||
input,
|
||||
entitlement: 'valid',
|
||||
licenseStatus: undefined,
|
||||
reasonCode: 'CAPABILITY_READY',
|
||||
message: '授权有效'
|
||||
})
|
||||
}
|
||||
|
||||
const probe = await this.deps.probeLicense(PROBE_TIMEOUT_MS)
|
||||
if (!probe.ok) {
|
||||
return this.build({
|
||||
input,
|
||||
entitlement: 'unavailable',
|
||||
licenseStatus: undefined,
|
||||
reasonCode: 'LICENSE_UNAVAILABLE',
|
||||
message: '暂时无法确认授权状态'
|
||||
})
|
||||
}
|
||||
const mapped = mapLicenseStatus(probe.status)
|
||||
return this.build({
|
||||
input,
|
||||
entitlement: mapped.entitlement,
|
||||
licenseStatus: probe.status,
|
||||
reasonCode: mapped.reasonCode,
|
||||
message: mapped.message
|
||||
})
|
||||
}
|
||||
|
||||
private build(args: {
|
||||
input: CapabilityInput
|
||||
entitlement: EntitlementState
|
||||
licenseStatus?: string
|
||||
reasonCode: CapabilityReasonCode
|
||||
message: string
|
||||
}): MessageInsertCapability {
|
||||
return this.compose(args.input, args.entitlement, args.licenseStatus, args.reasonCode, args.message)
|
||||
}
|
||||
|
||||
private compose(
|
||||
input: CapabilityInput,
|
||||
entitlement: EntitlementState,
|
||||
licenseStatus: string | undefined,
|
||||
reasonCode?: CapabilityReasonCode,
|
||||
message?: string
|
||||
): MessageInsertCapability {
|
||||
const platform = this.deps.platform
|
||||
const supportedPlatform = platform === 'win32' || platform === 'darwin'
|
||||
const component = supportedPlatform
|
||||
? inspectNativeComponent(
|
||||
this.deps.resolveNativeComponent(),
|
||||
process.arch,
|
||||
this.deps.statFile || defaultStat
|
||||
)
|
||||
: 'missing'
|
||||
const databaseReady = input.databaseReady === true
|
||||
|
||||
let code: CapabilityReasonCode = reasonCode || 'CAPABILITY_READY'
|
||||
let text = message || ''
|
||||
if (!code || code === 'CAPABILITY_READY') {
|
||||
if (entitlement === 'unsupported') {
|
||||
code = 'UNSUPPORTED_PLATFORM'
|
||||
text = text || '当前版本不包含微信内消息发送能力'
|
||||
} else if (entitlement === 'unavailable') {
|
||||
code = 'LICENSE_UNAVAILABLE'
|
||||
text = text || '暂时无法确认授权状态'
|
||||
} else if (entitlement === 'pending') {
|
||||
code = 'LICENSE_PENDING'
|
||||
text = text || '授权正在验证,请稍候'
|
||||
} else if (entitlement === 'invalid') {
|
||||
code = 'LICENSE_REQUIRED'
|
||||
text = text || '未检测到有效授权'
|
||||
} else if (component !== 'ready') {
|
||||
code = component === 'missing' ? 'COMPONENT_MISSING' : 'COMPONENT_INVALID'
|
||||
text =
|
||||
component === 'missing'
|
||||
? '未安装发送能力组件'
|
||||
: '发送能力组件不完整或版本不匹配'
|
||||
} else if (!databaseReady) {
|
||||
code = 'DATABASE_UNAVAILABLE'
|
||||
text = '微信数据库尚未连接'
|
||||
} else {
|
||||
code = 'CAPABILITY_READY'
|
||||
text = '授权与组件均已就绪'
|
||||
}
|
||||
}
|
||||
|
||||
const canEnable =
|
||||
supportedPlatform &&
|
||||
entitlement === 'valid' &&
|
||||
component === 'ready' &&
|
||||
databaseReady &&
|
||||
code === 'CAPABILITY_READY'
|
||||
/* 关闭不受授权限制:用户丢了授权也必须能把已有规则关掉 */
|
||||
const canDisable = supportedPlatform
|
||||
|
||||
return {
|
||||
entitlementState: entitlement,
|
||||
nativeComponentState: component,
|
||||
databaseReady,
|
||||
canEnable,
|
||||
canDisable,
|
||||
reasonCode: code,
|
||||
message: text,
|
||||
...(licenseStatus ? { licenseStatus } : {}),
|
||||
checkedAt: this.now()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function defaultStat(filePath: string): { size: number } | null {
|
||||
try {
|
||||
const stat = fs.statSync(filePath)
|
||||
return stat.isFile() ? { size: stat.size } : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const msgInsertCapabilityService = new MessageInsertCapabilityService({
|
||||
platform: process.platform,
|
||||
hasMacNativeBundle,
|
||||
isMacRuntimeUnavailable: isMacNativeRuntimeUnavailable,
|
||||
resolveNativeComponent: resolveHelperPath,
|
||||
probeLicense: probeLicenseStatus
|
||||
})
|
||||
@@ -30,6 +30,7 @@ import path from 'node:path'
|
||||
|
||||
import { findResource } from '../resource-paths'
|
||||
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { resolveExternalComponent } from './external-component-locator'
|
||||
import type { Wcdb4Client } from '../wcdb4-client'
|
||||
import {
|
||||
MSG_INSERT_SWITCHES,
|
||||
@@ -158,10 +159,13 @@ export function emptyMsgInsertStatus(
|
||||
*/
|
||||
export function resolveHelperPath(): string | null {
|
||||
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
|
||||
/* 优先用外置目录里的发送能力组件,避免自动更新清掉;校验不过当没装。 */
|
||||
const external = resolveExternalComponent()
|
||||
if (external) return external.helperPath
|
||||
/*
|
||||
* 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows),
|
||||
* 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null,
|
||||
* 表现为「缺少写入组件」+ 开关永久置灰。
|
||||
* 表现为「缺少发送能力组件」+ 开关永久置灰。
|
||||
*
|
||||
* 同目录还有 wcdb_api.dll / WCDB.dll / SDL2.dll,MSVC 运行库在 resources/runtime/win32/,
|
||||
* 两者都由 preload-env.ts 加进 DLL 搜索路径,所以 helper.exe 能直接加载。
|
||||
@@ -657,7 +661,7 @@ export async function applyMsgInsertSwitch(
|
||||
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '暂无法使用'),
|
||||
errorCode: 'HELPER_NOT_FOUND',
|
||||
/* 面向用户是能力语义;errorCode 仍是 HELPER_NOT_FOUND,门禁/授权层照旧能判。 */
|
||||
message: '暂无法使用:当前安装不包含微信内消息写入组件'
|
||||
message: '暂无法使用:当前安装不包含发送能力组件'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,9 @@ import { app } from 'electron'
|
||||
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
|
||||
import { renderLeaveNotificationText } from '../../shared/group-exit-event'
|
||||
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
|
||||
import { findResource } from '../resource-paths'
|
||||
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { msgInsertCapabilityService } from './msg-insert-capability-service'
|
||||
import { resolveHelperPath } from './msg-insert-switch-service'
|
||||
|
||||
export type LocalExitNoticeOutcome =
|
||||
| 'inserted'
|
||||
@@ -58,28 +59,18 @@ interface StoredState {
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
const HELPER_NAME = 'tm-wcdb-config-helper'
|
||||
const HELPER_TIMEOUT_MS = 20_000
|
||||
/** 最近若干次插入结果,只用于诊断展示,不参与判定 */
|
||||
const RECENT_LIMIT = 50
|
||||
|
||||
function helperPath(): string | null {
|
||||
if (process.platform === 'darwin') return resolveWcdbConfigHelper()
|
||||
/* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致:
|
||||
* Windows 走 wcdb/win32/<arch>/ 且文件名带 .exe。 */
|
||||
const arch = process.arch === 'x64' ? 'x64' : 'arm64'
|
||||
const other = arch === 'arm64' ? 'x64' : 'arm64'
|
||||
const platformDir = process.platform === 'win32' ? 'win32' : 'macos'
|
||||
const suffix = process.platform === 'win32' ? '.exe' : ''
|
||||
for (const candidate of [
|
||||
`wcdb/${platformDir}/${arch}/${HELPER_NAME}${suffix}`,
|
||||
`wcdb/${platformDir}/${other}/${HELPER_NAME}${suffix}`,
|
||||
`wcdb/${platformDir}/${HELPER_NAME}${suffix}`
|
||||
]) {
|
||||
const resolved = findResource(candidate)
|
||||
if (resolved) return resolved
|
||||
}
|
||||
return null
|
||||
/*
|
||||
* 不在这里重复一份 resources 搜索逻辑。
|
||||
* Windows 上 helper 可能被部署到外置目录,
|
||||
* 只有一处解析入口,两条链路才不会各解析各的。
|
||||
*/
|
||||
return resolveHelperPath()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,10 +142,14 @@ export class WechatLocalExitNoticeService {
|
||||
}
|
||||
try {
|
||||
this.ensureLoaded()
|
||||
if (isMacNativeRuntimeUnavailable()) {
|
||||
return this.finish({ ...base, outcome: 'disabled', code: 'SEND_CAPABILITY_UNAVAILABLE' })
|
||||
}
|
||||
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
|
||||
/* 判定走统一服务;未授权或超时一律不写,普通退群检测不受影响。 */
|
||||
const capability = await msgInsertCapabilityService.getCapability({
|
||||
databaseReady: true
|
||||
})
|
||||
if (!capability.canEnable) {
|
||||
return this.finish({ ...base, outcome: 'disabled', code: capability.reasonCode })
|
||||
}
|
||||
if (!event.eventId || !event.conversationId) {
|
||||
return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' })
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ export function MessageInsertSwitches(): React.JSX.Element {
|
||||
/** 把结果里的失败原因翻成人话;native code 只进日志。 */
|
||||
const humanize = React.useCallback((result: MsgInsertApplyResult): string => {
|
||||
const status = result.status
|
||||
if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少写入组件,请重新安装或更新 TraceMemo'
|
||||
if (result.errorCode === 'HELPER_NOT_FOUND') return '缺少发送能力组件,请重新安装或更新 TraceMemo'
|
||||
if (result.errorCode === 'DATABASE_UNAVAILABLE') return '微信数据库未连接'
|
||||
if (result.errorCode === 'NO_TARGET_ROOMS') return '没有可作用的目标会话'
|
||||
if (status && status.failedShards > 0) {
|
||||
@@ -174,21 +174,61 @@ export function MessageInsertSwitches(): React.JSX.Element {
|
||||
[humanize, pending, refresh, toast]
|
||||
)
|
||||
|
||||
/* 微信内消息插入必须依赖可用的发送组件;能力状态由主进程统一判定。 */
|
||||
/* 开启要全绿,关闭永远放行——授权过期后关不掉比开不了更糟。 */
|
||||
const capability = snapshot?.capability
|
||||
const helperMissing = snapshot?.helperAvailable === false
|
||||
const capabilityNotice = snapshot?.sendCapabilityAvailable === false
|
||||
? '微信内防撤回与退群消息插入仅在 TraceMemo 具备发送能力时开放;退群检测和历史记录不受影响'
|
||||
: null
|
||||
const blocked = capabilityNotice ?? blockedReason ?? (helperMissing ? '该能力暂不可用' : null)
|
||||
const disabled = blocked !== null
|
||||
|
||||
const noticeForEnable = ((): string | null => {
|
||||
if (capability) {
|
||||
if (capability.canEnable) return blockedReason ?? null
|
||||
switch (capability.reasonCode) {
|
||||
case 'LICENSE_REQUIRED':
|
||||
return '需要有效授权才能开启'
|
||||
case 'LICENSE_PENDING':
|
||||
return '授权正在验证,稍等片刻再试'
|
||||
case 'LICENSE_EXPIRED':
|
||||
return '授权已过期,重新激活后可开启'
|
||||
case 'LICENSE_INVALID':
|
||||
return '授权无效,请重新激活'
|
||||
case 'LICENSE_MACHINE_MISMATCH':
|
||||
return '这份授权不属于本机'
|
||||
case 'LICENSE_REVOKED':
|
||||
return '授权已被吊销'
|
||||
case 'LICENSE_UNAVAILABLE':
|
||||
return '暂时无法确认授权状态'
|
||||
case 'COMPONENT_MISSING':
|
||||
return '当前安装未包含发送能力组件'
|
||||
case 'COMPONENT_INVALID':
|
||||
return '发送能力组件不完整,请重新安装'
|
||||
case 'DATABASE_UNAVAILABLE':
|
||||
return '微信数据库尚未连接'
|
||||
case 'UNSUPPORTED_PLATFORM':
|
||||
return '当前版本不包含此能力'
|
||||
default:
|
||||
return capability.message || null
|
||||
}
|
||||
}
|
||||
if (helperMissing) return '该能力暂不可用'
|
||||
return blockedReason ?? null
|
||||
})()
|
||||
|
||||
const anyEnabled = MSG_INSERT_SWITCH_LABELS.some(
|
||||
({ name }) => snapshot?.switches?.[name]?.desiredEnabled === true
|
||||
)
|
||||
/* 顶部只给「想开但开不了」的场景一条总提示,避免每个开关重复一遍 */
|
||||
const capabilityNotice = noticeForEnable && !anyEnabled ? noticeForEnable : null
|
||||
|
||||
return (
|
||||
<div className="automation-msg-insert-switches" title={blocked ?? undefined}>
|
||||
<div className="automation-msg-insert-switches" title={capabilityNotice ?? undefined}>
|
||||
{capabilityNotice ? <p className="automation-notice warning" role="status">{capabilityNotice}</p> : null}
|
||||
{loading ? <Spinner /> : null}
|
||||
{MSG_INSERT_SWITCH_LABELS.map(({ name, label, hint }) => {
|
||||
const status: MsgInsertSwitchStatus | undefined = snapshot?.switches?.[name]
|
||||
const busy = pending === name
|
||||
const desired = status?.desiredEnabled === true
|
||||
/* 已开启 → 允许关;未开启 → 必须满足开启条件 */
|
||||
const switchNotice = desired ? null : noticeForEnable
|
||||
const switchDisabled = pending !== null || (!desired && switchNotice !== null)
|
||||
/* rules 型:显示「已就绪 / 可安装」;事件驱动型没有覆盖率这个概念。 */
|
||||
const showCoverage = status?.mode === 'rules' && status.totalInstallableRooms > 0
|
||||
const partial =
|
||||
@@ -206,8 +246,8 @@ export function MessageInsertSwitches(): React.JSX.Element {
|
||||
于是「点文字」也会切换开关。写微信库的开关不该这么容易被误触。 */
|
||||
<span
|
||||
key={name}
|
||||
className={`automation-msg-insert-switch ${disabled ? 'is-disabled' : ''}`}
|
||||
title={[hint, status?.message].filter(Boolean).join('\n') || blocked || hint}
|
||||
className={`automation-msg-insert-switch ${switchDisabled ? 'is-disabled' : ''}`}
|
||||
title={[hint, status?.message, switchNotice].filter(Boolean).join('\n') || hint}
|
||||
>
|
||||
<span className="automation-msg-insert-switch-label">{label}</span>
|
||||
{/* 写微信库要 spawn 子进程 + 装规则,耗时以秒计。
|
||||
@@ -219,8 +259,8 @@ export function MessageInsertSwitches(): React.JSX.Element {
|
||||
</span>
|
||||
) : null}
|
||||
<Switch
|
||||
checked={status?.desiredEnabled === true}
|
||||
disabled={disabled || pending !== null}
|
||||
checked={desired}
|
||||
disabled={switchDisabled}
|
||||
onCheckedChange={(checked) => void handleToggle(name, checked === true)}
|
||||
aria-label={label}
|
||||
/>
|
||||
|
||||
@@ -104,13 +104,56 @@ export interface MsgInsertSwitchStatus {
|
||||
message?: string
|
||||
}
|
||||
|
||||
/** 授权状态(与「能不能发消息」无关) */
|
||||
export type EntitlementState = 'valid' | 'invalid' | 'pending' | 'unavailable' | 'unsupported'
|
||||
|
||||
/** 发送能力组件状态 */
|
||||
export type NativeComponentState = 'ready' | 'missing' | 'invalid' | 'incompatible'
|
||||
|
||||
/**
|
||||
* 发送能力被拒的原因。**不要用 HELPER_NOT_FOUND 表达授权问题** ——
|
||||
* 那会让「没装组件」「没授权」「发不了消息」三种情况在界面上无法区分。
|
||||
*/
|
||||
export type CapabilityReasonCode =
|
||||
| 'CAPABILITY_READY'
|
||||
| 'UNSUPPORTED_PLATFORM'
|
||||
| 'LICENSE_REQUIRED'
|
||||
| 'LICENSE_PENDING'
|
||||
| 'LICENSE_EXPIRED'
|
||||
| 'LICENSE_INVALID'
|
||||
| 'LICENSE_MACHINE_MISMATCH'
|
||||
| 'LICENSE_REVOKED'
|
||||
| 'LICENSE_UNAVAILABLE'
|
||||
| 'COMPONENT_MISSING'
|
||||
| 'COMPONENT_INVALID'
|
||||
| 'DATABASE_UNAVAILABLE'
|
||||
|
||||
/** 主进程算好的发送能力视图,渲染层只读这个,不再自己判断 */
|
||||
export interface CapabilityView {
|
||||
entitlementState: EntitlementState
|
||||
nativeComponentState: NativeComponentState
|
||||
databaseReady: boolean
|
||||
canEnable: boolean
|
||||
canDisable: boolean
|
||||
reasonCode: CapabilityReasonCode
|
||||
message: string
|
||||
licenseStatus?: string
|
||||
checkedAt?: number
|
||||
}
|
||||
|
||||
export interface MsgInsertSwitchesSnapshot {
|
||||
success: boolean
|
||||
/** 原生发送能力(授权 + 组件 + 数据库),两个开关共用 */
|
||||
capability?: CapabilityView
|
||||
/**
|
||||
* @deprecated 语义漂移过:曾等于「这是不是 mac native 包」,在 Windows 上恒为 true。
|
||||
* 新代码请用 `capability.canEnable`;这里只留一个与它一致的值给旧调用方。
|
||||
*/
|
||||
sendCapabilityAvailable?: boolean
|
||||
switches: Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
|
||||
/** 写入组件是否可用(不可用时只能读不能写) */
|
||||
/** 发送能力组件是否可用(不可用时只能读不能写) */
|
||||
/**
|
||||
* **能力标志**:本机是否存在「微信内消息写入组件」。
|
||||
* **能力标志**:本机是否存在「微信内发送能力组件」。
|
||||
*
|
||||
* 这是「微信内防撤回提示」和「微信内退群监控消息」的**唯一硬门槛**:
|
||||
* 主进程对微信库只持只读连接,任何写入都必须 spawn 那个组件,没有它两个功能都做不了。
|
||||
@@ -151,6 +194,11 @@ export type MsgInsertErrorCode =
|
||||
| 'UNSUPPORTED_SWITCH'
|
||||
| 'NO_TARGET_ROOMS'
|
||||
| 'DATABASE_UNAVAILABLE'
|
||||
| 'LICENSE_REQUIRED'
|
||||
| 'LICENSE_PENDING'
|
||||
| 'LICENSE_EXPIRED'
|
||||
| 'COMPONENT_MISSING'
|
||||
| 'CAPABILITY_UNAVAILABLE'
|
||||
| 'UNKNOWN'
|
||||
|
||||
/** 界面上要展示的两个开关(顺序即展示顺序) */
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { MsgInsertSwitchesSnapshot } from '../../src/shared/msg-insert-switch'
|
||||
|
||||
vi.mock('../../src/renderer/src/components/ui', async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>()
|
||||
return { ...actual, useToast: () => ({ toast: () => undefined }) }
|
||||
})
|
||||
|
||||
import { MessageInsertSwitches } from '../../src/renderer/src/features/automation/MessageInsertSwitches'
|
||||
|
||||
/**
|
||||
* 开关的门禁语义:
|
||||
* 开启 → 看 capability.canEnable
|
||||
* 关闭 → 永远可点(授权失效也不能把用户锁死在开启状态)
|
||||
*/
|
||||
|
||||
function baseStatus(
|
||||
desiredEnabled: boolean,
|
||||
overrides: Record<string, unknown> = {}
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
switch: 'recall_notice',
|
||||
scope: 'all_sessions',
|
||||
mode: 'rules',
|
||||
desiredEnabled,
|
||||
effectiveEnabled: desiredEnabled,
|
||||
operationOk: true,
|
||||
totalInstallableRooms: 0,
|
||||
readyInstallableRooms: 0,
|
||||
roomsWithoutTable: 0,
|
||||
totalShards: 0,
|
||||
targetShards: 0,
|
||||
configuredShards: 0,
|
||||
readyShards: 0,
|
||||
notReadyShards: 0,
|
||||
failedShards: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotOf(
|
||||
canEnable: boolean,
|
||||
desired: { recall: boolean; exit: boolean },
|
||||
reasonCode = canEnable ? 'CAPABILITY_READY' : 'LICENSE_REQUIRED',
|
||||
message = canEnable ? '授权与组件均已就绪' : '未检测到有效授权'
|
||||
): MsgInsertSwitchesSnapshot {
|
||||
return {
|
||||
success: true,
|
||||
helperAvailable: true,
|
||||
capability: {
|
||||
entitlementState: canEnable ? 'valid' : 'invalid',
|
||||
nativeComponentState: 'ready',
|
||||
databaseReady: true,
|
||||
canEnable,
|
||||
canDisable: true,
|
||||
reasonCode: reasonCode as never,
|
||||
message
|
||||
},
|
||||
switches: {
|
||||
recall_notice: baseStatus(desired.recall) as never,
|
||||
group_exit_notice: baseStatus(desired.exit, {
|
||||
switch: 'group_exit_notice',
|
||||
mode: 'event',
|
||||
effectiveEnabled: canEnable ? desired.exit : false
|
||||
}) as never
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function installApi(snapshot: MsgInsertSwitchesSnapshot): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
getMsgInsertSwitches: async () => snapshot,
|
||||
setMsgInsertSwitch: async () => ({ success: true })
|
||||
}
|
||||
}
|
||||
|
||||
describe('MessageInsertSwitches 能力门禁', () => {
|
||||
it('没有授权时两个未开启的开关都不可操作,并给出激活引导', async () => {
|
||||
installApi(snapshotOf(false, { recall: false, exit: false }))
|
||||
render(<MessageInsertSwitches />)
|
||||
|
||||
await waitFor(() => expect(screen.getAllByRole('switch').length).toBe(2))
|
||||
const switches = screen.getAllByRole('switch')
|
||||
expect(switches[0]).toBeDisabled()
|
||||
expect(switches[1]).toBeDisabled()
|
||||
expect(screen.getByText(/需要有效授权才能开启/)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('已开启的开关在授权失效时仍可点击关闭(不能被锁死)', async () => {
|
||||
installApi(snapshotOf(false, { recall: true, exit: true }))
|
||||
render(<MessageInsertSwitches />)
|
||||
|
||||
await waitFor(() => expect(screen.getAllByRole('switch').length).toBe(2))
|
||||
const switches = screen.getAllByRole('switch')
|
||||
expect(switches[0]).not.toBeDisabled()
|
||||
expect(switches[1]).not.toBeDisabled()
|
||||
})
|
||||
|
||||
it('授权有效时允许开启', async () => {
|
||||
installApi(snapshotOf(true, { recall: false, exit: false }))
|
||||
render(<MessageInsertSwitches />)
|
||||
|
||||
await waitFor(() => expect(screen.getAllByRole('switch').length).toBe(2))
|
||||
const switches = screen.getAllByRole('switch')
|
||||
expect(switches[0]).not.toBeDisabled()
|
||||
expect(switches[1]).not.toBeDisabled()
|
||||
})
|
||||
|
||||
it('缺组件时提示组件缺失,而不是「没授权」', async () => {
|
||||
const snapshot = snapshotOf(
|
||||
false,
|
||||
{ recall: false, exit: false },
|
||||
'COMPONENT_MISSING',
|
||||
'未安装发送能力组件'
|
||||
)
|
||||
installApi(snapshot)
|
||||
render(<MessageInsertSwitches />)
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/发送能力组件/)).toBeTruthy())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,221 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
MessageInsertCapabilityService,
|
||||
mapLicenseStatus
|
||||
} from '../../src/main/services/msg-insert-capability-service'
|
||||
import {
|
||||
resetComponentCache,
|
||||
resolveExternalComponent
|
||||
} from '../../src/main/services/external-component-locator'
|
||||
|
||||
/**
|
||||
* 组件发现与能力判定的验收:真实文件与 PE 头,只替换 4290 探测。
|
||||
*/
|
||||
|
||||
const HELPER = 'tm-wcdb-config-helper.exe'
|
||||
const API = 'wcdb_api.dll'
|
||||
const CORE = 'WCDB.dll'
|
||||
|
||||
/** 造一个「PE 头合法、体积够大」的假组件,专门喂给 inspectNativeComponent。 */
|
||||
function fakePe(machine = 0x8664, total = 2048): Buffer {
|
||||
const buf = Buffer.alloc(total)
|
||||
buf.write('MZ', 0, 'latin1')
|
||||
buf.writeUInt32LE(0x80, 0x3c)
|
||||
buf.write('PE\0\0', 0x80, 'latin1')
|
||||
buf.writeUInt16LE(machine, 0x84)
|
||||
return buf
|
||||
}
|
||||
|
||||
function sha256(buf: Buffer): string {
|
||||
return crypto.createHash('sha256').update(buf).digest('hex')
|
||||
}
|
||||
|
||||
interface Fixture {
|
||||
root: string
|
||||
versionDir: string
|
||||
localAppData: string
|
||||
pointerPath: string
|
||||
}
|
||||
|
||||
function buildFixture(): Fixture {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-cap-'))
|
||||
const localAppData = path.join(root, 'LocalAppData')
|
||||
const versionDir = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', '1.0.0')
|
||||
fs.mkdirSync(versionDir, { recursive: true })
|
||||
|
||||
const files: Array<{ path: string; size: number; sha256: string }> = []
|
||||
for (const name of [API, CORE, HELPER]) {
|
||||
const buf = fakePe()
|
||||
fs.writeFileSync(path.join(versionDir, name), buf)
|
||||
files.push({ path: name, size: buf.length, sha256: sha256(buf) })
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(versionDir, 'manifest.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
product: 'TraceMemo',
|
||||
edition: 'oss',
|
||||
platform: 'windows-x64',
|
||||
componentVersion: '1.0.0',
|
||||
wchookCommit: 'test',
|
||||
dllCommit: 'test',
|
||||
worktreeDirty: false,
|
||||
installedAt: new Date().toISOString(),
|
||||
files
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
)
|
||||
const pointerPath = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', 'current.json')
|
||||
fs.writeFileSync(pointerPath, JSON.stringify({ version: '1.0.0', dir: versionDir }))
|
||||
return { root, versionDir, localAppData, pointerPath }
|
||||
}
|
||||
|
||||
/**
|
||||
* 组一个和生产同构的服务实例。
|
||||
* 定位器显式传 LOCALAPPDATA(不去改 process.env,避免用例之间互相污染),
|
||||
* 其余依赖保持生产实现。
|
||||
*/
|
||||
function makeService(
|
||||
localAppData: string | null,
|
||||
probe: { ok: true; status: string } | { ok: false; error: string }
|
||||
): MessageInsertCapabilityService {
|
||||
return new MessageInsertCapabilityService({
|
||||
platform: 'win32',
|
||||
hasMacNativeBundle: () => true,
|
||||
isMacRuntimeUnavailable: () => false,
|
||||
resolveNativeComponent: () =>
|
||||
localAppData
|
||||
? (resolveExternalComponent({ LOCALAPPDATA: localAppData } as never, 'win32')?.helperPath ??
|
||||
null)
|
||||
: null,
|
||||
probeLicense: async () => probe
|
||||
})
|
||||
}
|
||||
|
||||
const located = (localAppData: string): ReturnType<typeof resolveExternalComponent> =>
|
||||
resolveExternalComponent({ LOCALAPPDATA: localAppData } as never, 'win32')
|
||||
|
||||
describe('能力验收矩阵(真实文件 + 真实 PE 嗅探)', () => {
|
||||
let fixture: Fixture
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = buildFixture()
|
||||
resetComponentCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetComponentCache()
|
||||
fs.rmSync(fixture.root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('定位到外置 bundle 时返回 helper 绝对路径与版本', () => {
|
||||
const found = located(fixture.localAppData)
|
||||
expect(found).not.toBeNull()
|
||||
expect(found!.version).toBe('1.0.0')
|
||||
expect(found!.helperPath).toBe(path.join(fixture.versionDir, HELPER))
|
||||
expect(fs.existsSync(found!.helperPath)).toBe(true)
|
||||
})
|
||||
|
||||
it('1. 未安装组件:没有 current.json → 组件缺失,不支持开启', async () => {
|
||||
fs.rmSync(fixture.pointerPath)
|
||||
resetComponentCache()
|
||||
const cap = await makeService(fixture.localAppData, {
|
||||
ok: true,
|
||||
status: 'LICENSE_OK'
|
||||
}).refresh({ databaseReady: true })
|
||||
expect(cap.nativeComponentState).toBe('missing')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.reasonCode).toBe('COMPONENT_MISSING')
|
||||
})
|
||||
|
||||
it('2. 装了组件但授权不可达 → 不许开启,原因指向授权', async () => {
|
||||
const cap = await makeService(fixture.localAppData, {
|
||||
ok: false,
|
||||
error: 'ECONNREFUSED'
|
||||
}).refresh({ databaseReady: true })
|
||||
expect(cap.nativeComponentState).toBe('ready')
|
||||
expect(cap.entitlementState).toBe('unavailable')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.reasonCode).toBe('LICENSE_UNAVAILABLE')
|
||||
})
|
||||
|
||||
it('3. 授权有效 + 组件就绪 + 库已连接 → 允许开启', async () => {
|
||||
const cap = await makeService(fixture.localAppData, {
|
||||
ok: true,
|
||||
status: 'LICENSE_OK'
|
||||
}).refresh({ databaseReady: true })
|
||||
expect(cap.entitlementState).toBe('valid')
|
||||
expect(cap.nativeComponentState).toBe('ready')
|
||||
expect(cap.canEnable).toBe(true)
|
||||
expect(cap.reasonCode).toBe('CAPABILITY_READY')
|
||||
})
|
||||
|
||||
it('4. 授权过期 → 不许开启', async () => {
|
||||
const cap = await makeService(fixture.localAppData, {
|
||||
ok: true,
|
||||
status: 'LICENSE_EXPIRED'
|
||||
}).refresh({ databaseReady: true })
|
||||
expect(cap.entitlementState).toBe('invalid')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.reasonCode).toBe('LICENSE_EXPIRED')
|
||||
})
|
||||
|
||||
it('5. 组件文件缺失 → 定位失败,按未安装处理', () => {
|
||||
fs.rmSync(path.join(fixture.versionDir, HELPER))
|
||||
resetComponentCache()
|
||||
expect(located(fixture.localAppData)).toBeNull()
|
||||
})
|
||||
|
||||
it('6. 组件被篡改(大小不同)→ manifest 校验失败,按未安装处理', () => {
|
||||
fs.writeFileSync(path.join(fixture.versionDir, API), fakePe(0x8664, 4096))
|
||||
resetComponentCache()
|
||||
expect(located(fixture.localAppData)).toBeNull()
|
||||
})
|
||||
|
||||
it('7. 关闭永远不被授权拦住(授权过期 + 组件缺失也能关)', async () => {
|
||||
const svc = new MessageInsertCapabilityService({
|
||||
platform: 'win32',
|
||||
hasMacNativeBundle: () => true,
|
||||
isMacRuntimeUnavailable: () => false,
|
||||
resolveNativeComponent: () => null,
|
||||
probeLicense: async () => ({ ok: true, status: 'LICENSE_EXPIRED' })
|
||||
})
|
||||
const cap = await svc.refresh({ databaseReady: false })
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.canDisable).toBe(true)
|
||||
})
|
||||
|
||||
it('8. 微信库未连接 → 不许开启', async () => {
|
||||
const cap = await makeService(fixture.localAppData, {
|
||||
ok: true,
|
||||
status: 'LICENSE_OK'
|
||||
}).refresh({ databaseReady: false })
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.reasonCode).toBe('DATABASE_UNAVAILABLE')
|
||||
})
|
||||
|
||||
it('9. 授权状态映射:只有 LICENSE_OK 算 valid', () => {
|
||||
for (const status of [
|
||||
'LICENSE_EXPIRED',
|
||||
'LICENSE_MACHINE_MISMATCH',
|
||||
'LICENSE_REVOKED',
|
||||
'LICENSE_INVALID',
|
||||
'LICENSE_SERVICE_DOWN',
|
||||
'LICENSE_CHECKING',
|
||||
''
|
||||
]) {
|
||||
expect(mapLicenseStatus(status).entitlement).not.toBe('valid')
|
||||
}
|
||||
expect(mapLicenseStatus('LICENSE_OK').entitlement).toBe('valid')
|
||||
})
|
||||
})
|
||||
@@ -186,7 +186,7 @@ describe('派生库句柄的账号身份缓存', () => {
|
||||
h.service.resetAccount()
|
||||
})
|
||||
|
||||
it('identity resolution cost is paid once per pass, not per image', async () => {
|
||||
it('identity resolution cost is consumed once per pass, not per image', async () => {
|
||||
const RESOLVE_MS = 30
|
||||
const OCR_MS = 5
|
||||
const slow = createHarness({
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
isDefinitelyBlocked,
|
||||
isEntitlementBlocked,
|
||||
resolveExitNoticeGate,
|
||||
resolveSwitchPresentation
|
||||
} from '../../src/main/services/exit-notice-gate'
|
||||
import type { MessageInsertCapability } from '../../src/main/services/msg-insert-capability-service'
|
||||
|
||||
/** 开关呈现:授权不成立时,两个开关必须同时显示关闭。 */
|
||||
|
||||
function capability(over: Partial<MessageInsertCapability>): MessageInsertCapability {
|
||||
return {
|
||||
entitlementState: 'valid',
|
||||
nativeComponentState: 'ready',
|
||||
databaseReady: true,
|
||||
canEnable: true,
|
||||
canDisable: true,
|
||||
reasonCode: 'CAPABILITY_READY',
|
||||
message: '授权与组件均已就绪',
|
||||
checkedAt: 0,
|
||||
...over
|
||||
}
|
||||
}
|
||||
|
||||
describe('退群内提示开关判定', () => {
|
||||
it('授权有效 + 组件就绪 + 库已连接 + 用户开着 → 显示开、确实在跑', () => {
|
||||
const d = resolveExitNoticeGate(capability({}), true)
|
||||
expect(d).toEqual({ desiredEnabled: true, effectiveEnabled: true, persistDisable: false })
|
||||
})
|
||||
|
||||
it('用户本来关着 → 显示关,不落盘', () => {
|
||||
const d = resolveExitNoticeGate(capability({}), false)
|
||||
expect(d).toEqual({ desiredEnabled: false, effectiveEnabled: false, persistDisable: false })
|
||||
})
|
||||
|
||||
it('授权过期(invalid)→ 显示关闭,并把本地开关落盘关掉', () => {
|
||||
const cap = capability({
|
||||
entitlementState: 'invalid',
|
||||
canEnable: false,
|
||||
reasonCode: 'LICENSE_EXPIRED',
|
||||
message: '授权已过期,请重新激活后再开启'
|
||||
})
|
||||
const d = resolveExitNoticeGate(cap, true)
|
||||
expect(d.desiredEnabled).toBe(false)
|
||||
expect(d.effectiveEnabled).toBe(false)
|
||||
expect(d.persistDisable).toBe(true)
|
||||
})
|
||||
|
||||
it('授权服务探测失败(unavailable)→ 显示关闭,但不改写用户设置', () => {
|
||||
const cap = capability({
|
||||
entitlementState: 'unavailable',
|
||||
canEnable: false,
|
||||
reasonCode: 'LICENSE_UNAVAILABLE',
|
||||
message: '暂时无法确认授权状态'
|
||||
})
|
||||
const d = resolveExitNoticeGate(cap, true)
|
||||
expect(d.desiredEnabled).toBe(false)
|
||||
expect(d.effectiveEnabled).toBe(false)
|
||||
/* 微信刚启动时 4290 还没起来,这时落盘会把正常正常用户的开关误关 */
|
||||
expect(d.persistDisable).toBe(false)
|
||||
expect(isDefinitelyBlocked(cap)).toBe(false)
|
||||
expect(isEntitlementBlocked(cap)).toBe(true)
|
||||
})
|
||||
|
||||
it('组件缺失 → 显示关闭,落盘关掉(OSS 包的典型状态)', () => {
|
||||
const cap = capability({
|
||||
nativeComponentState: 'missing',
|
||||
canEnable: false,
|
||||
reasonCode: 'COMPONENT_MISSING',
|
||||
message: '未安装发送能力组件'
|
||||
})
|
||||
const d = resolveExitNoticeGate(cap, true)
|
||||
expect(d.desiredEnabled).toBe(false)
|
||||
expect(d.persistDisable).toBe(true)
|
||||
})
|
||||
|
||||
it('组件架构不匹配 → 显示关闭并落盘', () => {
|
||||
const cap = capability({
|
||||
nativeComponentState: 'incompatible',
|
||||
canEnable: false,
|
||||
reasonCode: 'COMPONENT_INVALID'
|
||||
})
|
||||
expect(resolveExitNoticeGate(cap, true).persistDisable).toBe(true)
|
||||
})
|
||||
|
||||
it('授权与组件都就绪、只是微信库没连 → 保留用户意愿,不显示成已生效', () => {
|
||||
const cap = capability({
|
||||
databaseReady: false,
|
||||
canEnable: false,
|
||||
reasonCode: 'DATABASE_UNAVAILABLE',
|
||||
message: '微信数据库尚未连接'
|
||||
})
|
||||
const d = resolveExitNoticeGate(cap, true)
|
||||
expect(d.desiredEnabled).toBe(true)
|
||||
expect(d.effectiveEnabled).toBe(false)
|
||||
/* 库连上是暂时的,不能因此把人家的开关关掉 */
|
||||
expect(d.persistDisable).toBe(false)
|
||||
})
|
||||
|
||||
it('平台不支持(公开版/非 Windows-mac 包)→ 显示关闭并落盘', () => {
|
||||
const cap = capability({
|
||||
entitlementState: 'unsupported',
|
||||
canEnable: false,
|
||||
reasonCode: 'UNSUPPORTED_PLATFORM',
|
||||
databaseReady: false
|
||||
})
|
||||
const d = resolveExitNoticeGate(cap, true)
|
||||
expect(d.desiredEnabled).toBe(false)
|
||||
expect(d.persistDisable).toBe(true)
|
||||
})
|
||||
|
||||
it('授权正在验证(pending)→ 先按关闭显示,不改写设置', () => {
|
||||
const cap = capability({
|
||||
entitlementState: 'pending',
|
||||
canEnable: false,
|
||||
reasonCode: 'LICENSE_PENDING'
|
||||
})
|
||||
const d = resolveExitNoticeGate(cap, true)
|
||||
expect(d.desiredEnabled).toBe(false)
|
||||
expect(d.persistDisable).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('两个微信内开关的呈现(防撤回 / 退群提示必须一致)', () => {
|
||||
const expired = capability({
|
||||
entitlementState: 'invalid',
|
||||
canEnable: false,
|
||||
reasonCode: 'LICENSE_EXPIRED'
|
||||
})
|
||||
const unavailable = capability({
|
||||
entitlementState: 'unavailable',
|
||||
canEnable: false,
|
||||
reasonCode: 'LICENSE_UNAVAILABLE'
|
||||
})
|
||||
const noComponent = capability({
|
||||
nativeComponentState: 'missing',
|
||||
canEnable: false,
|
||||
reasonCode: 'COMPONENT_MISSING'
|
||||
})
|
||||
|
||||
it('报障场景:库里 recall=1 且本地退群=true,没有授权 → 两个都显示关闭', () => {
|
||||
for (const cap of [expired, unavailable, noComponent]) {
|
||||
expect(resolveSwitchPresentation('recall_notice', true, cap)).toEqual({
|
||||
desiredEnabled: false,
|
||||
effectiveEnabled: false
|
||||
})
|
||||
expect(resolveSwitchPresentation('group_exit_notice', true, cap)).toEqual({
|
||||
desiredEnabled: false,
|
||||
effectiveEnabled: false
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('授权与组件都就绪、库已连接 → 两个都保持用户设置', () => {
|
||||
const ok = capability({})
|
||||
expect(resolveSwitchPresentation('recall_notice', true, ok)).toEqual({
|
||||
desiredEnabled: true,
|
||||
effectiveEnabled: true
|
||||
})
|
||||
expect(resolveSwitchPresentation('group_exit_notice', true, ok)).toEqual({
|
||||
desiredEnabled: true,
|
||||
effectiveEnabled: true
|
||||
})
|
||||
})
|
||||
|
||||
it('只是微信库没连 → 保留用户意愿但 effective 为 false', () => {
|
||||
const noDb = capability({
|
||||
databaseReady: false,
|
||||
canEnable: false,
|
||||
reasonCode: 'DATABASE_UNAVAILABLE'
|
||||
})
|
||||
expect(resolveSwitchPresentation('recall_notice', true, noDb)).toEqual({
|
||||
desiredEnabled: true,
|
||||
effectiveEnabled: false
|
||||
})
|
||||
expect(resolveSwitchPresentation('group_exit_notice', true, noDb)).toEqual({
|
||||
desiredEnabled: true,
|
||||
effectiveEnabled: false
|
||||
})
|
||||
})
|
||||
|
||||
it('用户本来就关着 + 无授权 → 依然是关闭,不会被"授权没问题"之外的逻辑打开', () => {
|
||||
expect(resolveSwitchPresentation('recall_notice', false, expired).desiredEnabled).toBe(false)
|
||||
expect(resolveSwitchPresentation('group_exit_notice', false, expired).desiredEnabled).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
resetComponentCache,
|
||||
resolveExternalComponent
|
||||
} from '../../src/main/services/external-component-locator'
|
||||
|
||||
/** 组件发现必须 fail-closed:指针/目录/哈希任一不对都当没装。 */
|
||||
|
||||
let tmpRoot = ''
|
||||
let localAppData = ''
|
||||
|
||||
function writeFile(filePath: string, content: Buffer | string): Buffer {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
const buf = Buffer.isBuffer(content) ? content : Buffer.from(content)
|
||||
fs.writeFileSync(filePath, buf)
|
||||
return buf
|
||||
}
|
||||
|
||||
function sha256(buf: Buffer): string {
|
||||
return crypto.createHash('sha256').update(buf).digest('hex')
|
||||
}
|
||||
|
||||
function buildBundle(options: { dirty?: boolean; corruptHash?: boolean } = {}): string {
|
||||
const versionDir = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', '1.0.0')
|
||||
const wcdbApi = writeFile(path.join(versionDir, 'wcdb_api.dll'), Buffer.alloc(2048, 0x11))
|
||||
const wcdb = writeFile(path.join(versionDir, 'WCDB.dll'), Buffer.alloc(4096, 0x22))
|
||||
const helper = writeFile(path.join(versionDir, 'tm-wcdb-config-helper.exe'), Buffer.alloc(1024, 0x33))
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
componentVersion: '1.0.0',
|
||||
worktreeDirty: options.dirty === true,
|
||||
files: [
|
||||
{ path: 'wcdb_api.dll', size: wcdbApi.length, sha256: sha256(wcdbApi) },
|
||||
{ path: 'WCDB.dll', size: wcdb.length, sha256: sha256(wcdb) },
|
||||
{
|
||||
path: 'tm-wcdb-config-helper.exe',
|
||||
size: helper.length,
|
||||
sha256: options.corruptHash ? 'a'.repeat(64) : sha256(helper)
|
||||
}
|
||||
]
|
||||
}
|
||||
writeFile(path.join(versionDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
||||
writeFile(
|
||||
path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', 'current.json'),
|
||||
JSON.stringify({ version: '1.0.0', dir: versionDir }, null, 2)
|
||||
)
|
||||
return versionDir
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-locator-'))
|
||||
localAppData = path.join(tmpRoot, 'LocalAppData')
|
||||
fs.mkdirSync(localAppData, { recursive: true })
|
||||
resetComponentCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(tmpRoot, { recursive: true, force: true })
|
||||
resetComponentCache()
|
||||
})
|
||||
|
||||
const env = (): NodeJS.ProcessEnv => ({ LOCALAPPDATA: localAppData })
|
||||
|
||||
describe('resolveExternalComponent', () => {
|
||||
it('没有 current.json 时返回 null(= 组件没装)', () => {
|
||||
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
|
||||
})
|
||||
|
||||
it('非 Windows 直接返回 null', () => {
|
||||
buildBundle()
|
||||
expect(resolveExternalComponent(env(), 'darwin')).toBeNull()
|
||||
})
|
||||
|
||||
it('校验通过时返回 helper 路径与版本', () => {
|
||||
const dir = buildBundle()
|
||||
const found = resolveExternalComponent(env(), 'win32')
|
||||
expect(found).not.toBeNull()
|
||||
expect(found?.helperPath).toBe(path.join(dir, 'tm-wcdb-config-helper.exe'))
|
||||
expect(found?.version).toBe('1.0.0')
|
||||
expect(found?.dirty).toBe(false)
|
||||
})
|
||||
|
||||
it('dirty 标记透传(内部调试构建)', () => {
|
||||
buildBundle({ dirty: true })
|
||||
expect(resolveExternalComponent(env(), 'win32')?.dirty).toBe(true)
|
||||
})
|
||||
|
||||
it('哈希不符时当作没装(不能返回可疑路径)', () => {
|
||||
buildBundle({ corruptHash: true })
|
||||
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
|
||||
})
|
||||
|
||||
it('指针指向的目录不存在时返回 null', () => {
|
||||
writeFile(
|
||||
path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64', 'current.json'),
|
||||
JSON.stringify({ version: '1.0.0', dir: path.join(tmpRoot, 'gone') })
|
||||
)
|
||||
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
|
||||
})
|
||||
|
||||
it('manifest 缺失时返回 null', () => {
|
||||
const dir = buildBundle()
|
||||
fs.rmSync(path.join(dir, 'manifest.json'))
|
||||
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
|
||||
})
|
||||
|
||||
it('helper 缺失时返回 null', () => {
|
||||
const dir = buildBundle()
|
||||
fs.rmSync(path.join(dir, 'tm-wcdb-config-helper.exe'))
|
||||
resetComponentCache()
|
||||
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
|
||||
})
|
||||
|
||||
it('文件被替换后校验会重新计算(不吃旧缓存)', () => {
|
||||
const dir = buildBundle()
|
||||
expect(resolveExternalComponent(env(), 'win32')).not.toBeNull()
|
||||
|
||||
/* 篡改 WCDB.dll 内容但不改 mtime 之外的东西:manifest mtime 变了就要重算 */
|
||||
const target = path.join(dir, 'WCDB.dll')
|
||||
fs.writeFileSync(target, Buffer.alloc(4096, 0x99))
|
||||
const manifestPath = path.join(dir, 'manifest.json')
|
||||
const stat = fs.statSync(manifestPath)
|
||||
fs.utimesSync(manifestPath, stat.atime, new Date(stat.mtimeMs + 5000))
|
||||
|
||||
expect(resolveExternalComponent(env(), 'win32')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,266 @@
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
MessageInsertCapabilityService,
|
||||
inspectNativeComponent,
|
||||
mapLicenseStatus,
|
||||
type CapabilityInput,
|
||||
type LicenseProbeResult,
|
||||
type CapabilityDeps
|
||||
} from '../../src/main/services/msg-insert-capability-service'
|
||||
|
||||
/** 判定矩阵:不确定即拒、三种原因可区分、关闭不受授权影响。 */
|
||||
|
||||
const tmpDirs: string[] = []
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-cap-'))
|
||||
tmpDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
/** 造一个最小的合法 PE:MZ + e_lfanew + PE 签名 + machine */
|
||||
function writeFakePe(machine = 0x8664, size = 4096): string {
|
||||
const dir = makeTempDir()
|
||||
const file = path.join(dir, 'tm-wcdb-config-helper.exe')
|
||||
const buf = Buffer.alloc(size)
|
||||
buf.write('MZ', 0, 'ascii')
|
||||
buf.writeUInt32LE(0x80, 0x3c)
|
||||
buf.write('PE\0\0', 0x80, 'ascii')
|
||||
buf.writeUInt16LE(machine, 0x80 + 4)
|
||||
fs.writeFileSync(file, buf)
|
||||
return file
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tmpDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function makeService(options: {
|
||||
platform?: NodeJS.Platform
|
||||
probe?: () => Promise<LicenseProbeResult>
|
||||
component?: string | null
|
||||
macBundle?: boolean
|
||||
now?: () => number
|
||||
}): { service: MessageInsertCapabilityService; probeCalls: () => number } {
|
||||
let calls = 0
|
||||
const deps: CapabilityDeps = {
|
||||
platform: options.platform ?? 'win32',
|
||||
hasMacNativeBundle: () => options.macBundle === true,
|
||||
isMacRuntimeUnavailable: () => options.macBundle !== true,
|
||||
resolveNativeComponent: () => (options.component === undefined ? null : options.component),
|
||||
probeLicense: async () => {
|
||||
calls += 1
|
||||
if (options.probe) return options.probe()
|
||||
return { ok: true, status: 'LICENSE_OK' }
|
||||
},
|
||||
now: options.now
|
||||
}
|
||||
return { service: new MessageInsertCapabilityService(deps), probeCalls: () => calls }
|
||||
}
|
||||
|
||||
const dbReady: CapabilityInput = { databaseReady: true }
|
||||
const dbDown: CapabilityInput = { databaseReady: false }
|
||||
|
||||
describe('mapLicenseStatus', () => {
|
||||
it('只有 LICENSE_OK 算有效', () => {
|
||||
expect(mapLicenseStatus('LICENSE_OK').entitlement).toBe('valid')
|
||||
for (const status of [
|
||||
'LICENSE_EXPIRED',
|
||||
'LICENSE_MACHINE_MISMATCH',
|
||||
'LICENSE_REVOKED',
|
||||
'LICENSE_INVALID',
|
||||
'LICENSE_TAMPERED',
|
||||
'LICENSE_NOT_FOUND'
|
||||
]) {
|
||||
expect(mapLicenseStatus(status).entitlement).toBe('invalid')
|
||||
}
|
||||
})
|
||||
|
||||
it('校验中与网络错误都不算有效,也不能算「没买」', () => {
|
||||
expect(mapLicenseStatus('LICENSE_CHECKING').entitlement).toBe('pending')
|
||||
expect(mapLicenseStatus('LICENSE_NETWORK_ERROR').entitlement).toBe('unavailable')
|
||||
expect(mapLicenseStatus('LICENSE_SERVER_ERROR').entitlement).toBe('unavailable')
|
||||
expect(mapLicenseStatus(undefined).entitlement).toBe('unavailable')
|
||||
expect(mapLicenseStatus('SOMETHING_NEW').entitlement).toBe('unavailable')
|
||||
})
|
||||
})
|
||||
|
||||
describe('inspectNativeComponent', () => {
|
||||
it('缺失与空文件都算 missing', () => {
|
||||
expect(inspectNativeComponent(null, 'x64', () => null)).toBe('missing')
|
||||
const dir = makeTempDir()
|
||||
const empty = path.join(dir, 'empty.exe')
|
||||
fs.writeFileSync(empty, Buffer.alloc(16))
|
||||
expect(inspectNativeComponent(empty, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('missing')
|
||||
})
|
||||
|
||||
it('不是 PE 的算 invalid', () => {
|
||||
const dir = makeTempDir()
|
||||
const junk = path.join(dir, 'junk.exe')
|
||||
fs.writeFileSync(junk, Buffer.alloc(4096, 0x41))
|
||||
expect(inspectNativeComponent(junk, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('invalid')
|
||||
})
|
||||
|
||||
it('架构不符算 incompatible', () => {
|
||||
const arm = writeFakePe(0xaa64)
|
||||
expect(inspectNativeComponent(arm, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('incompatible')
|
||||
const x64 = writeFakePe(0x8664)
|
||||
expect(inspectNativeComponent(x64, 'x64', (p) => ({ size: fs.statSync(p).size }))).toBe('ready')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Windows 能力判定', () => {
|
||||
it('Hook 无响应:不可开启,原因是有界失败而不是「未授权」', async () => {
|
||||
const { service } = makeService({ probe: async () => ({ ok: false, error: 'ECONNREFUSED' }) })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.entitlementState).toBe('unavailable')
|
||||
expect(cap.reasonCode).toBe('LICENSE_UNAVAILABLE')
|
||||
})
|
||||
|
||||
it('没有授权文件:要求先激活', async () => {
|
||||
const { service } = makeService({ probe: async () => ({ ok: true, status: 'LICENSE_NOT_FOUND' }) })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.reasonCode).toBe('LICENSE_REQUIRED')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
})
|
||||
|
||||
it('LICENSE_CHECKING 不能当有效', async () => {
|
||||
const { service } = makeService({ probe: async () => ({ ok: true, status: 'LICENSE_CHECKING' }) })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.entitlementState).toBe('pending')
|
||||
expect(cap.reasonCode).toBe('LICENSE_PENDING')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
})
|
||||
|
||||
it('过期 / 设备不匹配 / 吊销 各自有专属原因', async () => {
|
||||
const cases: Array<[string, string]> = [
|
||||
['LICENSE_EXPIRED', 'LICENSE_EXPIRED'],
|
||||
['LICENSE_MACHINE_MISMATCH', 'LICENSE_MACHINE_MISMATCH'],
|
||||
['LICENSE_REVOKED', 'LICENSE_REVOKED'],
|
||||
['LICENSE_INVALID', 'LICENSE_INVALID']
|
||||
]
|
||||
for (const [status, reason] of cases) {
|
||||
const { service } = makeService({ probe: async () => ({ ok: true, status }) })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.reasonCode).toBe(reason)
|
||||
expect(cap.canEnable).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('有授权但缺组件:不能开,且原因不是授权问题', async () => {
|
||||
const { service } = makeService({ component: null })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.entitlementState).toBe('valid')
|
||||
expect(cap.nativeComponentState).toBe('missing')
|
||||
expect(cap.reasonCode).toBe('COMPONENT_MISSING')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
})
|
||||
|
||||
it('组件损坏:不能开', async () => {
|
||||
const dir = makeTempDir()
|
||||
const junk = path.join(dir, 'broken.exe')
|
||||
fs.writeFileSync(junk, Buffer.alloc(4096, 0x00))
|
||||
const { service } = makeService({ component: junk })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.nativeComponentState).toBe('invalid')
|
||||
expect(cap.reasonCode).toBe('COMPONENT_INVALID')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
})
|
||||
|
||||
it('数据库没连:不能开', async () => {
|
||||
const { service } = makeService({ component: writeFakePe() })
|
||||
const cap = await service.refresh(dbDown)
|
||||
expect(cap.reasonCode).toBe('DATABASE_UNAVAILABLE')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
})
|
||||
|
||||
it('授权 + 组件 + 数据库齐了才允许开', async () => {
|
||||
const { service } = makeService({ component: writeFakePe() })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.canEnable).toBe(true)
|
||||
expect(cap.reasonCode).toBe('CAPABILITY_READY')
|
||||
})
|
||||
|
||||
it('关闭永远不受授权限制', async () => {
|
||||
const { service } = makeService({
|
||||
probe: async () => ({ ok: true, status: 'LICENSE_EXPIRED' }),
|
||||
component: null
|
||||
})
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.canDisable).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('macOS 双版本策略', () => {
|
||||
it('OSS 包:不支持,且不能说成「未授权」', async () => {
|
||||
const { service } = makeService({ platform: 'darwin', macBundle: false })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.entitlementState).toBe('unsupported')
|
||||
expect(cap.reasonCode).toBe('UNSUPPORTED_PLATFORM')
|
||||
expect(cap.canEnable).toBe(false)
|
||||
})
|
||||
|
||||
it('Native 包:组件与数据库就绪即可开,不看发送 ready', async () => {
|
||||
const { service } = makeService({ platform: 'darwin', macBundle: true, component: writeFakePe() })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.canEnable).toBe(true)
|
||||
expect(cap.entitlementState).toBe('valid')
|
||||
})
|
||||
|
||||
it('Native 包但缺组件:仍然不能开', async () => {
|
||||
const { service } = makeService({ platform: 'darwin', macBundle: true, component: null })
|
||||
const cap = await service.refresh(dbReady)
|
||||
expect(cap.canEnable).toBe(false)
|
||||
expect(cap.reasonCode).toBe('COMPONENT_MISSING')
|
||||
})
|
||||
})
|
||||
|
||||
describe('缓存与并发', () => {
|
||||
it('TTL 内复用结果,refresh 强制重查', async () => {
|
||||
let now = 1_000
|
||||
let status = 'LICENSE_REQUIRED'
|
||||
const { service, probeCalls } = makeService({
|
||||
component: writeFakePe(),
|
||||
now: () => now,
|
||||
probe: async () => ({ ok: true, status: status === 'LICENSE_REQUIRED' ? 'LICENSE_NOT_FOUND' : status })
|
||||
})
|
||||
|
||||
await service.getCapability(dbReady)
|
||||
const first = probeCalls()
|
||||
await service.getCapability(dbReady)
|
||||
expect(probeCalls()).toBe(first)
|
||||
|
||||
status = 'LICENSE_OK'
|
||||
const cached = await service.getCapability(dbReady)
|
||||
expect(cached.canEnable).toBe(false)
|
||||
|
||||
const fresh = await service.refresh(dbReady)
|
||||
expect(fresh.canEnable).toBe(true)
|
||||
expect(probeCalls()).toBeGreaterThan(first)
|
||||
|
||||
now += 31_000
|
||||
await service.getCapability(dbReady)
|
||||
expect(probeCalls()).toBeGreaterThan(first + 1)
|
||||
})
|
||||
|
||||
it('并发刷新只探一次', async () => {
|
||||
const { service, probeCalls } = makeService({ component: writeFakePe() })
|
||||
await Promise.all([service.refresh(dbReady), service.refresh(dbReady), service.refresh(dbReady)])
|
||||
expect(probeCalls()).toBe(1)
|
||||
})
|
||||
|
||||
it('数据库状态变化不受授权缓存影响', async () => {
|
||||
const { service } = makeService({ component: writeFakePe() })
|
||||
expect((await service.getCapability(dbReady)).canEnable).toBe(true)
|
||||
expect((await service.getCapability(dbDown)).canEnable).toBe(false)
|
||||
expect((await service.getCapability(dbReady)).canEnable).toBe(true)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user