Merge pull request '支持跨端加密消息编辑与撤回' (#12) from xhgit/encrypted-message-mutations into main
Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/12
This commit was merged in pull request #12.
This commit is contained in:
commit
11e6c88501
6 files changed
+140
-23
No files matched your search
@@ -18,7 +18,7 @@
|
||||
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
|
||||
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
|
||||
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 |
|
||||
| 消息管理 | 支持引用回复、搜索本机历史、收藏和本机删除。 |
|
||||
| 消息管理 | 支持引用回复、编辑、撤回、搜索本机历史、收藏和本机删除。 |
|
||||
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
|
||||
|
||||
当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
|
||||
|
||||
+3
-1
@@ -57,7 +57,9 @@ Windows 与 Web 支持发送和下载最多 8 MiB 的附件。文件名、长度
|
||||
|
||||
## 消息管理
|
||||
|
||||
Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按正文、引用和文件名搜索本机历史,以及收藏和本机删除。收藏标记与历史保存在加密本地记录中。集成测试覆盖引用跨端显示、收藏筛选、搜索及删除后另一端仍可读取原消息。远程撤回、编辑、转发与跨设备收藏同步待后续交付。
|
||||
Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按正文、引用和文件名搜索本机历史,以及收藏和本机删除。收藏标记与历史保存在加密本地记录中。集成测试覆盖引用跨端显示、收藏筛选、搜索及删除后另一端仍可读取原消息。
|
||||
|
||||
原发送设备可编辑文字及撤回文字或附件消息。更新作为 MLS 应用消息传递,由客户端核对原发送设备与消息 ID。撤回会更新对方客户端显示,先前保存的附件、截图和其他独立副本仍可能存在。转发与跨设备收藏同步待后续交付。
|
||||
|
||||
## 浏览器书签和历史
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+59
-10
@@ -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<void>
|
||||
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<void>
|
||||
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) }
|
||||
})
|
||||
}
|
||||
@@ -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<ChatLine>()
|
||||
const deleting = ref<ChatLine>()
|
||||
const editing = ref<ChatLine>()
|
||||
const recalling = ref<ChatLine>()
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
|
||||
@@ -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))
|
||||
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
|
||||
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }">
|
||||
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
|
||||
<button v-if="line.attachment" type="button" class="plain" :disabled="busy"
|
||||
<span v-if="line.recalled" class="muted">消息已撤回</span>
|
||||
<button v-else-if="line.attachment" type="button" class="plain" :disabled="busy"
|
||||
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
|
||||
<span v-else>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small>
|
||||
<small v-if="line.edited && !line.recalled">已编辑</small>
|
||||
<div class="message-actions">
|
||||
<button type="button" class="plain" :disabled="busy" @click="reply = line">引用</button>
|
||||
<button type="button" class="plain" :disabled="busy" @click="localAction(line, 'favorite')">
|
||||
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy || Boolean(editing)" @click="reply = line">引用</button>
|
||||
<button v-if="!line.recalled" type="button" class="plain" :disabled="busy" @click="localAction(line, 'favorite')">
|
||||
{{ line.favorite ? '取消收藏' : '收藏' }}
|
||||
</button>
|
||||
<button v-if="line.own && !line.recalled && !line.attachment" type="button" class="plain" :disabled="busy" @click="edit(line)">编辑</button>
|
||||
<button v-if="line.own && !line.recalled" type="button" class="plain" :disabled="busy" @click="recalling = line">撤回</button>
|
||||
<button type="button" class="plain" :disabled="busy || view?.unsent.includes(line.id)" @click="deleting = line">本机删除</button>
|
||||
</div>
|
||||
</li>
|
||||
@@ -187,14 +216,23 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
<button type="button" class="plain" :disabled="busy" @click="localAction(deleting, 'remove')">确认删除</button>
|
||||
<button type="button" class="plain" @click="deleting = undefined">取消</button>
|
||||
</div>
|
||||
<div v-if="recalling" class="confirmation">
|
||||
<p>撤回这条消息?</p>
|
||||
<button type="button" class="plain" :disabled="busy" @click="recall">确认撤回</button>
|
||||
<button type="button" class="plain" @click="recalling = undefined">取消</button>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
<div v-if="reply" class="chat-quote">
|
||||
<span>引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}</span>
|
||||
<button type="button" class="plain" @click="reply = undefined">取消引用</button>
|
||||
</div>
|
||||
<label>发送附件<input type="file" :disabled="busy" @change="attach"></label>
|
||||
<label v-if="!editing">发送附件<input type="file" :disabled="busy" @change="attach"></label>
|
||||
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
|
||||
<button class="primary" :disabled="busy || !draft.trim()">发送</button>
|
||||
<button class="primary" :disabled="busy || !draft.trim()">{{ editing ? '保存编辑' : '发送' }}</button>
|
||||
</form>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
Reference in new issue
Block a user