From 149028267ebfc9a07fa96b80e46c0163d20cb3bb Mon Sep 17 00:00:00 2001 From: xhgit Date: Fri, 13 Nov 2026 23:35:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BC=9A=E8=AF=9D=E5=AF=BC?= =?UTF-8?q?=E8=88=AA=E4=B8=8E=E5=8F=AF=E9=80=89=E5=8A=A0=E5=AF=86=E5=B7=B2?= =?UTF-8?q?=E8=AF=BB=E5=9B=9E=E6=89=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/progress.md | 4 ++ tests/encrypted-chat.test.mjs | 21 ++++++- web/src/chat/attachments.ts | 15 ++++- web/src/chat/chat.ts | 70 +++++++++++++++++++-- web/src/chat/vault.ts | 3 +- web/src/style.css | 8 +++ web/src/views/ChatView.vue | 112 +++++++++++++++++++++++++++++++--- 8 files changed, 218 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 0ef9cab..888c408 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ | 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 | | 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | | 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 | -| 消息管理 | 支持引用回复、编辑、撤回、转发、搜索本机历史、收藏和本机删除。 | +| 消息管理 | 支持会话查找、可选加密已读回执、引用回复、编辑、撤回、转发、本机搜索和收藏。 | | Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 | 当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) diff --git a/docs/progress.md b/docs/progress.md index 11f70b2..d476613 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -76,3 +76,7 @@ Windows 浏览器新增可跨窗口保留的本地书签和历史,每类最多 ## 聊天中的链接 加密文字消息中的 HTTPS 链接在端侧识别。Windows 从链接启动隔离 Chromium,Web 在独立标签页打开并隔离 opener。开发环境支持本机 HTTP。真实双端测试验证消息链接点击与 Chromium 地址显示。网页卡片与从浏览器分享给联系人仍待实现。 + +## 会话导航和已读回执 + +「消息」页支持按用户名或备注查找已接受的联系人,按本机最近消息时间排序。用户可按设备开启已读回执,默认关闭。开启后,仅在窗口聚焦且消息显示于可见区域时,通过 MLS 发送已读消息 ID。发送端根据对方设备身份和原消息 ID 更新状态。偏好、状态与待发回执保存在端侧加密记录中。 diff --git a/tests/encrypted-chat.test.mjs b/tests/encrypted-chat.test.mjs index 164318d..ebbb4da 100644 --- a/tests/encrypted-chat.test.mjs +++ b/tests/encrypted-chat.test.mjs @@ -70,7 +70,14 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢 await web.getByRole('button', { name: '添加好友' }).click() await windows.getByRole('button', { name: new RegExp(a) }).click() await windows.getByRole('button', { name: '接受申请' }).click() - await web.getByRole('link', { name: '打开加密聊天' }).click() + await web.getByRole('link', { name: '打开加密聊天' }).waitFor() + await work(web).getByRole('link', { name: '消息', exact: true }).click() + const conversation = web.getByRole('complementary', { name: '会话列表' }) + await conversation.getByRole('link', { name: b }).waitFor() + await web.getByLabel('查找会话').fill('没有匹配') + await web.getByText('没有匹配的会话。').waitFor() + await web.getByLabel('查找会话').clear() + await conversation.getByRole('link', { name: b }).click() await windows.getByRole('link', { name: '打开加密聊天' }).click() const windowsChat = windows.url() let webCode, desktopCode @@ -102,6 +109,18 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢 assert.ok(!Buffer.from(packet.ciphertext, 'base64').includes(Buffer.from(text))) assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice']) await windows.getByText(text, { exact: true }).waitFor() + const sentLine = web.getByRole('listitem').filter({ hasText: text }) + assert.equal(await sentLine.getByText('已读', { exact: true }).count(), 0) + assert.equal(await windows.getByLabel('发送已读回执').isChecked(), false) + const receiptPackets = [] + windows.on('request', (req) => { + if (req.method() === 'POST' && req.url().endsWith('/api/v1/inbox')) receiptPackets.push(req.postDataJSON()) + }) + await desktop.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].focus()) + await windows.getByLabel('发送已读回执').check() + await sentLine.getByText('已读', { exact: true }).waitFor({ timeout: 15_000 }) + assert.ok(receiptPackets.length > 0) + assert.ok(receiptPackets.every((item) => !JSON.stringify(item).includes(packet.messageId))) const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex') await windows.getByRole('listitem').filter({ hasText: text }).getByRole('button', { name: '引用', exact: true }).click() await send(windows, reply) diff --git a/web/src/chat/attachments.ts b/web/src/chat/attachments.ts index 24c7638..1077905 100644 --- a/web/src/chat/attachments.ts +++ b/web/src/chat/attachments.ts @@ -54,10 +54,19 @@ export function encodeAttachment(attachment: Attachment) { } export type Mutation = { action: 'edit' | 'recall'; id: string; text?: string } -type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation } +type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation; read?: string[] } +const messageID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/ export function decodeMessage(message: Uint8Array): ChatContent { if (message[0] !== 255) return { text: decoder.decode(message) } + if (message[1] === 4 && message.length <= 4096) { + const ids: unknown = JSON.parse(decoder.decode(message.subarray(2))) + if (!Array.isArray(ids) || ids.length === 0 || ids.length > 64 || + !ids.every((id) => typeof id === 'string' && messageID.test(id))) { + throw new Error('已读回执格式无效') + } + return { text: '', read: ids } + } if (message[1] === 3 && message.length <= 18_000) { const value = JSON.parse(decoder.decode(message.subarray(2))) as Mutation | null if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) || @@ -93,6 +102,10 @@ export function encodeMutation(mutation: Mutation) { return encodeContent(3, mutation) } +export function encodeRead(ids: string[]) { + return encodeContent(4, ids) +} + function encodeContent(kind: number, value: object) { const body = encoder.encode(JSON.stringify(value)) if (body.length + 2 > 18_000) throw new Error('消息内容过长') diff --git a/web/src/chat/chat.ts b/web/src/chat/chat.ts index 6671957..5162e3b 100644 --- a/web/src/chat/chat.ts +++ b/web/src/chat/chat.ts @@ -3,7 +3,7 @@ import { mlsBinding, signMls } from '../identity' import { base64, decode, fingerprint, loadEngine } from './engine' import type { DeviceMls } from './engine' import { withVault } from './vault' -import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, readAttachment, sealAttachment, uploadAttachment } from './attachments' +import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readAttachment, sealAttachment, uploadAttachment } from './attachments' import type { Attachment, Mutation } from './attachments' export interface Peer { @@ -31,6 +31,8 @@ export interface ChatLine { favorite?: boolean recalled?: boolean edited?: boolean + read?: boolean + contact?: string time: string own: boolean } @@ -45,6 +47,7 @@ interface ChatState { groups: Record package?: { lastPublished: number; item: Package } rejected: number + shareRead?: boolean } export type Call = (path: string, method?: string, body?: object, binary?: boolean) => Promise @@ -233,7 +236,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content: const id = crypto.randomUUID() 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, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true }) + state.lines.push({ id, peer: current.id, contact: user, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true }) state.engine = base64(engine.snapshot()) await save(state) await flush(state, save, call) @@ -266,9 +269,60 @@ export async function forwardMessage(identity: ChatIdentity, line: ChatLine, rec await send(identity, recipient, device, content, call) } +export function recentConversations(identity: ChatIdentity) { + return withVault>(identity.device.id, async (state) => { + const recent: Record = {} + for (const line of state?.lines ?? []) { + if (line.contact && (!recent[line.contact] || recent[line.contact] < line.time)) recent[line.contact] = line.time + } + return recent + }, true) +} + +export function markRead(identity: ChatIdentity, user: string, peer: Peer, visible: string[], call: Call) { + return update(identity, async (state, save, factory) => { + if (!state.shareRead) return + const selected = new Set(visible) + const lines = state.lines.filter((line) => line.peer === peer.id && !line.own && !line.read && !line.recalled && selected.has(line.id)).slice(0, 64) + const group = state.groups[peer.id] + if (!lines.length || !group || state.pinned[peer.id] !== peer.publicKey) return + const current = (await directory(call, user)).find((device) => device.id === peer.id) + if (!current || current.publicKey !== peer.publicKey) return + await verifiedPeer(current, user) + const engine = factory.DeviceMls.restore(decode(state.engine)) + try { + const id = crypto.randomUUID() + const bytes = engine.encrypt(decode(group), aad(id, identity.device.id, peer.id), encodeRead(lines.map((line) => line.id))) + state.outbox.push({ messageId: id, recipientDevice: peer.id, ciphertext: base64(bytes) }) + for (const line of lines) line.read = true + state.engine = base64(engine.snapshot()) + await save(state) + await flush(state, save, call) + } finally { + engine.free() + } + }) +} + +export function setReadReceipts(identity: ChatIdentity, enabled: boolean) { + return update(identity, async (state, save) => { + state.shareRead = enabled + await save(state) + }) +} + export function synchronize(identity: ChatIdentity, user: string, call: Call) { return update(identity, async (state, save, factory) => { const peers = await directory(call, user) + const peerIDs = new Set(peers.map((peer) => peer.id)) + let backfilled = false + for (const line of state.lines) { + if (!line.contact && peerIDs.has(line.peer)) { + line.contact = user + backfilled = true + } + } + if (backfilled) await save(state) for (let page = 0; page < 4; page++) { const inbox = await call('/inbox?after=' + state.cursor) if (!inbox.length) break @@ -292,12 +346,18 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) { } else { const plaintext = engine.decrypt(peer.id, key, aad(item.messageId, peer.id, identity.device.id), wire) const content = decodeMessage(plaintext) - if (content.mutation) { + if (content.read) { + const ids = new Set(content.read) + for (const line of state.lines) { + if (line.own && line.peer === peer.id && ids.has(line.id)) line.read = true + } + } else if (content.mutation) { const mutation = content.mutation const changed = state.lines.find((line) => !line.own && line.peer === peer.id && line.id === mutation.id) if (changed) applyMutation(changed, mutation) } else if (state.lines.length < 1000) { - state.lines.push({ id: item.messageId, peer: peer.id, ...content, time: item.createdAt, own: false }) + state.lines.push({ id: item.messageId, peer: peer.id, contact: user, text: content.text, + attachment: content.attachment, quote: content.quote, time: item.createdAt, own: false }) } } state.engine = base64(engine.snapshot()) @@ -316,7 +376,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) { } catch (cause) { deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试' } - return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, + return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, shareRead: state.shareRead === true, unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) } }) } diff --git a/web/src/chat/vault.ts b/web/src/chat/vault.ts index df3de40..f8cdc59 100644 --- a/web/src/chat/vault.ts +++ b/web/src/chat/vault.ts @@ -47,13 +47,14 @@ async function unsealKey(value: VaultRecord['key']) { } } -export async function withVault(device: string, update: (state: T | undefined, save: (state: T) => Promise) => Promise) { +export async function withVault(device: string, update: (state: T | undefined, save: (state: T) => Promise) => Promise, readOnly = false) { const scope = (window.xhchat?.apiBase ?? location.origin) + '/' + device const additionalData = new TextEncoder().encode(scope) return navigator.locks.request('xhchat-chat:' + scope, async () => { const db = await database() try { const stored = await record(db, scope) + if (!stored && readOnly) return await update(undefined, async () => { throw new Error('会话尚未启用') }) const wrapped = stored?.key ?? await newKey() const key = await unsealKey(wrapped) const state = stored?.iv && stored.sealed diff --git a/web/src/style.css b/web/src/style.css index a50040b..bad54e6 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -93,6 +93,14 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so .message-actions { margin-top: 5px; } .message-actions .plain { font-size: .78em; padding: 2px 6px; } .chat-link { border: 0; background: transparent; color: var(--green); text-decoration: underline; padding: 0; overflow-wrap: anywhere; font: inherit; } +.conversation-layout { display: grid; grid-template-columns: minmax(140px, 210px) minmax(0, 1fr); min-width: 0; } +.conversation-list { display: grid; align-content: start; gap: 6px; padding: 14px; border-right: 1px solid var(--line); min-width: 0; } +.conversation-list a { text-decoration: none; } +.conversation-list a.router-link-exact-active { background: var(--green-soft); } +@media (max-width: 840px) { + .conversation-layout { grid-template-columns: minmax(0, 1fr); } + .conversation-list { border-right: 0; border-bottom: 1px solid var(--line); max-height: 185px; overflow: auto; } +} .account-footer { display: grid; gap: 12px; margin-top: auto; } .account-footer p { color: var(--muted); font-size: 13px; } .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); margin: 0 8px 1px 4px; } diff --git a/web/src/views/ChatView.vue b/web/src/views/ChatView.vue index 37679a4..551a60b 100644 --- a/web/src/views/ChatView.vue +++ b/web/src/views/ChatView.vue @@ -1,8 +1,8 @@ -

在联系人详情打开聊天。

+

选择一个联系人开始聊天。

+