mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 17:25:15 +08:00
feat: 扩展中心支持多模态消息、HTML 渲染、一级导航与应用内通知
This commit is contained in:
1 parent
b20e514c90
commit
4ea73c3414
63 files changed
+8360
-644
No files matched your search
@@ -25,9 +25,12 @@ describe('example extensions', () => {
|
||||
const root = path.join(EXAMPLES_ROOT, directory)
|
||||
const manifestPath = path.join(root, 'manifest.json')
|
||||
expect(fs.existsSync(manifestPath), `${directory} 缺少 manifest.json`).toBe(true)
|
||||
const pkg = JSON.parse(
|
||||
fs.readFileSync(path.resolve(process.cwd(), 'package.json'), 'utf8')
|
||||
) as { version?: string }
|
||||
const parsed = parseExtensionManifest(
|
||||
JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown,
|
||||
{ appVersion: '2.6.0' }
|
||||
{ appVersion: pkg.version || '2.7.0' }
|
||||
)
|
||||
expect(parsed.ok, `${directory}: ${parsed.message || ''}`).toBe(true)
|
||||
const manifest = parsed.manifest
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildExtensionMessageEvent } from '../../src/shared/extensions/events'
|
||||
import {
|
||||
decodeExtensionMessageRef,
|
||||
encodeExtensionMessageRef
|
||||
} from '../../src/shared/extensions/media'
|
||||
import type { ExtensionPermission } from '../../src/shared/extensions/permissions'
|
||||
import type { ExtensionQueriedMessage } from '../../src/shared/extensions/rpc'
|
||||
import {
|
||||
ExtensionMediaGateway,
|
||||
paginateQueriedMessages,
|
||||
type ResolvedExtensionMediaMessage
|
||||
} from '../../src/main/extensions/extension-media-gateway'
|
||||
import { ExtensionMessageRefSigner } from '../../src/main/extensions/extension-message-ref-signer'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-media-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
|
||||
})
|
||||
|
||||
function createHarness(overrides: {
|
||||
accountId?: string
|
||||
databaseReady?: boolean
|
||||
permissionsByExtension?: Record<string, ExtensionPermission[]>
|
||||
messages?: Record<string, ResolvedExtensionMediaMessage>
|
||||
maxGlobalConcurrent?: number
|
||||
maxPerExtensionConcurrent?: number
|
||||
timeoutsMs?: Partial<Record<'readImage' | 'ocrImage', number>>
|
||||
} = {}) {
|
||||
const root = makeTempDir()
|
||||
const rawVideoDir = path.join(root, 'wechat-private-root', 'msg', 'video', '2026-12')
|
||||
fs.ensureDirSync(rawVideoDir)
|
||||
const rawVideoPath = path.join(rawVideoDir, 'fixture-video.mp4')
|
||||
const rawPosterPath = path.join(rawVideoDir, 'fixture-poster.jpg')
|
||||
fs.writeFileSync(rawVideoPath, Buffer.from('fixture-mp4-binary-payload'))
|
||||
fs.writeFileSync(rawPosterPath, Buffer.from('fixture-jpg-poster'))
|
||||
|
||||
let currentAccount = overrides.accountId ?? 'wxid_account_a'
|
||||
const databaseReady = overrides.databaseReady ?? true
|
||||
const permissionsByExtension = overrides.permissionsByExtension ?? {
|
||||
'com.example.alpha': ['media.read', 'media.ocr', 'media.transcribe', 'ai.vision'],
|
||||
'com.example.beta': ['media.read', 'media.ocr', 'media.transcribe', 'ai.vision']
|
||||
}
|
||||
|
||||
const imageMessage: ResolvedExtensionMediaMessage = {
|
||||
messageId: 'srv-img-1',
|
||||
localId: 101,
|
||||
serverId: 'srv-img-1',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
senderName: '张三',
|
||||
type: 'image',
|
||||
createTimeSeconds: 1_760_000_100,
|
||||
image: { md5: 'a'.repeat(32), datName: 'img101' }
|
||||
}
|
||||
const voiceMessage: ResolvedExtensionMediaMessage = {
|
||||
messageId: 'srv-voice-1',
|
||||
localId: 102,
|
||||
serverId: 'srv-voice-1',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
senderName: '李四',
|
||||
type: 'voice',
|
||||
createTimeSeconds: 1_760_000_200,
|
||||
voice: { durationSeconds: 4 }
|
||||
}
|
||||
const videoMessage: ResolvedExtensionMediaMessage = {
|
||||
messageId: 'srv-video-1',
|
||||
localId: 103,
|
||||
serverId: 'srv-video-1',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
senderName: '王五',
|
||||
type: 'video',
|
||||
createTimeSeconds: 1_760_000_300,
|
||||
video: { hashes: ['b'.repeat(32)], duration: 12, width: 720, height: 1280 }
|
||||
}
|
||||
const messages: Record<string, ResolvedExtensionMediaMessage> = {
|
||||
'srv-img-1': imageMessage,
|
||||
'srv-voice-1': voiceMessage,
|
||||
'srv-video-1': videoMessage,
|
||||
...(overrides.messages ?? {})
|
||||
}
|
||||
|
||||
const readImageData = vi.fn(async (_msg: ResolvedExtensionMediaMessage, quality: 'original' | 'thumbnail') => ({
|
||||
buffer: Buffer.from(`png-bytes-${quality}`),
|
||||
mimeType: 'image/png',
|
||||
imageHash: 'hash-img-1',
|
||||
quality
|
||||
}))
|
||||
const readVoiceData = vi.fn(async () => ({
|
||||
wavBuffer: Buffer.from('RIFF-fixture-wav-data'),
|
||||
durationMs: 4000
|
||||
}))
|
||||
const readVideoAsset = vi.fn(async () => ({
|
||||
filePath: rawVideoPath,
|
||||
posterPath: rawPosterPath,
|
||||
durationMs: 12_000,
|
||||
width: 720,
|
||||
height: 1280
|
||||
}))
|
||||
const getCachedOcr = vi.fn<
|
||||
(conversationId: string, messageId: string) => { text: string; language?: string | null; engine?: string } | null
|
||||
>(() => null)
|
||||
const recognizeOcr = vi.fn(async () => ({
|
||||
success: true,
|
||||
text: '测试图片识别文字',
|
||||
language: 'zh-Hans',
|
||||
engine: 'apple-vision'
|
||||
}))
|
||||
const transcribeVoice = vi.fn(async () => ({
|
||||
state: 'transcribed' as const,
|
||||
transcript: '明天上午十点开会',
|
||||
cached: false,
|
||||
durationMs: 4000
|
||||
}))
|
||||
const analyzeImage = vi.fn(async (input: { prompt?: string }) => ({
|
||||
description: input.prompt ? `自定义分析:${input.prompt}` : '一张包含日程表的截图',
|
||||
ocrText: '日程表',
|
||||
tags: ['截图'],
|
||||
category: 'screenshot',
|
||||
model: 'fixture-vision',
|
||||
cached: false
|
||||
}))
|
||||
|
||||
const gateway = new ExtensionMediaGateway({
|
||||
isDatabaseReady: () => databaseReady,
|
||||
getAccountId: () => currentAccount,
|
||||
getExtensionDataRoot: (extId) => path.join(root, 'extensions-data', extId),
|
||||
hasPermission: (extId, perm) => (permissionsByExtension[extId] ?? []).includes(perm),
|
||||
resolveMessage: async (ref) => messages[ref.messageId] ?? null,
|
||||
readImageData,
|
||||
readVoiceData,
|
||||
readVideoAsset,
|
||||
getCachedOcr,
|
||||
recognizeOcr,
|
||||
transcribeVoice,
|
||||
analyzeImage,
|
||||
maxGlobalConcurrent: overrides.maxGlobalConcurrent,
|
||||
maxPerExtensionConcurrent: overrides.maxPerExtensionConcurrent,
|
||||
timeoutsMs: overrides.timeoutsMs
|
||||
})
|
||||
|
||||
return {
|
||||
root,
|
||||
rawVideoPath,
|
||||
gateway,
|
||||
setAccount: (next: string) => {
|
||||
currentAccount = next
|
||||
},
|
||||
mocks: {
|
||||
readImageData,
|
||||
readVoiceData,
|
||||
readVideoAsset,
|
||||
getCachedOcr,
|
||||
recognizeOcr,
|
||||
transcribeVoice,
|
||||
analyzeImage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('ExtensionMediaGateway 与统一 messageRef', () => {
|
||||
it('实时事件与历史查询生成同一套可逆 messageRef,并拒绝篡改引用', () => {
|
||||
const event = buildExtensionMessageEvent({
|
||||
eventId: 'message:abc',
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1',
|
||||
localId: '101',
|
||||
isGroup: true,
|
||||
isSelf: false,
|
||||
messageType: 3,
|
||||
mentionsMe: false,
|
||||
createTimeSeconds: 1_760_000_100
|
||||
})
|
||||
const queryRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1',
|
||||
localId: '101',
|
||||
timestamp: 1_760_000_100_000
|
||||
})
|
||||
|
||||
expect(event.messageRef).toBe(queryRef)
|
||||
expect(decodeExtensionMessageRef(event.messageRef)).toEqual({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1',
|
||||
localId: '101',
|
||||
timestamp: 1_760_000_100_000
|
||||
})
|
||||
expect(decodeExtensionMessageRef('invalid-ref')).toBeNull()
|
||||
expect(decodeExtensionMessageRef('tmref1_!!!notbase64!!!')).toBeNull()
|
||||
})
|
||||
|
||||
it('主进程独立拒绝未授权的媒体读取、OCR、转写与视觉理解调用', async () => {
|
||||
const { gateway } = createHarness({
|
||||
permissionsByExtension: { 'com.example.readonly': ['messages.query'] }
|
||||
})
|
||||
const imgRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1'
|
||||
})
|
||||
const voiceRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-voice-1'
|
||||
})
|
||||
|
||||
await expect(gateway.readImage('com.example.readonly', { messageRef: imgRef })).rejects.toMatchObject({
|
||||
code: 'PERMISSION_DENIED'
|
||||
})
|
||||
await expect(gateway.ocrImage('com.example.readonly', { messageRef: imgRef })).rejects.toMatchObject({
|
||||
code: 'PERMISSION_DENIED'
|
||||
})
|
||||
await expect(
|
||||
gateway.transcribeVoice('com.example.readonly', { messageRef: voiceRef })
|
||||
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
|
||||
await expect(gateway.analyzeImage('com.example.readonly', { messageRef: imgRef })).rejects.toMatchObject({
|
||||
code: 'PERMISSION_DENIED'
|
||||
})
|
||||
})
|
||||
|
||||
it('跨账号 messageRef 被严格拒绝,切换账号后自动失效旧缓存', async () => {
|
||||
const { gateway, setAccount, mocks } = createHarness()
|
||||
const accountARef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1'
|
||||
})
|
||||
|
||||
const first = await gateway.ocrImage('com.example.alpha', { messageRef: accountARef })
|
||||
expect(first.cached).toBe(false)
|
||||
expect(mocks.recognizeOcr).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 切换到账号 B 后,账号 A 的 messageRef 必须被拒绝。
|
||||
setAccount('wxid_account_b')
|
||||
await expect(
|
||||
gateway.ocrImage('com.example.alpha', { messageRef: accountARef })
|
||||
).rejects.toMatchObject({ code: 'ACCOUNT_MISMATCH' })
|
||||
})
|
||||
|
||||
it('跨扩展媒体副本完全隔离在各自私有数据目录,不暴露原始微信路径', async () => {
|
||||
const { gateway, rawVideoPath } = createHarness()
|
||||
const imgRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1'
|
||||
})
|
||||
const videoRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-video-1'
|
||||
})
|
||||
|
||||
const alphaImg = await gateway.readImage('com.example.alpha', { messageRef: imgRef })
|
||||
const betaImg = await gateway.readImage('com.example.beta', { messageRef: imgRef })
|
||||
expect(alphaImg.path).toContain(path.join('extensions-data', 'com.example.alpha', 'media-cache'))
|
||||
expect(betaImg.path).toContain(path.join('extensions-data', 'com.example.beta', 'media-cache'))
|
||||
expect(alphaImg.path).not.toBe(betaImg.path)
|
||||
|
||||
// 同扩展二次读取命中磁盘缓存。
|
||||
const alphaImgAgain = await gateway.readImage('com.example.alpha', { messageRef: imgRef })
|
||||
expect(alphaImgAgain.cached).toBe(true)
|
||||
|
||||
const video = await gateway.readVideo('com.example.alpha', { messageRef: videoRef })
|
||||
expect(video.path).not.toBe(rawVideoPath)
|
||||
expect(video.path).not.toContain('wechat-private-root')
|
||||
expect(video.path).toContain(path.join('extensions-data', 'com.example.alpha', 'media-cache'))
|
||||
expect(fs.existsSync(video.path)).toBe(true)
|
||||
expect(video.posterPath && fs.existsSync(video.posterPath)).toBe(true)
|
||||
})
|
||||
|
||||
it('支持 OCR 索引缓存命中、语音转写复用与 AI 视觉理解缓存', async () => {
|
||||
const { gateway, mocks } = createHarness()
|
||||
const imgRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1'
|
||||
})
|
||||
const voiceRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-voice-1'
|
||||
})
|
||||
|
||||
// 命中既有图片文字索引缓存时不再触发 SystemOcr。
|
||||
mocks.getCachedOcr.mockReturnValueOnce({ text: '索引已有 OCR', language: 'zh-Hans', engine: 'system-ocr' })
|
||||
const cachedOcr = await gateway.ocrImage('com.example.alpha', { messageRef: imgRef })
|
||||
expect(cachedOcr).toMatchObject({ text: '索引已有 OCR', cached: true })
|
||||
expect(mocks.recognizeOcr).not.toHaveBeenCalled()
|
||||
|
||||
// force=true 时强制重新识别,并写入网关缓存。
|
||||
const freshOcr = await gateway.ocrImage('com.example.alpha', { messageRef: imgRef, force: true })
|
||||
expect(freshOcr).toMatchObject({ text: '测试图片识别文字', cached: false })
|
||||
const secondOcr = await gateway.ocrImage('com.example.alpha', { messageRef: imgRef })
|
||||
expect(secondOcr).toMatchObject({ text: '测试图片识别文字', cached: true })
|
||||
expect(mocks.recognizeOcr).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 语音读取与语音转写。
|
||||
const voiceFile = await gateway.readVoice('com.example.alpha', { messageRef: voiceRef })
|
||||
expect(voiceFile.mimeType).toBe('audio/wav')
|
||||
expect(fs.existsSync(voiceFile.path)).toBe(true)
|
||||
|
||||
const transcript = await gateway.transcribeVoice('com.example.alpha', { messageRef: voiceRef })
|
||||
expect(transcript).toMatchObject({ state: 'transcribed', transcript: '明天上午十点开会' })
|
||||
|
||||
// 视觉理解缓存命中,不同 prompt 隔离缓存键。
|
||||
const vision1 = await gateway.analyzeImage('com.example.alpha', { messageRef: imgRef })
|
||||
const vision2 = await gateway.analyzeImage('com.example.alpha', { messageRef: imgRef })
|
||||
const visionCustom = await gateway.analyzeImage('com.example.alpha', {
|
||||
messageRef: imgRef,
|
||||
prompt: '提取价格'
|
||||
})
|
||||
expect(vision1.cached).toBe(false)
|
||||
expect(vision2.cached).toBe(true)
|
||||
expect(visionCustom.description).toBe('自定义分析:提取价格')
|
||||
expect(mocks.analyzeImage).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('并发限制、超时与批量部分失败隔离生效', async () => {
|
||||
const { gateway, mocks } = createHarness({
|
||||
maxGlobalConcurrent: 1,
|
||||
maxPerExtensionConcurrent: 1,
|
||||
timeoutsMs: { readImage: 60 }
|
||||
})
|
||||
|
||||
let releaseFirst!: () => void
|
||||
mocks.readImageData.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
releaseFirst = () =>
|
||||
resolve({
|
||||
buffer: Buffer.from('slow-image'),
|
||||
mimeType: 'image/png',
|
||||
imageHash: 'hash-slow',
|
||||
quality: 'original'
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
const imgRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-img-1'
|
||||
})
|
||||
const voiceRef = encodeExtensionMessageRef({
|
||||
accountId: 'wxid_account_a',
|
||||
conversationId: 'fixture-group@chatroom',
|
||||
messageId: 'srv-voice-1'
|
||||
})
|
||||
|
||||
// 启动第一个慢任务占用唯一并发槽,第二个不同任务应命中 CONCURRENCY_LIMITED。
|
||||
const slowTask = gateway.readImage('com.example.alpha', { messageRef: imgRef })
|
||||
await expect(
|
||||
gateway.readVoice('com.example.alpha', { messageRef: voiceRef })
|
||||
).rejects.toMatchObject({ code: 'CONCURRENCY_LIMITED' })
|
||||
|
||||
// 等待超过 60ms,慢任务触发 ACTION_TIMEOUT。
|
||||
await expect(slowTask).rejects.toMatchObject({ code: 'ACTION_TIMEOUT' })
|
||||
releaseFirst()
|
||||
|
||||
// 批量调用中部分项类型不匹配不影响其他项成功。
|
||||
const batch = await gateway.batch('com.example.alpha', {
|
||||
concurrency: 1,
|
||||
items: [
|
||||
{ op: 'readImage', messageRef: imgRef },
|
||||
{ op: 'readVoice', messageRef: imgRef },
|
||||
{ op: 'transcribeVoice', messageRef: voiceRef }
|
||||
]
|
||||
})
|
||||
expect(batch.results).toHaveLength(3)
|
||||
expect(batch.results[0].ok).toBe(true)
|
||||
expect(batch.results[1].ok).toBe(false)
|
||||
expect(batch.results[1].error?.code).toBe('MEDIA_UNSUPPORTED')
|
||||
expect(batch.results[2].ok).toBe(true)
|
||||
})
|
||||
|
||||
it('游标分页在同时间戳多条消息下零遗漏、零重复,且兼容 v1 默认顺序', () => {
|
||||
const dataset: ExtensionQueriedMessage[] = [
|
||||
{ messageId: 'm1', messageRef: 'r1', conversationId: 'g1', isSelf: false, type: 'text', text: '1', timestamp: 1000 },
|
||||
{ messageId: 'm2', messageRef: 'r2', conversationId: 'g1', isSelf: false, type: 'text', text: '2', timestamp: 2000 },
|
||||
{ messageId: 'm3', messageRef: 'r3', conversationId: 'g1', isSelf: false, type: 'image', timestamp: 2000 },
|
||||
{ messageId: 'm4', messageRef: 'r4', conversationId: 'g1', isSelf: false, type: 'text', text: '4', timestamp: 2000 },
|
||||
{ messageId: 'm5', messageRef: 'r5', conversationId: 'g1', isSelf: false, type: 'voice', timestamp: 3000 }
|
||||
]
|
||||
|
||||
// 升序分页:每页 2 条,走完刚好 5 条无遗漏无重复。
|
||||
const collectedAsc: string[] = []
|
||||
let cursor: string | undefined
|
||||
for (let guard = 0; guard < 10; guard += 1) {
|
||||
const page = paginateQueriedMessages(dataset, {
|
||||
conversationId: 'g1',
|
||||
order: 'asc',
|
||||
limit: 2,
|
||||
cursor
|
||||
})
|
||||
collectedAsc.push(...page.messages.map((item) => item.messageId))
|
||||
if (!page.hasMore) break
|
||||
cursor = page.nextCursor
|
||||
}
|
||||
expect(collectedAsc).toEqual(['m1', 'm2', 'm3', 'm4', 'm5'])
|
||||
|
||||
// 默认 v1 语义(不传 order):首屏返回最新 2 条,续页向更早历史翻页仍覆盖全部 5 条。
|
||||
const firstDefault = paginateQueriedMessages(dataset, { conversationId: 'g1', limit: 2 })
|
||||
expect(firstDefault.messages.map((item) => item.messageId)).toEqual(['m4', 'm5'])
|
||||
expect(firstDefault.hasMore).toBe(true)
|
||||
|
||||
const secondDefault = paginateQueriedMessages(dataset, {
|
||||
conversationId: 'g1',
|
||||
limit: 2,
|
||||
cursor: firstDefault.nextCursor
|
||||
})
|
||||
expect(secondDefault.messages.map((item) => item.messageId)).toEqual(['m2', 'm3'])
|
||||
|
||||
const thirdDefault = paginateQueriedMessages(dataset, {
|
||||
conversationId: 'g1',
|
||||
limit: 2,
|
||||
cursor: secondDefault.nextCursor
|
||||
})
|
||||
expect(thirdDefault.messages.map((item) => item.messageId)).toEqual(['m1'])
|
||||
expect(thirdDefault.hasMore).toBe(false)
|
||||
|
||||
// 按类型过滤。
|
||||
const onlyMedia = paginateQueriedMessages(dataset, {
|
||||
conversationId: 'g1',
|
||||
order: 'asc',
|
||||
types: ['image', 'voice'],
|
||||
limit: 10
|
||||
})
|
||||
expect(onlyMedia.messages.map((item) => item.messageId)).toEqual(['m3', 'm5'])
|
||||
|
||||
// 默认模式不接受 asc 游标,避免反向错漏。
|
||||
const ascFirst = paginateQueriedMessages(dataset, { conversationId: 'g1', order: 'asc', limit: 2 })
|
||||
expect(() =>
|
||||
paginateQueriedMessages(dataset, { conversationId: 'g1', limit: 2, cursor: ascFirst.nextCursor })
|
||||
).toThrowError(/游标/)
|
||||
})
|
||||
|
||||
it('签名校验拒绝伪造/篡改/切号旧引用、越权会话访问,且磁盘缓存按账号物理隔离', async () => {
|
||||
const root = makeTempDir()
|
||||
const signer = new ExtensionMessageRefSigner()
|
||||
let currentAccount = 'wxid_account_a'
|
||||
|
||||
const imageMsg: ResolvedExtensionMediaMessage = {
|
||||
messageId: 'srv-img-sec',
|
||||
conversationId: 'allowed@chatroom',
|
||||
type: 'image',
|
||||
createTimeSeconds: 1700001000
|
||||
}
|
||||
const forbiddenMsg: ResolvedExtensionMediaMessage = {
|
||||
messageId: 'srv-img-forbid',
|
||||
conversationId: 'secret@chatroom',
|
||||
type: 'image',
|
||||
createTimeSeconds: 1700001000
|
||||
}
|
||||
const textMsg: ResolvedExtensionMediaMessage = {
|
||||
messageId: 'srv-text-1',
|
||||
conversationId: 'allowed@chatroom',
|
||||
type: 'other',
|
||||
createTimeSeconds: 1700001000
|
||||
}
|
||||
|
||||
const gateway = new ExtensionMediaGateway({
|
||||
isDatabaseReady: () => true,
|
||||
getAccountId: () => currentAccount,
|
||||
getExtensionDataRoot: (extId) => path.join(root, 'extensions-data', extId),
|
||||
hasPermission: () => true,
|
||||
isConversationAllowed: (_extId, conversationId) => conversationId === 'allowed@chatroom',
|
||||
verifySignedRef: (rawRef, accountId) => signer.verify(rawRef, accountId),
|
||||
resolveMessage: async (ref) => {
|
||||
if (ref.messageId === 'srv-img-sec') return imageMsg
|
||||
if (ref.messageId === 'srv-img-forbid') return forbiddenMsg
|
||||
if (ref.messageId === 'srv-text-1') return textMsg
|
||||
return null
|
||||
},
|
||||
readImageData: async () => ({
|
||||
buffer: Buffer.from('same-image-bytes'),
|
||||
mimeType: 'image/png',
|
||||
quality: 'original'
|
||||
}),
|
||||
readVoiceData: async () => null,
|
||||
readVideoAsset: async () => null,
|
||||
getCachedOcr: () => ({ text: '不应该被非图片消息命中', engine: 'system-ocr' }),
|
||||
recognizeOcr: async () => ({ success: true, text: 'ok', language: 'zh-Hans', engine: 'vision' }),
|
||||
transcribeVoice: async () => null,
|
||||
analyzeImage: async () => ({ description: 'ok' })
|
||||
})
|
||||
|
||||
// 1. 未签名伪造的 tmref1_ 被拒绝。
|
||||
const forgedRef = encodeExtensionMessageRef({
|
||||
accountId: currentAccount,
|
||||
conversationId: 'allowed@chatroom',
|
||||
messageId: 'srv-img-sec'
|
||||
})
|
||||
await expect(
|
||||
gateway.readImage('com.example.alpha', { messageRef: forgedRef })
|
||||
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
|
||||
|
||||
// 2. 合法签发后正常读取,并返回受控 previewUrl。
|
||||
const signedAllowed = signer.sign({
|
||||
accountId: currentAccount,
|
||||
conversationId: 'allowed@chatroom',
|
||||
messageId: 'srv-img-sec'
|
||||
})
|
||||
const imgA = await gateway.readImage('com.example.alpha', { messageRef: signedAllowed })
|
||||
expect(imgA.previewUrl).toMatch(/^tm-extension:\/\/com\.example\.alpha\/_data\/media-cache\//)
|
||||
|
||||
// 3. 篡改签发 token 任意字符被拒绝。
|
||||
const tampered = `${signedAllowed.slice(0, -1)}${signedAllowed.endsWith('a') ? 'b' : 'a'}`
|
||||
await expect(
|
||||
gateway.readImage('com.example.alpha', { messageRef: tampered })
|
||||
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
|
||||
|
||||
// 4. 超出声明会话范围被拒绝。
|
||||
const signedForbidden = signer.sign({
|
||||
accountId: currentAccount,
|
||||
conversationId: 'secret@chatroom',
|
||||
messageId: 'srv-img-forbid'
|
||||
})
|
||||
await expect(
|
||||
gateway.readImage('com.example.alpha', { messageRef: signedForbidden })
|
||||
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' })
|
||||
|
||||
// 5. 非图片消息调用 ocrImage 不能误命中索引缓存。
|
||||
const signedText = signer.sign({
|
||||
accountId: currentAccount,
|
||||
conversationId: 'allowed@chatroom',
|
||||
messageId: 'srv-text-1'
|
||||
})
|
||||
await expect(
|
||||
gateway.ocrImage('com.example.alpha', { messageRef: signedText })
|
||||
).rejects.toMatchObject({ code: 'MEDIA_UNSUPPORTED' })
|
||||
|
||||
// 6. 切换账号到 B 后,磁盘缓存落在独立账号桶;再切回账号 A,旧世代签名引用已失效。
|
||||
currentAccount = 'wxid_account_b'
|
||||
const signedB = signer.sign({
|
||||
accountId: currentAccount,
|
||||
conversationId: 'allowed@chatroom',
|
||||
messageId: 'srv-img-sec'
|
||||
})
|
||||
const imgB = await gateway.readImage('com.example.alpha', { messageRef: signedB })
|
||||
expect(imgB.path).not.toBe(imgA.path)
|
||||
expect(imgB.cached).toBe(false)
|
||||
|
||||
currentAccount = 'wxid_account_a'
|
||||
await expect(
|
||||
gateway.readImage('com.example.alpha', { messageRef: signedAllowed })
|
||||
).rejects.toMatchObject({ code: 'INVALID_REQUEST' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,202 @@
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { parseExtensionManifest } from '../../src/shared/extensions/manifest'
|
||||
import { ExtensionNavigationStore } from '../../src/main/extensions/extension-navigation-store'
|
||||
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
|
||||
import { ExtensionManager } from '../../src/main/extensions/extension-manager'
|
||||
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
|
||||
import type { WechatActionResult } from '../../src/shared/wechat-action'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-nav-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
|
||||
})
|
||||
|
||||
function writeSampleExtension(
|
||||
dir: string,
|
||||
id: string,
|
||||
name: string,
|
||||
navigation?: { label: string; icon?: string; pageId?: string }
|
||||
): void {
|
||||
fs.ensureDirSync(path.join(dir, 'ui'))
|
||||
fs.writeFileSync(path.join(dir, 'ui', 'index.html'), '<!doctype html><html><body>hi</body></html>')
|
||||
fs.writeJsonSync(path.join(dir, 'manifest.json'), {
|
||||
manifestVersion: 1,
|
||||
id,
|
||||
name,
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
permissions: ['storage'],
|
||||
entrypoints: { page: 'ui/index.html' },
|
||||
contributions: {
|
||||
pages: [{ id: 'main', title: name }],
|
||||
automationActions: [],
|
||||
...(navigation ? { navigation } : {})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
describe('动态一级导航声明与持久化', () => {
|
||||
it('manifest 校验 contributions.navigation 并兼容旧版无 navigation 清单', () => {
|
||||
const valid = parseExtensionManifest({
|
||||
manifestVersion: 1,
|
||||
id: 'com.example.digest',
|
||||
name: 'AI 晨报',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
permissions: ['storage'],
|
||||
entrypoints: { page: 'ui/index.html' },
|
||||
contributions: {
|
||||
pages: [{ id: 'main', title: '晨报' }],
|
||||
navigation: { label: '晨报', icon: 'digest', pageId: 'main', order: 10 }
|
||||
}
|
||||
})
|
||||
expect(valid.ok).toBe(true)
|
||||
expect(valid.manifest?.contributions.navigation).toEqual({
|
||||
label: '晨报',
|
||||
icon: 'digest',
|
||||
pageId: 'main',
|
||||
order: 10
|
||||
})
|
||||
|
||||
const legacy = parseExtensionManifest({
|
||||
manifestVersion: 1,
|
||||
id: 'com.example.legacy',
|
||||
name: '旧扩展',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
permissions: ['storage'],
|
||||
entrypoints: { page: 'ui/index.html' }
|
||||
})
|
||||
expect(legacy.ok).toBe(true)
|
||||
expect(legacy.manifest?.contributions.navigation).toBeUndefined()
|
||||
|
||||
const badIcon = parseExtensionManifest({
|
||||
manifestVersion: 1,
|
||||
id: 'com.example.bad',
|
||||
name: '坏图标',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
permissions: [],
|
||||
entrypoints: { page: 'ui/index.html' },
|
||||
contributions: {
|
||||
pages: [{ id: 'main', title: '首页' }],
|
||||
navigation: { label: '测试', icon: 'evil-svg' }
|
||||
}
|
||||
})
|
||||
expect(badIcon.ok).toBe(false)
|
||||
|
||||
const missingPage = parseExtensionManifest({
|
||||
manifestVersion: 1,
|
||||
id: 'com.example.nopage',
|
||||
name: '无页面',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
permissions: [],
|
||||
entrypoints: { background: 'bg.js' },
|
||||
contributions: {
|
||||
navigation: { label: '测试', icon: 'spark' }
|
||||
}
|
||||
})
|
||||
expect(missingPage.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('固定、排序、重启恢复与卸载自动清理完整生效', async () => {
|
||||
const root = makeTempDir()
|
||||
const extADir = path.join(root, 'src-a')
|
||||
const extBDir = path.join(root, 'src-b')
|
||||
writeSampleExtension(extADir, 'com.example.alpha', '晨报助手', {
|
||||
label: '晨报',
|
||||
icon: 'digest',
|
||||
pageId: 'main'
|
||||
})
|
||||
writeSampleExtension(extBDir, 'com.example.beta', '群聊机器人', {
|
||||
label: '机器人',
|
||||
icon: 'bot',
|
||||
pageId: 'main'
|
||||
})
|
||||
|
||||
const paths = createExtensionPaths(path.join(root, 'userData'))
|
||||
const createManager = () =>
|
||||
new ExtensionManager({
|
||||
paths,
|
||||
appVersion: '2.7.0',
|
||||
getCapability: async () =>
|
||||
({
|
||||
supported: true,
|
||||
ready: true,
|
||||
status: 'ready',
|
||||
capabilities: { text: true, image: true, voice: true },
|
||||
senderStatus: {},
|
||||
message: ''
|
||||
}) as unknown as PersonalWechatSendCapability,
|
||||
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
|
||||
executeAction: async (): Promise<WechatActionResult> => ({
|
||||
actionId: 'a1',
|
||||
status: 'sent',
|
||||
decision: 'allow',
|
||||
startedAt: '2026-01-01T00:00:00.000Z',
|
||||
finishedAt: '2026-01-01T00:00:01.000Z'
|
||||
}),
|
||||
queryMessages: async () => [],
|
||||
listGroups: async () => [],
|
||||
aiChat: async () => ({ text: 'ok' }),
|
||||
getAccountId: () => 'wxid_fixture',
|
||||
getSelfUsernames: () => ['wxid_fixture'],
|
||||
isDatabaseReady: () => true,
|
||||
secretCipher: {
|
||||
isAvailable: () => false,
|
||||
encrypt: () => Buffer.alloc(0),
|
||||
decrypt: () => ''
|
||||
}
|
||||
})
|
||||
|
||||
const manager1 = createManager()
|
||||
await manager1.initialize()
|
||||
expect((await manager1.installFromDirectory(extADir)).success).toBe(true)
|
||||
expect((await manager1.installFromDirectory(extBDir)).success).toBe(true)
|
||||
|
||||
expect(manager1.pinNavigation('com.example.alpha').success).toBe(true)
|
||||
expect(manager1.pinNavigation('com.example.beta').success).toBe(true)
|
||||
expect(manager1.listPinnedNavigation().map((item) => item.extensionId)).toEqual([
|
||||
'com.example.alpha',
|
||||
'com.example.beta'
|
||||
])
|
||||
|
||||
// 调整排序。
|
||||
manager1.reorderPinnedNavigation(['com.example.beta', 'com.example.alpha'])
|
||||
expect(manager1.listPinnedNavigation().map((item) => item.extensionId)).toEqual([
|
||||
'com.example.beta',
|
||||
'com.example.alpha'
|
||||
])
|
||||
await manager1.dispose()
|
||||
|
||||
// 模拟应用重启:新建 Manager,固定项与顺序必须恢复。
|
||||
const manager2 = createManager()
|
||||
await manager2.initialize()
|
||||
expect(manager2.listPinnedNavigation().map((item) => [item.extensionId, item.label, item.icon])).toEqual([
|
||||
['com.example.beta', '机器人', 'bot'],
|
||||
['com.example.alpha', '晨报', 'digest']
|
||||
])
|
||||
|
||||
// 卸载扩展后自动从一级导航移除。
|
||||
await manager2.uninstall('com.example.beta', true)
|
||||
expect(manager2.listPinnedNavigation().map((item) => item.extensionId)).toEqual([
|
||||
'com.example.alpha'
|
||||
])
|
||||
|
||||
// 底层存储同步已清理。
|
||||
const store = new ExtensionNavigationStore(paths.pinnedNavigationFile)
|
||||
expect(store.list().map((item) => item.extensionId)).toEqual(['com.example.alpha'])
|
||||
await manager2.dispose()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,195 @@
|
||||
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 { ExtensionManager } from '../../src/main/extensions/extension-manager'
|
||||
import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
|
||||
import type { WechatActionResult } from '../../src/shared/wechat-action'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-notify-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
|
||||
})
|
||||
|
||||
function writeExtension(dir: string, id: string, name: string, permissions: string[]): void {
|
||||
fs.ensureDirSync(path.join(dir, 'ui'))
|
||||
fs.writeFileSync(path.join(dir, 'ui', 'index.html'), '<!doctype html><html><body>ok</body></html>')
|
||||
fs.writeJsonSync(path.join(dir, 'manifest.json'), {
|
||||
manifestVersion: 1,
|
||||
id,
|
||||
name,
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
permissions,
|
||||
entrypoints: { page: 'ui/index.html' },
|
||||
contributions: {
|
||||
pages: [{ id: 'main', title: name }],
|
||||
navigation: { label: name, icon: 'bell', pageId: 'main' }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function makeManager(userData: string): ExtensionManager {
|
||||
return new ExtensionManager({
|
||||
paths: createExtensionPaths(userData),
|
||||
appVersion: '2.7.0',
|
||||
getCapability: async () =>
|
||||
({
|
||||
supported: true,
|
||||
ready: true,
|
||||
status: 'ready',
|
||||
capabilities: { text: true, image: true, voice: true },
|
||||
senderStatus: {},
|
||||
message: ''
|
||||
}) as unknown as PersonalWechatSendCapability,
|
||||
checkEntitlement: async () => ({ ok: true, message: '授权有效', source: 'mac_license' }),
|
||||
executeAction: async (): Promise<WechatActionResult> => ({
|
||||
actionId: 'a1',
|
||||
status: 'sent',
|
||||
decision: 'allow',
|
||||
startedAt: '2026-01-01T00:00:00.000Z',
|
||||
finishedAt: '2026-01-01T00:00:01.000Z'
|
||||
}),
|
||||
queryMessages: async () => [],
|
||||
listGroups: async () => [],
|
||||
aiChat: async () => ({ text: 'ok' }),
|
||||
getAccountId: () => 'wxid_fixture',
|
||||
getSelfUsernames: () => ['wxid_fixture'],
|
||||
isDatabaseReady: () => true,
|
||||
secretCipher: {
|
||||
isAvailable: () => false,
|
||||
encrypt: () => Buffer.alloc(0),
|
||||
decrypt: () => ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
describe('ExtensionNotificationCenter 持久化、去重与生命周期', () => {
|
||||
it('校验权限、拒绝停用扩展写入、支持 dedupeKey 去重与重启恢复,并在卸载后清理', async () => {
|
||||
const root = makeTempDir()
|
||||
const userData = path.join(root, 'userData')
|
||||
const extA = path.join(root, 'ext-a')
|
||||
const extB = path.join(root, 'ext-b')
|
||||
writeExtension(extA, 'com.example.digest', '晨报', ['notifications.create'])
|
||||
writeExtension(extB, 'com.example.bot', '机器人', ['notifications.create'])
|
||||
|
||||
const manager = makeManager(userData)
|
||||
await manager.initialize()
|
||||
await manager.installFromDirectory(extA)
|
||||
await manager.installFromDirectory(extB)
|
||||
|
||||
// 未启用扩展必须拒绝写入新通知。
|
||||
expect(() =>
|
||||
manager.createNotification('com.example.digest', { title: '不应写入' })
|
||||
).toThrowError(/停用/)
|
||||
|
||||
// 启用后若撤销 notifications.create 权限,主进程必须独立拒绝写入。
|
||||
await manager.setEnabled('com.example.digest', true)
|
||||
await manager.revokePermission('com.example.digest', 'notifications.create')
|
||||
expect(() =>
|
||||
manager.createNotification('com.example.digest', { title: '无权限' })
|
||||
).toThrowError(/notifications\.create/)
|
||||
|
||||
// 重新授权后正常写入,并支持 dedupeKey 去重。
|
||||
await manager.grantPermissions('com.example.digest', ['notifications.create'])
|
||||
await manager.setEnabled('com.example.bot', true)
|
||||
|
||||
const first = manager.createNotification('com.example.digest', {
|
||||
title: '今日晨报已生成',
|
||||
body: '覆盖 3 个群聊',
|
||||
level: 'success',
|
||||
dedupeKey: 'morning-2026-12-01'
|
||||
})
|
||||
expect(first.deduped).toBe(false)
|
||||
|
||||
const duplicate = manager.createNotification('com.example.digest', {
|
||||
title: '今日晨报已更新',
|
||||
body: '覆盖 4 个群聊',
|
||||
level: 'info',
|
||||
dedupeKey: 'morning-2026-12-01'
|
||||
})
|
||||
expect(duplicate.deduped).toBe(true)
|
||||
expect(duplicate.id).toBe(first.id)
|
||||
expect(manager.listNotifications('com.example.digest')).toHaveLength(1)
|
||||
expect(manager.listNotifications('com.example.digest')[0].title).toBe('今日晨报已更新')
|
||||
|
||||
// 另一个扩展使用相同 dedupeKey 不会跨扩展碰撞。
|
||||
const other = manager.createNotification('com.example.bot', {
|
||||
title: '机器人提醒',
|
||||
level: 'warning',
|
||||
dedupeKey: 'morning-2026-12-01'
|
||||
})
|
||||
expect(other.deduped).toBe(false)
|
||||
|
||||
// 固定 digest 到一级菜单后,digest 的未读在 unreadByExtension,而 bot 的未读聚合到 unpinnedUnread。
|
||||
manager.pinNavigation('com.example.digest')
|
||||
const summary = manager.getNotificationSummary()
|
||||
expect(summary.totalUnread).toBe(2)
|
||||
expect(summary.unpinnedUnread).toBe(1)
|
||||
expect(summary.unreadByExtension['com.example.digest']).toBe(1)
|
||||
expect(summary.unreadByExtension['com.example.bot']).toBe(1)
|
||||
|
||||
// 标记单条已读。
|
||||
expect(manager.markNotificationsRead({ id: first.id })).toBe(1)
|
||||
expect(manager.getNotificationSummary().totalUnread).toBe(1)
|
||||
|
||||
// 停用扩展后拒绝新通知。
|
||||
await manager.setEnabled('com.example.bot', false)
|
||||
expect(() =>
|
||||
manager.createNotification('com.example.bot', { title: '停用后新通知' })
|
||||
).toThrowError(/停用/)
|
||||
|
||||
await manager.dispose()
|
||||
|
||||
// 模拟重启恢复后通知与未读计数保持一致。
|
||||
const manager2 = makeManager(userData)
|
||||
await manager2.initialize()
|
||||
expect(manager2.listNotifications()).toHaveLength(2)
|
||||
expect(manager2.getNotificationSummary().unpinnedUnread).toBe(1)
|
||||
|
||||
// 卸载扩展后清理该扩展所有宿主通知状态。
|
||||
await manager2.uninstall('com.example.bot', true)
|
||||
expect(manager2.listNotifications('com.example.bot')).toEqual([])
|
||||
expect(manager2.getNotificationSummary().totalUnread).toBe(0)
|
||||
await manager2.dispose()
|
||||
})
|
||||
|
||||
it('单扩展高频写入触发防刷屏限频,且标记已读严格按扩展隔离', async () => {
|
||||
const root = makeTempDir()
|
||||
const userData = path.join(root, 'userData')
|
||||
const extA = path.join(root, 'ext-flood')
|
||||
const extB = path.join(root, 'ext-peer')
|
||||
writeExtension(extA, 'com.example.flood', '刷屏测试', ['notifications.create'])
|
||||
writeExtension(extB, 'com.example.peer', '相邻扩展', ['notifications.create'])
|
||||
const manager = makeManager(userData)
|
||||
await manager.initialize()
|
||||
await manager.installFromDirectory(extA)
|
||||
await manager.installFromDirectory(extB)
|
||||
await manager.setEnabled('com.example.flood', true)
|
||||
await manager.setEnabled('com.example.peer', true)
|
||||
|
||||
const peerNotice = manager.createNotification('com.example.peer', { title: 'B 扩展通知' })
|
||||
// 使用 flood 的 extensionId 尝试标记 peer 的通知已读不得生效。
|
||||
expect(
|
||||
manager.markNotificationsRead({ extensionId: 'com.example.flood', id: peerNotice.id })
|
||||
).toBe(0)
|
||||
expect(manager.listNotifications('com.example.peer')[0].read).toBe(false)
|
||||
|
||||
// 连续创建 20 条新通知成功,第 21 条触发 CONCURRENCY_LIMITED。
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
manager.createNotification('com.example.flood', { title: `通知 ${i}` })
|
||||
}
|
||||
expect(() =>
|
||||
manager.createNotification('com.example.flood', { title: '第 21 条刷屏通知' })
|
||||
).toThrowError(/过于频繁/)
|
||||
await manager.dispose()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
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 {
|
||||
buildExtensionPrivateMediaPreviewUrl,
|
||||
resolveExtensionProtocolFile
|
||||
} from '../../src/main/extensions/extension-protocol'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-ext-protocol-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop()
|
||||
if (dir) fs.removeSync(dir)
|
||||
}
|
||||
})
|
||||
|
||||
describe('extension-protocol 受控私有媒体预览', () => {
|
||||
it('仅放行本扩展 rendered/ 与 media-cache/ 下的白名单媒体文件,拒绝越界与敏感文件', async () => {
|
||||
const root = makeTempDir()
|
||||
const paths = createExtensionPaths(root)
|
||||
const extId = 'com.example.preview'
|
||||
const otherId = 'com.example.other'
|
||||
const extInstallDir = paths.installDir(extId)
|
||||
const extDataDir = paths.extensionDataDir(extId)
|
||||
const otherDataDir = paths.extensionDataDir(otherId)
|
||||
|
||||
fs.ensureDirSync(path.join(extInstallDir, 'ui'))
|
||||
fs.writeFileSync(path.join(extInstallDir, 'ui', 'index.html'), '<html></html>')
|
||||
fs.ensureDirSync(path.join(extDataDir, 'rendered'))
|
||||
fs.ensureDirSync(path.join(extDataDir, 'media-cache', 'acct1234', 'images'))
|
||||
fs.ensureDirSync(path.join(otherDataDir, 'rendered'))
|
||||
|
||||
const pngPath = path.join(extDataDir, 'rendered', 'digest.png')
|
||||
const cachedJpgPath = path.join(extDataDir, 'media-cache', 'acct1234', 'images', 'a.jpg')
|
||||
const storagePath = path.join(extDataDir, 'storage.json')
|
||||
const htmlInRendered = path.join(extDataDir, 'rendered', 'evil.html')
|
||||
const outsideSecret = path.join(root, 'secret.png')
|
||||
const symlinkInRendered = path.join(extDataDir, 'rendered', 'link.png')
|
||||
const otherPngPath = path.join(otherDataDir, 'rendered', 'other.png')
|
||||
|
||||
fs.writeFileSync(pngPath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]))
|
||||
fs.writeFileSync(cachedJpgPath, Buffer.from([0xff, 0xd8, 0xff, 0xe0]))
|
||||
fs.writeFileSync(storagePath, '{"token":"secret"}')
|
||||
fs.writeFileSync(htmlInRendered, '<script>alert(1)</script>')
|
||||
fs.writeFileSync(outsideSecret, Buffer.from([0x89, 0x50, 0x4e, 0x47, 9, 9]))
|
||||
fs.writeFileSync(otherPngPath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 7, 7]))
|
||||
fs.symlinkSync(outsideSecret, symlinkInRendered)
|
||||
|
||||
const deps = {
|
||||
paths,
|
||||
resolveRoot: (id: string) => (id === extId ? extInstallDir : null)
|
||||
}
|
||||
|
||||
const previewUrl = buildExtensionPrivateMediaPreviewUrl(extId, extDataDir, pngPath)
|
||||
expect(previewUrl).toBe(`tm-extension://${extId}/_data/rendered/digest.png`)
|
||||
const resolvedPng = await resolveExtensionProtocolFile(previewUrl!, deps)
|
||||
expect(resolvedPng).not.toBeNull()
|
||||
expect(resolvedPng?.contentType).toBe('image/png')
|
||||
expect(resolvedPng?.isPrivateMedia).toBe(true)
|
||||
expect(resolvedPng?.csp).toContain("default-src 'none'")
|
||||
|
||||
const cachedPreviewUrl = buildExtensionPrivateMediaPreviewUrl(extId, extDataDir, cachedJpgPath)
|
||||
expect(cachedPreviewUrl).toBe(`tm-extension://${extId}/_data/media-cache/acct1234/images/a.jpg`)
|
||||
const resolvedJpg = await resolveExtensionProtocolFile(cachedPreviewUrl!, deps)
|
||||
expect(resolvedJpg?.contentType).toBe('image/jpeg')
|
||||
|
||||
// 拒绝 storage.json 与非白名单后缀(如 html)。
|
||||
expect(buildExtensionPrivateMediaPreviewUrl(extId, extDataDir, storagePath)).toBeUndefined()
|
||||
expect(
|
||||
await resolveExtensionProtocolFile(`tm-extension://${extId}/_data/storage.json`, deps)
|
||||
).toBeNull()
|
||||
expect(
|
||||
await resolveExtensionProtocolFile(`tm-extension://${extId}/_data/rendered/evil.html`, deps)
|
||||
).toBeNull()
|
||||
|
||||
// 拒绝路径穿越、符号链接逃逸和未安装扩展访问。
|
||||
expect(
|
||||
await resolveExtensionProtocolFile(
|
||||
`tm-extension://${extId}/_data/rendered/../../secret.png`,
|
||||
deps
|
||||
)
|
||||
).toBeNull()
|
||||
expect(
|
||||
await resolveExtensionProtocolFile(`tm-extension://${extId}/_data/rendered/link.png`, deps)
|
||||
).toBeNull()
|
||||
expect(
|
||||
await resolveExtensionProtocolFile(`tm-extension://${otherId}/_data/rendered/other.png`, deps)
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -75,13 +75,14 @@ function record(overrides: Partial<ExtensionRegistryRecord>): ExtensionRegistryR
|
||||
}
|
||||
|
||||
describe('官方模板目录', () => {
|
||||
it('列出三个模板,未安装时状态为 not-installed', async () => {
|
||||
it('列出四个模板,未安装时状态为 not-installed', async () => {
|
||||
const { catalog } = setup()
|
||||
const list = await catalog.list()
|
||||
expect(list.map((item) => item.template.templateId).sort()).toEqual([
|
||||
'douyin-sender',
|
||||
'group-chat-bot',
|
||||
'keyword-bot'
|
||||
'keyword-bot',
|
||||
'morning-digest'
|
||||
])
|
||||
expect(list.every((item) => item.state === 'not-installed')).toBe(true)
|
||||
// 版本来自 manifest,不是硬编码。
|
||||
|
||||
@@ -39,7 +39,7 @@ function stageExamples(): { sourceRoot: string; lockFile: string } {
|
||||
}
|
||||
|
||||
describe('官方模板构建', () => {
|
||||
it('产出三个模板与索引,索引指向真实文件', () => {
|
||||
it('产出四个模板与索引,索引指向真实文件', () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
const outputDir = path.join(tempRoot(), 'out')
|
||||
const result = buildTemplates({ sourceRoot, outputDir, lockFile })
|
||||
@@ -47,11 +47,12 @@ describe('官方模板构建', () => {
|
||||
expect(result.templates.map((item) => item.templateId).sort()).toEqual([
|
||||
'douyin-sender',
|
||||
'group-chat-bot',
|
||||
'keyword-bot'
|
||||
'keyword-bot',
|
||||
'morning-digest'
|
||||
])
|
||||
const index = fs.readJsonSync(path.join(outputDir, 'index.json'))
|
||||
expect(index.version).toBe(1)
|
||||
expect(index.templates).toHaveLength(3)
|
||||
expect(index.templates).toHaveLength(4)
|
||||
for (const template of index.templates) {
|
||||
expect(fs.existsSync(path.join(outputDir, template.file))).toBe(true)
|
||||
expect(template.sha256).toMatch(/^[a-f0-9]{64}$/)
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
HtmlRenderService,
|
||||
STATIC_RENDER_CSP,
|
||||
assertSafeStaticHtml,
|
||||
buildIsolatedHtmlDocument,
|
||||
createDocumentIsolationHandler,
|
||||
type RenderWindowAdapter
|
||||
} from '../../src/main/services/html-render-service'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-html-render-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) fs.removeSync(dir)
|
||||
})
|
||||
|
||||
function createMockWindow(options: {
|
||||
width?: number
|
||||
height?: number
|
||||
pngBuffer?: Buffer
|
||||
delayMs?: number
|
||||
throwOnCapture?: Error
|
||||
} = {}) {
|
||||
let destroyed = false
|
||||
let contentSize: [number, number] = [options.width ?? 430, 800]
|
||||
let readyCallback: (() => void) | null = null
|
||||
let resizeCallback: (() => void) | null = null
|
||||
const loadedFiles: string[] = []
|
||||
let filterCleared = false
|
||||
let filterInstalled = false
|
||||
|
||||
const adapter: RenderWindowAdapter = {
|
||||
loadFile: vi.fn(async (filePath: string) => {
|
||||
loadedFiles.push(filePath)
|
||||
if (options.delayMs) {
|
||||
await new Promise((resolve) => setTimeout(resolve, options.delayMs))
|
||||
}
|
||||
readyCallback?.()
|
||||
}),
|
||||
onceReadyToShow: (cb) => {
|
||||
readyCallback = cb
|
||||
},
|
||||
onceResize: (cb) => {
|
||||
resizeCallback = cb
|
||||
},
|
||||
getContentSize: () => contentSize,
|
||||
setContentSize: (w, h) => {
|
||||
contentSize = [w, h]
|
||||
resizeCallback?.()
|
||||
},
|
||||
executeJavaScript: vi.fn(async (code: string) => {
|
||||
if (code.includes('scrollWidth')) {
|
||||
return { width: options.width ?? 430, height: options.height ?? 1280 }
|
||||
}
|
||||
return undefined
|
||||
}),
|
||||
capturePage: vi.fn(async () => {
|
||||
if (options.throwOnCapture) throw options.throwOnCapture
|
||||
return options.pngBuffer ?? Buffer.alloc(1500, 0x89)
|
||||
}),
|
||||
installRequestFilter: vi.fn(() => {
|
||||
filterInstalled = true
|
||||
}),
|
||||
clearRequestFilter: vi.fn(() => {
|
||||
filterCleared = true
|
||||
}),
|
||||
isDestroyed: () => destroyed,
|
||||
destroy: vi.fn(() => {
|
||||
destroyed = true
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
adapter,
|
||||
getState: () => ({ destroyed, loadedFiles, filterInstalled, filterCleared, contentSize })
|
||||
}
|
||||
}
|
||||
|
||||
describe('HtmlRenderService 通用渲染与安全隔离', () => {
|
||||
it('成功渲染静态 HTML/CSS 到扩展私有目录,注入严格 CSP 并清理临时 HTML', async () => {
|
||||
const root = makeTempDir()
|
||||
const tempDir = path.join(root, 'tmp-html')
|
||||
const extDataDir = path.join(root, 'extensions-data', 'com.example.digest')
|
||||
const mockWin = createMockWindow({ width: 520, height: 1400 })
|
||||
const partitions: string[] = []
|
||||
|
||||
const service = new HtmlRenderService({
|
||||
tempDir,
|
||||
createWindow: (opts) => {
|
||||
partitions.push(opts.partition)
|
||||
expect(opts.enforceStaticCsp).toBe(true)
|
||||
return mockWin.adapter
|
||||
}
|
||||
})
|
||||
|
||||
const result = await service.renderExtensionHtmlToPng({
|
||||
html: '<main><h1>晨报</h1><p>今日重点</p></main>',
|
||||
css: 'main { padding: 20px; }',
|
||||
extensionDataRoot: extDataDir,
|
||||
fileName: 'morning-2026-12-01.png',
|
||||
width: 520
|
||||
})
|
||||
|
||||
expect(result.mimeType).toBe('image/png')
|
||||
expect(result.width).toBe(520)
|
||||
expect(result.height).toBe(1400)
|
||||
expect(result.path).toBe(path.join(extDataDir, 'rendered', 'morning-2026-12-01.png'))
|
||||
expect(fs.existsSync(result.path)).toBe(true)
|
||||
expect(partitions[0]).toMatch(/^html-render-/)
|
||||
|
||||
const state = mockWin.getState()
|
||||
expect(state.destroyed).toBe(true)
|
||||
expect(state.filterInstalled).toBe(true)
|
||||
expect(state.filterCleared).toBe(true)
|
||||
// 临时 HTML 已被完整清理。
|
||||
expect(state.loadedFiles).toHaveLength(1)
|
||||
expect(fs.existsSync(state.loadedFiles[0])).toBe(false)
|
||||
|
||||
const doc = buildIsolatedHtmlDocument('<div>hi</div>', 'div{color:#111}')
|
||||
expect(doc).toContain(STATIC_RENDER_CSP)
|
||||
})
|
||||
|
||||
it('拒绝脚本、内联事件、iframe、meta refresh 与外部网络资源等恶意 HTML', () => {
|
||||
const maliciousCases = [
|
||||
'<script>alert(1)</script>',
|
||||
'<img src="data:image/png;base64,AA" onerror="fetch(1)">',
|
||||
'<iframe src="about:blank"></iframe>',
|
||||
'<a href="javascript:alert(1)">click</a>',
|
||||
'<meta http-equiv="refresh" content="0;url=https://example.com">',
|
||||
'<img src="https://example.com/pixel.png">',
|
||||
'<img src="file:///etc/passwd">'
|
||||
]
|
||||
for (const html of maliciousCases) {
|
||||
expect(() => assertSafeStaticHtml(html)).toThrowError()
|
||||
}
|
||||
expect(() =>
|
||||
assertSafeStaticHtml('<div>ok</div>', '@import url("https://example.com/a.css");')
|
||||
).toThrowError()
|
||||
expect(() =>
|
||||
assertSafeStaticHtml('<div>ok</div>', 'body { background: url(https://example.com/bg.png); }')
|
||||
).toThrowError()
|
||||
})
|
||||
|
||||
it('拒绝路径越界与符号链接逃逸,输出路径必须落在扩展私有目录内', async () => {
|
||||
const root = makeTempDir()
|
||||
const extDataDir = path.join(root, 'extensions-data', 'com.example.digest')
|
||||
const outsideDir = path.join(root, 'outside')
|
||||
fs.ensureDirSync(extDataDir)
|
||||
fs.ensureDirSync(outsideDir)
|
||||
|
||||
const service = new HtmlRenderService({
|
||||
tempDir: path.join(root, 'tmp'),
|
||||
createWindow: () => createMockWindow().adapter
|
||||
})
|
||||
|
||||
await expect(
|
||||
service.renderExtensionHtmlToPng({
|
||||
html: '<div>safe</div>',
|
||||
extensionDataRoot: extDataDir,
|
||||
fileName: '../escape.png'
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'EXTENSION_INVALID_PATH' })
|
||||
|
||||
await expect(
|
||||
service.renderExtensionHtmlToPng({
|
||||
html: '<div>safe</div>',
|
||||
extensionDataRoot: extDataDir,
|
||||
fileName: '/tmp/escape.png'
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'EXTENSION_INVALID_PATH' })
|
||||
|
||||
// 在扩展目录内放一个指向外部目录的符号链接,必须被 realpath 拦截。
|
||||
fs.symlinkSync(outsideDir, path.join(extDataDir, 'rendered'))
|
||||
await expect(
|
||||
service.renderExtensionHtmlToPng({
|
||||
html: '<div>safe</div>',
|
||||
extensionDataRoot: extDataDir,
|
||||
fileName: 'symlink-escape.png'
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'EXTENSION_INVALID_PATH' })
|
||||
})
|
||||
|
||||
it('网络隔离拦截器只放行当前单个 HTML 文件,拦截所有外链与其他本地文件', () => {
|
||||
const root = makeTempDir()
|
||||
const allowed = path.join(root, 'allowed.html')
|
||||
const other = path.join(root, 'other.html')
|
||||
const blocked: Array<{ url: string; reason: string }> = []
|
||||
const handler = createDocumentIsolationHandler(allowed, (details, reason) => {
|
||||
blocked.push({ url: details.url, reason })
|
||||
})
|
||||
|
||||
const runCheck = (url: string): boolean => {
|
||||
let canceled = false
|
||||
handler({ url, method: 'GET', resourceType: 'other' }, (res) => {
|
||||
canceled = res.cancel
|
||||
})
|
||||
return canceled
|
||||
}
|
||||
|
||||
expect(runCheck(pathToFileURL(allowed).href)).toBe(false)
|
||||
expect(runCheck(pathToFileURL(other).href)).toBe(true)
|
||||
expect(runCheck('https://example.com/a.png')).toBe(true)
|
||||
expect(runCheck('http://127.0.0.1:8080/api')).toBe(true)
|
||||
expect(runCheck('ws://127.0.0.1:9000')).toBe(true)
|
||||
expect(blocked).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('并发限制、超时与失败后完整销毁窗口并清理临时文件', async () => {
|
||||
const root = makeTempDir()
|
||||
const tempDir = path.join(root, 'tmp-cleanup')
|
||||
const extDataDir = path.join(root, 'extensions-data', 'com.example.digest')
|
||||
const slowWin = createMockWindow({ delayMs: 800 })
|
||||
|
||||
const service = new HtmlRenderService({
|
||||
tempDir,
|
||||
maxConcurrent: 1,
|
||||
createWindow: () => slowWin.adapter
|
||||
})
|
||||
|
||||
const first = service.renderExtensionHtmlToPng({
|
||||
html: '<div>slow</div>',
|
||||
extensionDataRoot: extDataDir,
|
||||
timeoutMs: 500
|
||||
})
|
||||
|
||||
// 等待第一个任务进入 renderFileToPng 占用并发槽。
|
||||
await new Promise((resolve) => setTimeout(resolve, 40))
|
||||
|
||||
// 第二个并发渲染必须立即被拒绝。
|
||||
await expect(
|
||||
service.renderExtensionHtmlToPng({
|
||||
html: '<div>second</div>',
|
||||
extensionDataRoot: extDataDir
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'CONCURRENCY_LIMITED' })
|
||||
|
||||
// 第一个超时后必须销毁窗口并清理临时 HTML,且释放并发槽。
|
||||
await expect(first).rejects.toMatchObject({ code: 'ACTION_TIMEOUT' })
|
||||
expect(slowWin.getState().destroyed).toBe(true)
|
||||
expect(service.activeRenders).toBe(0)
|
||||
expect(fs.readdirSync(tempDir)).toEqual([])
|
||||
|
||||
// 超过 PNG 体积上限时拒绝且不残留输出文件。
|
||||
const hugeService = new HtmlRenderService({
|
||||
tempDir,
|
||||
maxPngBytes: 1024,
|
||||
createWindow: () => createMockWindow({ pngBuffer: Buffer.alloc(2048, 0x89) }).adapter
|
||||
})
|
||||
await expect(
|
||||
hugeService.renderExtensionHtmlToPng({
|
||||
html: '<div>huge</div>',
|
||||
extensionDataRoot: extDataDir,
|
||||
fileName: 'huge.png'
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'STORAGE_LIMIT_EXCEEDED' })
|
||||
expect(fs.existsSync(path.join(extDataDir, 'rendered', 'huge.png'))).toBe(false)
|
||||
})
|
||||
|
||||
it('阻断 srcset/xlink:href/style 逃逸并解析真实 PNG IHDR 像素尺寸', async () => {
|
||||
expect(() => assertSafeStaticHtml('<img srcset="https://evil.example/a.png 2x">')).toThrowError(
|
||||
/外部网络/
|
||||
)
|
||||
expect(() =>
|
||||
assertSafeStaticHtml('<svg><image xlink:href="https://evil.example/b.png"/></svg>')
|
||||
).toThrowError(/外部网络/)
|
||||
expect(() => assertSafeStaticHtml('<div>ok</div>', 'body{}</style><div>x</div>')).toThrowError(
|
||||
/style/
|
||||
)
|
||||
|
||||
// 构造带合法 IHDR(860x1600)的 2x Retina PNG 头,校验 pixelWidth/pixelHeight/deviceScaleFactor。
|
||||
const pngHeader = Buffer.alloc(160, 0)
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(pngHeader, 0)
|
||||
pngHeader.writeUInt32BE(860, 16)
|
||||
pngHeader.writeUInt32BE(1600, 20)
|
||||
|
||||
const root = makeTempDir()
|
||||
const service = new HtmlRenderService({
|
||||
tempDir: path.join(root, 'tmp'),
|
||||
createWindow: () => createMockWindow({ width: 430, height: 800, pngBuffer: pngHeader }).adapter
|
||||
})
|
||||
const res = await service.renderExtensionHtmlToPng({
|
||||
html: '<div>retina</div>',
|
||||
width: 430,
|
||||
extensionDataRoot: path.join(root, 'extensions-data', 'com.example.retina')
|
||||
})
|
||||
expect(res.width).toBe(430)
|
||||
expect(res.height).toBe(800)
|
||||
expect(res.pixelWidth).toBe(860)
|
||||
expect(res.pixelHeight).toBe(1600)
|
||||
expect(res.deviceScaleFactor).toBe(2)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user