diff --git a/Desktop/src/main.ts b/Desktop/src/main.ts index e81aed4..fe3835a 100644 --- a/Desktop/src/main.ts +++ b/Desktop/src/main.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, ipcMain, Notification, protocol, safeStorage, session } from 'electron' +import { app, BrowserWindow, dialog, ipcMain, Notification, protocol, safeStorage, session } from 'electron' import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { signChallenge, signMls } from './identity' @@ -72,6 +72,14 @@ async function start() { win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })) win.webContents.on('will-navigate', (event) => event.preventDefault()) win.webContents.on('will-attach-webview', (event) => event.preventDefault()) + win.webContents.on('will-prevent-unload', (event) => { + const choice = dialog.showMessageBoxSync(win, { + type: 'warning', title: 'XHChat', message: '还有草稿尚未保存。', + detail: '留在应用中等待保存完成或重试。直接离开可能丢失未保存的文字。', + buttons: ['继续保存', '离开并放弃未保存内容'], defaultId: 0, cancelId: 0, + }) + if (choice === 1) event.preventDefault() + }) function trustedSender(event: Electron.IpcMainInvokeEvent) { const frame = event.senderFrame return !win.isDestroyed() && event.sender === win.webContents && frame && frame === win.webContents.mainFrame && diff --git a/README.md b/README.md index a4e82c4..8da7708 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ | 功能 | 可体验内容 | | --- | --- | -| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 | +| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、修改密码、退出其他登录会话、查看最近登录记录、设备重命名和远程撤销。 | | 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 | | 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | | 私聊会话 | 会话置顶随账号同步。当前设备的未读数可在重新登录后恢复,免打扰会话仍显示未读。 | @@ -26,6 +26,9 @@ | 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 | | 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索、收藏和本机删除。可打开消息里的网页链接,并将消息转发到加密群或已核验的联系人设备。私聊支持可选加密已读回执。 | | 本机收藏 | 汇总私聊与群聊收藏,支持本机搜索、按来源、内容类型和标签筛选。可预览媒体、播放语音、下载加密附件、查看原消息或批量取消收藏。 | +| 外观 | 在设置中切换浅色、深色或跟随系统,偏好保存在本机。 | +| 发送方式 | 私聊和群聊可选择按钮发送、Enter 发送或 Ctrl / ⌘ + Enter 发送,支持 Shift + Enter 换行。 | +| 本机草稿 | 私聊按联系人设备、群聊按群保存加密文字草稿,返回会话或重新登录可恢复。编辑已有消息时保留原草稿。 | | Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 | 当前为开发预览。大文件分片、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) diff --git a/docs/encryption.md b/docs/encryption.md index 61be1ed..84ee426 100644 --- a/docs/encryption.md +++ b/docs/encryption.md @@ -17,3 +17,5 @@ OpenMLS 0.9.2 兼容性用例已在 Linux 原生和 Windows Chrome WebAssembly 群附件复用整文件 AES-256-GCM。群、世代和附件标识用于服务端授权,文件名和解密材料由群 MLS 消息保护。收件设备校验 MLS 描述与投递附件 ID 一致,并验证文件认证标签后才读取字节。成员离开后失去服务器下载权限,已下载的副本仍由成员保有。 群编辑和撤回通过 MLS 应用消息传递。接收端按已认证的发送设备、群世代和目标消息 ID 匹配本机记录。引用是加密发送的文本快照,原消息编辑或撤回后,引用仍显示发送时的片段。 + +文字草稿复用端侧加密库,与 MLS 状态和历史一起在本机密文记录中保存。Windows 的库密钥由 DPAPI 封装,Web 使用 IndexedDB 中不可导出的 AES-GCM CryptoKey;草稿正文只在客户端内存中解密。私聊草稿绑定联系人与设备,群草稿绑定群。发送时同一加密库事务提交发件箱并消费对应草稿,转发默认不消费草稿。跨标签保存使用 Web Lock 串行化,并比较已读内容以检测覆盖冲突。此机制不能保护已执行的恶意同源脚本,也不提供跨设备草稿同步。 diff --git a/docs/progress.md b/docs/progress.md index 5a296c8..7fc37e8 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -232,3 +232,25 @@ Windows 和 Web 可从工作区进入收藏,查看当前设备本机密文库 收藏可跳回当前账号仍可查看的私聊与群聊。客户端按设备和消息标识匹配本机历史,滚动并聚焦到原消息。跳转参数只有标识,恢复会话仍沿用设备核验和群成员权限。找不到已缓存原消息时显示明确提示。 Windows Electron 与 Edge 验证同一设备上的私聊与群聊收藏汇总、来源和类型筛选、解密下载及播放、标签持久化、批量取消后原消息仍在、双端原消息定位和焦点。客户端搜索和收藏操作未向服务端发送搜索词或标签。 + +## 外观与输入设置 + +工作区新增设置入口,可选择浅色、深色或跟随系统。偏好保存在本机,重新打开生效,同一浏览器的多个页面会同步偏好。登录页也使用所选主题。 + +私聊和群聊可选择点击按钮、Enter 或 Ctrl / ⌘ + Enter 发送。Shift + Enter 保留换行,中文输入法组合输入和长按重复按键不会触发快捷发送。默认沿用按钮发送。 + +## 账号安全与设备设置 + +双端新增账号安全页,支持校验当前密码后修改密码、退出其他登录会话和查看最近 50 次成功登录。修改密码使所有会话失效,设备身份和已有本机密文保留;退出其他会话保留当前令牌,包括同一设备上的其他令牌在内均失效。设备可设置最多 64 个字符的名称,重新登录保留自定义名称。登录记录使用当次设备名称和平台快照,从启用迁移后开始记录,不保存密码、令牌或聊天内容。 + +密码修改、旧密码登录与退出会话通过账号行锁和事务协调,避免并发旧密码登录在密码修改后继续持有有效会话。真实 API 验证错误密码、跨账号隔离、设备名称持久化、WebSocket 会话结束和密码修改与登录并发。Windows 与 Edge 验证操作界面、重新登录和 390px 布局。 + +## 私聊与群聊加密草稿 + +文字草稿保存在原有端侧加密库中:私聊按联系人与对方设备隔离,群聊按群隔离。切换页面和重新登录后恢复,发送进入持久化发件箱时原子消费对应草稿,转发相同文字不消费未发送草稿。编辑或取消编辑原消息不会覆盖普通草稿。附件选择和引用目标暂不恢复。 + +保存中的写入必须完成后才发送。写失败保留当前运行中的草稿,可返回会话重试。草稿未保存时,Web 请求浏览器显示关页提醒,Windows 通讯窗口显示继续保存或离开确认。异常终止进程仍可能丢失未落盘输入。多标签页按已读取的草稿内容检查冲突,保留当前输入并由用户明确选择是否覆盖。草稿仅保存在本机,不做跨设备同步,不放入 LocalStorage 或上传服务端。 [Electron 关窗事件](https://www.electronjs.org/docs/latest/api/web-contents#event-will-prevent-unload) + +Windows 与 Edge 真实私聊、群聊用例验证恢复、快捷发送及本机加密存储。补充 6 项确定性测试覆盖写入等待、切换会话后的写失败恢复、跨标签冲突、编辑恢复和两种转发不误删草稿。发现并修复联系人多设备目录顺序导致默认选中未启用加密设备的问题;新增用例将未启用设备排在首位,验证优先选择已核验设备。 + +本批 20 项 Node 回归全部通过。Go 单元测试、`go vet`、双端构建与 Compose 健康检查通过。 diff --git a/tests/account-settings.test.mjs b/tests/account-settings.test.mjs new file mode 100644 index 0000000..36f0b23 --- /dev/null +++ b/tests/account-settings.test.mjs @@ -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 }) + } +}) diff --git a/tests/client-preferences.test.mjs b/tests/client-preferences.test.mjs new file mode 100644 index 0000000..6146c75 --- /dev/null +++ b/tests/client-preferences.test.mjs @@ -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() + } +}) diff --git a/tests/encrypted-chat.test.mjs b/tests/encrypted-chat.test.mjs index cc400ee..e9ba9e5 100644 --- a/tests/encrypted-chat.test.mjs +++ b/tests/encrypted-chat.test.mjs @@ -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 }) diff --git a/tests/encrypted-drafts.test.mjs b/tests/encrypted-drafts.test.mjs new file mode 100644 index 0000000..bad5ecb --- /dev/null +++ b/tests/encrypted-drafts.test.mjs @@ -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) +}) diff --git a/tests/group-chat.test.mjs b/tests/group-chat.test.mjs index 99abb6e..bf4027f 100644 --- a/tests/group-chat.test.mjs +++ b/tests/group-chat.test.mjs @@ -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 }) diff --git a/web/src/chat/GroupChat.vue b/web/src/chat/GroupChat.vue index e3873fe..06cf1e0 100644 --- a/web/src/chat/GroupChat.vue +++ b/web/src/chat/GroupChat.vue @@ -13,6 +13,8 @@ import VoiceRecorder from './VoiceRecorder.vue' import { enableChat, trust } from './chat' import { discardPendingGroupMessage, forwardGroupMessage, groupAttachmentPath, groupQuote, publishGroup, removeLocalGroupMessage, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat' import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat' +import { useEncryptedDraft } from './drafts' +import { handleComposerKey } from '../preferences' import { focusMessage, groupMessageFocus, groupMessageKey } from './message-key' const props = defineProps<{ group: GroupDetail }>() @@ -51,6 +53,8 @@ const draggingFiles = ref(false) const batchProgress = ref('') const pendingVoice = ref<{ file: File; epoch: string }>() const busy = ref(false) +const draftStorage = useEncryptedDraft(() => session.identity?.device.id, + () => code.value ? 'group/' + props.group.id : '', draft, () => Boolean(editing.value)) const error = ref('') const ready = computed(() => view.value?.ready && view.value.current?.membershipVersion === props.group.membershipVersion) const currentEpoch = computed(() => ready.value ? view.value?.current?.id : undefined) @@ -172,17 +176,20 @@ function saveAnnouncement() { } function send() { + if (!draft.value.trim() || view.value?.hasPending || !draftStorage.ready.value) return const identity = session.identity if (identity) void run(async () => { - const text = draft.value - if (editing.value?.epoch) { - await sendGroupMessage(identity, props.group, { action: 'edit', id: editing.value.id, epoch: editing.value.epoch, text }, session.authorized) + const text = draft.value, edited = editing.value, quoted = replying.value + if (edited?.epoch) { + await sendGroupMessage(identity, props.group, { action: 'edit', id: edited.id, epoch: edited.epoch, text }, session.authorized) } else { - await sendGroupMessage(identity, props.group, replying.value ? { text, reply: replying.value } : text, session.authorized) + await draftStorage.flush() + await sendGroupMessage(identity, props.group, quoted ? { text, reply: quoted } : text, session.authorized, undefined, { expectedDraft: text }) } - if (draft.value === text) draft.value = '' - editing.value = undefined - replying.value = undefined + if (!active) return + if (!edited && !editing.value && draft.value === text) draft.value = '' + if (editing.value === edited) editing.value = undefined + if (replying.value === quoted) replying.value = undefined await refresh() }) } @@ -294,7 +301,7 @@ function removeLocal() { const updated = await removeLocalGroupMessage(identity, props.group, message) if (view.value) view.value.lines = updated if (matches(replying.value)) replying.value = undefined - if (matches(editing.value)) { editing.value = undefined; draft.value = '' } + if (matches(editing.value)) editing.value = undefined if (matches(recalling.value)) recalling.value = undefined if (matches(forwarding.value)) forwarding.value = undefined deleting.value = undefined @@ -344,7 +351,6 @@ watch(currentEpoch, (epoch, previous) => { if (!previous || epoch === previous) return announcementDraft.value = undefined draggingFiles.value = false - if (editing.value || replying.value) draft.value = '' editing.value = undefined replying.value = undefined recalling.value = undefined @@ -492,13 +498,16 @@ onBeforeUnmount(() => {
编辑消息 - +
引用 {{ groupQuote(replying) }}
- + +

{{ draftStorage.status.value }}

+ +
diff --git a/web/src/views/DeviceView.vue b/web/src/views/DeviceView.vue index e1721c9..1525e36 100644 --- a/web/src/views/DeviceView.vue +++ b/web/src/views/DeviceView.vue @@ -8,6 +8,8 @@ const devices = ref([]) const error = ref('') const busy = ref(false) const target = ref() +const renaming = ref() +const name = ref('') const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' }) async function perform(operation: () => Promise) { @@ -34,6 +36,16 @@ async function revoke() { devices.value = await session.devices() }) } + +function rename() { + const device = renaming.value + if (!device || busy.value) return + void perform(async () => { + await session.authorized('/devices/' + device.id, 'POST', { name: name.value }) + renaming.value = undefined + devices.value = await session.devices() + }) +}