Files
XHChat/tests/group-chat.test.mjs
T

189 lines
10 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)
await page.locator('button.primary').click()
await page.getByText('实时连接已建立').waitFor()
}
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) {
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: '发送群消息' }).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)))
}
test('群聊跨 Windows 与 Web 加密投递文字和附件,移除成员后切换会话', { timeout: 120_000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
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 Promise.all([owner.goto(base), removed.goto(base)])
desktop = await _electron.launch({
executablePath: electron,
args: [join(import.meta.dirname, '..', 'Desktop'), '--user-data-dir=' + profile],
env: { ...process.env, XHCHAT_SERVER_URL: base },
})
const windows = await desktop.firstWindow()
pages.push(owner, windows, removed)
const names = pages.map(() => 'groupqa_' + id())
const password = randomBytes(24).toString('hex')
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 contents = Buffer.from('Windows 群文件内容 ' + id() + '\n'.repeat(9000))
const filename = '群附件-' + id() + '.txt'
await sendFile(windows, filename, 'text/plain', contents)
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 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' })
await chat(windows).getByText('等待群主建立群加密会话。').waitFor()
await publish(owner, [owner, windows])
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)
assert.equal(await chat(windows).getByText(first, { exact: true }).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 })
}
})