Merge pull request '双端账号安全设置、发送快捷键与加密草稿' (#48) from xhgit/client-security-and-drafts into main

Reviewed-on: #48
This commit was merged in pull request #48.
This commit is contained in:
xhgit committed 2026-11-17 10:57:52 +00:00
commit e7098f2dd2
22 files changed
+896 -38

No files matched your search

+9 -1
View File
@@ -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 &&
+4 -1
View File
@@ -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)
+2
View File
@@ -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 串行化,并比较已读内容以检测覆盖冲突。此机制不能保护已执行的恶意同源脚本,也不提供跨设备草稿同步。
+22
View File
@@ -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 健康检查通过。
+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 })
+20 -11
View File
@@ -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(() => {
<form v-if="ready" class="group-chat-composer" @submit.prevent="send">
<div v-if="editing" class="chat-quote">
<span>编辑消息</span>
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
<button type="button" class="plain" @click="editing = undefined">取消编辑</button>
</div>
<div v-else-if="replying" class="chat-quote">
<span>引用 {{ groupQuote(replying) }}</span>
<button type="button" class="plain" @click="replying = undefined">取消引用</button>
</div>
<label>群消息<textarea v-model="draft" rows="3" maxlength="8000" required /></label>
<label>群消息<textarea v-model="draft" :readonly="busy || !draftStorage.ready.value" rows="3" maxlength="8000" required @keydown="handleComposerKey($event, send)" /></label>
<p v-if="draftStorage.status.value" class="muted" role="status">{{ draftStorage.status.value }}</p>
<button v-if="draftStorage.status.value.includes('保存失败')" type="button" class="plain" @click="draftStorage.retry()">重试保存草稿</button>
<button v-if="draftStorage.conflict.value" type="button" class="plain" @click="draftStorage.overwrite()">使用当前草稿覆盖本机记录</button>
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">{{ editing ? '保存编辑' : '发送群消息' }}</button>
</form>
<div v-if="ready && !editing" class="group-chat-composer">
+4 -1
View File
@@ -40,6 +40,7 @@ export interface ChatLine extends FavoriteFields {
}
export interface ChatState {
drafts?: Record<string, string>
engine: string
cursor: string
pending: Incoming[]
@@ -220,7 +221,7 @@ export function mutateMessage(identity: ChatIdentity, user: string, peer: Peer,
}
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call,
{ reply, onQueued }: { reply?: ChatLine; onQueued?: () => void } = {}) {
{ reply, onQueued, expectedDraft }: { reply?: ChatLine; onQueued?: () => void; expectedDraft?: string } = {}) {
return update(identity, async (state, save, factory) => {
const current = (await directory(call, user)).find((item) => item.id === peer.id)
if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码')
@@ -258,6 +259,8 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext)
state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext) })
state.lines.push({ id, peer: current.id, contact: user, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
const draftKey = 'private/' + user + '/' + current.id
if (expectedDraft !== undefined && content === expectedDraft && state.drafts?.[draftKey] === expectedDraft) delete state.drafts[draftKey]
state.engine = base64(engine.snapshot())
await save(state)
onQueued?.()
+149
View File
@@ -0,0 +1,149 @@
import { computed, onBeforeUnmount, shallowReactive, shallowRef, watch } from 'vue'
import type { Ref } from 'vue'
import type { ChatState } from './chat'
import { withVault } from './vault'
interface Draft {
device: string
scope: string
value: string
saved: string
loaded: boolean
restored: boolean
error: string
conflict: boolean
users: number
loading?: Promise<void>
writing?: Promise<void>
}
// Failed writes stay available in memory when a user changes conversations.
const pending = new Map<string, Draft>()
const keyOf = (draft: Draft) => draft.device + ':' + draft.scope
window.addEventListener('beforeunload', (event) => {
if ([...pending.values()].some((draft) => draft.value !== draft.saved || draft.writing)) {
event.preventDefault()
event.returnValue = ''
}
})
function release(draft: Draft) {
if (!draft.users && !draft.writing && (draft.loaded && draft.value === draft.saved || !draft.loaded)) {
if (pending.get(keyOf(draft)) === draft) pending.delete(keyOf(draft))
}
}
function obtain(device: string, scope: string): Draft {
const existing = pending.get(device + ':' + scope)
if (existing) return existing
const draft = shallowReactive<Draft>({ device, scope, value: '', saved: '', loaded: false, restored: true,
error: '', conflict: false, users: 0 })
pending.set(keyOf(draft), draft)
draft.loading = withVault<ChatState, void>(device, async (state) => {
if (!state) throw new Error('请先启用本机加密聊天')
draft.value = draft.saved = state.drafts?.[scope] ?? ''
draft.loaded = true
}, true).catch(() => {
draft.error = '草稿读取失败,请重新进入会话后重试'
})
return draft
}
async function persist(draft: Draft, overwrite = false): Promise<void> {
await draft.loading
if (!draft.loaded) throw new Error(draft.error)
if (draft.writing) {
await draft.writing
return persist(draft, overwrite)
}
if (draft.value === draft.saved && !overwrite) return
const value = draft.value, previous = draft.saved
draft.error = ''
draft.conflict = false
draft.writing = withVault<ChatState, void>(draft.device, async (state, save) => {
if (!state) throw new Error('请先启用本机加密聊天')
const drafts = state.drafts ??= {}
const stored = drafts[draft.scope] ?? ''
if (!overwrite && stored !== previous && stored !== value) {
draft.conflict = true
throw new Error('草稿已在其他页面变更,当前输入已保留。可复制内容,或使用当前草稿覆盖本机记录。')
}
if (stored !== value) {
if (value) drafts[draft.scope] = value
else delete drafts[draft.scope]
await save(state)
}
draft.saved = value
draft.restored = false
}, true).catch((cause: unknown) => {
draft.error = draft.conflict && cause instanceof Error ? cause.message : '草稿保存失败,请保留当前页面并重试'
throw new Error(draft.error)
}).finally(() => {
draft.writing = undefined
release(draft)
})
await draft.writing
if (draft.value !== draft.saved) await persist(draft)
}
export function useEncryptedDraft(device: () => string | undefined, scope: () => string, text: Ref<string>, editing: () => boolean) {
const current = shallowRef<Draft>()
const ready = computed(() => Boolean(current.value?.loaded))
const conflict = computed(() => Boolean(current.value?.conflict))
const status = computed(() => {
const draft = current.value
if (!draft) return ''
if (draft.error) return draft.error
if (!draft.loaded) return '正在读取本机草稿…'
if (draft.writing || draft.value !== draft.saved) return '正在保存草稿…'
return draft.value ? draft.restored ? '已恢复本机草稿' : '草稿已保存在本机' : ''
})
let timer: ReturnType<typeof setTimeout> | undefined
let active = true
function backgroundSave(draft = current.value) {
clearTimeout(timer)
if (draft) void persist(draft).catch(() => {})
}
function detach() {
const draft = current.value
if (!draft) return
backgroundSave(draft)
draft.users--
release(draft)
current.value = undefined
}
watch(() => [device(), scope()] as const, async ([deviceID, key]) => {
detach()
text.value = ''
if (!deviceID || !key) return
const draft = obtain(deviceID, key)
draft.users++
current.value = draft
await draft.loading
if (active && current.value === draft && draft.loaded && !editing()) text.value = draft.value
}, { immediate: true, flush: 'sync' })
watch(text, (value) => {
const draft = current.value
if (!draft?.loaded || editing() || value === draft.value) return
draft.value = value
draft.restored = false
clearTimeout(timer)
timer = setTimeout(backgroundSave, 350)
}, { flush: 'sync' })
watch(editing, (value) => {
if (value) backgroundSave()
else if (current.value?.loaded) text.value = current.value.value
}, { flush: 'sync' })
onBeforeUnmount(() => {
active = false
detach()
})
async function flush() {
clearTimeout(timer)
if (current.value) await persist(current.value)
}
function overwrite() {
clearTimeout(timer)
if (current.value) void persist(current.value, true).catch(() => {})
}
return { status, ready, conflict, flush, retry: backgroundSave, overwrite }
}
+5 -1
View File
@@ -355,7 +355,8 @@ export async function forwardContent(identity: ChatIdentity, destination: Forwar
return '转发待投递,请打开目标群重试'
}
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: GroupContent, call: Call, expectedEpoch?: string) {
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: GroupContent, call: Call, expectedEpoch?: string,
{ expectedDraft }: { expectedDraft?: string } = {}) {
return update(identity, async (state, save, factory) => {
const announcement = typeof message === 'object' && 'announcement' in message ? message.announcement.trim() : undefined
const text = (typeof message === 'string' ? message : !(message instanceof File) && 'text' in message ? message.text ?? '' : '').trim()
@@ -406,6 +407,9 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, mes
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire), mutation, announcement,
line: { id, epoch: epoch.id, user: identity.user.id, name: own.name, sender: identity.device.id,
text, quote, attachment, time: new Date().toISOString() } }
const draftedText = typeof message === 'string' ? message : typeof message === 'object' && 'reply' in message ? message.text : undefined
const draftKey = 'group/' + group.id
if (expectedDraft !== undefined && draftedText === expectedDraft && state.drafts?.[draftKey] === expectedDraft) delete state.drafts[draftKey]
state.engine = base64(engine.snapshot())
await save(state)
} finally {
+6
View File
@@ -8,11 +8,15 @@ import ContactsView from './views/ContactsView.vue'
import ChatView from './views/ChatView.vue'
import GroupView from './views/GroupView.vue'
import FavoritesView from './views/FavoritesView.vue'
import PreferencesView from './views/PreferencesView.vue'
import SecurityView from './views/SecurityView.vue'
import { initializePreferences } from './preferences'
import Workspace from './views/Workspace.vue'
import { useSession } from './session'
import { incomingGroupInvite, parseGroupInvite } from './chat/group-invites'
import './style.css'
initializePreferences()
const pinia = createPinia()
const router = createRouter({
history: createWebHashHistory(),
@@ -25,6 +29,8 @@ const router = createRouter({
{ path: 'chat/:user?', component: ChatView },
{ path: 'groups/:id?', component: GroupView },
{ path: 'favorites', component: FavoritesView },
{ path: 'settings', component: PreferencesView },
{ path: 'security', component: SecurityView },
] },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
+51
View File
@@ -0,0 +1,51 @@
import { readonly, ref } from 'vue'
export type Theme = 'system' | 'light' | 'dark'
export type SendMode = 'button' | 'enter' | 'ctrl-enter'
const key = 'xhchat-appearance-and-input'
const theme = ref<Theme>('system')
const sendMode = ref<SendMode>('button')
function readPreferences() {
try {
const stored = JSON.parse(localStorage.getItem(key) ?? '{}')
theme.value = stored?.theme === 'light' || stored?.theme === 'dark' ? stored.theme : 'system'
sendMode.value = stored?.sendMode === 'enter' || stored?.sendMode === 'ctrl-enter' ? stored.sendMode : 'button'
} catch {
theme.value = 'system'
sendMode.value = 'button'
}
document.documentElement.dataset.theme = theme.value
}
export const preferences = { theme: readonly(theme), sendMode: readonly(sendMode) }
export function savePreferences(nextTheme: Theme, nextSendMode: SendMode) {
if (!['system', 'light', 'dark'].includes(nextTheme) || !['button', 'enter', 'ctrl-enter'].includes(nextSendMode)) {
throw new Error('请选择有效的外观和发送方式')
}
try {
localStorage.setItem(key, JSON.stringify({ theme: nextTheme, sendMode: nextSendMode }))
} catch {
throw new Error('本机无法保存设置,请检查浏览器存储权限')
}
theme.value = nextTheme
sendMode.value = nextSendMode
document.documentElement.dataset.theme = nextTheme
}
export function initializePreferences() {
readPreferences()
window.addEventListener('storage', (event) => {
if (event.key === key || event.key === null) readPreferences()
})
}
export function handleComposerKey(event: KeyboardEvent, send: () => void) {
if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229 || event.shiftKey || event.altKey) return
const matches = sendMode.value === 'enter' ? !event.ctrlKey && !event.metaKey :
sendMode.value === 'ctrl-enter' && (event.ctrlKey || event.metaKey)
if (!matches) return
event.preventDefault()
if (!event.repeat) send()
}
+6 -1
View File
@@ -118,8 +118,13 @@ export const useSession = defineStore('session', () => {
clear()
}
async function changePassword(currentPassword: string, newPassword: string) {
await authorized('/auth/password', 'POST', { currentPassword, newPassword })
clear()
}
return {
identity, connection, contactChanges, inboxChanges, privateNotice, groupChange, groupListChanges, authenticate, logout, authorized,
identity, connection, contactChanges, inboxChanges, privateNotice, groupChange, groupListChanges, authenticate, logout, changePassword, authorized,
devices: () => authorized<Device[]>('/devices'),
revoke: (id: string) => authorized<void>('/devices/' + encodeURIComponent(id), 'DELETE'),
contacts: () => authorized<Contact[]>('/contacts'),
+9 -3
View File
@@ -1,6 +1,6 @@
* { box-sizing: border-box; }
:root {
color-scheme: light dark;
color-scheme: light;
--surface: #ffffff;
--base: #f1f5f3;
--text: #182822;
@@ -14,11 +14,17 @@
background: var(--base);
}
@media (prefers-color-scheme: dark) {
:root {
:root:not([data-theme='light']) {
color-scheme: dark;
--surface: #182520; --base: #101a16; --text: #edf4ef; --muted: #a8bcb0;
--line: #34483d; --green: #7ed8b1; --green-soft: #244236; --danger: #ff9aa2;
}
}
:root[data-theme='dark'] {
color-scheme: dark;
--surface: #182520; --base: #101a16; --text: #edf4ef; --muted: #a8bcb0;
--line: #34483d; --green: #7ed8b1; --green-soft: #244236; --danger: #ff9aa2;
}
body { margin: 0; }
button, input { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
@@ -143,7 +149,7 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.brand-art, .rail, .panel-nav { display: none; }
.workspace { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
.account-panel { padding: 12px; flex-direction: row; align-items: center; justify-content: space-between; border-right: 0; border-bottom: 1px solid var(--line); }
.panel-links { grid-auto-flow: column; grid-column: 1 / -1; grid-row: 2; justify-content: start; gap: 5px; }
.panel-links { display: flex; flex-wrap: wrap; grid-column: 1 / -1; grid-row: 2; justify-content: start; gap: 5px; }
.account-panel { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; }
.mobile-browser { display: block; }
.contacts-layout { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
+46 -18
View File
@@ -15,6 +15,8 @@ import VoiceRecorder from '../chat/VoiceRecorder.vue'
import VoiceMessage from '../chat/VoiceMessage.vue'
import MediaPreview from '../chat/MediaPreview.vue'
import MessageText from '../chat/MessageText.vue'
import { handleComposerKey } from '../preferences'
import { useEncryptedDraft } from '../chat/drafts'
import { focusMessage, privateMessageFocus, privateMessageKey } from '../chat/message-key'
const session = useSession()
@@ -52,6 +54,8 @@ const activeContact = computed(() => contacts.value.find((item) => item.id === t
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
const draftStorage = useEncryptedDraft(() => session.identity?.device.id,
() => ownCode.value && target.value && selected.value ? 'private/' + target.value + '/' + selected.value : '', draft, () => Boolean(editing.value))
const conversations = computed(() => {
const query = conversationQuery.value.trim().toLowerCase()
return contacts.value.filter((item) => item.state === 'friend' &&
@@ -77,6 +81,7 @@ let markingSeen = false
let active = true
let refreshRequested = false
let refreshTimer: ReturnType<typeof setTimeout> | undefined
let backgroundTask: Promise<void> | undefined
const seen = new Map<string, string>()
async function loadConversations() {
@@ -132,9 +137,12 @@ function queueSeen() {
async function execute(action: () => Promise<void>) {
if (busy.value || !session.identity) return
const deviceID = session.identity.device.id, contact = target.value, peerID = selected.value
busy.value = true
error.value = ''
try {
await backgroundTask
if (!active || session.identity?.device.id !== deviceID || target.value !== contact || selected.value !== peerID) return
await action()
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '加密聊天暂不可用'
@@ -145,6 +153,18 @@ async function execute(action: () => Promise<void>) {
}
}
function background(action: () => Promise<void>) {
if (!active || busy.value || backgroundTask) return
backgroundTask = action().catch((cause: unknown) => {
if (active && !busy.value) error.value = cause instanceof Error ? cause.message : '同步暂不可用'
}).finally(() => {
backgroundTask = undefined
if (!active) return
scheduleReceipt()
if (refreshRequested) sync()
})
}
async function refresh() {
const identity = session.identity
if (!identity || !target.value || !ownCode.value) return
@@ -162,7 +182,8 @@ async function refresh() {
if (requested && openedMessage.value !== requested.key && current.peers.some((device) => device.id === requested.device)) {
selected.value = requested.device
} else if (!current.peers.some((device) => device.id === selected.value)) {
selected.value = current.peers[0]?.id ?? ''
selected.value = (current.peers.find((device) => device.mls && current.pinned[device.id] === device.publicKey) ??
current.peers.find((device) => device.mls) ?? current.peers[0])?.id ?? ''
}
queueSeen()
}
@@ -179,20 +200,20 @@ function togglePreference(preference: 'mute' | 'pin') {
function scheduleReceipt() {
clearTimeout(receiptTimer)
if (!view.value?.shareRead || busy.value || !trusted.value) return
if (!view.value?.shareRead || busy.value || backgroundTask || !trusted.value) return
receiptTimer = setTimeout(async () => {
await nextTick()
const identity = session.identity
const selectedPeer = peer.value
const list = history.value
if (busy.value || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
if (busy.value || backgroundTask || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
const bounds = list.getBoundingClientRect()
const ids = Array.from(list.querySelectorAll<HTMLElement>('[data-unread]')).filter((row) => {
const rect = row.getBoundingClientRect()
return Math.min(rect.bottom, bounds.bottom, innerHeight) - Math.max(rect.top, bounds.top, 0) >= Math.min(rect.height, 24)
}).map((row) => row.dataset.unread!).slice(0, 64)
if (!ids.length) return
await execute(async () => {
background(async () => {
await markRead(identity, target.value, selectedPeer, ids, session.authorized)
await refresh()
})
@@ -232,16 +253,22 @@ function confirm() {
}
function submit() {
if (!draft.value.trim() || !draftStorage.ready.value) return
void execute(async () => {
if (!session.identity || !peer.value) return
if (editing.value) {
await mutateMessage(session.identity, target.value, peer.value, { action: 'edit', id: editing.value.id, text: draft.value }, session.authorized)
const identity = session.identity
if (!identity || !peer.value) return
const text = draft.value, contact = target.value, device = peer.value, edited = editing.value, quoted = reply.value
if (edited) {
await mutateMessage(identity, contact, device, { action: 'edit', id: edited.id, text }, session.authorized)
} else {
await send(session.identity, target.value, peer.value, draft.value, session.authorized, { reply: reply.value })
await draftStorage.flush()
await send(identity, contact, device, text, session.authorized, { reply: quoted, expectedDraft: text, onQueued: () => {
if (target.value === contact && selected.value === device.id && draft.value === text) draft.value = ''
} })
}
draft.value = ''
reply.value = undefined
editing.value = undefined
if (!active || target.value !== contact || selected.value !== device.id) return
if (reply.value === quoted) reply.value = undefined
if (editing.value === edited) editing.value = undefined
await refresh()
})
}
@@ -377,12 +404,12 @@ function submitForward(destination: ForwardDestination) {
function sync() {
if (!active || !ownCode.value || !target.value) return
refreshRequested = true
if (busy.value || refreshTimer) return
if (busy.value || backgroundTask || refreshTimer) return
refreshTimer = setTimeout(() => {
refreshTimer = undefined
if (busy.value) return
if (busy.value || backgroundTask) return
refreshRequested = false
void execute(refresh)
background(refresh)
}, 180)
}
@@ -390,7 +417,6 @@ watch(target, () => {
view.value = undefined
selected.value = ''
code.value = ''
draft.value = ''
sync()
})
watch(selected, () => {
@@ -405,7 +431,6 @@ watch(selected, () => {
pendingVoice.value = undefined
files.value = []
draggingFiles.value = false
draft.value = ''
scheduleReceipt()
queueSeen()
})
@@ -552,7 +577,7 @@ onBeforeUnmount(() => {
<form class="chat-compose" @submit.prevent="submit">
<div v-if="editing" class="chat-quote">
<span>正在编辑消息</span>
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
<button type="button" class="plain" @click="editing = undefined">取消编辑</button>
</div>
<div v-if="reply" class="chat-quote">
<span>引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}</span>
@@ -575,7 +600,10 @@ onBeforeUnmount(() => {
</div>
</section>
<VoiceRecorder v-if="!editing" :key="selected" :disabled="busy" @send="sendVoice" @error="error = $event" />
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
<label>消息<textarea v-model="draft" :readonly="busy || !draftStorage.ready.value" required rows="3" maxlength="4000" @keydown="handleComposerKey($event, submit)"></textarea></label>
<p v-if="draftStorage.status.value" class="muted" role="status">{{ draftStorage.status.value }}</p>
<button v-if="draftStorage.status.value.includes('保存失败')" type="button" class="plain" @click="draftStorage.retry()">重试保存草稿</button>
<button v-if="draftStorage.conflict.value" type="button" class="plain" @click="draftStorage.overwrite()">使用当前草稿覆盖本机记录</button>
<button class="primary" :disabled="busy || !draft.trim()">{{ editing ? '保存编辑' : '发送' }}</button>
</form>
</template>
+19 -1
View File
@@ -8,6 +8,8 @@ const devices = ref<Device[]>([])
const error = ref('')
const busy = ref(false)
const target = ref<Device>()
const renaming = ref<Device>()
const name = ref('')
const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
async function perform(operation: () => Promise<void>) {
@@ -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()
})
}
</script>
<template>
@@ -50,8 +62,14 @@ async function revoke() {
<small>首次登录 {{ dates.format(new Date(device.createdAt)) }} · 最近活动 {{ dates.format(new Date(device.lastActiveAt)) }}</small>
</div>
<span v-if="device.revokedAt" class="muted">已撤销</span>
<button v-else-if="device.id !== session.identity.device.id" class="plain danger" :disabled="busy" @click="target = device">撤销</button>
<button v-if="!device.revokedAt" class="plain" :disabled="busy" @click="renaming = device; name = device.name">重命名</button>
<button v-if="!device.revokedAt && device.id !== session.identity.device.id" class="plain danger" :disabled="busy" @click="target = device">撤销</button>
</article>
<form v-if="renaming" class="contact-preferences" aria-label="设备重命名" @submit.prevent="rename">
<label>设备新名称<input v-model="name" required maxlength="64"></label>
<button class="plain" :disabled="busy || !name.trim()">保存设备名称</button>
<button type="button" class="plain" :disabled="busy" @click="renaming = undefined">取消</button>
</form>
<section v-if="target" class="confirmation" aria-label="确认撤销">
<p>撤销「{{ target.name }}」后,该设备的登录会话将结束。</p>
<button class="plain" @click="target = undefined">取消</button>
+56
View File
@@ -0,0 +1,56 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { preferences, savePreferences } from '../preferences'
const theme = ref(preferences.theme.value)
const sendMode = ref(preferences.sendMode.value)
const error = ref('')
const saved = ref(false)
watch([preferences.theme, preferences.sendMode], ([nextTheme, nextSendMode]) => {
theme.value = nextTheme
sendMode.value = nextSendMode
})
watch([theme, sendMode], () => { saved.value = false })
function save() {
error.value = ''
try {
savePreferences(theme.value, sendMode.value)
saved.value = true
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法保存设置'
}
}
</script>
<template>
<section class="device-page">
<header class="page-header"><h1>设置</h1></header>
<div class="device-content">
<form class="preference-form" @submit.prevent="save">
<label><span id="theme-label">外观</span>
<select v-model="theme" aria-labelledby="theme-label">
<option value="system">跟随系统</option><option value="light">浅色</option><option value="dark">深色</option>
</select>
</label>
<label><span id="send-mode-label">消息发送方式</span>
<select v-model="sendMode" aria-labelledby="send-mode-label">
<option value="button">点击发送按钮</option><option value="enter">Enter 发送,Shift + Enter 换行</option>
<option value="ctrl-enter">Ctrl / ⌘ + Enter 发送</option>
</select>
</label>
<p class="muted">应用于此设备的私聊和群聊。</p>
<p v-if="error" role="alert" class="error">{{ error }}</p>
<p v-if="saved" role="status">已保存本机设置</p>
<button class="primary">保存设置</button>
</form>
</div>
</section>
</template>
<style scoped>
.preference-form { display: grid; gap: 1rem; max-width: 25rem; }
.preference-form select { font: inherit; width: 100%; padding: .65rem; background: var(--base); color: var(--text); border: 1px solid var(--line); border-radius: .5rem; }
.preference-form button { justify-self: start; }
</style>
+96
View File
@@ -0,0 +1,96 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useSession } from '../session'
interface LoginRecord { id: string; deviceName: string; platform: string; createdAt: string; currentDevice: boolean }
const session = useSession()
const currentPassword = ref('')
const newPassword = ref('')
const confirmation = ref('')
const confirmLogout = ref(false)
const busy = ref(false)
const error = ref('')
const status = ref('')
const history = ref<LoginRecord[]>([])
const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
async function run(action: () => Promise<void>) {
if (busy.value) return
busy.value = true
error.value = ''
status.value = ''
try { await action() }
catch (cause) { error.value = cause instanceof Error ? cause.message : '账号操作失败' }
finally { busy.value = false }
}
function refresh() {
void run(async () => { history.value = await session.authorized<LoginRecord[]>('/auth/history') })
}
function password() {
void run(async () => {
if (newPassword.value !== confirmation.value) throw new Error('两次输入的新密码不一致')
if ([...newPassword.value].length < 12 || new TextEncoder().encode(newPassword.value).length > 256) {
throw new Error('新密码须至少 12 个字符且最多 256 字节')
}
await session.changePassword(currentPassword.value, newPassword.value)
currentPassword.value = newPassword.value = confirmation.value = ''
})
}
function logoutOthers() {
void run(async () => {
await session.authorized('/auth/logout-others', 'POST')
confirmLogout.value = false
status.value = '其他登录会话已退出'
})
}
onMounted(refresh)
</script>
<template>
<section class="device-page">
<header class="page-header"><h1>账号安全</h1></header>
<div class="device-content security-settings">
<p v-if="error" role="alert" class="error">{{ error }}</p>
<p v-if="status" role="status">{{ status }}</p>
<form class="security-password" aria-label="修改密码" @submit.prevent="password">
<h2>修改密码</h2>
<label>当前密码<input v-model="currentPassword" type="password" autocomplete="current-password" required maxlength="256"></label>
<label>新密码<input v-model="newPassword" type="password" autocomplete="new-password" required maxlength="256"></label>
<label>确认新密码<input v-model="confirmation" type="password" autocomplete="new-password" required maxlength="256"></label>
<p class="muted">修改成功后,所有设备需要使用新密码重新登录。</p>
<button class="primary" :disabled="busy">修改密码并重新登录</button>
</form>
<section aria-label="登录会话">
<h2>登录会话</h2>
<button class="plain" :disabled="busy" @click="confirmLogout = true">退出其他登录会话</button>
<div v-if="confirmLogout" class="confirmation">
<p>结束此账号的其他登录会话?再次使用时需要重新登录。</p>
<button class="plain danger" :disabled="busy" @click="logoutOthers">确认退出其他会话</button>
<button class="plain" :disabled="busy" @click="confirmLogout = false">取消</button>
</div>
</section>
<section aria-label="登录记录" class="security-history">
<div class="contact-heading"><h2>最近登录记录</h2><button class="plain" :disabled="busy" @click="refresh">刷新记录</button></div>
<p class="muted">显示最近 50 次成功登录,记录从此功能启用后开始保存。</p>
<p v-if="!history.length && !busy">暂无登录记录。</p>
<ul><li v-for="item in history" :key="item.id">
<strong>{{ item.deviceName }}</strong><span v-if="item.currentDevice" class="tag">当前设备</span>
<small>{{ item.platform === 'windows' ? 'Windows' : 'Web' }} · {{ dates.format(new Date(item.createdAt)) }}</small>
</li></ul>
</section>
</div>
</section>
</template>
<style scoped>
.security-settings { display: grid; gap: 1.5rem; }
.security-password { display: grid; gap: .75rem; width: min(100%, 26rem); }
.security-password button { justify-self: start; white-space: normal; }
.security-settings h2 { font-size: 1.15rem; margin: 0 0 .5rem; }
.security-history ul { margin: .5rem 0; padding: 0; list-style: none; }
.security-history li { padding: .6rem 0; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
.security-history small { display: block; }
</style>
+2
View File
@@ -145,6 +145,8 @@ async function act(action: () => Promise<void>) {
<RouterLink to="/groups">群组</RouterLink>
<RouterLink to="/favorites">收藏</RouterLink>
<RouterLink to="/devices">设备管理</RouterLink>
<RouterLink to="/settings">设置</RouterLink>
<RouterLink to="/security">账号安全</RouterLink>
<button v-if="browser" class="plain mobile-browser" @click="act(browser)">浏览器</button>
</nav>
<div class="account-footer">