232 lines
13 KiB
JavaScript
232 lines
13 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, chromium } from 'playwright'
|
|
import electron from 'electron'
|
|
|
|
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
|
|
const work = (page) => page.getByRole('navigation', { name: '工作区' })
|
|
const testUser = () => 'qa_' + randomBytes(6).toString('hex')
|
|
|
|
async function login(page, username, password, register) {
|
|
if (register) 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 enable(page) {
|
|
await page.getByRole('button', { name: '启用本机加密聊天' }).click()
|
|
await page.locator('.security-code').waitFor({ timeout: 10_000 })
|
|
return page.locator('.security-code').textContent()
|
|
}
|
|
|
|
async function trust(page, code) {
|
|
await page.getByLabel('对方安全码').fill(code)
|
|
await page.getByRole('button', { name: '核验设备' }).click()
|
|
await page.getByText('设备已验证').waitFor()
|
|
}
|
|
|
|
async function send(page, text) {
|
|
await page.getByRole('textbox', { name: '消息', exact: true }).fill(text)
|
|
await page.getByRole('button', { name: '发送', exact: true }).click()
|
|
try {
|
|
await page.getByText(text, { exact: true }).waitFor({ timeout: 10_000 })
|
|
} catch (error) {
|
|
throw new Error(JSON.stringify(await page.locator('[role=alert]').allTextContents()), { cause: error })
|
|
}
|
|
}
|
|
|
|
test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢复', { timeout: 90000 }, async () => {
|
|
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
|
|
const profile = await mkdtemp(join(tmpdir(), 'xhchat-mls-test-'))
|
|
let desktop
|
|
try {
|
|
const web = await browser.newPage({ acceptDownloads: true })
|
|
await web.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()
|
|
const clientErrors = []
|
|
for (const [label, page] of [['web', web], ['windows', windows]]) {
|
|
page.on('pageerror', (error) => clientErrors.push(label + ': ' + error.message))
|
|
page.on('console', (message) => { if (message.type() === 'error') clientErrors.push(label + ': ' + message.text()) })
|
|
}
|
|
const a = testUser(), b = testUser()
|
|
const password = randomBytes(24).toString('hex')
|
|
await login(web, a, password, true)
|
|
await login(windows, b, password, true)
|
|
await work(web).getByRole('link', { name: '联系人' }).click()
|
|
await work(windows).getByRole('link', { name: '联系人' }).click()
|
|
await web.getByLabel('按用户名查找').fill(b)
|
|
await web.getByRole('button', { name: '查找' }).click()
|
|
await web.getByRole('button', { name: '添加好友' }).click()
|
|
await windows.getByRole('button', { name: new RegExp(a) }).click()
|
|
await windows.getByRole('button', { name: '接受申请' }).click()
|
|
await web.getByRole('link', { name: '打开加密聊天' }).waitFor()
|
|
await work(web).getByRole('link', { name: '消息', exact: true }).click()
|
|
const conversation = web.getByRole('complementary', { name: '会话列表' })
|
|
await conversation.getByRole('link', { name: b }).waitFor()
|
|
await web.getByLabel('查找会话').fill('没有匹配')
|
|
await web.getByText('没有匹配的会话。').waitFor()
|
|
await web.getByLabel('查找会话').clear()
|
|
await conversation.getByRole('link', { name: b }).click()
|
|
await windows.getByRole('link', { name: '打开加密聊天' }).click()
|
|
const windowsChat = windows.url()
|
|
let webCode, desktopCode
|
|
try {
|
|
;[webCode, desktopCode] = await Promise.all([enable(web), enable(windows)])
|
|
} catch (error) {
|
|
throw new Error(JSON.stringify({ web: await web.locator('[role=alert]').allTextContents(), windows: await windows.locator('[role=alert]').allTextContents(), clientErrors }), { cause: error })
|
|
}
|
|
assert.match(webCode, /^[0-9a-f]{64}$/)
|
|
assert.match(desktopCode, /^[0-9a-f]{64}$/)
|
|
assert.notEqual(webCode, desktopCode)
|
|
await web.getByRole('button', { name: '刷新' }).click()
|
|
await windows.getByRole('button', { name: '刷新' }).click()
|
|
await web.getByLabel('对方安全码').fill('0'.repeat(64))
|
|
await web.getByRole('button', { name: '核验设备' }).click()
|
|
await web.getByText('安全码不匹配').waitFor()
|
|
assert.equal(await web.getByRole('button', { name: '发送', exact: true }).count(), 0)
|
|
await trust(web, desktopCode)
|
|
await trust(windows, webCode)
|
|
|
|
const text = 'Web 到 Windows ' + randomBytes(8).toString('hex')
|
|
const packets = []
|
|
web.on('request', (req) => {
|
|
if (req.method() === 'POST' && req.url().endsWith('/api/v1/inbox')) packets.push(req.postDataJSON())
|
|
})
|
|
await send(web, text)
|
|
const packet = packets.find((entry) => Buffer.from(entry.ciphertext, 'base64')[3] === 2)
|
|
assert.ok(packet)
|
|
assert.ok(!Buffer.from(packet.ciphertext, 'base64').includes(Buffer.from(text)))
|
|
assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice'])
|
|
await windows.getByText(text, { exact: true }).waitFor()
|
|
const sentLine = web.getByRole('listitem').filter({ hasText: text })
|
|
assert.equal(await sentLine.getByText('已读', { exact: true }).count(), 0)
|
|
assert.equal(await windows.getByLabel('发送已读回执').isChecked(), false)
|
|
const receiptPackets = []
|
|
windows.on('request', (req) => {
|
|
if (req.method() === 'POST' && req.url().endsWith('/api/v1/inbox')) receiptPackets.push(req.postDataJSON())
|
|
})
|
|
await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].focus())
|
|
await windows.getByLabel('发送已读回执').check()
|
|
await sentLine.getByText('已读', { exact: true }).waitFor({ timeout: 15_000 })
|
|
assert.ok(receiptPackets.length > 0)
|
|
assert.ok(receiptPackets.every((item) => !JSON.stringify(item).includes(packet.messageId)))
|
|
const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex')
|
|
await windows.getByRole('listitem').filter({ hasText: text }).getByRole('button', { name: '引用', exact: true }).click()
|
|
await send(windows, reply)
|
|
await web.getByText(reply, { exact: true }).waitFor()
|
|
await web.getByRole('listitem').filter({ hasText: reply }).locator('blockquote').getByText(text, { exact: true }).waitFor()
|
|
assert.equal(await web.getByRole('listitem').filter({ hasText: reply }).getByRole('button', { name: '编辑', exact: true }).count(), 0)
|
|
const edited = '编辑后 ' + randomBytes(8).toString('hex')
|
|
await windows.getByRole('listitem').filter({ hasText: reply }).getByRole('button', { name: '编辑', exact: true }).click()
|
|
await windows.getByRole('textbox', { name: '消息', exact: true }).fill(edited)
|
|
await windows.getByRole('button', { name: '保存编辑', exact: true }).click()
|
|
await web.getByRole('listitem').filter({ hasText: edited }).getByText('已编辑', { exact: true }).waitFor()
|
|
await windows.getByRole('listitem').filter({ hasText: edited }).getByRole('button', { name: '撤回', exact: true }).click()
|
|
await windows.getByRole('button', { name: '确认撤回', exact: true }).click()
|
|
await web.getByText('消息已撤回', { exact: true }).waitFor()
|
|
assert.equal(await web.getByText(edited, { exact: true }).count(), 0)
|
|
const original = web.getByRole('listitem').filter({ has: web.getByText(text, { exact: true }) }).filter({ hasNot: web.locator('blockquote') })
|
|
await original.getByRole('button', { name: '收藏', exact: true }).click()
|
|
await original.getByRole('button', { name: '取消收藏' }).waitFor()
|
|
await web.getByLabel('只看收藏').check()
|
|
assert.equal(await web.getByRole('listitem').count(), 1)
|
|
await web.getByLabel('搜索本机消息').fill('无匹配的搜索词')
|
|
await web.getByText('没有匹配的消息。').waitFor()
|
|
await web.getByLabel('搜索本机消息').clear()
|
|
await web.getByLabel('只看收藏').uncheck()
|
|
await original.getByRole('button', { name: '本机删除' }).click()
|
|
await web.getByRole('button', { name: '确认删除' }).click()
|
|
await original.waitFor({ state: 'detached' })
|
|
await windows.getByRole('listitem').filter({ hasText: text }).filter({ hasNot: windows.locator('blockquote') }).waitFor()
|
|
|
|
const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex'))
|
|
const fileName = '跨端验收.txt'
|
|
const upload = windows.waitForRequest((req) => req.method() === 'POST' && req.url().includes('/api/v1/attachments/'))
|
|
await windows.locator('input[type=file]').setInputFiles({ name: fileName, mimeType: 'text/plain', buffer: contents })
|
|
const fileRequest = await upload
|
|
const uploaded = fileRequest.postDataBuffer()
|
|
assert.ok(uploaded)
|
|
assert.equal(uploaded.length, contents.length + 16)
|
|
assert.ok(!uploaded.includes(contents))
|
|
assert.ok(!fileRequest.url().includes(encodeURIComponent(fileName)))
|
|
const fileButton = web.getByRole('button', { name: '下载 ' + fileName, exact: true })
|
|
await fileButton.waitFor()
|
|
const fileURL = new URL(fileRequest.url())
|
|
await web.route(fileURL.origin + fileURL.pathname, async (route) => {
|
|
const response = await route.fetch()
|
|
const corrupted = await response.body()
|
|
corrupted[0] ^= 1
|
|
await route.fulfill({ response, body: corrupted })
|
|
}, { times: 1 })
|
|
await fileButton.click()
|
|
await web.getByText('附件完整性校验失败').waitFor()
|
|
const downloaded = web.waitForEvent('download')
|
|
await fileButton.click()
|
|
const file = await downloaded
|
|
assert.equal(file.suggestedFilename(), fileName)
|
|
assert.deepEqual(await readFile(await file.path()), contents)
|
|
const forwardedRequest = web.waitForRequest((req) => req.method() === 'POST' && req.url().includes('/api/v1/attachments/'))
|
|
await web.getByRole('listitem').filter({ hasText: fileName }).getByRole('button', { name: '转发', exact: true }).click()
|
|
await web.getByLabel('转发给').selectOption({ label: b })
|
|
await web.getByRole('button', { name: '确认转发' }).click()
|
|
const forwarded = await forwardedRequest
|
|
assert.notEqual(new URL(forwarded.url()).pathname, fileURL.pathname)
|
|
assert.notDeepEqual(forwarded.postDataBuffer(), uploaded)
|
|
await windows.getByRole('button', { name: '下载 ' + fileName, exact: true }).nth(1).waitFor()
|
|
|
|
await windows.getByRole('button', { name: '退出登录' }).click()
|
|
await windows.getByRole('heading', { name: '登录 XHChat' }).waitFor()
|
|
const offline = '离线补拉 ' + randomBytes(8).toString('hex')
|
|
await send(web, offline)
|
|
await login(windows, b, password, false)
|
|
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
|
|
assert.equal(await enable(windows), desktopCode)
|
|
await windows.getByText(offline, { exact: true }).waitFor()
|
|
const stored = await windows.evaluate(async () => {
|
|
const db = await new Promise((resolve, reject) => {
|
|
const request = indexedDB.open('xhchat-encrypted-chat', 1)
|
|
request.onsuccess = () => resolve(request.result)
|
|
request.onerror = () => reject(request.error)
|
|
})
|
|
try {
|
|
return await new Promise((resolve, reject) => {
|
|
const request = db.transaction('vaults').objectStore('vaults').getAll()
|
|
request.onsuccess = () => resolve(request.result.map((value) => ({
|
|
wrapped: typeof value.key === 'string',
|
|
encrypted: value.sealed instanceof ArrayBuffer && value.sealed.byteLength > 0,
|
|
fields: Object.keys(value).sort(),
|
|
})))
|
|
request.onerror = () => reject(request.error)
|
|
})
|
|
} finally { db.close() }
|
|
})
|
|
assert.deepEqual(stored, [{ wrapped: true, encrypted: true, fields: ['iv', 'key', 'sealed'] }])
|
|
const link = base + '/healthz'
|
|
await send(web, link)
|
|
const webLink = web.getByRole('link', { name: link, exact: true })
|
|
assert.equal(await webLink.getAttribute('href'), link)
|
|
assert.equal(await webLink.getAttribute('rel'), 'noopener noreferrer')
|
|
const windowOpened = desktop.waitForEvent('window')
|
|
await windows.getByRole('button', { name: link, exact: true }).click()
|
|
const toolbar = await windowOpened
|
|
const address = toolbar.getByRole('textbox', { name: '网址或搜索关键词' })
|
|
await toolbar.waitForFunction((expected) => document.querySelector('#address')?.value === expected, link)
|
|
assert.equal(await address.inputValue(), link)
|
|
} finally {
|
|
await desktop?.close()
|
|
await browser.close()
|
|
await rm(profile, { recursive: true, maxRetries: 5, retryDelay: 200, force: true })
|
|
}
|
|
})
|