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

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

+1 -1
View File
@@ -22,7 +22,7 @@
| 加密群聊 | 创建群组、邀请联系人和管理成员。每个账号选一台已核验设备参与 MLS 加密文字聊天。 |
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。 |
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
| 消息管理 | 支持会话查找、可选加密已读回执、引用回复、编辑、撤回、转发、本机搜索和收藏。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字和撤回。私聊还支持可选加密已读回执、转发、本机搜索和收藏。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+2
View File
@@ -15,3 +15,5 @@ OpenMLS 0.9.2 兼容性用例已在 Linux 原生和 Windows Chrome WebAssembly
预览版群聊的每个投递世代使用独立的 OpenMLS 会话,最多 32 个账号,每个账号选一台设备。参与设备各自在可信渠道核验其他设备安全码,并核对 Welcome 的签名创建者、完整 MLS 叶节点名单和群标识。加密消息绑定群、世代、消息 ID 和发送设备。成员加入、离开或绑定设备撤销后,群主为有效设备重新建立会话。服务端拒绝旧世代新消息,已离开的设备拿不到新会话的 Welcome。旧会话的已解密消息保存在本机。正式版仍需同一 MLS 群中的密钥更新、入侵后恢复、多设备授权和群历史同步。
群附件复用整文件 AES-256-GCM。群、世代和附件标识用于服务端授权,文件名和解密材料由群 MLS 消息保护。收件设备校验 MLS 描述与投递附件 ID 一致,并验证文件认证标签后才读取字节。成员离开后失去服务器下载权限,已下载的副本仍由成员保有。
群编辑和撤回通过 MLS 应用消息传递。接收端按已认证的发送设备、群世代和目标消息 ID 匹配本机记录。引用是加密发送的文本快照,原消息编辑或撤回后,引用仍显示发送时的片段。
+7 -1
View File
@@ -19,7 +19,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg
## 尚待实现
- 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。
- 阶段二与三还需分片附件、群聊消息操作、多设备可信授权、加密备份与跨设备历史同步。群聊和私聊的文字及小附件已进入开发预览。
- 阶段二与三还需分片附件、群聊转发与收藏、多设备可信授权、加密备份与跨设备历史同步。群聊和私聊的文字及小附件已进入开发预览。
- 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。
- 阶段五还需反钓鱼及聊天联动。
- 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。
@@ -120,3 +120,9 @@ Windows 和 Web 可发送和下载最多 8 MiB 的群附件,并在本机预览
双端在群聊录制最长 60 秒的 Opus 语音。取消录音即释放麦克风,不产生上传。语音按群附件加密,群世代变更会取消当前录音或拒绝发送上一个世代的录音。接收设备下载并验证密文后,通过本机播放器播放、暂停或拖动进度。语音转写及未听提醒待实现。
Windows Electron 与 Edge 集成测试使用虚拟麦克风验证双向播放和暂停、取消录音与世代切换均不上传,以及群成员移除和设备撤销后拒绝下载。私聊语音和桌面浏览器隔离回归通过。
## 加密群消息操作
Windows 与 Web 可在当前加密会话引用消息、编辑自己发送的文字及撤回自己发送的消息。客户端按原消息 ID、MLS 会话及发送设备校验编辑和撤回。引用片段、更新类型及目标标识留在 MLS 密文中。此前缓存且未记录会话标识的消息,以及旧会话中的消息仍可查看。撤回更新聊天显示,成员已经下载或复制的内容仍可能保留。
Windows Electron 与 Edge 验证引用渲染、编辑补收、文字与图片撤回、其他成员不可操作及旧会话的操作限制。私聊和服务端密文投递回归通过。
+42 -4
View File
@@ -55,10 +55,10 @@ async function publish(owner, pages) {
await Promise.all(pages.map((page) => chat(page).getByText('群加密已建立', { exact: true }).waitFor()))
}
async function send(sender, text) {
async function send(sender, text, action = '发送群消息') {
await chat(sender).getByRole('textbox', { name: '群消息' }).fill(text)
const response = sender.waitForResponse((item) => /\/groups\/[^/]+\/messages$/.test(item.url()) && item.request().method() === 'POST')
await chat(sender).getByRole('button', { name: '发送群消息' }).click()
await chat(sender).getByRole('button', { name: action, exact: true }).click()
const sent = await response
assert.equal(sent.status(), 200, await sent.text())
const packet = sent.request().postDataJSON()
@@ -114,7 +114,7 @@ async function playVoice(page, sender, downloadPath) {
assert.equal(await player.evaluate((element) => element.paused), true)
}
test('Windows 与 Web 群聊加密投递文字、附件和语音,成员变更后隔离访问', { timeout: 120_000 }, async () => {
test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员隔离', { timeout: 120_000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge', args: ['--use-fake-device-for-media-stream'] })
const profile = await mkdtemp(join(tmpdir(), 'xhchat-group-test-'))
let desktop
@@ -170,6 +170,37 @@ test('Windows 与 Web 群聊加密投递文字、附件和语音,成员变更
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
await chat(removed).getByText(first, { exact: true }).waitFor()
const original = chat(owner).getByRole('listitem').filter({ hasText: first })
assert.equal(await original.getByRole('button', { name: '编辑', exact: true }).count(), 0)
assert.equal(await original.getByRole('button', { name: '撤回', exact: true }).count(), 0)
await original.getByRole('button', { name: '引用', exact: true }).click()
const reply = '加密引用回复 ' + id()
assert.equal(await send(owner, reply), epoch)
const receivedReply = chat(windows).getByRole('listitem').filter({ hasText: reply })
await receivedReply.locator('blockquote').getByText(first, { exact: true }).waitFor()
await work(removed).getByRole('link', { name: '联系人' }).click()
const own = chat(windows).getByRole('listitem').filter({ has: windows.getByText(first, { exact: true }) }).first()
await own.getByRole('button', { name: '编辑', exact: true }).click()
const edited = '已修改群消息 ' + id()
assert.equal(await send(windows, edited, '保存编辑'), epoch)
const incomingEdit = chat(owner).getByRole('listitem').filter({ has: owner.getByText(edited, { exact: true }) })
await incomingEdit.getByText('已编辑', { exact: true }).waitFor()
await work(removed).getByRole('link', { name: '群组' }).click()
await removed.getByRole('link', { name: new RegExp(group) }).click()
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
await chat(removed).getByText(edited, { exact: true }).waitFor()
const temporary = '待撤回群消息 ' + id()
assert.equal(await send(windows, temporary), epoch)
const outgoing = chat(windows).getByRole('listitem').filter({ hasText: temporary })
await chat(owner).getByText(temporary, { exact: true }).waitFor()
await outgoing.getByRole('button', { name: '撤回', exact: true }).click()
await chat(windows).getByRole('button', { name: '确认撤回' }).click()
for (const page of pages) {
await chat(page).getByText('消息已撤回', { exact: true }).waitFor()
assert.equal(await chat(page).getByText(temporary, { exact: true }).count(), 0)
}
const contents = Buffer.from('Windows 群文件内容 ' + id() + '\n'.repeat(9000))
const filename = '群附件-' + id() + '.txt'
await sendFile(windows, filename, 'text/plain', contents)
@@ -202,6 +233,11 @@ test('Windows 与 Web 群聊加密投递文字、附件和语音,成员变更
assert.equal(await image.evaluate((element) => element.naturalWidth), 1)
await chat(windows).getByRole('button', { name: '关闭预览' }).click()
await image.waitFor({ state: 'detached' })
const photoLine = chat(owner).getByRole('listitem').filter({ hasText: photo })
assert.equal(await photoLine.getByRole('button', { name: '编辑', exact: true }).count(), 0)
await photoLine.getByRole('button', { name: '撤回', exact: true }).click()
await chat(owner).getByRole('button', { name: '确认撤回' }).click()
await chat(windows).getByRole('button', { name: '预览 ' + photo }).waitFor({ state: 'detached' })
const voiceUploads = []
windows.on('request', (request) => {
@@ -237,7 +273,9 @@ test('Windows 与 Web 群聊加密投递文字、附件和语音,成员变更
assert.notEqual(await send(owner, second), epoch)
await chat(windows).getByText(second, { exact: true }).waitFor()
assert.equal(await removed.getByText(second, { exact: true }).count(), 0)
assert.equal(await chat(windows).getByText(first, { exact: true }).count(), 1)
const history = chat(windows).getByRole('listitem').filter({ hasText: edited })
assert.equal(await history.count(), 1)
assert.equal(await history.getByRole('button', { name: '编辑', exact: true }).count(), 0)
} catch (error) {
const status = await Promise.all(pages.map((page) => page.locator('[role=alert], .group-chat [role=status]').allTextContents()))
throw new Error(JSON.stringify(status), { cause: error })
+67 -10
View File
@@ -7,8 +7,8 @@ import MediaPreview from './MediaPreview.vue'
import VoiceMessage from './VoiceMessage.vue'
import VoiceRecorder from './VoiceRecorder.vue'
import { enableChat, trust } from './chat'
import { discardPendingGroupMessage, groupAttachmentPath, publishGroup, sendGroupMessage, synchronizeGroup } from './group-chat'
import type { GroupDetail, GroupDevice } from './group-chat'
import { discardPendingGroupMessage, groupAttachmentPath, groupQuote, publishGroup, sendGroupMessage, synchronizeGroup } from './group-chat'
import type { GroupDetail, GroupDevice, GroupLine } from './group-chat'
const props = defineProps<{ group: GroupDetail }>()
const session = useSession()
@@ -17,12 +17,15 @@ const code = ref('')
const codes = ref<Record<string, string>>({})
const selected = ref<Record<string, string>>({})
const draft = ref('')
const replying = ref<GroupLine>()
const editing = ref<GroupLine>()
const recalling = ref<GroupLine>()
const file = ref<File>()
const pendingVoice = ref<{ file: File; epoch: string }>()
const busy = ref(false)
const error = ref('')
const ready = computed(() => view.value?.ready && view.value.current?.membershipVersion === props.group.membershipVersion)
const recordingEpoch = computed(() => ready.value ? view.value?.current?.id : undefined)
const currentEpoch = computed(() => ready.value ? view.value?.current?.id : undefined)
const members = computed(() => props.group.members.filter((member) => member.state === 'active' && member.id !== session.identity?.user.id))
const canPublish = computed(() => Boolean(view.value && !view.value.current && members.value.every((member) =>
view.value?.devices.some((device) => device.user === member.id && device.id === selected.value[member.id] && pinned(device)))))
@@ -86,8 +89,31 @@ function send() {
const identity = session.identity
if (identity) void run(async () => {
const text = draft.value
await sendGroupMessage(identity, props.group, text, session.authorized)
if (editing.value?.epoch) {
await sendGroupMessage(identity, props.group, { action: 'edit', id: editing.value.id, epoch: editing.value.epoch, text }, session.authorized)
} else {
await sendGroupMessage(identity, props.group, replying.value ? { text, reply: replying.value } : text, session.authorized)
}
if (draft.value === text) draft.value = ''
editing.value = undefined
replying.value = undefined
await refresh()
})
}
function edit(line: GroupLine) {
editing.value = line
replying.value = undefined
draft.value = line.text
}
function recall() {
const identity = session.identity
const { id, epoch } = recalling.value ?? {}
if (!identity || !id || !epoch) return
void run(async () => {
await sendGroupMessage(identity, props.group, { action: 'recall', id, epoch }, session.authorized)
recalling.value = undefined
await refresh()
})
}
@@ -125,7 +151,14 @@ function discard() {
}
watch(() => props.group.membershipVersion, () => void run(refresh))
watch([pendingVoice, busy, recordingEpoch, () => view.value?.hasPending], ([voice, inProgress, epoch, hasPending]) => {
watch(currentEpoch, (epoch, previous) => {
if (!previous || epoch === previous) return
if (editing.value || replying.value) draft.value = ''
editing.value = undefined
replying.value = undefined
recalling.value = undefined
})
watch([pendingVoice, busy, currentEpoch, () => view.value?.hasPending], ([voice, inProgress, epoch, hasPending]) => {
const identity = session.identity
if (!voice || !identity) return
if (voice.epoch !== epoch) {
@@ -180,27 +213,50 @@ onBeforeUnmount(() => clearInterval(timer))
<button v-if="group.role === 'owner' && !view?.current" class="primary" :disabled="busy || !canPublish" @click="establish">建立群加密会话</button>
</details>
<ul v-if="view?.lines.length" class="group-chat-lines" aria-label="群消息记录">
<li v-for="line in view.lines" :key="line.id">
<li v-for="line in view.lines" :key="[line.epoch, line.sender, line.id].join('/')">
<small>{{ line.name }} · {{ new Date(line.time).toLocaleString() }}</small>
<VoiceMessage v-if="line.attachment?.voice" :attachment="line.attachment" :path="groupAttachmentPath(group, line.attachment.id)" />
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<p v-if="line.recalled" class="muted">消息已撤回</p>
<VoiceMessage v-else-if="line.attachment?.voice" :attachment="line.attachment" :path="groupAttachmentPath(group, line.attachment.id)" />
<template v-else-if="line.attachment">
<p>{{ line.attachment.name }} · {{ new Intl.NumberFormat().format(line.attachment.size) }} 字节</p>
<MediaPreview v-if="line.attachment.media" :attachment="line.attachment" :path="groupAttachmentPath(group, line.attachment.id)" />
<button type="button" class="plain" :disabled="busy" @click="download(line.attachment)">下载 {{ line.attachment.name }}</button>
</template>
<p v-else>{{ line.text }}</p>
<small v-if="line.edited && !line.recalled" class="muted">已编辑</small>
<div v-if="currentEpoch && line.epoch === currentEpoch && !line.recalled" class="message-actions">
<button type="button" class="plain" :disabled="busy || view.hasPending || !!editing" @click="replying = line">引用</button>
<template v-if="line.sender === session.identity?.device.id">
<button v-if="!line.attachment" type="button" class="plain" :disabled="busy || view.hasPending" @click="edit(line)">编辑</button>
<button type="button" class="plain" :disabled="busy || view.hasPending" @click="recalling = line">撤回</button>
</template>
</div>
</li>
</ul>
<div v-if="ready && recalling" class="confirmation">
<p>撤回后,群成员的聊天界面会更新。成员可能已保存副本。</p>
<button type="button" class="plain" :disabled="busy || view?.hasPending" @click="recall">确认撤回</button>
<button type="button" class="plain" @click="recalling = undefined">取消</button>
</div>
<p v-if="view?.hasPending" role="status">
{{ view.stalePending ? '待发消息属于旧会话。' : '消息待投递,将自动重试。' }}
<button v-if="view.stalePending" class="plain" :disabled="busy" @click="discard">清除待发消息</button>
</p>
<form v-if="ready" class="group-chat-composer" @submit.prevent="send">
<div v-if="editing" class="chat-quote">
<span>编辑消息</span>
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
</div>
<div v-else-if="replying" class="chat-quote">
<span>引用 {{ groupQuote(replying) }}</span>
<button type="button" class="plain" @click="replying = undefined">取消引用</button>
</div>
<label>群消息<textarea v-model="draft" rows="3" maxlength="8000" required /></label>
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">发送群消息</button>
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">{{ editing ? '保存编辑' : '发送群消息' }}</button>
</form>
<div v-if="ready" class="group-chat-composer">
<VoiceRecorder v-if="recordingEpoch" :key="recordingEpoch" :epoch="recordingEpoch" :disabled="busy || view?.hasPending || !!pendingVoice"
<div v-if="ready && !editing" class="group-chat-composer">
<VoiceRecorder v-if="currentEpoch" :key="currentEpoch" :epoch="currentEpoch" :disabled="busy || view?.hasPending || !!pendingVoice"
@send="sendVoice" @error="error = $event" />
<label>选择群附件 <input type="file" :disabled="busy || view?.hasPending" @change="chooseFile"></label>
<div v-if="file" class="message-actions">
@@ -220,6 +276,7 @@ onBeforeUnmount(() => clearInterval(timer))
.group-device-member { margin-block: .75rem; }
.group-chat-lines { display: grid; gap: .75rem; max-height: 24rem; overflow-y: auto; margin: 0; padding: .7rem 0; list-style: none; }
.group-chat-lines p { white-space: pre-wrap; overflow-wrap: anywhere; }
.group-chat-lines blockquote { margin: .25rem 0; padding-inline-start: .5rem; border-inline-start: 2px solid currentColor; overflow-wrap: anywhere; }
.group-chat-composer { display: grid; gap: .55rem; }
.group-chat-composer textarea { display: block; width: 100%; resize: vertical; font: inherit; }
.group-chat button { justify-self: start; }
+1 -1
View File
@@ -170,7 +170,7 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
return unavailable
}
function applyMutation(line: ChatLine, mutation: Mutation) {
export function applyMutation(line: Pick<ChatLine, 'text' | 'attachment' | 'quote' | 'recalled' | 'edited'>, mutation: Mutation) {
if (line.recalled) return
if (mutation.action === 'recall') {
line.recalled = true
+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 {