feat: 新增拓展中心功能, 提供 关键词回复 去水印模板

This commit is contained in:
Wxw-Gu committed 2026-11-13 17:54:37 +08:00
1 parent aca103cb96
commit b9ad4e1d71
85 files changed
+14750 -106

No files matched your search

@@ -0,0 +1,272 @@
import fs from 'fs-extra'
import path from 'node:path'
import { describe, expect, it, vi } from 'vitest'
const root = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs')
// eslint-disable-next-line @typescript-eslint/no-require-imports
const os = require('node:os') as typeof import('node:os')
// eslint-disable-next-line @typescript-eslint/no-require-imports
const path = require('node:path') as typeof import('node:path')
return fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-automation-'))
})
vi.mock('electron', () => ({
app: { getPath: () => root },
safeStorage: {
isEncryptionAvailable: () => false,
encryptString: (value: string) => Buffer.from(value, 'utf8'),
decryptString: (value: Buffer) => value.toString('utf8')
},
BrowserWindow: { getAllWindows: () => [] }
}))
import {
createDefaultDailyReportRule,
describeRuleActions,
normalizeRuleDraft,
type AutomationRule
} from '../../src/shared/automation'
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
import { AutomationActionRunner } from '../../src/main/services/automation-action-runner'
import { AutomationRuleStore } from '../../src/main/services/automation-rule-store'
const sent: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
function extensionRule(): AutomationRule {
return {
...createDefaultDailyReportRule(0),
id: 'rule-with-extension',
name: '关键词回复',
conditions: {
requireMentionMe: false,
keyword: '你好',
keywordMatchMode: 'contains',
conversationIds: [],
ignoreSelf: true
},
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
}
]
}
}
function runner(dependencies: {
reply?: { type: 'text'; text: string }
canSend?: boolean
fail?: boolean
}): {
instance: AutomationActionRunner
executeAction: ReturnType<
typeof vi.fn<(request: WechatActionRequest) => Promise<WechatActionResult>>
>
} {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sent
})
const instance = new AutomationActionRunner({
executeAction,
invokeExtensionAction: async () => {
if (dependencies.fail) throw new Error('扩展崩溃')
return {
success: true,
output: { matched: true },
...(dependencies.reply ? { reply: dependencies.reply } : {})
}
},
canExtensionSendText: () => dependencies.canSend !== false,
delay: async () => undefined,
now: () => 1_000
})
return { instance, executeAction }
}
const message = {
eventId: 'message:1',
accountId: 'wxid_self',
conversationId: 'fixture-room@chatroom',
messageId: '9001',
senderId: 'wxid_peer',
senderName: '张三',
isGroup: true,
isSelf: false,
type: 'text' as const,
text: '你好',
mentionsMe: false,
timestamp: 1_700_000_000_000
}
describe('extension automation action', () => {
it('扩展返回 reply 后由宿主经 Gateway 发送', async () => {
const { instance, executeAction } = runner({ reply: { type: 'text', text: '你好呀!' } })
const result = await instance.run({
executionId: 'exec-1',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('success')
expect(result.steps.map((step) => step.key)).toEqual([
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
])
expect(executeAction).toHaveBeenCalledTimes(1)
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_action')
expect(request.triggerType).toBe('automation')
expect(request.idempotencyKey).toBe('extension_action:exec-1')
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture-room@chatroom' })
expect(request.content).toEqual({ type: 'text', text: '你好呀!' })
expect((request.metadata as { extensionId: string }).extensionId).toBe(
'com.example.keyword-bot'
)
})
it('扩展没有发送权限时拒绝发送,且不调用 Gateway', async () => {
const { instance, executeAction } = runner({
reply: { type: 'text', text: '你好呀!' },
canSend: false
})
const result = await instance.run({
executionId: 'exec-2',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('failed')
expect(result.errorSummary).toContain('wechat.send.text')
expect(executeAction).not.toHaveBeenCalled()
const reply = result.steps.find((step) => step.key === 'reply')
expect(reply?.status).toBe('failed')
})
it('扩展动作失败时后续步骤全部跳过', async () => {
const { instance, executeAction } = runner({ fail: true })
const result = await instance.run({
executionId: 'exec-3',
rule: extensionRule(),
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.status).toBe('failed')
expect(result.steps.find((step) => step.key === 'extension_action')?.status).toBe('failed')
expect(result.steps.filter((step) => step.status === 'skipped')).toHaveLength(3)
expect(executeAction).not.toHaveBeenCalled()
})
it('未配置扩展动作时步骤列表保持原样', async () => {
const { instance } = runner({})
const rule: AutomationRule = {
...createDefaultDailyReportRule(0),
actions: [{ type: 'replyText', enabled: true, text: '收到' }]
}
const result = await instance.run({
executionId: 'exec-4',
rule,
conversationId: 'fixture-room@chatroom',
isGroup: true,
sourceDisplayName: '测试群',
message
})
expect(result.steps.map((step) => step.key)).toEqual([
'received',
'matched',
'reply',
'report',
'send'
])
})
})
describe('extension action persistence', () => {
it('规则保存后仍保留扩展动作,缺少扩展/动作 id 的草稿会被丢弃', () => {
const store = new AutomationRuleStore({ userDataPath: () => path.join(root, 'rules') })
const created = store.createRule({
name: '扩展规则',
enabled: true,
ruleType: 'daily_report',
scope: 'group',
conditions: { keyword: '你好', keywordMatchMode: 'contains' },
cooldownSeconds: 30,
replyDelaySeconds: 0,
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
},
{ type: 'extensionAction', enabled: true }
]
})
expect(created.actions).toHaveLength(1)
expect(created.actions[0]).toMatchObject({
type: 'extensionAction',
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply'
})
const reloaded = new AutomationRuleStore({
userDataPath: () => path.join(root, 'rules')
}).getRule(created.id)
expect(reloaded?.actions[0].extensionId).toBe('com.example.keyword-bot')
expect(describeRuleActions(reloaded!)).toBe('执行扩展动作')
})
it('input 只接受 JSON 对象,超限丢弃', () => {
const normalized = normalizeRuleDraft({
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
input: { url: 'https://example.com', nested: { ok: true } }
}
]
})
expect(normalized.actions[0].input).toEqual({
url: 'https://example.com',
nested: { ok: true }
})
const tooBig = normalizeRuleDraft({
actions: [
{
type: 'extensionAction',
enabled: true,
extensionId: 'com.example.keyword-bot',
actionId: 'keyword.reply',
input: { blob: 'x'.repeat(5_000) }
}
]
})
expect(tooBig.actions[0].input).toBeUndefined()
})
})
process.on('exit', () => {
fs.removeSync(root)
})
@@ -0,0 +1,328 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
import type {
ExtensionHostChild,
ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionResult } from '../../src/shared/wechat-action'
const MANIFEST = {
manifestVersion: 1,
id: 'com.example.fixture-bot',
name: 'Fixture Bot',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['messages.subscribe', 'wechat.send.text', 'storage', 'automation.action', 'contacts.list'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
subscriptions: {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false
},
contributions: {
pages: [{ id: 'settings', title: '配置' }],
automationActions: [{ id: 'keyword.reply', title: '关键词回复' }]
}
}
const capability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: false },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const sentResult: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
private readonly listeners = new Map<string, Listener[]>()
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() => {
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: true
})
this.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
})
}
if (payload.type === 'invoke-action') {
queueMicrotask(() =>
this.emit('message', {
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
output: { success: true, reply: { type: 'text', text: '你好呀!' } }
})
)
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
}
kill(): void {
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
events(): Array<Record<string, unknown>> {
return this.sent.filter((message) => message.type === 'event')
}
}
const roots: string[] = []
let userData: string
function createSourceExtension(): string {
const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-src-'))
roots.push(parent)
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), MANIFEST)
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>fixture</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports = () => {}')
return source
}
function createManager(): {
manager: ExtensionManager
paths: ReturnType<typeof createExtensionPaths>
children: FakeChild[]
executeAction: ReturnType<typeof vi.fn>
} {
const paths = createExtensionPaths(userData)
const children: FakeChild[] = []
const executeAction = vi.fn(async () => sentResult)
const manager = new ExtensionManager({
paths,
appVersion: '2.6.0',
spawn: (options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
},
getCapability: async () => capability,
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
executeAction,
queryMessages: async () => [],
listGroups: async () => [{ id: 'fixture-room@chatroom', name: '测试群' }],
aiChat: async () => ({ text: '' }),
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self'],
isDatabaseReady: () => true,
now: () => 1_000
})
return { manager, paths, children, executeAction }
}
async function tick(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
userData = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-manager-'))
roots.push(userData)
})
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension lifecycle', () => {
it('安装 → 页面读写配置 → 启用 → 事件 → 动作 → 发送 → 停用 → 卸载', async () => {
const { manager, paths, children, executeAction } = createManager()
await manager.initialize()
const source = createSourceExtension()
const installed = await manager.installFromDirectory(source)
expect(installed.success).toBe(true)
expect(installed.extension?.enabled).toBe(false)
// 安装只自动授予低风险权限。
expect(installed.extension?.grantedPermissions).toEqual(['storage'])
const page = manager.pageUrl('com.example.fixture-bot')
expect(page.url).toBe('tm-extension://com.example.fixture-bot/ui/index.html')
const saved = await manager.pageRequest('com.example.fixture-bot', 'storage.set', {
key: 'greeting',
value: '你好'
})
expect(saved.ok).toBe(true)
expect(
(await manager.pageRequest('com.example.fixture-bot', 'storage.get', { key: 'greeting' }))
.result
).toBe('你好')
// 页面不能发送微信消息。
expect((await manager.pageRequest('com.example.fixture-bot', 'wechat.send.text', {})).ok).toBe(
false
)
// 页面可以读取群列表(manifest 已声明 contacts.list)。
const groups = await manager.pageRequest('com.example.fixture-bot', 'contacts.listGroups', {})
expect(groups.ok).toBe(true)
expect(groups.result).toEqual({
groups: [{ id: 'fixture-room@chatroom', name: '测试群' }]
})
const enabled = await manager.setEnabled('com.example.fixture-bot', true)
expect(enabled.success).toBe(true)
await tick()
const child = children[0]
expect(manager.get('com.example.fixture-bot')?.runtime.state).toBe('active')
expect(manager.get('com.example.fixture-bot')?.automationActions[0]).toMatchObject({
id: 'keyword.reply',
registered: true
})
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1001',
serverId: '9001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
senderId: 'wxid_peer',
senderNickname: '张三',
content: '@我 你好',
isGroup: true,
mentionTargets: ['wxid_self']
})
const event = child.events()[0]
expect(event).toBeTruthy()
const envelope = event.envelope as { event: { mentionsMe: boolean; text: string } }
expect(envelope.event.mentionsMe).toBe(true)
expect(envelope.event.text).toBe('@我 你好')
// 同一条消息重复投递不会再分发。
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
content: '@我 你好',
isGroup: true,
mentionTargets: ['wxid_self']
})
expect(child.events()).toHaveLength(1)
const output = await manager.invokeAutomationAction(
'com.example.fixture-bot',
'keyword.reply',
{ text: '你好' }
)
expect(output.reply).toEqual({ type: 'text', text: '你好呀!' })
// 后台主动发送:宿主填 origin/purpose,扩展只描述收件人与内容。
child.emit('message', {
type: 'call',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: 'call-1',
method: 'wechat.send.text',
params: { to: 'fixture-room@chatroom', text: '你好呀!' }
})
await tick()
const callResult = child.sent.find(
(message) => message.type === 'call-result' && message.callId === 'call-1'
)
expect(callResult?.ok).toBe(true)
expect(executeAction).toHaveBeenCalledTimes(1)
expect(executeAction.mock.calls[0][0]).toMatchObject({
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: 'group', id: 'fixture-room@chatroom' },
content: { type: 'text', text: '你好呀!' }
})
const disabled = await manager.setEnabled('com.example.fixture-bot', false)
expect(disabled.success).toBe(true)
expect(manager.get('com.example.fixture-bot')?.grantedPermissions).toEqual(['storage'])
manager.handleMessage({
sessionId: 'fixture-room@chatroom',
localId: '1002',
createTime: 1_700_000_100,
messageType: 1,
isSelf: false,
content: '还在吗',
isGroup: true,
mentionTargets: []
})
expect(child.events()).toHaveLength(1)
const removed = await manager.uninstall('com.example.fixture-bot', true)
expect(removed.success).toBe(true)
expect(fs.existsSync(paths.installDir('com.example.fixture-bot'))).toBe(false)
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture-bot'))).toBe(true)
expect(manager.list()).toEqual([])
})
it('不兼容的扩展安装被拒绝', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSourceExtension()
fs.writeJsonSync(path.join(source, 'manifest.json'), { ...MANIFEST, minAppVersion: '9.9.0' })
const result = await manager.installFromDirectory(source)
expect(result.success).toBe(false)
expect(result.error?.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('停用状态下页面仍可打开与保存配置', async () => {
const { manager } = createManager()
await manager.initialize()
const source = createSourceExtension()
await manager.installFromDirectory(source)
const page = manager.pageUrl('com.example.fixture-bot', 'settings')
expect(page.pageId).toBe('settings')
const result = await manager.pageRequest('com.example.fixture-bot', 'storage.set', {
key: 'draft',
value: 1
})
expect(result.ok).toBe(true)
})
})
+177
View File
@@ -0,0 +1,177 @@
import { describe, expect, it } from 'vitest'
import { ExtensionEventBus } from '../../src/main/extensions/extension-event-bus'
import type { ExtensionEventEnvelope } from '../../src/shared/extensions/events'
import type { ExtensionSubscriptions } from '../../src/shared/extensions/manifest'
import type { NormalizedIncomingMessage } from '../../src/main/services/message-listener-service'
function message(overrides: Partial<NormalizedIncomingMessage> = {}): NormalizedIncomingMessage {
return {
sessionId: 'fixture-room@chatroom',
localId: '1001',
serverId: '9001',
createTime: 1_700_000_000,
messageType: 1,
isSelf: false,
senderId: 'wxid_peer',
senderNickname: '张三',
content: '你好',
isGroup: true,
mentionTargets: [],
...overrides
}
}
function subscriptions(overrides: Partial<ExtensionSubscriptions> = {}): ExtensionSubscriptions {
return {
messageTypes: ['text'],
conversationIds: [],
requireMentionMe: false,
includeSelf: false,
...overrides
}
}
describe('extension event bus', () => {
it('为同一条消息生成稳定 eventId,并做跨扩展去重', () => {
const first: ExtensionEventEnvelope[] = []
const second: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (first.push(e), true)
},
{
extensionId: 'com.example.b',
subscriptions: subscriptions(),
deliver: (e) => (second.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message())
bus.handleMessage(message())
expect(first).toHaveLength(1)
expect(second).toHaveLength(1)
expect(first[0].event.eventId).toMatch(/^message:[0-9a-f]{40}$/)
expect(bus.stats().deduped).toBe(1)
})
it('按消息类型与会话范围过滤', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions({
messageTypes: ['text'],
conversationIds: ['other@chatroom']
}),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message())
bus.handleMessage(message({ localId: '1002', messageType: 3 }))
expect(delivered).toHaveLength(0)
})
it('mentionsMe 只认真实 atuserlist 与自身 username 的交集', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message({ content: '@someone 你好', mentionTargets: ['wxid_other'] }))
bus.handleMessage(
message({ localId: '1002', content: '@张三 你好', mentionTargets: ['wxid_self'] })
)
expect(delivered[0].event.mentionsMe).toBe(false)
expect(delivered[1].event.mentionsMe).toBe(true)
})
it('拿不到自身身份时绝不猜测 @我', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => '',
getSelfUsernames: () => []
})
bus.handleMessage(message({ mentionTargets: ['wxid_fixture'] }))
expect(delivered[0].event.mentionsMe).toBe(false)
})
it('默认不投递自己发送的消息', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message({ isSelf: true }))
expect(delivered).toHaveLength(0)
})
it('账号切换后旧账号相同 localId 的消息会重新投递', () => {
const delivered: ExtensionEventEnvelope[] = []
const accountId = 'wxid_a'
const bus = new ExtensionEventBus({
listSubscribers: () => [
{
extensionId: 'com.example.a',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => accountId,
getSelfUsernames: () => ['wxid_self']
})
bus.handleMessage(message())
bus.setAccountId('wxid_b')
bus.handleMessage(message())
expect(delivered).toHaveLength(2)
expect(delivered[1].event.accountId).toBe('wxid_b')
})
it('扩展投递失败计入 dropped,不影响其它订阅者', () => {
const delivered: ExtensionEventEnvelope[] = []
const bus = new ExtensionEventBus({
listSubscribers: () => [
{ extensionId: 'com.example.a', subscriptions: subscriptions(), deliver: () => false },
{
extensionId: 'com.example.b',
subscriptions: subscriptions(),
deliver: (e) => (delivered.push(e), true)
}
],
getAccountId: () => 'wxid_self',
getSelfUsernames: () => []
})
bus.handleMessage(message())
expect(delivered).toHaveLength(1)
expect(bus.stats().dropped).toBe(1)
})
})
+46
View File
@@ -0,0 +1,46 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { parseExtensionManifest } from '../../src/shared/extensions/manifest'
const EXAMPLES_ROOT = path.resolve(process.cwd(), 'examples/extensions')
function exampleDirectories(): string[] {
return fs
.readdirSync(EXAMPLES_ROOT, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort()
}
/**
* 示例扩展是文档的一部分:manifest 失配或入口文件缺失时必须在这里失败,
* 而不是等用户点「安装目录」才看到错误。
*/
describe('example extensions', () => {
it('每个示例都有合法 manifest 与真实入口文件', () => {
const directories = exampleDirectories()
expect(directories.length).toBeGreaterThanOrEqual(2)
for (const directory of directories) {
const root = path.join(EXAMPLES_ROOT, directory)
const manifestPath = path.join(root, 'manifest.json')
expect(fs.existsSync(manifestPath), `${directory} 缺少 manifest.json`).toBe(true)
const parsed = parseExtensionManifest(
JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown,
{ appVersion: '2.6.0' }
)
expect(parsed.ok, `${directory}: ${parsed.message || ''}`).toBe(true)
const manifest = parsed.manifest
if (!manifest) throw new Error(`${directory} manifest 未解析`)
for (const [key, entry] of Object.entries(manifest.entrypoints)) {
if (!entry) continue
expect(fs.existsSync(path.join(root, entry)), `${directory} 缺少 ${key}: ${entry}`).toBe(true)
}
for (const page of manifest.contributions.pages) {
const entry = page.entry || manifest.entrypoints.page
expect(Boolean(entry), `${directory} 页面 ${page.id} 缺少入口`).toBe(true)
if (entry) expect(fs.existsSync(path.join(root, entry))).toBe(true)
}
}
})
})
+230
View File
@@ -0,0 +1,230 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import {
ExtensionHost,
type ExtensionHostChild,
type ExtensionHostSpawnOptions
} from '../../src/main/extensions/extension-host'
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
type Listener = (...args: unknown[]) => void
class FakeChild implements ExtensionHostChild {
readonly sent: Array<Record<string, unknown>> = []
readonly listeners = new Map<string, Listener[]>()
killed = false
autoActivate = true
activationOk = true
actionOutput: unknown = { success: true, output: { matched: true } }
send(message: unknown): void {
const payload = message as Record<string, unknown>
this.sent.push(payload)
if (payload.type === 'activate') {
queueMicrotask(() => {
this.emit('message', {
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: this.activationOk,
...(this.activationOk ? {} : { error: { code: 'ACTION_FAILED', message: 'boom' } })
})
})
}
if (payload.type === 'shutdown') {
queueMicrotask(() => this.emit('exit', 0, null))
}
if (payload.type === 'invoke-action') {
queueMicrotask(() => {
this.emit('message', {
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: payload.requestId,
ok: true,
output: this.actionOutput
})
})
}
}
kill(): void {
this.killed = true
this.emit('exit', 1, null)
}
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
on(event: string, listener: (...args: never[]) => void): void {
const list = this.listeners.get(event) ?? []
list.push(listener as unknown as Listener)
this.listeners.set(event, list)
}
once(event: string, listener: Listener): void {
this.on(event as 'message', listener as (message: unknown) => void)
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) listener(...args)
}
}
const roots: string[] = []
function storage(): ExtensionStorage {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-host-'))
roots.push(root)
return new ExtensionStorage({ dataRoot: root })
}
function createHost(overrides: Partial<ConstructorParameters<typeof ExtensionHost>[0]> = {}): {
host: ExtensionHost
child: FakeChild
spawn: ReturnType<typeof vi.fn>
} {
const child = new FakeChild()
const spawn = vi.fn((options: ExtensionHostSpawnOptions) => {
void options
return child
})
const host = new ExtensionHost({
extensionId: 'com.example.keyword-bot',
extensionDir: '/tmp/fixture-extension',
dataDir: '/tmp/fixture-extension-data',
permissions: ['storage', 'wechat.send.text'],
storage: storage(),
spawn,
...overrides
})
return { host, child, spawn }
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
vi.useRealTimers()
})
describe('extension host', () => {
it('激活握手后进入 active,并把权限传给子进程', async () => {
const { host, child } = createHost()
await host.start()
expect(host.snapshot().state).toBe('active')
const activate = child.sent.find((message) => message.type === 'activate')
expect(activate?.extensionId).toBe('com.example.keyword-bot')
expect(activate?.permissions).toEqual(['wechat.send.text', 'storage'])
})
it('后台注册的动作会被记录,未注册的动作拒绝调用', async () => {
const { host, child } = createHost()
await host.start()
await expect(host.invokeAction('keyword.reply', {})).rejects.toMatchObject({
code: 'ACTION_FAILED'
})
child.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
expect(host.registeredActions()).toEqual([{ id: 'keyword.reply', title: '关键词回复' }])
})
it('动作调用走 invoke-action 并回传输出', async () => {
const { host, child } = createHost()
await host.start()
child.emit('message', {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: true }
})
const result = await host.invokeAction('keyword.reply', { text: '你好' })
expect(result).toMatchObject({ success: true, output: { matched: true } })
expect(child.sent.some((message) => message.type === 'invoke-action')).toBe(true)
})
it('激活失败时 start 拒绝,状态为 error', async () => {
const { host, child } = createHost()
child.activationOk = false
await expect(host.start()).rejects.toMatchObject({ code: 'ACTION_FAILED' })
expect(host.snapshot().state).toBe('error')
})
it('未激活时不投递事件,激活后按 envelope 投递', async () => {
const { host } = createHost()
expect(host.deliverEvent({ version: 1, kind: 'message.received', event: {} as never })).toBe(
false
)
await host.start()
expect(
host.deliverEvent({
version: 1,
kind: 'message.received',
event: {
eventId: 'message:1',
accountId: 'wxid_self',
conversationId: 'fixture@chatroom',
messageId: '1',
isGroup: true,
isSelf: false,
type: 'text',
mentionsMe: false,
timestamp: 1
}
})
).toBe(true)
})
it('停止时发送 shutdown 并回到 inactive', async () => {
const { host, child } = createHost()
await host.start()
await host.stop()
expect(child.sent.some((message) => message.type === 'shutdown')).toBe(true)
expect(host.snapshot().state).toBe('inactive')
})
it('异常退出后按退避重启,超过次数标记 crashed', async () => {
vi.useFakeTimers()
const children: FakeChild[] = []
const spawn = vi.fn((options: ExtensionHostSpawnOptions) => {
void options
const child = new FakeChild()
children.push(child)
return child
})
const host = new ExtensionHost({
extensionId: 'com.example.keyword-bot',
extensionDir: '/tmp/fixture-extension',
dataDir: '/tmp/fixture-extension-data',
permissions: [],
storage: storage(),
spawn,
now: () => Date.now()
})
await host.start()
for (let attempt = 0; attempt < 3; attempt += 1) {
children[children.length - 1].emit('exit', 1, null)
await vi.advanceTimersByTimeAsync(10_000)
}
children[children.length - 1].emit('exit', 1, null)
await vi.advanceTimersByTimeAsync(10_000)
expect(host.snapshot().state).toBe('crashed')
})
it('子进程请求的能力在未授权时被拒绝', async () => {
const { host, child } = createHost({ permissions: [] })
await host.start()
child.emit('message', {
type: 'call',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: 'call-1',
method: 'storage.get',
params: { key: 'x' }
})
await new Promise((resolve) => setTimeout(resolve, 0))
const result = child.sent.find((message) => message.type === 'call-result')
expect(result?.ok).toBe(false)
expect((result?.error as { code: string }).code).toBe('PERMISSION_DENIED')
})
})
+242
View File
@@ -0,0 +1,242 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
import { ExtensionInstaller } from '../../src/main/extensions/extension-installer'
const MANIFEST = (overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
manifestVersion: 1,
id: 'com.example.fixture',
name: 'Fixture',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
contributions: { pages: [{ id: 'settings', title: '设置' }] },
...overrides
})
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-installer-'))
roots.push(root)
return root
}
function createExtensionSource(root: string, overrides: Record<string, unknown> = {}): string {
const parent = fs.mkdtempSync(path.join(root, 'source-'))
const source = path.join(parent, 'extension')
fs.ensureDirSync(path.join(source, 'ui'))
fs.ensureDirSync(path.join(source, 'background'))
fs.writeJsonSync(path.join(source, 'manifest.json'), MANIFEST(overrides))
fs.writeFileSync(path.join(source, 'ui', 'index.html'), '<!doctype html><title>fixture</title>')
fs.writeFileSync(path.join(source, 'background', 'index.js'), 'module.exports = function(){}')
return source
}
function setup(): {
paths: ReturnType<typeof createExtensionPaths>
registry: ExtensionRegistry
installer: ExtensionInstaller
} {
const root = tempRoot()
const paths = createExtensionPaths(root)
const registry = new ExtensionRegistry({ registryFile: paths.registryFile })
const installer = new ExtensionInstaller({ paths, registry })
return { paths, registry, installer }
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension installer', () => {
it('安装目录后登记为未启用,代码位于 extensions/<id>', async () => {
const { paths, registry, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
const outcome = await installer.installFromDirectory(source, { appVersion: '2.6.0' })
expect(outcome.upgraded).toBe(false)
expect(fs.existsSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json'))).toBe(
true
)
const record = registry.get('com.example.fixture')
expect(record?.enabled).toBe(false)
expect(record?.grantedPermissions).toEqual([])
})
it('升级保留启用状态与授权,不改动数据目录', async () => {
const { paths, registry, installer } = setup()
const root = path.dirname(paths.userData)
const first = createExtensionSource(root)
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
registry.setEnabled('com.example.fixture', true)
registry.setGrantedPermissions('com.example.fixture', ['storage', 'messages.subscribe'])
fs.ensureDirSync(paths.extensionDataDir('com.example.fixture'))
fs.writeJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'), {
version: 1,
values: { greeting: '保留我' }
})
const second = path.join(root, 'source-v2')
fs.copySync(first, second)
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
expect(outcome.upgraded).toBe(true)
expect(outcome.previousVersion).toBe('1.0.0')
const record = registry.get('com.example.fixture')
expect(record?.version).toBe('1.2.0')
expect(record?.enabled).toBe(true)
expect(record?.grantedPermissions).toEqual(['storage', 'messages.subscribe'])
expect(
fs.readJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'))
.values.greeting
).toBe('保留我')
})
it('卸载默认保留数据,选择清除时一并删除', async () => {
const { paths, registry, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
await installer.installFromDirectory(source, { appVersion: '2.6.0' })
fs.ensureDirSync(paths.extensionDataDir('com.example.fixture'))
fs.writeFileSync(path.join(paths.extensionDataDir('com.example.fixture'), 'keep.txt'), 'x')
await installer.uninstall('com.example.fixture', { keepData: true })
expect(fs.existsSync(paths.installDir('com.example.fixture'))).toBe(false)
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture'))).toBe(true)
expect(registry.get('com.example.fixture')).toBeUndefined()
await installer.uninstall('com.example.fixture', { keepData: false })
expect(fs.existsSync(paths.extensionDataDir('com.example.fixture'))).toBe(false)
})
it('拒绝符号链接,且不留下半装目录', async () => {
const { paths, installer } = setup()
const source = createExtensionSource(path.dirname(paths.userData))
fs.symlinkSync('/etc/hosts', path.join(source, 'ui', 'link.html'))
await expect(
installer.installFromDirectory(source, { appVersion: '2.6.0' })
).rejects.toMatchObject({
code: 'EXTENSION_INVALID_PATH'
})
expect(fs.existsSync(paths.installDir('com.example.fixture'))).toBe(false)
expect(fs.existsSync(paths.stagingDir) ? fs.readdirSync(paths.stagingDir) : []).toEqual([])
})
it('入口文件缺失时拒绝安装', async () => {
const { installer } = setup()
const root = tempRoot()
const source = createExtensionSource(root)
fs.removeSync(path.join(source, 'background', 'index.js'))
await expect(
installer.installFromDirectory(source, { appVersion: '2.6.0' })
).rejects.toMatchObject({
code: 'EXTENSION_INVALID_MANIFEST'
})
})
it('ZIP 条目穿越时拒绝,且不会写到扩展目录之外', async () => {
const { paths, installer } = setup()
const zipPath = path.join(tempRoot(), 'evil.zip')
fs.writeFileSync(
zipPath,
buildZip([
{ name: 'manifest.json', data: JSON.stringify(MANIFEST()) },
{ name: 'ui/index.html', data: '<!doctype html>' },
{ name: 'background/index.js', data: 'module.exports=()=>{}' },
{ name: '../escaped.txt', data: 'escaped' }
])
)
await expect(
installer.installFromPackage(zipPath, { appVersion: '2.6.0' })
).rejects.toMatchObject({
code: 'EXTENSION_INVALID_PATH'
})
expect(fs.existsSync(path.join(paths.userData, 'escaped.txt'))).toBe(false)
expect(fs.existsSync(paths.installDir('com.example.fixture'))).toBe(false)
})
it('合法 ZIP 可安装', async () => {
const { paths, installer } = setup()
const zipPath = path.join(tempRoot(), 'fixture.zip')
fs.writeFileSync(
zipPath,
buildZip([
{ name: 'manifest.json', data: JSON.stringify(MANIFEST()) },
{ name: 'ui/index.html', data: '<!doctype html>' },
{ name: 'background/index.js', data: 'module.exports=()=>{}' }
])
)
const outcome = await installer.installFromPackage(zipPath, { appVersion: '2.6.0' })
expect(outcome.manifest.id).toBe('com.example.fixture')
expect(
fs.existsSync(path.join(paths.installDir('com.example.fixture'), 'ui', 'index.html'))
).toBe(true)
})
})
/* 最小 ZIP 写入器:只支持 stored(无压缩)条目,用于构造非法路径样本。 */
const CRC_TABLE = (() => {
const table = new Uint32Array(256)
for (let index = 0; index < 256; index += 1) {
let value = index
for (let bit = 0; bit < 8; bit += 1) {
value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1
}
table[index] = value >>> 0
}
return table
})()
function crc32(buffer: Buffer): number {
let crc = 0xffffffff
for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)
return (crc ^ 0xffffffff) >>> 0
}
function buildZip(entries: Array<{ name: string; data: string }>): Buffer {
const locals: Buffer[] = []
const centrals: Buffer[] = []
let offset = 0
for (const entry of entries) {
const name = Buffer.from(entry.name, 'utf8')
const data = Buffer.from(entry.data, 'utf8')
const crc = crc32(data)
const local = Buffer.alloc(30)
local.writeUInt32LE(0x04034b50, 0)
local.writeUInt16LE(20, 4)
local.writeUInt16LE(0, 6)
local.writeUInt16LE(0, 8)
local.writeUInt32LE(crc, 14)
local.writeUInt32LE(data.length, 18)
local.writeUInt32LE(data.length, 22)
local.writeUInt16LE(name.length, 26)
local.writeUInt16LE(0, 28)
locals.push(local, name, data)
const central = Buffer.alloc(46)
central.writeUInt32LE(0x02014b50, 0)
central.writeUInt16LE(20, 4)
central.writeUInt16LE(20, 6)
central.writeUInt32LE(crc, 16)
central.writeUInt32LE(data.length, 20)
central.writeUInt32LE(data.length, 24)
central.writeUInt16LE(name.length, 28)
central.writeUInt32LE(offset, 42)
centrals.push(central, name)
offset += local.length + name.length + data.length
}
const centralBuffer = Buffer.concat(centrals)
const end = Buffer.alloc(22)
end.writeUInt32LE(0x06054b50, 0)
end.writeUInt16LE(entries.length, 8)
end.writeUInt16LE(entries.length, 10)
end.writeUInt32LE(centralBuffer.length, 12)
end.writeUInt32LE(offset, 16)
return Buffer.concat([...locals, centralBuffer, end])
}
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest'
import {
checkExtensionCompatibility,
compareSemver,
isSafeRelativeEntryPath,
isValidExtensionId,
parseExtensionManifest,
parseExtensionManifestJson
} from '../../src/shared/extensions/manifest'
const base = {
manifestVersion: 1,
id: 'com.example.fixture-bot',
name: 'Fixture Bot',
version: '1.0.0',
apiVersion: '1',
minAppVersion: '2.6.0',
permissions: ['storage'],
entrypoints: { page: 'ui/index.html', background: 'background/index.js' },
contributions: { pages: [{ id: 'settings', title: '设置' }] }
}
describe('extension manifest', () => {
it('接受合法的反向域名 id 并补齐默认值', () => {
const result = parseExtensionManifest(base)
expect(result.ok).toBe(true)
expect(result.manifest?.id).toBe('com.example.fixture-bot')
expect(result.manifest?.permissions).toEqual(['storage'])
expect(result.manifest?.contributions.automationActions).toEqual([])
})
it('拒绝保留前缀与大写 id', () => {
expect(isValidExtensionId('com.tracememo.reader')).toBe(false)
expect(isValidExtensionId('com.Example.Hello')).toBe(false)
expect(isValidExtensionId('hello')).toBe(false)
expect(isValidExtensionId('com.example.ok')).toBe(true)
})
it('拒绝未知权限,而不是静默丢弃', () => {
const result = parseExtensionManifest({ ...base, permissions: ['storage', 'fs.read'] })
expect(result.ok).toBe(false)
expect(result.message).toContain('未知权限')
})
it('拒绝与宿主不兼容的 apiVersion', () => {
const result = parseExtensionManifest({ ...base, apiVersion: '2' })
expect(result.ok).toBe(false)
expect(result.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('minAppVersion 高于当前版本时拒绝安装', () => {
const result = parseExtensionManifest(
{ ...base, minAppVersion: '2.7.0' },
{ appVersion: '2.6.0' }
)
expect(result.ok).toBe(false)
expect(result.code).toBe('EXTENSION_INCOMPATIBLE')
})
it('声明消息订阅但没有 background 时拒绝', () => {
const result = parseExtensionManifest({
...base,
entrypoints: { page: 'ui/index.html' },
permissions: ['messages.subscribe'],
subscriptions: { messageTypes: ['text'], conversationIds: [] }
})
expect(result.ok).toBe(false)
expect(result.message).toContain('entrypoints.background')
})
it('拒绝目录穿越的入口路径', () => {
const result = parseExtensionManifest({
...base,
entrypoints: { page: '../../etc/passwd' }
})
expect(result.ok).toBe(false)
expect(result.message).toContain('entrypoints.page')
})
it('入口路径检查覆盖穿越、盘符、保留名与反斜杠', () => {
expect(isSafeRelativeEntryPath('ui/index.html')).toBe(true)
expect(isSafeRelativeEntryPath('../evil.html')).toBe(false)
expect(isSafeRelativeEntryPath('/etc/passwd')).toBe(false)
expect(isSafeRelativeEntryPath('C:/Windows/system32')).toBe(false)
expect(isSafeRelativeEntryPath('ui\\index.html')).toBe(true)
expect(isSafeRelativeEntryPath('ui/con.txt')).toBe(false)
expect(isSafeRelativeEntryPath('ui//index.html')).toBe(false)
})
it('页面 id 与动作 id 不合法时拒绝', () => {
expect(
parseExtensionManifest({
...base,
contributions: { pages: [{ id: 'Bad Page', title: 'x' }] }
}).ok
).toBe(false)
expect(
parseExtensionManifest({
...base,
contributions: { automationActions: [{ id: 'UPPER', title: 'x' }] }
}).ok
).toBe(false)
})
it('JSON 语法错误与 schema 错误分开报', () => {
expect(parseExtensionManifestJson('{').message).toContain('JSON')
expect(parseExtensionManifestJson('[]').message).toContain('manifest')
})
it('semver 比较忽略 prerelease 且不误伤预发布构建', () => {
expect(compareSemver('2.6.0', '2.5.9')).toBe(1)
expect(compareSemver('2.6.0-beta.1', '2.6.0')).toBe(0)
expect(compareSemver('bad', '2.6.0')).toBeNull()
expect(
checkExtensionCompatibility({ apiVersion: '1', minAppVersion: '2.6.0' }, '2.6.0-rc.1')
).toEqual({
compatible: true
})
})
})
+338
View File
@@ -0,0 +1,338 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ExtensionSendGateway } from '../../src/main/extensions/extension-send-gateway'
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
const readyCapability = {
supported: true,
ready: true,
status: 'ready',
capabilities: { text: true, image: true, voice: false, video: true },
senderStatus: {},
message: '已就绪'
} as unknown as PersonalWechatSendCapability
const sentResult: WechatActionResult = {
actionId: 'action-1',
status: 'sent',
decision: 'allow',
startedAt: '2026-01-01T00:00:00.000Z',
finishedAt: '2026-01-01T00:00:01.000Z'
}
function gateway(
overrides: {
capability?: PersonalWechatSendCapability
entitlement?: {
ok: boolean
message: string
source: 'mac_license' | 'hook_license' | 'unsupported'
}
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
dataRoot?: string
now?: () => number
} = {}
): {
instance: ExtensionSendGateway
executeAction: ReturnType<
typeof vi.fn<(request: WechatActionRequest) => Promise<WechatActionResult>>
>
} {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
if (overrides.executeAction) return overrides.executeAction(request)
return sentResult
})
const instance = new ExtensionSendGateway({
getCapability: async () => overrides.capability ?? readyCapability,
checkEntitlement: async () =>
overrides.entitlement ?? { ok: true, message: '授权有效', source: 'mac_license' },
executeAction: executeAction as never,
...(overrides.dataRoot ? { getExtensionDataRoot: () => overrides.dataRoot as string } : {}),
now: overrides.now ?? (() => 1_000_000)
})
return { instance, executeAction }
}
const context = {
extensionId: 'com.example.keyword-bot',
permissions: ['wechat.send.text' as const],
conversationScope: [] as string[]
}
describe('extension send gateway', () => {
it('缺少权限时拒绝,且不触碰 Gateway', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({ executeAction })
await expect(
instance.sendText({ ...context, permissions: [] }, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
expect(executeAction).not.toHaveBeenCalled()
})
it('目标超出扩展声明的会话范围时拒绝', async () => {
const { instance } = gateway()
await expect(
instance.sendText(
{ ...context, conversationScope: ['allowed@chatroom'] },
{ to: 'other@chatroom', text: 'hi' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('发送能力未就绪时返回 CAPABILITY_UNAVAILABLE', async () => {
const { instance } = gateway({
capability: { ...readyCapability, ready: false, message: '请先绑定个人微信' }
})
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
it('没有有效授权时返回 LICENSE_REQUIRED', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({
entitlement: { ok: false, message: '需要有效授权', source: 'mac_license' },
executeAction
})
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'LICENSE_REQUIRED' })
expect(executeAction).not.toHaveBeenCalled()
})
it('成功时由宿主填写 origin / purpose / 幂等键', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({ executeAction })
const result = await instance.sendText(context, {
to: 'fixture@chatroom',
text: '你好',
dedupeKey: 'event-1'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
const request = executeAction.mock.calls[0][0] as unknown as Record<string, unknown>
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_send')
expect(request.triggerType).toBe('automation')
expect((request.metadata as { extensionId: string }).extensionId).toBe(context.extensionId)
expect(String(request.idempotencyKey)).toMatch(/^extension:com\.example\.keyword-bot:/)
expect((request.recipient as { type: string }).type).toBe('group')
})
it('两条之间至少 2 秒,超限返回 RATE_LIMITED', async () => {
let now = 1_000_000
const { instance } = gateway({ now: () => now })
await instance.sendText(context, { to: 'fixture@chatroom', text: 'one' })
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'two' })
).rejects.toMatchObject({ code: 'RATE_LIMITED' })
now += 2_001
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'three' })
).resolves.toEqual({
actionId: 'action-1',
status: 'sent'
})
})
it('网关失败时把底层错误码映射成扩展错误码', async () => {
const { instance } = gateway({
executeAction: async () => ({
actionId: 'action-2',
status: 'failed',
decision: 'allow',
errorCode: 'SEND_NOT_READY',
reason: '未绑定',
startedAt: '',
finishedAt: ''
})
})
await expect(
instance.sendText(context, { to: 'fixture@chatroom', text: 'hi' })
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
it('非群聊忽略 at 参数,文本长度超限直接拒绝', async () => {
const executeAction = vi.fn(async (request: WechatActionRequest) => {
void request
return sentResult
})
const { instance } = gateway({ executeAction })
await instance.sendText(context, {
to: 'wxid_peer',
text: 'hi',
at: { wxid_peer: '张三' }
})
expect(executeAction).toHaveBeenCalledTimes(1)
const request = executeAction.mock.calls[0][0] as { content: { at?: unknown } }
expect(request.content.at).toBeUndefined()
await expect(
instance.sendText(context, { to: 'wxid_peer', text: 'x'.repeat(2_001) })
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
})
})
describe('extension send gateway / image', () => {
const cleanup: string[] = []
function tempDir(prefix: string): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
cleanup.push(root)
return root
}
afterEach(() => {
for (const root of cleanup.splice(0)) fs.rmSync(root, { recursive: true, force: true })
})
const imageContext = {
extensionId: 'com.example.douyin',
permissions: ['wechat.send.image' as const],
conversationScope: [] as string[]
}
it('缺少 wechat.send.image 权限时拒绝', async () => {
const { instance } = gateway({ dataRoot: tempDir('tm-ext-data-') })
await expect(
instance.sendImage(
{ ...imageContext, permissions: [] },
{ to: 'fixture@chatroom', path: '/tmp/a.mp4' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('只能发送扩展数据目录或临时目录内的文件', async () => {
const dataRoot = tempDir('tm-ext-data-')
// 刻意放在仓库工作目录下:它既不在扩展数据目录,也不在系统临时目录。
const outside = fs.mkdtempSync(path.join(process.cwd(), '.tm-ext-outside-'))
cleanup.push(outside)
const file = path.join(outside, 'cover.png')
fs.writeFileSync(file, Buffer.from('fixture'))
const { instance, executeAction } = gateway({ dataRoot })
await expect(
instance.sendImage(imageContext, { to: 'fixture@chatroom', path: file })
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
expect(executeAction).not.toHaveBeenCalled()
})
it('图片按 image 类型提交,路径取 realpath', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'cover.png')
fs.writeFileSync(file, Buffer.from('fixture-image'))
const { instance, executeAction } = gateway({ dataRoot })
const result = await instance.sendImage(imageContext, {
to: 'fixture@chatroom',
path: file,
dedupeKey: 'message:fixture'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_send')
expect(request.content).toEqual({ type: 'image', path: fs.realpathSync(file) })
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture@chatroom' })
expect(String(request.idempotencyKey)).toMatch(/^extension:com\.example\.douyin:/)
})
it('拒绝非图片/视频扩展名与不存在的路径', async () => {
const dataRoot = tempDir('tm-ext-data-')
const textFile = path.join(dataRoot, 'note.txt')
fs.writeFileSync(textFile, Buffer.from('fixture'))
const { instance } = gateway({ dataRoot })
await expect(
instance.sendImage(imageContext, { to: 'fixture@chatroom', path: textFile })
).rejects.toMatchObject({ code: 'SEND_NOT_SUPPORTED' })
await expect(
instance.sendImage(imageContext, {
to: 'fixture@chatroom',
path: path.join(dataRoot, 'missing.mp4')
})
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
})
})
describe('extension send gateway / video', () => {
const cleanup: string[] = []
function tempDir(prefix: string): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
cleanup.push(root)
return root
}
afterEach(() => {
for (const root of cleanup.splice(0)) fs.rmSync(root, { recursive: true, force: true })
})
const videoContext = {
extensionId: 'com.example.douyin',
permissions: ['wechat.send.video' as const],
conversationScope: [] as string[]
}
it('缺 wechat.send.video 权限时拒绝', async () => {
const { instance } = gateway({ dataRoot: tempDir('tm-ext-data-') })
await expect(
instance.sendVideo(
{ ...videoContext, permissions: [] },
{ to: 'fixture@chatroom', path: '/tmp/a.mp4' }
)
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
})
it('视频按 video 类型提交,不复用 image 通道', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'clip.mp4')
fs.writeFileSync(file, Buffer.from('fixture-video'))
const { instance, executeAction } = gateway({ dataRoot })
const result = await instance.sendVideo(videoContext, {
to: 'fixture@chatroom',
path: file,
dedupeKey: 'message:fixture:video'
})
expect(result).toEqual({ actionId: 'action-1', status: 'sent' })
const request = executeAction.mock.calls[0][0]
expect(request.origin).toBe('extension')
expect(request.purpose).toBe('extension_send')
expect(request.content).toEqual({ type: 'video', path: fs.realpathSync(file) })
expect(request.recipient).toMatchObject({ type: 'group', id: 'fixture@chatroom' })
expect(String(request.idempotencyKey)).toMatch(/^extension:com\.example\.douyin:/)
})
it('视频通道拒绝图片扩展名', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'cover.png')
fs.writeFileSync(file, Buffer.from('fixture-image'))
const { instance } = gateway({ dataRoot })
await expect(
instance.sendVideo(videoContext, { to: 'fixture@chatroom', path: file })
).rejects.toMatchObject({ code: 'SEND_NOT_SUPPORTED' })
})
it('本机能力没有视频时返回 CAPABILITY_UNAVAILABLE', async () => {
const dataRoot = tempDir('tm-ext-data-')
const file = path.join(dataRoot, 'clip.mp4')
fs.writeFileSync(file, Buffer.from('fixture-video'))
const { instance } = gateway({
dataRoot,
capability: {
...readyCapability,
capabilities: { text: true, image: true, voice: false, video: false }
}
})
await expect(
instance.sendVideo(videoContext, { to: 'fixture@chatroom', path: file })
).rejects.toMatchObject({ code: 'CAPABILITY_UNAVAILABLE' })
})
})
+111
View File
@@ -0,0 +1,111 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createExtensionPaths, isPathInside } from '../../src/main/extensions/extension-paths'
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
import { ExtensionLogStore } from '../../src/main/extensions/extension-log'
const roots: string[] = []
function tempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-state-'))
roots.push(root)
return root
}
afterEach(() => {
for (const root of roots.splice(0)) fs.removeSync(root)
})
describe('extension paths', () => {
it('三段目录彼此分离且都在 userData 下', () => {
const paths = createExtensionPaths('/tmp/user-data')
expect(paths.extensionsDir).toBe(path.join('/tmp/user-data', 'extensions'))
expect(paths.extensionDataDir('com.example.a')).toBe(
path.join('/tmp/user-data', 'extensions-data', 'com.example.a')
)
expect(paths.registryFile).toBe(
path.join('/tmp/user-data', 'extensions-state', 'registry.json')
)
expect(isPathInside(paths.extensionsDir, path.join(paths.extensionsDir, 'a'))).toBe(true)
expect(isPathInside(paths.extensionsDir, 'a/../../etc')).toBe(false)
})
})
describe('extension registry', () => {
it('持久化启用状态与授权,重启后仍可读', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
const first = new ExtensionRegistry({ registryFile })
first.upsert({
id: 'com.example.a',
version: '1.0.0',
apiVersion: '1',
enabled: true,
grantedPermissions: ['storage', 'messages.subscribe'],
installedAt: 1,
updatedAt: 2,
source: 'directory'
})
const second = new ExtensionRegistry({ registryFile })
const record = second.get('com.example.a')
expect(record?.enabled).toBe(true)
expect(record?.grantedPermissions).toEqual(['storage', 'messages.subscribe'])
})
it('文件损坏时按未安装处理,不抛异常', () => {
const root = tempRoot()
const registryFile = path.join(root, 'registry.json')
fs.ensureDirSync(root)
fs.writeFileSync(registryFile, '{broken', 'utf8')
const registry = new ExtensionRegistry({ registryFile })
expect(registry.list()).toEqual([])
})
})
describe('extension storage', () => {
it('按扩展隔离键空间并支持删除', () => {
const root = tempRoot()
const storage = new ExtensionStorage({ dataRoot: root })
storage.set('com.example.a', 'greeting', '你好')
storage.set('com.example.b', 'greeting', 'hello')
expect(storage.get('com.example.a', 'greeting')).toBe('你好')
expect(storage.get('com.example.b', 'greeting')).toBe('hello')
expect(storage.remove('com.example.a', 'greeting')).toBe(true)
expect(storage.get('com.example.a', 'greeting')).toBeUndefined()
})
it('拒绝非法键与不可序列化的值', () => {
const storage = new ExtensionStorage({ dataRoot: tempRoot() })
expect(() => storage.set('com.example.a', '../escape', 1)).toThrowError(/存储键/)
expect(() => storage.set('com.example.a', 'fn', () => undefined)).toThrowError(/JSON/)
})
it('单值超限时拒绝而不是截断', () => {
const storage = new ExtensionStorage({ dataRoot: tempRoot(), maxValueBytes: 32 })
expect(() => storage.set('com.example.a', 'big', 'x'.repeat(64))).toThrowError(/上限/)
})
})
describe('extension log store', () => {
it('落盘后可被新的实例读回,并按数量截断', () => {
const root = tempRoot()
const first = new ExtensionLogStore(root)
for (let index = 0; index < 5; index += 1) {
first.append('com.example.a', 'info', 'extension', `line-${index}`)
}
const second = new ExtensionLogStore(root)
const entries = second.list('com.example.a', 10)
expect(entries).toHaveLength(5)
expect(entries[0].message).toBe('line-4')
})
it('清洗控制字符并截断超长日志', () => {
const store = new ExtensionLogStore(tempRoot())
const entry = store.append('com.example.a', 'warn', 'extension', `a\u0000b${'x'.repeat(800)}`)
expect(entry.message).not.toContain('\u0000')
expect(entry.message.length).toBeLessThanOrEqual(501)
})
})
@@ -103,6 +103,11 @@ describe('mention parser(纯函数)', () => {
// 若实现里写了 `startsWith('wxid_')` 过滤,这条会变成 []
expect(extractMentionTargets(source)).toEqual(['SELF_USER'])
})
it('多人 @(逗号分隔)能够拆分为独立 username 列表', () => {
const source = '<msgsource><atuserlist><![CDATA[,OTHER_USER,SELF_USER]]></atuserlist></msgsource>'
expect(extractMentionTargets(source)).toEqual(['OTHER_USER', 'SELF_USER'])
})
})
describe('decodeSourcePayload', () => {
@@ -121,8 +126,14 @@ describe('decodeSourcePayload', () => {
expect(decodeSourcePayload(jsonForm)).toBe(xml)
})
it('TEXT 列直接返回明文 XML 字符串时原样保留', () => {
const xml = '<msgsource><atuserlist>SELF_USER</atuserlist></msgsource>'
expect(decodeSourcePayload(xml)).toBe(xml)
})
it('空值 / 非 zstd 内容安全返回', () => {
expect(decodeSourcePayload(undefined)).toBeUndefined()
expect(decodeSourcePayload('')).toBeUndefined()
expect(decodeSourcePayload(Buffer.alloc(0))).toBeUndefined()
expect(decodeSourcePayload(Buffer.from('plain text'))).toBe('plain text')
})
@@ -418,6 +418,20 @@ describe('Windows request', () => {
})
})
it('builds the unified video request with type=video', () => {
expect(
buildWindowsWechatRequest({
to: 'room@chatroom',
type: 'video',
filePath: '/tmp/tm-test.mp4',
isGroup: true
})
).toEqual({
endpoint: '/SendMsg',
body: { toWxid: 'room@chatroom', type: 'video', msg: '/tmp/tm-test.mp4' }
})
})
it('builds the unified voice request with sender wxid and duration', () => {
expect(
buildWindowsWechatRequest(