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, '--use-fake-device-for-media-stream'], 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) const packageRefill = windows.waitForResponse((response) => response.request().method() === 'POST' && response.url().endsWith('/api/v1/key-packages') && response.status() === 204) 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 pin = web.getByRole('button', { name: '会话置顶', exact: true }) await pin.click() await conversation.getByText('已置顶', { exact: true }).waitFor() assert.equal(await pin.getAttribute('aria-pressed'), 'true') assert.equal(await windows.getByRole('button', { name: '会话置顶' }).getAttribute('aria-pressed'), 'false') 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() await packageRefill 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) => item.silent === true)) 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: '录制语音', exact: true }).click() await windows.getByRole('button', { name: '发送语音', exact: true }).waitFor() await windows.getByText(/录音中 1 \/ 60 秒/).waitFor() await windows.getByRole('button', { name: '发送语音', exact: true }).click() await web.getByRole('button', { name: '播放语音', exact: true }).click() await web.waitForFunction(() => { const audio = document.querySelector('audio') return audio && audio.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && audio.currentTime > 0 }) const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jf2sAAAAASUVORK5CYII=', 'base64') await web.locator('input[type=file]').setInputFiles({ name: '加密预览.png', mimeType: 'image/png', buffer: pixel }) await windows.getByRole('button', { name: '预览 加密预览.png' }).click() const image = windows.getByRole('img', { name: '加密预览.png' }) await image.waitFor() await windows.waitForFunction(() => document.querySelector('img[alt="加密预览.png"]')?.naturalWidth === 1) assert.match(await image.getAttribute('src'), /^blob:/) await windows.getByRole('button', { name: '关闭预览' }).click() assert.equal(await image.count(), 0) 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 systemToggle = (page) => page.getByRole('button', { name: '消息系统通知', exact: true }) const privateNotice = (page) => page.getByRole('link', { name: '有新的私聊消息', exact: true }) const muteToggle = (page) => page.getByRole('button', { name: '消息免打扰', exact: true }) await desktop.evaluate(({ Notification }) => { const nativeShow = Notification.prototype.show globalThis.privateNotificationLog = [] Notification.prototype.show = function () { globalThis.privateNotificationLog.push({ title: this.title, body: this.body }) return nativeShow.call(this) } }) await systemToggle(windows).click() await windows.getByText('已在本设备启用消息系统通知', { exact: true }).waitFor() await work(windows).getByRole('link', { name: '设备管理' }).click() const desktopNoticeText = 'Windows 后台私聊 ' + randomBytes(8).toString('hex') await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].minimize()) try { await send(web, desktopNoticeText) const toast = await desktop.evaluate(async () => { for (let attempt = 0; attempt < 30 && !globalThis.privateNotificationLog.length; attempt++) { await new Promise((resolve) => setTimeout(resolve, 150)) } return globalThis.privateNotificationLog[0] }) assert.deepEqual(toast, { title: 'XHChat', body: '有新的私聊消息' }) } finally { await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].restore()) } await privateNotice(windows).click() await windows.waitForURL(windowsChat) await enable(windows) await windows.getByText(desktopNoticeText, { exact: true }).waitFor() assert.equal(await systemToggle(web).getAttribute('aria-pressed'), 'false') await web.context().grantPermissions(['notifications'], { origin: base }) await web.evaluate(() => { const BrowserNotification = window.Notification window.privateNotificationLog = [] window.Notification = class extends BrowserNotification { constructor(title, options) { super(title, options) window.privateNotificationLog.push({ title, body: options.body, tag: options.tag }) } } document.hasFocus = () => false }) await systemToggle(web).click() await web.getByText('已在本设备启用消息系统通知', { exact: true }).waitFor() const webChat = web.url() await work(web).getByRole('link', { name: '设备管理' }).click() const webNoticeText = 'Edge 后台私聊 ' + randomBytes(8).toString('hex') await send(windows, webNoticeText) await privateNotice(web).waitFor() await web.waitForFunction(() => window.privateNotificationLog.length === 1) assert.deepEqual(await web.evaluate(() => window.privateNotificationLog[0]), { title: 'XHChat', body: '有新的私聊消息', tag: 'xhchat-private' }) await privateNotice(web).click() await web.waitForURL(webChat) await enable(web) await web.getByText(webNoticeText, { exact: true }).waitFor() await conversation.getByText('已置顶', { exact: true }).waitFor() await pin.click() await conversation.getByText('已置顶', { exact: true }).waitFor({ state: 'detached' }) await conversation.locator('.unread-badge').waitFor() await web.evaluate(() => { document.hasFocus = () => true; window.dispatchEvent(new Event('focus')) }) await conversation.locator('.unread-badge').waitFor({ state: 'detached' }) await muteToggle(web).click() await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor() assert.equal(await muteToggle(windows).getAttribute('aria-pressed'), 'false') await work(web).getByRole('link', { name: '联系人' }).click() await web.getByRole('button', { name: new RegExp(b) }).click() await web.getByRole('button', { name: '消息免打扰', pressed: true }).waitFor() const mutedText = '免打扰仍能同步 ' + randomBytes(8).toString('hex') await send(windows, mutedText) await work(web).getByRole('link', { name: '消息', exact: true }).click() const badge = conversation.getByRole('link', { name: new RegExp(b) }).locator('.unread-badge.muted') await badge.waitFor() assert.equal(await badge.locator('.unread-label').textContent(), '1 条未读') await work(web).getByRole('link', { name: '联系人' }).click() await web.getByRole('button', { name: new RegExp(b) }).click() await web.getByRole('link', { name: '打开加密聊天' }).click() await enable(web) await web.getByText(mutedText, { exact: true }).waitFor() await badge.waitFor({ state: 'detached' }) assert.equal(await privateNotice(web).count(), 0) assert.equal(await web.evaluate(() => window.privateNotificationLog.length), 1) 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 }) } })