Merge branch 'develop_1030' into develop

# Conflicts:
#	.gitignore
This commit is contained in:
Wxw-Gu committed 2026-11-04 16:07:42 +08:00
commit 7e9997cc06
48 files changed
+4835 -513

No files matched your search

@@ -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())
})
})
@@ -41,7 +41,6 @@ const readyStatus = {
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
@@ -23,7 +23,6 @@ const senderStatus = {
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
@@ -59,7 +58,25 @@ describe('PersonalWechatSendPage on macOS', () => {
value: {
getPersonalWechatSendCapability: getCapability,
getPersonalWechatSenderStatus: getSenderStatus,
rebindPersonalWechatSender: rebindSender
rebindPersonalWechatSender: rebindSender,
// 发送能力授权卡所需的两个入口。页面在 Native 档位会调用它们,
// 缺 mock 会让 refresh 抛错、整页停在错误态。
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getMacLicenseStatus: vi.fn(async () => ({
deviceId: null,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
})),
refreshMacLicense: vi.fn()
}
})
})
@@ -67,7 +84,9 @@ describe('PersonalWechatSendPage on macOS', () => {
it('shows the native runtime readiness', async () => {
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByText('微信消息发送已配置完成')).toBeVisible()
// 页面重构后「就绪」的落点从 SetupGuide 尾部文案变成了「微信发送环境」卡片的状态标签;
// 断言改到新位置,语义仍是“运行时准备好了”。
expect(await screen.findByText('运行环境已就绪')).toBeVisible()
expect(screen.getAllByText('已就绪')).not.toHaveLength(0)
expect(screen.queryByText('查看支持的微信版本')).not.toBeInTheDocument()
expect(screen.queryByText('高级诊断')).not.toBeInTheDocument()
@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PersonalWechatSetupGuide } from '../../src/renderer/src/components/chat/PersonalWechatSetupGuide'
@@ -41,6 +41,10 @@ describe('personal WeChat unavailable product state', () => {
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getPersonalWechatSendCapability: vi.fn(async () => ({
supported: true,
ready: false,
@@ -50,7 +54,19 @@ describe('personal WeChat unavailable product state', () => {
message: '暂无发送能力',
error: '暂无发送能力'
})),
getPersonalWechatSenderStatus: vi.fn(async () => unavailableStatus)
getPersonalWechatSenderStatus: vi.fn(async () => unavailableStatus),
getMacLicenseStatus: vi.fn(async () => ({
deviceId: `mac_${'c'.repeat(64)}`,
state: 'unlicensed',
authorized: false,
source: 'none',
features: [],
lastCheckedAt: null,
licenseExpiresAt: null,
tokenExpiresAt: null,
message: '当前设备暂无发送能力授权'
})),
refreshMacLicense: vi.fn()
}
})
})
@@ -85,12 +101,195 @@ describe('personal WeChat unavailable product state', () => {
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByRole('heading', { name: '先准备好微信消息功能' })).toBeVisible()
expect(screen.getByRole('button', { name: '绑定微信' })).toBeDisabled()
expect(screen.getByRole('button', { name: '授权后可绑定微信' })).toBeDisabled()
expect(screen.getByRole('region', { name: '微信发送环境' })).toBeVisible()
expect(screen.getByText('运行时正常')).toBeVisible()
expect(screen.getByText('微信已绑定')).toBeVisible()
expect(screen.getByText('发送组件正常')).toBeVisible()
expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute(
'aria-expanded',
'true'
)
expect(await screen.findByRole('region', { name: '发送能力授权' })).toBeVisible()
expect(screen.queryByText(/发送能力属授权制,需要联系群主/)).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: '这里' })).not.toBeInTheDocument()
expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument()
})
it('shows real environment status and keeps first-use details collapsed when ready', async () => {
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getPersonalWechatSendCapability: vi.fn(async () => ({
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: true },
senderStatus: readyStatus,
message: '已就绪'
})),
getPersonalWechatSenderStatus: vi.fn(async () => readyStatus),
getMacLicenseStatus: vi.fn(async () => ({
...licenseStatus,
state: 'revoked',
authorized: false
})),
refreshMacLicense: vi.fn()
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByText('运行环境已就绪')).toBeVisible()
expect(screen.getAllByText('正常')).toHaveLength(3)
expect(screen.getByRole('button', { name: '授权后可开始发送' })).toBeDisabled()
expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute(
'aria-expanded',
'false'
)
expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument()
expect(await screen.findByText('授权已撤销')).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '首次使用配置' }))
expect(screen.getByRole('button', { name: '首次使用配置' })).toHaveAttribute(
'aria-expanded',
'true'
)
expect(screen.queryByRole('button', { name: '绑定微信' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '开始发送' })).not.toBeInTheDocument()
expect(screen.getAllByRole('listitem')).toHaveLength(2)
expect(screen.getByText('每个微信进程只能绑定一次')).toBeVisible()
expect(screen.getByText(/4\.1\.13以下请保持微信未登录窗口状态/)).toBeVisible()
expect(screen.getByText('4.1.13以上登录状态微信直接点击“绑定微信”')).toBeVisible()
expect(screen.queryByText('能力检测')).not.toBeInTheDocument()
expect(screen.queryByText('文字消息')).not.toBeInTheDocument()
expect(screen.queryByText('图片消息')).not.toBeInTheDocument()
expect(screen.queryByText('语音消息')).not.toBeInTheDocument()
})
it('copies the full device id and shows refresh loading without disabling copy', async () => {
const deviceId = `mac_${'a'.repeat(64)}`
let resolveRefresh: ((value: typeof licenseStatus) => void) | undefined
const refreshMacLicense = vi.fn(
() => new Promise<typeof licenseStatus>((resolve) => (resolveRefresh = resolve))
)
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: vi.fn(async () => undefined) }
})
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'available',
message: '微信发送组件可用'
})),
getPersonalWechatSendCapability: vi.fn(async () => ({
supported: true,
ready: false,
status: 'unconfigured',
capabilities: { text: false, image: false, voice: false },
senderStatus: readyStatus,
message: '未配置'
})),
getPersonalWechatSenderStatus: vi.fn(async () => readyStatus),
getMacLicenseStatus: vi.fn(async () => ({ ...licenseStatus, deviceId, state: 'expired' })),
refreshMacLicense
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
const copyButton = await screen.findByRole('button', { name: '复制完整设备 ID' })
fireEvent.click(copyButton)
await waitFor(() => expect(navigator.clipboard.writeText).toHaveBeenCalledWith(deviceId))
expect(await screen.findByText('授权已过期')).toBeVisible()
fireEvent.click(screen.getByRole('button', { name: '重新检测授权' }))
expect(await screen.findByRole('button', { name: '检测中…' })).toBeDisabled()
expect(copyButton).toBeEnabled()
resolveRefresh?.({ ...licenseStatus, deviceId, state: 'valid', authorized: true })
})
it('does not query or render License when the send runtime is unavailable', async () => {
const getMacLicenseStatus = vi.fn()
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'unavailable',
message: '当前版本没有微信发送能力'
})),
getMacLicenseStatus,
getPersonalWechatSendCapability: vi.fn(),
getPersonalWechatSenderStatus: vi.fn()
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByRole('button', { name: '当前版本没有微信发送能力' })).toBeDisabled()
expect(screen.getByText(/发送能力属授权制,需要联系群主/)).toBeVisible()
expect(screen.getByRole('link', { name: '这里' })).toHaveAttribute(
'href',
'https://github.com/Wxw-Gu/TraceMemo#-交流与反馈'
)
expect(screen.queryByText(/manifest|dylib|runtime missing|文件缺失/i)).not.toBeInTheDocument()
expect(screen.queryByRole('region', { name: '发送能力授权' })).not.toBeInTheDocument()
expect(getMacLicenseStatus).not.toHaveBeenCalled()
})
it('shows component failure without querying License when send runtime files are damaged', async () => {
const getMacLicenseStatus = vi.fn()
Object.defineProperty(window, 'api', {
configurable: true,
value: {
getMacSendRuntimeAvailability: vi.fn(async () => ({
state: 'component_error',
message: '发送组件缺失或异常:manifest missing'
})),
getMacLicenseStatus,
getPersonalWechatSendCapability: vi.fn(),
getPersonalWechatSenderStatus: vi.fn()
}
})
render(<PersonalWechatSendPage onNotice={vi.fn()} />)
expect(await screen.findByRole('button', { name: '发送组件缺失或异常' })).toBeDisabled()
expect(screen.getAllByText('发送组件缺失或异常').length).toBeGreaterThan(0)
expect(screen.queryByText(/发送能力属授权制,需要联系群主/)).not.toBeInTheDocument()
expect(getMacLicenseStatus).not.toHaveBeenCalled()
expect(screen.queryByRole('region', { name: '发送能力授权' })).not.toBeInTheDocument()
})
})
const readyStatus: PersonalWechatSenderStatus = {
...unavailableStatus,
state: 'online',
wechatRunning: true,
wechatPid: 1234,
boundWechatPid: 1234,
endpointReady: true,
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
canSend: true,
canSendText: true,
canSendImage: true,
canSendVoice: true
}
const licenseStatus = {
deviceId: `mac_${'b'.repeat(64)}`,
state: 'valid' as const,
authorized: true,
source: 'online' as const,
features: ['wechat', 'api'],
lastCheckedAt: '2026-11-04T09:44:00+08:00',
licenseExpiresAt: '2027-11-03T00:00:00+08:00',
tokenExpiresAt: null,
message: '已授权'
}
-1
View File
@@ -663,7 +663,6 @@ handle('wechat-personal:getStatus', () => ({
boundWechatPid: 4668,
endpoint: '127.0.0.1:4290',
endpointReady: true,
wechatVersion: '4.1.11.53',
runtimeReady: true,
attachReady: true,
baseAddress: '0x114ef8000',
+221
View File
@@ -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({
+190
View File
@@ -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,70 @@
import { describe, expect, it } from 'vitest'
import { resolveLicenseRefreshFailure } from '../../src/main/services/mac-wechat-runtime-manager'
import type { MacLicenseStatus } from '../../src/shared/personal-wechat-mac-license'
const DEVICE_ID = `mac_${'a'.repeat(64)}`
function status(overrides: Partial<MacLicenseStatus> = {}): MacLicenseStatus {
return {
deviceId: DEVICE_ID,
state: 'cached',
authorized: true,
source: 'cache',
features: ['wechat'],
lastCheckedAt: '2026-11-04T07:00:00Z',
licenseExpiresAt: null,
tokenExpiresAt: '2026-11-05T07:00:00Z',
message: '授权有效(本地缓存)',
...overrides
}
}
const DIAGNOSTIC = '无法连接授权服务器,请检查网络后重试'
describe('resolveLicenseRefreshFailure', () => {
it('有效缓存时保留授权,并把本次失败写进诊断信息', () => {
const result = resolveLicenseRefreshFailure(status(), DIAGNOSTIC)
// 授权状态不变 —— 网络故障不能让已授权设备变成未授权。
expect(result.authorized).toBe(true)
expect(result.state).toBe('cached')
expect(result.deviceId).toBe(DEVICE_ID)
expect(result.features).toEqual(['wechat'])
// 但这次失败必须可见,不能被快照整个盖掉。
expect(result.message).toContain('本次刷新失败')
expect(result.message).toContain(DIAGNOSTIC)
expect(result.message).toContain('本地缓存授权')
})
it('无有效缓存时明确报 server_unavailable,而不是未授权或已撤销', () => {
const result = resolveLicenseRefreshFailure(null, DIAGNOSTIC)
expect(result.state).toBe('server_unavailable')
expect(result.authorized).toBe(false)
expect(result.state).not.toBe('revoked')
expect(result.state).not.toBe('unlicensed')
expect(result.message).toBe(DIAGNOSTIC)
})
it('快照存在但未授权时同样按网络故障处理', () => {
const result = resolveLicenseRefreshFailure(
status({ state: 'unlicensed', authorized: false, message: '当前设备暂无发送能力授权' }),
DIAGNOSTIC
)
expect(result.state).toBe('server_unavailable')
expect(result.authorized).toBe(false)
expect(result.message).toBe(DIAGNOSTIC)
})
it('不把 revoked 快照改写成授权有效', () => {
const result = resolveLicenseRefreshFailure(
status({ state: 'revoked', authorized: false, message: '授权已被撤销' }),
DIAGNOSTIC
)
expect(result.authorized).toBe(false)
expect(result.state).toBe('server_unavailable')
})
})
@@ -1,127 +0,0 @@
import { createRequire } from 'module'
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { describe, expect, it } from 'vitest'
import {
bindingMatchesRuntimeManifest,
readMacWechatRuntimeManifest
} from '../../src/main/services/mac-wechat-runtime-artifact'
const nodeRequire = createRequire(import.meta.url)
const { readAndValidateArtifact, syncArtifact } = nodeRequire(
'../../scripts/prepare-wechat-native-runtime.cjs'
) as {
readAndValidateArtifact: (sourceDir: string) => { manifest: { tmSendSourceSha256: string } }
syncArtifact: (sourceDir: string, targetDir: string) => unknown
}
const AGENT_HASH = 'a'.repeat(64)
const ADDRESS_PROFILE_HASH = 'b'.repeat(64)
function writeMachOArm64(filePath: string, suffix = Buffer.alloc(0)): void {
const header = Buffer.alloc(32)
header.writeUInt32LE(0xfeedfacf, 0)
header.writeUInt32LE(0x0100000c, 4)
writeFileSync(filePath, Buffer.concat([header, suffix]))
}
function createArtifact(root: string): void {
writeMachOArm64(join(root, 'tm-wechat-host'))
writeMachOArm64(
join(root, 'libtmwechat.dylib'),
Buffer.from(`${AGENT_HASH}${ADDRESS_PROFILE_HASH}`)
)
writeFileSync(
join(root, 'runtime-manifest.json'),
JSON.stringify({
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: ADDRESS_PROFILE_HASH,
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
})
)
}
describe('macOS self-contained WeChat runtime artifact', () => {
it('validates the manifest, architecture, capabilities and embedded agent identity', () => {
const root = mkdtempSync(join(tmpdir(), 'tm-native-runtime-'))
createArtifact(root)
const manifest = readMacWechatRuntimeManifest(root, 'arm64')
expect(manifest.tmSendSourceSha256).toBe(AGENT_HASH)
expect(
bindingMatchesRuntimeManifest(
{
hostPid: 123,
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH,
embeddedAddressProfileSha256: ADDRESS_PROFILE_HASH
},
manifest
)
).toBe(true)
expect(
bindingMatchesRuntimeManifest(
{ hostPid: 123, runtimeVersion: 'tm-wechat-runtime/0.1.0' },
manifest
)
).toBe(false)
expect(
bindingMatchesRuntimeManifest(
{
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH
},
manifest
)
).toBe(false)
})
it('rejects a manifest whose embedded address profile hash is absent from the dylib', () => {
const root = mkdtempSync(join(tmpdir(), 'tm-native-runtime-profile-mismatch-'))
createArtifact(root)
writeFileSync(
join(root, 'runtime-manifest.json'),
JSON.stringify({
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: 'c'.repeat(64),
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
})
)
expect(() => readMacWechatRuntimeManifest(root, 'arm64')).toThrow(/address profile hash/)
})
it('prepares an exact runtime tree and removes old external agent and table directories', () => {
const source = mkdtempSync(join(tmpdir(), 'tm-native-source-'))
const target = mkdtempSync(join(tmpdir(), 'tm-native-target-parent-'))
const targetRuntime = join(target, 'darwin-arm64')
createArtifact(source)
mkdirSync(join(targetRuntime, 'scripts'), { recursive: true })
writeFileSync(join(targetRuntime, 'scripts', 'tm_send.js'), 'old external agent')
mkdirSync(join(targetRuntime, 'wechat_version'), { recursive: true })
writeFileSync(join(targetRuntime, 'wechat_version', '4_1_11_53_mac.json'), '{}')
expect(readAndValidateArtifact(source).manifest.tmSendSourceSha256).toBe(AGENT_HASH)
syncArtifact(source, targetRuntime)
expect(existsSync(join(targetRuntime, 'scripts'))).toBe(false)
expect(existsSync(join(targetRuntime, 'wechat_version'))).toBe(false)
expect(existsSync(join(targetRuntime, 'runtime-manifest.json'))).toBe(true)
expect(readAndValidateArtifact(targetRuntime).manifest.tmSendSourceSha256).toBe(AGENT_HASH)
})
})
@@ -1,138 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('electron', () => ({
app: {
getAppPath: () => '/fixture/app',
isPackaged: false
}
}))
import {
deriveMacWechatSenderStatus,
shouldClearWechatRestartRequired
} from '../../src/main/services/mac-wechat-runtime-manager'
import type {
MacWechatBindingStatus,
MacWechatRuntimeManifest,
MacWechatRuntimeSnapshot
} from '../../src/shared/personal-wechat-mac-runtime'
const AGENT_HASH = 'a'.repeat(64)
const ADDRESS_PROFILE_HASH = 'b'.repeat(64)
const manifest: MacWechatRuntimeManifest = {
runtime: 'tm-wechat-native',
version: '0.1.0',
platform: 'darwin-arm64',
architecture: 'arm64',
protocolVersion: 1,
buildCommit: 'test',
tmSendSourceSha256: AGENT_HASH,
addressProfileSha256: ADDRESS_PROFILE_HASH,
supportedWechatVersions: ['4.1.11.53'],
capabilities: ['text', 'image', 'voice']
}
function snapshot(overrides: Partial<MacWechatRuntimeSnapshot> = {}): MacWechatRuntimeSnapshot {
return {
lifecycle: 'online',
wechatRestartRequired: false,
endpoint: 'http://127.0.0.1:4290',
port: 4290,
manifest,
...overrides
}
}
function binding(overrides: Partial<MacWechatBindingStatus> = {}): MacWechatBindingStatus {
return {
runtime: true,
hostPid: 123,
runtimeState: 'ready',
runtimeVersion: 'tm-wechat-runtime/0.1.0',
embeddedAgentSha256: AGENT_HASH,
embeddedAddressProfileSha256: ADDRESS_PROFILE_HASH,
wechatRunning: true,
wechatPid: 456,
wechatVersion: '4.1.11.53',
supported: true,
bindingState: 'ready',
bound: true,
boundWechatPid: 456,
sessionAttached: true,
scriptLoaded: true,
sendContextReady: true,
canSendText: true,
canSendImage: true,
canSendVoice: true,
attachCount: 1,
...overrides
}
}
describe('macOS native runtime sender status mapping', () => {
it('exposes capabilities only for a ready binding with matching runtime identity', () => {
expect(
deriveMacWechatSenderStatus({ snapshot: snapshot(), binding: binding(), manifest })
).toMatchObject({
state: 'online',
runtimeReady: true,
attachReady: true,
baseAddressReady: true,
messageListenerReady: true,
canSend: true,
canSendText: true,
canSendImage: true,
canSendVoice: true
})
})
it('rejects a live host whose embedded runtime identity does not match the manifest', () => {
const status = deriveMacWechatSenderStatus({
snapshot: snapshot(),
binding: binding({ embeddedAgentSha256: 'b'.repeat(64) }),
manifest
})
expect(status).toMatchObject({
state: 'error',
runtimeReady: false,
canSend: false,
canSendText: false,
canSendImage: false,
canSendVoice: false
})
expect(status.error).toContain('Native Runtime 不一致')
})
it('maps a stale binding to a rebind-required stopped state', () => {
expect(
deriveMacWechatSenderStatus({
snapshot: snapshot(),
binding: binding({ bindingState: 'stale', sendContextReady: false }),
manifest
})
).toMatchObject({
state: 'stopped',
message: '检测到微信已重启,请重新绑定',
canSend: false
})
})
it('keeps restart-required errors above otherwise ready binding state', () => {
expect(
deriveMacWechatSenderStatus({
snapshot: snapshot({ wechatRestartRequired: true }),
binding: binding(),
manifest
})
).toMatchObject({ state: 'error', canSend: false })
})
it('clears restart-required only after WeChat has a different positive pid', () => {
expect(shouldClearWechatRestartRequired(100, 200)).toBe(true)
expect(shouldClearWechatRestartRequired(100, 100)).toBe(false)
expect(shouldClearWechatRestartRequired(0, 200)).toBe(false)
expect(shouldClearWechatRestartRequired(100, 0)).toBe(false)
})
})
+266
View File
@@ -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)
})
})
+60 -1
View File
@@ -19,6 +19,19 @@ const asar = nodeRequire('@electron/asar') as {
const { hasWindowsSherpaRuntime } = nodeRequire('../../scripts/prepare-win-runtime.cjs') as {
hasWindowsSherpaRuntime: (runtimeRoot: string) => boolean
}
const { createBuilderConfig } = nodeRequire('../../scripts/build-macos-edition.cjs') as {
createBuilderConfig: (options: {
edition: 'public' | 'native'
stageRoot: string
buildOutput: string
outputRoot: string
appVersion: string
}) => {
files: Array<string | { from?: string; to?: string }>
extraResources: Array<{ from: string; to: string }>
dmg: { artifactName: string }
}
}
const {
validateAsarRuntimeDependencies,
validateFfmpegRuntime,
@@ -32,7 +45,11 @@ const {
signMacosAppBundle
} = nodeRequire('../../scripts/after-pack.cjs') as {
validateAsarRuntimeDependencies: (runtimeResources: string) => void
validateFfmpegRuntime: (runtimeResources: string, platform?: NodeJS.Platform) => void
validateFfmpegRuntime: (
runtimeResources: string,
platform?: NodeJS.Platform,
edition?: string
) => string
validateKoffiRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void
validateReaderSkillRuntime: (runtimeResources: string) => string
validateSherpaRuntime: (runtimeResources: string, platform: NodeJS.Platform, arch: string) => void
@@ -246,6 +263,48 @@ describe('production runtime packaging', () => {
expect(config).toContain('node_modules/ffmpeg-static/**')
})
it('requires staged arm64 edition ffmpeg before removing the shared binary', () => {
const resources = join(root, 'edition-ffmpeg-resources')
const shared = join(resources, 'app.asar.unpacked', 'node_modules', 'ffmpeg-static', 'ffmpeg')
mkdirSync(dirname(shared), { recursive: true })
writeFileSync(shared, 'existing shared binary')
expect(() => validateFfmpegRuntime(resources, 'darwin', 'public')).toThrow(/staged macOS ffmpeg/)
expect(readFileSync(shared, 'utf8')).toBe('existing shared binary')
})
it('builds each edition from an isolated native resource allowlist', () => {
const stageRoot = join(root, 'mac-staging', 'public')
const config = createBuilderConfig({
edition: 'public',
stageRoot,
buildOutput: join(stageRoot, 'out'),
outputRoot: join(root, 'dist', 'mac', 'public'),
appVersion: '2.5.2'
})
expect(config.extraResources.map((item) => item.to)).toEqual([
'resources',
'app-update.yml',
'skill/tracememo-reader'
])
expect(config.extraResources[0].from).toBe(join(stageRoot, 'resources'))
expect(config.files).toContainEqual({ from: join(stageRoot, 'out'), to: 'out', filter: ['**/*'] })
expect(config.files).toContain('package.json')
expect(
config.files.some(
(item) => typeof item === 'string' && !item.startsWith('!') && item.includes('resources')
)
).toBe(false)
expect(config.dmg.artifactName).toBe('TraceMemo-2.5.2-mac-arm64-public.dmg')
const nativeConfig = createBuilderConfig({
edition: 'native',
stageRoot: join(root, 'mac-staging', 'native'),
buildOutput: join(root, 'mac-staging', 'native', 'out'),
outputRoot: join(root, 'dist', 'mac', 'native'),
appVersion: '2.5.2'
})
expect(nativeConfig.dmg.artifactName).toBe('TraceMemo-2.5.2-mac-arm64-native.dmg')
})
it('requires the matching Windows and macOS sherpa native runtime', () => {
const resources = join(root, 'sherpa-resources')
const unpacked = join(resources, 'app.asar.unpacked', 'node_modules')