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
@@ -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