diff --git a/README.md b/README.md index 28f3e98..7cd6be1 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 b80b314..7652983 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -57,7 +57,9 @@ Windows 与 Web 支持发送和下载最多 8 MiB 的附件。文件名、长度 ## 消息管理 -Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按正文、引用和文件名搜索本机历史,以及收藏和本机删除。收藏标记与历史保存在加密本地记录中。集成测试覆盖引用跨端显示、收藏筛选、搜索及删除后另一端仍可读取原消息。远程撤回、编辑、转发与跨设备收藏同步待后续交付。 +Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按正文、引用和文件名搜索本机历史,以及收藏和本机删除。收藏标记与历史保存在加密本地记录中。集成测试覆盖引用跨端显示、收藏筛选、搜索及删除后另一端仍可读取原消息。 + +原发送设备可编辑文字及撤回文字或附件消息。更新作为 MLS 应用消息传递,由客户端核对原发送设备与消息 ID。撤回会更新对方客户端显示,先前保存的附件、截图和其他独立副本仍可能存在。转发与跨设备收藏同步待后续交付。 ## 浏览器书签和历史 diff --git a/tests/encrypted-chat.test.mjs b/tests/encrypted-chat.test.mjs index eacbbc1..92c37d2 100644 --- a/tests/encrypted-chat.test.mjs +++ b/tests/encrypted-chat.test.mjs @@ -107,6 +107,16 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢 await send(windows, reply) await web.getByText(reply, { exact: true }).waitFor() await web.getByRole('listitem').filter({ hasText: reply }).locator('blockquote').getByText(text, { exact: true }).waitFor() + assert.equal(await web.getByRole('listitem').filter({ hasText: reply }).getByRole('button', { name: '编辑', exact: true }).count(), 0) + const edited = '编辑后 ' + randomBytes(8).toString('hex') + await windows.getByRole('listitem').filter({ hasText: reply }).getByRole('button', { name: '编辑', exact: true }).click() + await windows.getByRole('textbox', { name: '消息', exact: true }).fill(edited) + await windows.getByRole('button', { name: '保存编辑', exact: true }).click() + await web.getByRole('listitem').filter({ hasText: edited }).getByText('已编辑', { exact: true }).waitFor() + await windows.getByRole('listitem').filter({ hasText: edited }).getByRole('button', { name: '撤回', exact: true }).click() + await windows.getByRole('button', { name: '确认撤回', exact: true }).click() + await web.getByText('消息已撤回', { exact: true }).waitFor() + assert.equal(await web.getByText(edited, { exact: true }).count(), 0) const original = web.getByRole('listitem').filter({ has: web.getByText(text, { exact: true }) }).filter({ hasNot: web.locator('blockquote') }) await original.getByRole('button', { name: '收藏', exact: true }).click() await original.getByRole('button', { name: '取消收藏' }).waitFor() diff --git a/web/src/chat/attachments.ts b/web/src/chat/attachments.ts index 669cf88..2810755 100644 --- a/web/src/chat/attachments.ts +++ b/web/src/chat/attachments.ts @@ -53,8 +53,18 @@ export function encodeAttachment(attachment: Attachment) { return message } -export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment; quote?: string } { +export type Mutation = { action: 'edit' | 'recall'; id: string; text?: string } +type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation } + +export function decodeMessage(message: Uint8Array): ChatContent { if (message[0] !== 255) return { text: decoder.decode(message) } + 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) || + !(value.action === 'recall' || value.action === 'edit' && typeof value.text === 'string' && + value.text.trim() && encoder.encode(value.text).length <= 8000)) throw new Error('消息更新格式无效') + return { text: '', mutation: value } + } if (message[1] === 2 && message.length <= 18_000) { const value = JSON.parse(decoder.decode(message.subarray(2))) as { text?: unknown; quote?: unknown } | null if (!value || typeof value.text !== 'string' || !value.text.trim() || typeof value.quote !== 'string' || @@ -76,10 +86,18 @@ export function decodeMessage(message: Uint8Array): { text: string; attachment?: } export function encodeReply(text: string, quote: string) { - const body = encoder.encode(JSON.stringify({ text, quote })) - if (body.length + 2 > 18_000) throw new Error('引用消息过长') + return encodeContent(2, { text, quote }) +} + +export function encodeMutation(mutation: Mutation) { + return encodeContent(3, mutation) +} + +function encodeContent(kind: number, value: object) { + const body = encoder.encode(JSON.stringify(value)) + if (body.length + 2 > 18_000) throw new Error('消息内容过长') const message = new Uint8Array(body.length + 2) - message.set([255, 2]) + message.set([255, kind]) message.set(body, 2) return message } diff --git a/web/src/chat/chat.ts b/web/src/chat/chat.ts index 3153a16..83e451d 100644 --- a/web/src/chat/chat.ts +++ b/web/src/chat/chat.ts @@ -3,8 +3,8 @@ import { mlsBinding, signMls } from '../identity' import { base64, decode, fingerprint, loadEngine } from './engine' import type { DeviceMls } from './engine' import { withVault } from './vault' -import { decodeMessage, encodeAttachment, encodeReply, sealAttachment, uploadAttachment } from './attachments' -import type { Attachment } from './attachments' +import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, sealAttachment, uploadAttachment } from './attachments' +import type { Attachment, Mutation } from './attachments' export interface Peer { id: string @@ -19,7 +19,7 @@ export interface ChatIdentity { } interface Package { package: string; signature: string } -interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string } +interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string; mutationTarget?: string } interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string } export interface ChatLine { @@ -29,6 +29,8 @@ export interface ChatLine { attachment?: Attachment quote?: string favorite?: boolean + recalled?: boolean + edited?: boolean time: string own: boolean } @@ -140,7 +142,7 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise for (const item of [...state.outbox]) { if (unavailable.has(item.recipientDevice)) continue try { - await call('/inbox', 'POST', item) + await call('/inbox', 'POST', { messageId: item.messageId, recipientDevice: item.recipientDevice, ciphertext: item.ciphertext }) state.outbox = state.outbox.filter((pending) => pending.messageId !== item.messageId) await save(state) } catch (error) { @@ -151,6 +153,49 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise return unavailable } +function applyMutation(line: ChatLine, mutation: Mutation) { + if (line.recalled) return + if (mutation.action === 'recall') { + line.recalled = true + line.text = '' + delete line.attachment + delete line.quote + } else if (!line.attachment && mutation.text) { + line.text = mutation.text + line.edited = true + } +} + +export function mutateMessage(identity: ChatIdentity, user: string, peer: Peer, mutation: Mutation, call: Call) { + 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('请核验对方设备安全码') + await verifiedPeer(current, user) + const unavailable = await flush(state, save, call) + if (unavailable.has(current.id)) throw new Error('该设备暂不可接收消息') + const line = state.lines.find((item) => item.id === mutation.id && item.peer === current.id && item.own) + if (!line || line.recalled || (mutation.action === 'edit' && line.attachment)) throw new Error('此消息无法更新') + if (mutation.action === 'edit') { + mutation = { ...mutation, text: mutation.text?.trim() } + if (!mutation.text || encoder.encode(mutation.text).length > 8000) throw new Error('消息须为 1 至 8000 字节') + } + const group = state.groups[current.id] + if (!group) throw new Error('会话尚未建立') + const engine = factory.DeviceMls.restore(decode(state.engine)) + try { + const id = crypto.randomUUID() + const ciphertext = engine.encrypt(decode(group), aad(id, identity.device.id, current.id), encodeMutation(mutation)) + state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext), mutationTarget: line.id }) + applyMutation(line, mutation) + state.engine = base64(engine.snapshot()) + await save(state) + await flush(state, save, call) + } finally { + engine.free() + } + }) +} + export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call, reply?: ChatLine) { return update(identity, async (state, save, factory) => { const current = (await directory(call, user)).find((item) => item.id === peer.id) @@ -203,7 +248,7 @@ export function localMessageAction(identity: ChatIdentity, line: ChatLine, actio const index = state.lines.findIndex((item) => item.id === line.id && item.peer === line.peer && item.own === line.own) if (index < 0) return if (action === 'remove') { - if (state.outbox.some((item) => item.messageId === line.id && item.recipientDevice === line.peer)) { + if (state.outbox.some((item) => (item.mutationTarget ?? item.messageId) === line.id && item.recipientDevice === line.peer)) { throw new Error('待发送消息暂不能删除') } state.lines.splice(index, 1) @@ -239,10 +284,14 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) { if (!previous || group < previous) state.groups[peer.id] = group } else { const plaintext = engine.decrypt(peer.id, key, aad(item.messageId, peer.id, identity.device.id), wire) - if (state.lines.length < 1000) state.lines.push({ - id: item.messageId, peer: peer.id, ...decodeMessage(plaintext), - time: item.createdAt, own: false, - }) + const content = decodeMessage(plaintext) + 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.engine = base64(engine.snapshot()) } catch { @@ -261,6 +310,6 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) { deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试' } return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, - unsent: state.outbox.map((item) => item.messageId) } + unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) } }) } diff --git a/web/src/views/ChatView.vue b/web/src/views/ChatView.vue index 24a2fde..c4783fe 100644 --- a/web/src/views/ChatView.vue +++ b/web/src/views/ChatView.vue @@ -2,7 +2,7 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { useRoute } from 'vue-router' import { useSession } from '../session' -import { enableChat, localMessageAction, send, synchronize, trust } from '../chat/chat' +import { enableChat, localMessageAction, mutateMessage, send, synchronize, trust } from '../chat/chat' import type { ChatLine } from '../chat/chat' import { downloadAttachment } from '../chat/attachments' import type { Attachment } from '../chat/attachments' @@ -17,6 +17,8 @@ const search = ref('') const favoritesOnly = ref(false) const reply = ref() const deleting = ref() +const editing = ref() +const recalling = ref() const error = ref('') const busy = ref(false) const view = ref>>() @@ -75,9 +77,29 @@ function confirm() { function submit() { void execute(async () => { if (!session.identity || !peer.value) return - await send(session.identity, target.value, peer.value, draft.value, session.authorized, reply.value) + if (editing.value) { + await mutateMessage(session.identity, target.value, peer.value, { action: 'edit', id: editing.value.id, text: draft.value }, session.authorized) + } else { + await send(session.identity, target.value, peer.value, draft.value, session.authorized, reply.value) + } draft.value = '' reply.value = undefined + editing.value = undefined + await refresh() + }) +} + +function edit(line: ChatLine) { + editing.value = line + reply.value = undefined + draft.value = line.text +} + +function recall() { + void execute(async () => { + if (!session.identity || !peer.value || !recalling.value) return + await mutateMessage(session.identity, target.value, peer.value, { action: 'recall', id: recalling.value.id }, session.authorized) + recalling.value = undefined await refresh() }) } @@ -124,6 +146,9 @@ watch(selected, () => { favoritesOnly.value = false reply.value = undefined deleting.value = undefined + editing.value = undefined + recalling.value = undefined + draft.value = '' }) watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync) onMounted(() => { timer = setInterval(sync, 10_000) }) @@ -169,14 +194,18 @@ onBeforeUnmount(() => clearInterval(timer))
  1. {{ line.quote }}
    - {{ line.text }}待发送 + 已编辑
    - - + + +
  2. @@ -187,14 +216,23 @@ onBeforeUnmount(() => clearInterval(timer)) +
    +

    撤回这条消息?

    + + +
    +
    + 正在编辑消息 + +
    引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}
    - + - +