支持跨端加密消息编辑与撤回

This commit is contained in:
xhgit committed 2026-11-13 19:26:17 +08:00
1 parent 9b8c2026ea
commit f5f116a266
6 files changed
+140 -23

No files matched your search

+59 -10
View File
@@ -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) }
})
}