交付双端账号安全、外观设置和加密草稿

This commit is contained in:
xhgit committed 2026-11-17 12:56:04 +08:00
1 parent 961fd68f49
commit 752ba88c5c
22 files changed
+896 -38

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { mkdtemp, 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: '工作区' })
test('Windows 与 Web 修改密码和退出其他会话', { timeout: 45000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
const profile = await mkdtemp(join(tmpdir(), 'xhchat-security-'))
let desktop
try {
const web = await browser.newPage({ viewport: { width: 390, height: 844 } })
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 username = 'secure_' + randomBytes(6).toString('hex')
const password = randomBytes(24).toString('hex')
const nextPassword = randomBytes(24).toString('hex')
async function login(page, pass) {
await page.getByLabel('用户名').fill(username)
await page.getByLabel('密码', { exact: true }).fill(pass)
await page.locator('button.primary').click()
await page.getByText('实时连接已建立').waitFor()
}
await web.getByRole('button', { name: '注册', exact: true }).click()
await login(web,password)
await login(windows,password)
await windows.locator('.device-row').filter({ hasText: '当前设备' }).getByRole('button', { name:'重命名' }).click()
await windows.getByLabel('设备新名称').fill('工作电脑')
await windows.getByRole('button', { name:'保存设备名称' }).click()
await windows.getByText('工作电脑', { exact: true }).waitFor()
await work(web).getByRole('link', { name:'账号安全' }).click()
await web.getByRole('region', { name:'登录记录', exact: true }).getByText('Windows 电脑', { exact: true }).waitFor()
assert.equal(await web.evaluate(() => document.documentElement.scrollWidth), 390)
await web.getByRole('button', { name:'退出其他登录会话' }).click()
await web.getByRole('button', { name:'确认退出其他会话' }).click()
await windows.getByRole('heading', { name:'登录 XHChat' }).waitFor()
await web.getByText('其他登录会话已退出').waitFor()
await login(windows,password)
await windows.getByText('工作电脑', { exact: true }).waitFor()
await web.getByLabel('当前密码').fill(password)
await web.getByLabel('新密码', { exact: true }).fill(nextPassword)
await web.getByLabel('确认新密码').fill(nextPassword+'x')
await web.getByRole('button', { name:'修改密码并重新登录' }).click()
await web.getByText('两次输入的新密码不一致').waitFor()
await web.getByLabel('确认新密码').fill(nextPassword)
await web.getByRole('button', { name:'修改密码并重新登录' }).click()
await web.getByRole('heading', { name:'登录 XHChat' }).waitFor()
await windows.getByRole('heading', { name:'登录 XHChat' }).waitFor()
await login(windows,nextPassword)
await windows.getByText('工作电脑', { exact: true }).waitFor()
} finally {
await desktop?.close()
await browser.close()
await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 })
}
})
+45
View File
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import test from 'node:test'
import { chromium } from 'playwright'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
test('主题可手动选择、跟随系统并跨页面保存', { timeout: 30000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
try {
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, colorScheme: 'dark' })
const page = await context.newPage()
await page.goto(base)
await page.getByRole('button', { name: '注册', exact: true }).click()
await page.getByLabel('用户名').fill('theme_' + randomBytes(6).toString('hex'))
await page.getByLabel('密码', { exact: true }).fill(randomBytes(24).toString('hex'))
await page.getByRole('button', { name: '创建账号' }).click()
await page.getByText('实时连接已建立').waitFor()
await page.getByRole('navigation', { name: '工作区' }).getByRole('link', { name: '设置', exact: true }).click()
const scheme = () => page.evaluate(() => getComputedStyle(document.documentElement).colorScheme)
assert.equal(await scheme(), 'dark')
await page.getByLabel('外观', { exact: true }).selectOption('light')
await page.getByRole('button', { name: '保存设置' }).click()
await page.getByText('已保存本机设置').waitFor()
assert.equal(await scheme(), 'light')
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth), 390)
const sibling = await page.context().newPage()
await sibling.goto(base)
assert.equal(await sibling.evaluate(() => getComputedStyle(document.documentElement).colorScheme), 'light')
await page.getByLabel('外观', { exact: true }).selectOption('dark')
await page.getByRole('button', { name: '保存设置' }).click()
await sibling.waitForFunction(() => document.documentElement.dataset.theme === 'dark')
await page.getByLabel('外观', { exact: true }).selectOption('system')
await page.getByRole('button', { name: '保存设置' }).click()
await page.emulateMedia({ colorScheme: 'light' })
assert.equal(await scheme(), 'light')
await page.emulateMedia({ colorScheme: 'dark' })
assert.equal(await scheme(), 'dark')
await page.reload()
assert.equal(await scheme(), 'dark')
assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), 'system')
} finally {
await browser.close()
}
})
+32
View File
@@ -261,6 +261,10 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
await windows.getByRole('button', { name: '关闭预览' }).click()
assert.equal(await image.count(), 0)
const privateDraft = '重新登录恢复的私聊草稿 ' + randomBytes(8).toString('hex')
await windows.getByRole('textbox', { name: '消息', exact: true }).fill(privateDraft)
await windows.getByText('草稿已保存在本机', { exact: true }).waitFor()
assert.ok(!(await windows.evaluate(() => JSON.stringify(localStorage))).includes(privateDraft))
await windows.getByRole('button', { name: '退出登录' }).click()
await windows.getByRole('heading', { name: '登录 XHChat' }).waitFor()
const offline = '离线补拉 ' + randomBytes(8).toString('hex')
@@ -268,6 +272,9 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
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('已恢复本机草稿', { exact: true }).waitFor()
assert.equal(await windows.getByRole('textbox', { name: '消息', exact: true }).inputValue(), privateDraft)
await windows.getByRole('textbox', { name: '消息', exact: true }).clear()
await windows.getByText(offline, { exact: true }).waitFor()
const stored = await windows.evaluate(async () => {
const db = await new Promise((resolve, reject) => {
@@ -466,7 +473,32 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
await enable(windows)
await windows.getByRole('button', { name: '预览 加密预览.png', exact: true }).waitFor()
await windows.getByRole('button', { name: '播放语音', exact: true }).waitFor()
await work(windows).getByRole('link', { name: '设置', exact: true }).click()
await windows.getByLabel('消息发送方式', { exact: true }).selectOption('ctrl-enter')
await windows.getByRole('button', { name: '保存设置' }).click()
await windows.getByText('已保存本机设置').waitFor()
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
await enable(windows)
const composer = windows.getByRole('textbox', { name: '消息', exact: true })
const shortcutText = '快捷键验收 ' + randomBytes(8).toString('hex')
await composer.fill(shortcutText)
await composer.press('Enter')
assert.equal(await composer.inputValue(), shortcutText + '\n')
await composer.dispatchEvent('keydown', { key: 'Enter', ctrlKey: true, isComposing: true, bubbles: true, cancelable: true })
assert.equal(await windows.getByRole('list', { name: '消息记录' }).getByText(shortcutText, { exact: true }).count(), 0)
await composer.press('Control+Enter')
await web.getByRole('list', { name: '消息记录' }).getByText(shortcutText, { exact: true }).waitFor()
await work(windows).getByRole('link', { name: '联系人' }).click()
await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat)
await enable(windows)
await composer.fill('编辑时保留的草稿')
await windows.getByText('草稿已保存在本机', { exact: true }).waitFor()
await windows.getByRole('listitem').filter({ hasText: shortcutText }).getByRole('button', { name: '编辑', exact: true }).click()
await composer.fill('临时编辑内容')
await windows.getByRole('button', { name: '取消编辑' }).click()
assert.equal(await composer.inputValue(), '编辑时保留的草稿')
} finally {
if (desktop) await desktop.evaluate(({ dialog }) => { dialog.showMessageBoxSync = () => 1 }).catch(() => {})
await desktop?.close()
await browser.close()
await rm(profile, { recursive: true, maxRetries: 5, retryDelay: 200, force: true })
+217
View File
@@ -0,0 +1,217 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { setTimeout as delay } from 'node:timers/promises'
import { webcrypto } from 'node:crypto'
import test from 'node:test'
import ts from 'typescript'
import * as vue from 'vue'
function load(source, dependencies, crypto = webcrypto, window = new EventTarget()) {
const code = ts.transpileModule(readFileSync(new URL('../web/src/' + source, import.meta.url), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText
const exports = {}
new Function('require', 'exports', 'crypto', 'window', code)((id) => {
if (id in dependencies) return dependencies[id]
throw new Error('Unexpected test dependency: ' + id)
}, exports, crypto, window)
return exports
}
function deferred() {
const { promise, resolve, reject } = Promise.withResolvers()
return { promise, resolve, reject }
}
async function until(condition) {
for (let attempt = 0; attempt < 200; attempt++) {
if (condition()) return
await delay(5)
}
assert.fail('Condition did not become true')
}
// Models the vault's exclusive Web Lock and atomic IndexedDB transaction. The
// save gate exposes in-flight writes and failures without encrypting test text.
function vault(initial = {}) {
const states = new Map(Object.entries(structuredClone(initial)))
const gates = []
let tail = Promise.resolve()
return {
read: (device = 'device') => structuredClone(states.get(device)),
holdNextSave() {
const gate = { started: deferred(), finish: deferred() }
gates.push(gate)
return gate
},
withVault(device, update) {
const work = tail.then(async () => {
const state = structuredClone(states.get(device))
return update(state, async (next) => {
const gate = gates.shift()
if (gate) {
gate.started.resolve()
await gate.finish.promise
}
states.set(device, structuredClone(next))
})
})
tail = work.catch(() => {})
return work
},
}
}
function draftClient(storage) {
let hooks
const module = load('chat/drafts.ts', {
vue: { ...vue, onBeforeUnmount: (hook) => hooks.push(hook) },
'./vault': { withVault: storage.withVault },
})
return (scope = 'private/contact/peer', device = 'device') => {
const effect = vue.effectScope()
const lifecycle = []
hooks = lifecycle
const currentScope = vue.ref(scope), currentDevice = vue.ref(device), text = vue.ref(''), editing = vue.ref(false)
const draft = effect.run(() => module.useEncryptedDraft(() => currentDevice.value, () => currentScope.value, text, () => editing.value))
return { draft, text, scope: currentScope, device: currentDevice, editing,
close() { lifecycle.forEach((hook) => hook()); effect.stop() },
}
}
}
test('draft flush waits for an already-running vault write', { timeout: 5000 }, async (t) => {
const storage = vault({ device: { drafts: {} } })
const client = draftClient(storage)()
t.after(client.close)
await until(() => client.draft.ready.value)
client.text.value = 'This write is still in flight'
const gate = storage.holdNextSave()
const first = client.draft.flush()
await gate.started.promise
let finished = false
const second = client.draft.flush().then(() => { finished = true })
await delay(10)
try {
assert.equal(finished, false, 'flush must wait for the existing write')
} finally {
gate.finish.resolve()
await Promise.all([first, second])
}
assert.equal(storage.read().drafts['private/contact/peer'], client.text.value)
})
test('failed draft remains recoverable after switching conversations', { timeout: 5000 }, async (t) => {
const storage = vault({ device: { drafts: {} } })
const client = draftClient(storage)('private/first/peer')
t.after(client.close)
await until(() => client.draft.ready.value)
const message = 'Retain this unsaved draft after a storage failure'
client.text.value = message
const gate = storage.holdNextSave()
const saved = client.draft.flush().then(() => ({ failed: false }), () => ({ failed: true }))
await gate.started.promise
client.scope.value = 'private/second/peer'
gate.finish.reject(new Error('Simulated disk full'))
assert.equal((await saved).failed, true)
await until(() => client.draft.ready.value && client.text.value === '')
assert.equal(storage.read().drafts['private/first/peer'], undefined)
client.scope.value = 'private/first/peer'
await until(() => client.draft.ready.value && client.text.value === message)
await client.draft.retry()
await client.draft.flush()
assert.equal(storage.read().drafts['private/first/peer'], message)
})
test('separate tabs preserve conflicting drafts until explicit overwrite', { timeout: 5000 }, async (t) => {
const key = 'group/shared'
const storage = vault({ device: { drafts: { [key]: 'Initial draft' } } })
// Separate modules match separate browser tabs, while storage remains shared.
const first = draftClient(storage)(key), second = draftClient(storage)(key)
t.after(first.close)
t.after(second.close)
await until(() => first.draft.ready.value && second.draft.ready.value)
second.text.value = 'Draft from the other tab'
await second.draft.flush()
first.text.value = 'Keep my local unsaved version too'
await assert.rejects(first.draft.flush())
assert.equal(first.draft.conflict.value, true)
assert.equal(first.text.value, 'Keep my local unsaved version too')
assert.equal(storage.read().drafts[key], 'Draft from the other tab')
await first.draft.overwrite()
await first.draft.flush()
assert.equal(first.draft.conflict.value, false)
assert.equal(storage.read().drafts[key], 'Keep my local unsaved version too')
})
test('ordinary draft survives entering and cancelling message editing', { timeout: 5000 }, async (t) => {
const key = 'group/editing'
const storage = vault({ device: { drafts: {} } })
const client = draftClient(storage)(key)
t.after(client.close)
await until(() => client.draft.ready.value)
client.text.value = 'An ordinary unsent draft'
await client.draft.flush()
client.editing.value = true
client.text.value = 'An edit to a previously sent message'
await delay(10)
client.editing.value = false
assert.equal(client.text.value, 'An ordinary unsent draft')
await client.draft.flush()
assert.equal(storage.read().drafts[key], 'An ordinary unsent draft')
})
const bytes = (value) => new Uint8Array(Buffer.from(value, 'base64'))
const engineModule = {
base64: (value) => Buffer.from(value).toString('base64'), decode: bytes,
loadEngine: async () => ({ DeviceMls: { restore: () => ({
encrypt: () => new Uint8Array([1]), snapshot: () => new Uint8Array([2]), free() {},
}) } }),
}
test('private forwarding preserves drafts; composer consumes only its expected text', async () => {
const key = 'private/contact/peer', content = 'Same text as a pending draft'
const initial = { engine: '', outbox: [], lines: [], pinned: { peer: 'key' }, groups: { peer: 'group' }, drafts: { [key]: content } }
const storage = vault({ device: initial })
const peer = { id: 'peer', publicKey: 'key', mls: { publicKey: '', signature: '' } }
const identity = { user: { id: 'user' }, device: { id: 'device' } }
// Cryptographic primitives are intentionally stubbed: this test covers draft
// consumption only; ciphertext and cross-client verification have E2E tests.
const module = load('chat/chat.ts', {
'../api': { APIError: class extends Error {} }, '../identity': { mlsBinding: () => new Uint8Array() },
'./engine': engineModule, './vault': { withVault: storage.withVault }, './attachments': {}, './favorites': {},
}, { randomUUID: () => webcrypto.randomUUID(), subtle: { importKey: async () => ({}), verify: async () => true } })
const call = async (path) => path.endsWith('/devices') ? [peer] : undefined
await module.send(identity, 'contact', peer, content, call)
assert.equal(storage.read().drafts[key], content)
await module.send(identity, 'contact', peer, content, call, { expectedDraft: 'Stale composer contents' })
assert.equal(storage.read().drafts[key], content)
await module.send(identity, 'contact', peer, content, call, { expectedDraft: content })
assert.equal(storage.read().drafts[key], undefined)
})
test('group forwarding preserves drafts; composer consumes only its expected text', async () => {
const key = 'group/group', content = 'Same text as a pending group draft'
const initial = { engine: '', drafts: { [key]: content }, groupChats: { group: {
cursor: '0', lines: [], epochs: { epoch: { version: '1', roster: { device: { user: 'user', name: 'Owner' } } } },
} } }
const storage = vault({ device: initial })
const identity = { user: { id: 'user' }, device: { id: 'device' } }
const group = { id: 'group', membershipVersion: '1', role: 'owner', members: [{ id: 'user', state: 'active', role: 'owner' }] }
const update = (who, action) => storage.withVault(who.device.id, async (state, save) => {
// A prior envelope has been delivered before this next independent send.
delete state.groupChats.group.pendingMessage
return action(state, save, await engineModule.loadEngine())
})
const module = load('chat/group-chat.ts', {
'../api': { APIError: class extends Error {} }, './engine': engineModule,
'./chat': { update }, './attachments': {}, './favorites': {},
})
const call = async () => [{ id: 'epoch', creatorDevice: 'device', membershipVersion: '1', current: true, roster: ['device'] }]
await module.sendGroupMessage(identity, group, content, call)
assert.equal(storage.read().drafts[key], content)
await module.sendGroupMessage(identity, group, content, call, undefined, { expectedDraft: 'Stale composer contents' })
assert.equal(storage.read().drafts[key], content)
await module.sendGroupMessage(identity, group, content, call, undefined, { expectedDraft: content })
assert.equal(storage.read().drafts[key], undefined)
})
+32
View File
@@ -215,6 +215,15 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
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 draftText = '群聊未发送草稿 ' + id()
await chat(windows).getByRole('textbox', { name: '群消息', exact: true }).fill(draftText)
await chat(windows).getByText('草稿已保存在本机', { exact: true }).waitFor()
await work(windows).getByRole('link', { name: '联系人', exact: true }).click()
await work(windows).getByRole('link', { name: '群组', exact: true }).click()
await windows.getByRole('link', { name: new RegExp(group) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
await chat(windows).getByText('已恢复本机草稿', { exact: true }).waitFor()
assert.equal(await chat(windows).getByRole('textbox', { name: '群消息', exact: true }).inputValue(), draftText)
const first = 'Windows 群消息 ' + id()
await work(removed).getByRole('link', { name: '联系人' }).click()
holdConnection = true
@@ -627,8 +636,17 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await work(windows).getByRole('link', { name: '消息', exact: true }).click()
await windows.getByRole('link', { name: names[0] }).click()
await windows.waitForURL(/#\/chat\/[0-9a-f-]+$/)
await windows.route('**/contacts/*/devices', async (route) => {
const response = await route.fetch()
const devices = await response.json()
assert.ok(devices.some((device) => !device.mls))
devices.sort((a, b) => Number(Boolean(a.mls)) - Number(Boolean(b.mls)))
await route.fulfill({ response, json: devices })
})
await windows.getByRole('button', { name: '启用本机加密聊天' }).click()
await windows.getByText('设备已验证', { exact: true }).waitFor()
assert.notEqual(await windows.getByLabel('对方设备').inputValue(), await windows.locator('.chat-page select option').first().getAttribute('value'))
await windows.unroute('**/contacts/*/devices')
const privateFile = '私聊文件-' + id() + '.txt'
const privateAttachments = windows.getByRole('region', { name: '私聊附件发送区' })
await privateAttachments.locator('input:enabled').setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents })
@@ -741,10 +759,24 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await windows.getByLabel('来源', { exact: true }).selectOption('private')
await downloads.waitFor()
assert.equal(await downloads.count(), 1)
await work(windows).getByRole('link', { name: '设置', exact: true }).click()
await windows.getByLabel('消息发送方式', { exact: true }).selectOption('enter')
await windows.getByRole('button', { name: '保存设置' }).click()
await work(windows).getByRole('link', { name: '群组', exact: true }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
const keyboardText = '群聊 Enter 发送 ' + id()
const composer = chat(windows).getByRole('textbox', { name: '群消息', exact: true })
await composer.fill(keyboardText)
await composer.press('Shift+Enter')
assert.equal(await composer.inputValue(), keyboardText + '\n')
await composer.press('Enter')
await chat(windows).getByRole('list', { name: '群消息记录' }).getByText(keyboardText, { exact: true }).waitFor()
} 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 {
if (desktop) await desktop.evaluate(({ dialog }) => { dialog.showMessageBoxSync = () => 1 }).catch(() => {})
await desktop?.close()
await browser.close()
await rm(profile, { recursive: true, force: true })