增加加密群消息引用、编辑和撤回

This commit is contained in:
xhgit committed 2026-11-14 09:25:45 +08:00
1 parent de722039d6
commit 7beb0cf795
7 files changed
+177 -36

No files matched your search

+57 -19
View File
@@ -1,9 +1,9 @@
import { APIError } from '../api'
import { base64, decode } from './engine'
import { replenishPackages, update, verifiedPeer, verify } from './chat'
import { applyMutation, replenishPackages, update, verifiedPeer, verify } from './chat'
import type { Call, ChatIdentity, Package, Peer } from './chat'
import { decodeMessage, encodeAttachment, sealAttachment } from './attachments'
import type { Attachment } from './attachments'
import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, sealAttachment } from './attachments'
import type { Attachment, Mutation } from './attachments'
export type GroupMember = { id: string; username: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member' }
export type GroupDetail = { id: string; membershipVersion: string; members: GroupMember[]; role: GroupMember['role'] }
@@ -12,15 +12,20 @@ type Epoch = { id: string; creatorDevice: string; membershipVersion: string; wel
type Publishing = { id: string; membershipVersion: string; devices: { device: string; wire?: string }[] }
type Outgoing = { id: string; epoch: string; wire: string }
type Packet = Outgoing & { sequence: string; senderDevice: string; createdAt: string; attachmentId?: string }
type Line = { id: string; user: string; sender: string; name: string; text: string; time: string; attachment?: Attachment }
export type GroupLine = {
id: string; user: string; sender: string; name: string; text: string; time: string; epoch?: string
attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean
}
type LineRef = Pick<GroupLine, 'id' | 'sender' | 'epoch'>
type GroupContent = string | File | { text: string; reply: LineRef } | (Mutation & { epoch: string })
type Verified = { user: string; key: string; name: string }
type VerifiedEpoch = { version: string; roster: Record<string, Verified> }
export type GroupChatState = {
cursor: string
lines: Line[]
lines: GroupLine[]
epochs: Record<string, VerifiedEpoch>
pendingEpoch?: Publishing
pendingMessage?: Pick<Packet, 'id' | 'epoch' | 'wire'> & { line: Line }
pendingMessage?: Outgoing & { line: GroupLine; mutation?: Mutation }
}
const encoder = new TextEncoder()
@@ -33,6 +38,22 @@ function local(chats: Record<string, GroupChatState>, group: string) {
return chats[group] ??= { cursor: '0', lines: [], epochs: {} }
}
function finishPending(chat: GroupChatState, pending: NonNullable<GroupChatState['pendingMessage']>) {
pending.line.epoch ??= pending.epoch
if (pending.mutation) applyGroupMutation(chat, pending.epoch, pending.line.sender, pending.mutation)
else chat.lines.push(pending.line)
delete chat.pendingMessage
}
function applyGroupMutation(chat: GroupChatState, epoch: string, sender: string, mutation: Mutation) {
const target = chat.lines.find((line) => line.id === mutation.id && line.epoch === epoch && line.sender === sender)
if (target) applyMutation(target, mutation)
}
export function groupQuote(line: GroupLine) {
return (line.text || line.attachment?.name || '').slice(0, 240)
}
function activeMembers(group: GroupDetail) {
return group.members.filter((member) => member.state === 'active')
}
@@ -137,8 +158,7 @@ async function sendPending(group: GroupDetail, chat: GroupChatState, call: Call)
await call(path(group) + '/messages', 'POST', {
id: pending.id, epoch: pending.epoch, wire: pending.wire, attachmentId: pending.line.attachment?.id,
})
chat.lines.push(pending.line)
delete chat.pendingMessage
finishPending(chat, pending)
}
export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, call: Call) {
@@ -192,8 +212,7 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
const pending = chat.pendingMessage
if (pending && pending.id === item.id && pending.epoch === item.epoch && pending.wire === item.wire &&
pending.line.attachment?.id === item.attachmentId) {
chat.lines.push(pending.line)
delete chat.pendingMessage
finishPending(chat, pending)
}
} else {
if (item.epoch === current?.id && !ready) break
@@ -204,10 +223,13 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
const bytes = engine.decrypt_group(await groupID(group.id, item.epoch), item.senderDevice, decode(sender.key),
aad(group.id, item.epoch, item.id, item.senderDevice), decode(item.wire))
state.engine = base64(engine.snapshot())
const { text, attachment, quote } = decodeMessage(bytes)
const { text, attachment, quote, mutation } = decodeMessage(bytes)
if (attachment?.id !== item.attachmentId) throw new Error('群附件标识不匹配')
if (attachment || (!quote && text.length > 0 && bytes.length <= 8000)) {
chat.lines.push({ id: item.id, user: sender.user, name: sender.name, sender: item.senderDevice, text, attachment, time: item.createdAt })
if (mutation) {
applyGroupMutation(chat, item.epoch, item.senderDevice, mutation)
} else if (attachment || quote || (text.length > 0 && bytes.length <= 8000)) {
chat.lines.push({ id: item.id, epoch: item.epoch, user: sender.user, name: sender.name,
sender: item.senderDevice, text, quote, attachment, time: item.createdAt })
}
} catch {
warning ||= '已跳过无法通过验证的群消息'
@@ -239,11 +261,12 @@ export function discardPendingGroupMessage(identity: ChatIdentity, group: GroupD
})
}
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: string | File, call: Call, expectedEpoch?: string) {
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: GroupContent, call: Call, expectedEpoch?: string) {
return update(identity, async (state, save, factory) => {
const text = typeof message === 'string' ? message.trim() : ''
const text = (typeof message === 'string' ? message : message instanceof File ? '' : message.text ?? '').trim()
let content: Uint8Array = encoder.encode(text)
if (typeof message === 'string' && (content.length === 0 || content.length > 8000)) throw new Error('消息须为 1 至 8000 字节')
if (!(message instanceof File) && !(typeof message === 'object' && 'action' in message && message.action === 'recall') &&
(content.length === 0 || content.length > 8000)) throw new Error('消息须为 1 至 8000 字节')
const chat = local(state.groupChats ??= {}, group.id)
const epochs = await call<Epoch[]>(path(group) + '/epochs')
const epoch = epochs.find((item) => item.current && item.membershipVersion === group.membershipVersion)
@@ -254,17 +277,32 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, mes
const own = chat.epochs[epoch.id]!.roster[identity.device.id]
if (!own) throw new Error('当前设备未加入群加密世代')
let attachment: Attachment | undefined
if (typeof message !== 'string') {
let quote: string | undefined
let mutation: Mutation | undefined
if (message instanceof File) {
const sealed = await sealAttachment(message)
attachment = sealed.attachment
await call(groupAttachmentPath(group, attachment.id) + '?' + new URLSearchParams({ epoch: epoch.id }), 'POST', sealed.ciphertext)
content = encodeAttachment(attachment)
} else if (typeof message === 'object' && 'reply' in message) {
const target = chat.lines.find((line) => line.epoch === epoch.id && line.epoch === message.reply.epoch &&
line.id === message.reply.id && line.sender === message.reply.sender)
if (!target || target.recalled) throw new Error('当前会话中没有可引用的消息')
quote = groupQuote(target)
content = encodeReply(text, quote)
} else if (typeof message === 'object') {
const target = chat.lines.find((line) => line.epoch === epoch.id && line.epoch === message.epoch &&
line.id === message.id && line.sender === identity.device.id)
if (!target || target.recalled || (message.action === 'edit' && target.attachment)) throw new Error('此群消息无法更新')
mutation = message.action === 'edit' ? { action: 'edit', id: target.id, text } : { action: 'recall', id: target.id }
content = encodeMutation(mutation)
}
const engine = factory.DeviceMls.restore(decode(state.engine))
try {
const wire = engine.encrypt(await groupID(group.id, epoch.id), aad(group.id, epoch.id, id, identity.device.id), content)
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire),
line: { id, user: identity.user.id, name: own.name, sender: identity.device.id, text, attachment, time: new Date().toISOString() } }
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire), mutation,
line: { id, epoch: epoch.id, user: identity.user.id, name: own.name, sender: identity.device.id,
text, quote, attachment, time: new Date().toISOString() } }
state.engine = base64(engine.snapshot())
await save(state)
} finally {