mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 17:25:15 +08:00
561 lines
22 KiB
TypeScript
561 lines
22 KiB
TypeScript
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' })
|
|
})
|
|
})
|