333 lines
19 KiB
JavaScript
333 lines
19 KiB
JavaScript
import assert from 'node:assert/strict'
|
|
import { randomBytes } from 'node:crypto'
|
|
import { mkdtemp, readFile, rm } from 'node:fs/promises'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import test from 'node:test'
|
|
import electron from 'electron'
|
|
import { _electron, chromium } from 'playwright'
|
|
|
|
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
|
|
const work = (page) => page.getByRole('navigation', { name: '工作区' })
|
|
const chat = (page) => page.getByRole('region', { name: '群消息' })
|
|
const id = () => randomBytes(6).toString('hex')
|
|
|
|
async function register(page, username, password) {
|
|
await page.getByRole('button', { name: '注册', exact: true }).click()
|
|
await page.getByLabel('用户名').fill(username)
|
|
await page.getByLabel('密码', { exact: true }).fill(password)
|
|
const registration = page.waitForResponse((item) => item.url().endsWith('/auth/register') && item.status() === 201)
|
|
await page.locator('button.primary').click()
|
|
await page.getByText('实时连接已建立').waitFor()
|
|
return (await registration).json()
|
|
}
|
|
|
|
async function connect(owner, member, ownerName, memberName) {
|
|
await work(owner).getByRole('link', { name: '联系人' }).click()
|
|
await work(member).getByRole('link', { name: '联系人' }).click()
|
|
await owner.getByLabel('按用户名查找').fill(memberName)
|
|
await owner.getByRole('button', { name: '查找' }).click()
|
|
await owner.getByRole('button', { name: '添加好友' }).click()
|
|
await member.getByRole('button', { name: new RegExp(ownerName) }).click()
|
|
await member.getByRole('button', { name: '接受申请' }).click()
|
|
await owner.getByRole('link', { name: '打开加密聊天' }).waitFor()
|
|
}
|
|
|
|
async function invite(owner, member, memberName, group) {
|
|
await owner.getByLabel('邀请联系人').selectOption({ label: memberName })
|
|
await owner.getByRole('button', { name: '发送邀请' }).click()
|
|
await work(member).getByRole('link', { name: '群组' }).click()
|
|
await member.getByRole('link', { name: new RegExp(group) }).click()
|
|
await member.getByRole('button', { name: '接受邀请' }).click()
|
|
await chat(member).getByRole('button', { name: '启用本机群聊' }).waitFor()
|
|
}
|
|
|
|
async function verify(page, name, code) {
|
|
const section = chat(page).locator('.group-device-member').filter({ hasText: name })
|
|
const securityCode = section.getByLabel(new RegExp(name + '.*安全码'))
|
|
await securityCode.fill(code)
|
|
await section.getByRole('button', { name: '核验设备' }).click()
|
|
await securityCode.waitFor({ state: 'detached' })
|
|
}
|
|
|
|
async function publish(owner, pages) {
|
|
await chat(owner).getByRole('button', { name: '建立群加密会话' }).click()
|
|
await Promise.all(pages.map((page) => chat(page).getByText('群加密已建立', { exact: true }).waitFor()))
|
|
}
|
|
|
|
async function send(sender, text, action = '发送群消息') {
|
|
await chat(sender).getByRole('textbox', { name: '群消息' }).fill(text)
|
|
const response = sender.waitForResponse((item) => /\/groups\/[^/]+\/messages$/.test(item.url()) && item.request().method() === 'POST')
|
|
await chat(sender).getByRole('button', { name: action, exact: true }).click()
|
|
const sent = await response
|
|
assert.equal(sent.status(), 200, await sent.text())
|
|
const packet = sent.request().postDataJSON()
|
|
assert.deepEqual(Object.keys(packet).sort(), ['epoch', 'id', 'wire'])
|
|
const wire = Buffer.from(packet.wire, 'base64')
|
|
assert.equal(wire[3], 2)
|
|
assert.ok(!wire.includes(Buffer.from(text)))
|
|
return packet.epoch
|
|
}
|
|
|
|
async function sendFile(sender, name, mimeType, contents) {
|
|
const upload = sender.waitForResponse((item) => /\/groups\/[^/]+\/attachments\/[^/]+\?epoch=/.test(item.url()) && item.request().method() === 'POST')
|
|
const message = sender.waitForResponse((item) => /\/groups\/[^/]+\/messages$/.test(item.url()) && item.request().method() === 'POST')
|
|
await chat(sender).getByLabel('选择群附件').setInputFiles({ name, mimeType, buffer: contents })
|
|
await chat(sender).getByRole('button', { name: '发送群附件' }).click()
|
|
const uploaded = await upload
|
|
assert.equal(uploaded.status(), 204)
|
|
const sent = await message
|
|
assert.equal(sent.status(), 200, await sent.text())
|
|
const packet = sent.request().postDataJSON()
|
|
assert.match(new URL(uploaded.url()).pathname, new RegExp('/' + packet.attachmentId + '$'))
|
|
assert.ok(!Buffer.from(packet.wire, 'base64').includes(Buffer.from(name)))
|
|
}
|
|
|
|
async function sendVoice(sender) {
|
|
const response = sender.waitForResponse((item) => /\/groups\/[^/]+\/attachments\/[^/]+\?epoch=/.test(item.url()) &&
|
|
item.request().method() === 'POST' && item.status() === 204)
|
|
await chat(sender).getByRole('button', { name: '录制语音' }).click()
|
|
await chat(sender).getByText(/录音中 1 \/ 60 秒/).waitFor()
|
|
await chat(sender).getByRole('button', { name: '发送语音' }).click()
|
|
const path = new URL((await response).url()).pathname
|
|
return path
|
|
}
|
|
|
|
async function playVoice(page, sender, downloadPath) {
|
|
const message = chat(page).getByRole('listitem').filter({ hasText: sender }).filter({
|
|
has: page.getByRole('button', { name: '播放语音' }),
|
|
})
|
|
const download = page.waitForResponse((item) => item.url().endsWith(downloadPath) && item.request().method() === 'GET')
|
|
await message.getByRole('button', { name: '播放语音' }).click()
|
|
const response = await download
|
|
assert.equal(response.status(), 200)
|
|
const ciphertext = await response.body()
|
|
assert.ok(ciphertext.length > 16)
|
|
assert.notDeepEqual(ciphertext.subarray(0, 4), Buffer.from([0x1a, 0x45, 0xdf, 0xa3]))
|
|
const player = chat(page).getByRole('listitem').filter({ hasText: sender }).locator('audio[aria-label="语音消息"]')
|
|
await player.waitFor()
|
|
const src = await player.getAttribute('src')
|
|
await page.waitForFunction((url) => [...document.querySelectorAll('.group-chat audio')].some((item) =>
|
|
item.getAttribute('src') === url && item.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && item.currentTime > 0), src)
|
|
assert.match(src, /^blob:/)
|
|
await player.evaluate((element) => element.pause())
|
|
assert.equal(await player.evaluate((element) => element.paused), true)
|
|
}
|
|
|
|
test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员隔离', { timeout: 120_000 }, async () => {
|
|
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge', args: ['--use-fake-device-for-media-stream'] })
|
|
const profile = await mkdtemp(join(tmpdir(), 'xhchat-group-test-'))
|
|
let desktop
|
|
const pages = []
|
|
try {
|
|
const [owner, removed] = await Promise.all([browser.newPage(), browser.newPage()])
|
|
await owner.context().grantPermissions(['microphone'], { origin: base })
|
|
await Promise.all([owner.goto(base), removed.goto(base)])
|
|
desktop = await _electron.launch({
|
|
executablePath: electron,
|
|
args: [join(import.meta.dirname, '..', 'Desktop'), '--user-data-dir=' + profile, '--use-fake-device-for-media-stream'],
|
|
env: { ...process.env, XHCHAT_SERVER_URL: base },
|
|
})
|
|
const windows = await desktop.firstWindow()
|
|
pages.push(owner, windows, removed)
|
|
assert.equal(await windows.evaluate(async () => {
|
|
try { await window.xhchat.allowVoiceRecording(); return true } catch { return false }
|
|
}), false)
|
|
const names = pages.map(() => 'groupqa_' + id())
|
|
const password = randomBytes(24).toString('hex')
|
|
const [, , removedIdentity] = await Promise.all(pages.map((page, index) => register(page, names[index], password)))
|
|
await connect(owner, windows, names[0], names[1])
|
|
await connect(owner, removed, names[0], names[2])
|
|
await work(owner).getByRole('link', { name: '群组' }).click()
|
|
const group = '加密测试 ' + id()
|
|
await owner.getByLabel('群名称', { exact: true }).fill(group)
|
|
await owner.getByRole('button', { name: '创建群组' }).click()
|
|
await owner.getByRole('heading', { name: group }).waitFor()
|
|
await invite(owner, windows, names[1], group)
|
|
await invite(owner, removed, names[2], group)
|
|
const codes = await Promise.all(pages.map(async (page) => {
|
|
await chat(page).getByRole('button', { name: '启用本机群聊' }).click()
|
|
const code = page.locator('.group-security-code')
|
|
await code.waitFor()
|
|
return code.textContent()
|
|
}))
|
|
assert.ok(codes.every((code) => /^[0-9a-f]{64}$/.test(code)))
|
|
assert.equal(await chat(owner).getByRole('button', { name: '建立群加密会话' }).isEnabled(), false)
|
|
await verify(owner, names[1], codes[1])
|
|
await verify(owner, names[2], codes[2])
|
|
await publish(owner, [owner])
|
|
await chat(windows).getByText('请先核验名单内每台设备的安全码').waitFor()
|
|
assert.equal(await chat(windows).getByRole('button', { name: '发送群消息' }).count(), 0)
|
|
await Promise.all([verify(windows, names[0], codes[0]), verify(removed, names[0], codes[0])])
|
|
await Promise.all([verify(windows, names[2], codes[2]), verify(removed, names[1], codes[1])])
|
|
await Promise.all(pages.map((page) => chat(page).getByText('群加密已建立', { exact: true }).waitFor()))
|
|
const first = 'Windows 群消息 ' + id()
|
|
await work(removed).getByRole('link', { name: '联系人' }).click()
|
|
const epoch = await send(windows, first)
|
|
await Promise.all([owner, windows].map((page) => chat(page).getByText(first, { exact: true }).waitFor()))
|
|
await work(removed).getByRole('link', { name: '群组' }).click()
|
|
await removed.getByRole('link', { name: new RegExp(group) }).click()
|
|
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
|
|
await chat(removed).getByText(first, { exact: true }).waitFor()
|
|
|
|
const original = chat(owner).getByRole('listitem').filter({ hasText: first })
|
|
assert.equal(await original.getByRole('button', { name: '编辑', exact: true }).count(), 0)
|
|
assert.equal(await original.getByRole('button', { name: '撤回', exact: true }).count(), 0)
|
|
await original.getByRole('button', { name: '引用', exact: true }).click()
|
|
const reply = '加密引用回复 ' + id()
|
|
assert.equal(await send(owner, reply), epoch)
|
|
const receivedReply = chat(windows).getByRole('listitem').filter({ hasText: reply })
|
|
await receivedReply.locator('blockquote').getByText(first, { exact: true }).waitFor()
|
|
await work(removed).getByRole('link', { name: '联系人' }).click()
|
|
const own = chat(windows).getByRole('listitem').filter({ has: windows.getByText(first, { exact: true }) }).first()
|
|
await own.getByRole('button', { name: '编辑', exact: true }).click()
|
|
const edited = '已修改群消息 ' + id()
|
|
assert.equal(await send(windows, edited, '保存编辑'), epoch)
|
|
const incomingEdit = chat(owner).getByRole('listitem').filter({ has: owner.getByText(edited, { exact: true }) })
|
|
await incomingEdit.getByText('已编辑', { exact: true }).waitFor()
|
|
await work(removed).getByRole('link', { name: '群组' }).click()
|
|
await removed.getByRole('link', { name: new RegExp(group) }).click()
|
|
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
|
|
await chat(removed).getByText(edited, { exact: true }).waitFor()
|
|
|
|
const keyword = chat(owner).getByRole('searchbox', { name: '搜索本机群消息' })
|
|
const favorites = chat(owner).getByRole('checkbox', { name: '只看收藏' })
|
|
const searchedRequests = []
|
|
const trackSearch = (request) => searchedRequests.push({ url: request.url(), method: request.method() })
|
|
owner.on('request', trackSearch)
|
|
await keyword.fill(first.toUpperCase())
|
|
await chat(owner).getByRole('listitem').filter({ hasText: reply }).waitFor()
|
|
assert.equal(await incomingEdit.count(), 0)
|
|
await keyword.fill(edited)
|
|
await incomingEdit.getByRole('button', { name: '收藏', exact: true }).click()
|
|
await incomingEdit.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
|
|
await favorites.check()
|
|
assert.equal(await chat(owner).getByRole('listitem').count(), 1)
|
|
const unmatched = '没有匹配的验收关键词 ' + id()
|
|
await keyword.fill(unmatched)
|
|
await chat(owner).getByText('没有匹配的群消息。').waitFor()
|
|
owner.off('request', trackSearch)
|
|
assert.ok(searchedRequests.filter(({ url }) => url.includes('/groups/')).every(({ url, method }) =>
|
|
method === 'GET' && !/search|favorite/i.test(new URL(url).pathname) && !decodeURIComponent(url).includes(unmatched)))
|
|
await work(owner).getByRole('link', { name: '联系人' }).click()
|
|
await work(owner).getByRole('link', { name: '群组' }).click()
|
|
await owner.getByRole('link', { name: new RegExp(group) }).click()
|
|
await chat(owner).getByRole('button', { name: '启用本机群聊' }).click()
|
|
await favorites.check()
|
|
await incomingEdit.getByRole('button', { name: '取消收藏', exact: true }).click()
|
|
await chat(owner).getByText('没有匹配的群消息。').waitFor()
|
|
await favorites.uncheck()
|
|
assert.equal(await chat(windows).getByRole('listitem').filter({ hasText: edited })
|
|
.getByRole('button', { name: '取消收藏', exact: true }).count(), 0)
|
|
|
|
const temporary = '待撤回群消息 ' + id()
|
|
assert.equal(await send(windows, temporary), epoch)
|
|
const outgoing = chat(windows).getByRole('listitem').filter({ hasText: temporary })
|
|
await chat(owner).getByText(temporary, { exact: true }).waitFor()
|
|
const incoming = chat(owner).getByRole('listitem').filter({ hasText: temporary })
|
|
await incoming.getByRole('button', { name: '收藏', exact: true }).click()
|
|
await incoming.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
|
|
await outgoing.getByRole('button', { name: '撤回', exact: true }).click()
|
|
await chat(windows).getByRole('button', { name: '确认撤回' }).click()
|
|
for (const page of pages) {
|
|
await chat(page).getByText('消息已撤回', { exact: true }).waitFor()
|
|
assert.equal(await chat(page).getByText(temporary, { exact: true }).count(), 0)
|
|
}
|
|
await favorites.check()
|
|
await chat(owner).getByText('没有匹配的群消息。').waitFor()
|
|
await favorites.uncheck()
|
|
|
|
const contents = Buffer.from('Windows 群文件内容 ' + id() + '\n'.repeat(9000))
|
|
const filename = '群附件-' + id() + '.txt'
|
|
await sendFile(windows, filename, 'text/plain', contents)
|
|
await keyword.fill(filename.toUpperCase())
|
|
await chat(owner).getByRole('button', { name: '下载 ' + filename }).waitFor()
|
|
assert.equal(await chat(owner).getByRole('listitem').count(), 1)
|
|
await keyword.clear()
|
|
const fileDownload = owner.waitForEvent('download')
|
|
const fileResponse = owner.waitForResponse((item) => item.url().includes('/attachments/') && item.request().method() === 'GET')
|
|
await chat(owner).getByRole('button', { name: '下载 ' + filename }).click()
|
|
const response = await fileResponse
|
|
assert.equal(response.status(), 200)
|
|
const ciphertext = await response.body()
|
|
assert.equal(ciphertext.length, contents.length + 16)
|
|
assert.ok(!ciphertext.includes(contents.subarray(0, 24)))
|
|
const downloaded = await fileDownload
|
|
assert.equal(downloaded.suggestedFilename(), filename)
|
|
assert.deepEqual(await readFile(await downloaded.path()), contents)
|
|
|
|
await owner.route(response.url(), async (route) => {
|
|
const tampered = Buffer.from(ciphertext)
|
|
tampered[0] ^= 1
|
|
await route.fulfill({ status: 200, contentType: 'application/octet-stream', body: tampered })
|
|
}, { times: 1 })
|
|
await chat(owner).getByRole('button', { name: '下载 ' + filename }).click()
|
|
await chat(owner).getByRole('alert').getByText('附件完整性校验失败').waitFor()
|
|
|
|
const photo = '群图片-' + id() + '.png'
|
|
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX2sAAAAASUVORK5CYII=', 'base64')
|
|
await sendFile(owner, photo, 'image/png', pixel)
|
|
await chat(windows).getByRole('button', { name: '预览 ' + photo }).click()
|
|
const image = chat(windows).getByRole('img', { name: photo })
|
|
await image.evaluate((element) => element.decode())
|
|
assert.equal(await image.evaluate((element) => element.naturalWidth), 1)
|
|
await chat(windows).getByRole('button', { name: '关闭预览' }).click()
|
|
await image.waitFor({ state: 'detached' })
|
|
const photoLine = chat(owner).getByRole('listitem').filter({ hasText: photo })
|
|
assert.equal(await photoLine.getByRole('button', { name: '编辑', exact: true }).count(), 0)
|
|
await photoLine.getByRole('button', { name: '撤回', exact: true }).click()
|
|
await chat(owner).getByRole('button', { name: '确认撤回' }).click()
|
|
await chat(windows).getByRole('button', { name: '预览 ' + photo }).waitFor({ state: 'detached' })
|
|
|
|
const voiceUploads = []
|
|
windows.on('request', (request) => {
|
|
if (request.method() === 'POST' && request.url().includes('/attachments/')) voiceUploads.push(request.url())
|
|
})
|
|
await chat(windows).getByRole('button', { name: '录制语音' }).click()
|
|
await chat(windows).getByText(/录音中 1 \/ 60 秒/).waitFor()
|
|
await chat(windows).getByRole('button', { name: '取消录音' }).click()
|
|
const desktopVoice = await sendVoice(windows)
|
|
assert.equal(voiceUploads.length, 1)
|
|
await playVoice(owner, names[1], desktopVoice)
|
|
await playVoice(removed, names[1], desktopVoice)
|
|
const webVoice = await sendVoice(owner)
|
|
await playVoice(windows, names[0], webVoice)
|
|
|
|
await chat(windows).getByRole('button', { name: '录制语音' }).click()
|
|
await chat(windows).getByText(/录音中 1 \/ 60 秒/).waitFor()
|
|
const member = owner.getByRole('list', { name: '群成员' }).getByRole('listitem').filter({ hasText: names[2] })
|
|
await member.getByRole('button', { name: '移除成员' }).click()
|
|
await owner.getByRole('button', { name: '确认操作' }).click()
|
|
await removed.getByRole('heading', { name: group }).waitFor({ state: 'hidden' })
|
|
const fetchRemovedVoice = () => fetch(base + desktopVoice, { headers: { Authorization: 'Bearer ' + removedIdentity.token } })
|
|
assert.equal((await fetchRemovedVoice()).status, 404)
|
|
assert.equal((await fetch(base + '/api/v1/devices/' + removedIdentity.device.id, {
|
|
method: 'DELETE', headers: { Authorization: 'Bearer ' + removedIdentity.token },
|
|
})).status, 204)
|
|
assert.equal((await fetchRemovedVoice()).status, 401)
|
|
await chat(windows).getByText('等待群主建立群加密会话。').waitFor()
|
|
assert.equal(await chat(windows).getByRole('button', { name: '发送语音' }).count(), 0)
|
|
await publish(owner, [owner, windows])
|
|
assert.equal(voiceUploads.length, 1)
|
|
const second = '新世代 Web 群消息 ' + id()
|
|
assert.notEqual(await send(owner, second), epoch)
|
|
await chat(windows).getByText(second, { exact: true }).waitFor()
|
|
assert.equal(await removed.getByText(second, { exact: true }).count(), 0)
|
|
const history = chat(windows).getByRole('listitem').filter({ hasText: edited })
|
|
assert.equal(await history.count(), 1)
|
|
assert.equal(await history.getByRole('button', { name: '编辑', exact: true }).count(), 0)
|
|
await chat(windows).getByRole('searchbox', { name: '搜索本机群消息' }).fill(edited)
|
|
await history.getByRole('button', { name: '收藏', exact: true }).click()
|
|
await chat(windows).getByRole('checkbox', { name: '只看收藏' }).check()
|
|
await history.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
|
|
assert.equal(await chat(windows).getByRole('listitem').count(), 1)
|
|
} catch (error) {
|
|
const status = await Promise.all(pages.map((page) => page.locator('[role=alert], .group-chat [role=status]').allTextContents()))
|
|
throw new Error(JSON.stringify(status), { cause: error })
|
|
} finally {
|
|
await desktop?.close()
|
|
await browser.close()
|
|
await rm(profile, { recursive: true, force: true })
|
|
}
|
|
})
|