Merge pull request '增加群消息跨会话加密转发' (#29) from xhgit/group-forwarding into main

Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/29
This commit was merged in pull request #29.
This commit is contained in:
xhgit committed 2026-11-14 01:40:50 +00:00
commit 20e179a877
9 files changed
+212 -13

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@
| 加密群聊 | 创建群组、邀请联系人和管理成员。每个账号选一台已核验设备参与 MLS 加密文字聊天。 |
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。 |
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索和收藏。私聊还支持可选加密已读回执和转发。 |
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索和收藏。群消息可转发到其他已建立加密会话的群或已核验的联系人设备。私聊支持转发给联系人及可选加密已读回执。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+7 -1
View File
@@ -19,7 +19,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg
## 尚待实现
- 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。
- 阶段二与三还需分片附件、群聊转发、多设备可信授权、加密备份与跨设备历史同步。群聊和私聊的文字及小附件已进入开发预览。
- 阶段二与三还需分片附件、私聊转发至群聊、多设备可信授权、加密备份与跨设备历史同步。群聊和私聊的文字及小附件已进入开发预览。
- 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。
- 阶段五还需反钓鱼及聊天联动。
- 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。
@@ -132,3 +132,9 @@ Windows Electron 与 Edge 验证引用渲染、编辑补收、文字与图片撤
在群聊中可组合使用关键词和「只看收藏」,搜索本机已解密的消息文本、引用与附件名。收藏状态保存在设备的加密存储中,保留超过最近 1,000 条的收藏记录,撤回会取消收藏。附件仍受原会话权限和服务端保留期限制。跨设备收藏同步待实现。
Windows Electron 与 Edge 集成测试覆盖搜索引用和附件名、离开群页后恢复收藏、设备间收藏独立、撤回取消收藏和会话变更后的历史搜索。私聊和服务端投递回归通过。
## 群消息转发
双端可将群消息转发到其他已加入且已核验的群加密会话,或转发到已核验的联系人设备。转发携带文字正文或附件。图片、视频和语音保留原有媒体类型。附件经本机完整性校验和解密,再以新的附件标识、文件密钥与随机数加密上传。待投递的群转发可在目标群继续重试。原消息的引用片段和发送人信息不随转发发送。
Windows Electron 与 Edge 验证向尚无加密会话的群转发会被拒绝、转发群文件后附件标识和密文不同且下载内容逐字节相同,以及群文字转发到联系人私聊。私聊附件转发回归通过。
+52
View File
@@ -321,6 +321,58 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
await chat(windows).getByRole('checkbox', { name: '只看收藏' }).check()
await history.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
assert.equal(await chat(windows).getByRole('listitem').count(), 1)
await chat(windows).getByRole('searchbox', { name: '搜索本机群消息' }).clear()
await chat(windows).getByRole('checkbox', { name: '只看收藏' }).uncheck()
const targetGroup = '转发目标 ' + id()
await owner.getByLabel('群名称', { exact: true }).fill(targetGroup)
await owner.getByRole('button', { name: '创建群组' }).click()
await owner.getByRole('heading', { name: targetGroup }).waitFor()
await owner.getByLabel('邀请联系人').selectOption({ label: names[1] })
await owner.getByRole('button', { name: '发送邀请' }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
await windows.getByRole('button', { name: '接受邀请' }).click()
await owner.getByRole('list', { name: '群成员' }).getByRole('listitem').getByText(names[1] + ' · 成员', { exact: true }).waitFor()
await windows.getByRole('link', { name: new RegExp(group) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
const forwardPanel = chat(windows).getByRole('form', { name: '转发群消息' })
const forwardFile = chat(windows).getByRole('listitem').filter({ hasText: filename }).getByRole('button', { name: '转发', exact: true })
await forwardFile.click()
await forwardPanel.getByLabel('转发给').selectOption({ label: targetGroup })
await forwardPanel.getByRole('button', { name: '确认转发' }).click()
await chat(windows).getByRole('alert').getByText('请先在目标群加入加密会话').waitFor()
await forwardPanel.getByRole('button', { name: '取消', exact: true }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
await chat(owner).getByRole('button', { name: '启用本机群聊' }).click()
await publish(owner, [owner, windows])
await windows.getByRole('link', { name: new RegExp(group) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
const forwarded = windows.waitForResponse((item) => /\/groups\/[^/]+\/attachments\/[^/]+\?epoch=/.test(item.url()) &&
item.request().method() === 'POST')
await forwardFile.click()
await forwardPanel.getByLabel('转发给').selectOption({ label: targetGroup })
await forwardPanel.getByRole('button', { name: '确认转发' }).click()
const newBlob = await forwarded
assert.equal(newBlob.status(), 204)
assert.notEqual(new URL(newBlob.url()).pathname.split('/').at(-1), new URL(response.url()).pathname.split('/').at(-1))
await chat(windows).getByText('已转发到群聊', { exact: true }).waitFor()
const newResponse = owner.waitForResponse((item) => item.url().endsWith(new URL(newBlob.url()).pathname) && item.request().method() === 'GET')
const newDownload = owner.waitForEvent('download')
await chat(owner).getByRole('button', { name: '下载 ' + filename }).click()
assert.notDeepEqual(await (await newResponse).body(), ciphertext)
assert.deepEqual(await readFile(await (await newDownload).path()), contents)
await chat(windows).getByRole('listitem').filter({ hasText: edited }).getByRole('button', { name: '转发', exact: true }).click()
await forwardPanel.getByLabel('转发给').selectOption({ label: names[0] })
await forwardPanel.getByLabel('目标设备').waitFor()
await forwardPanel.getByRole('button', { name: '确认转发' }).click()
await chat(windows).getByText('已提交转发', { exact: true }).waitFor()
await work(owner).getByRole('link', { name: '消息', exact: true }).click()
await owner.getByRole('link', { name: names[1] }).click()
await owner.getByRole('button', { name: '启用本机加密聊天' }).click()
await owner.getByText(edited, { exact: true }).waitFor()
} 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 })
+23 -2
View File
@@ -4,11 +4,12 @@ import { useSession } from '../session'
import { downloadAttachment } from './attachments'
import type { Attachment } from './attachments'
import MediaPreview from './MediaPreview.vue'
import GroupForward from './GroupForward.vue'
import VoiceMessage from './VoiceMessage.vue'
import VoiceRecorder from './VoiceRecorder.vue'
import { enableChat, trust } from './chat'
import { discardPendingGroupMessage, groupAttachmentPath, groupQuote, publishGroup, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat'
import type { GroupDetail, GroupDevice, GroupLine } from './group-chat'
import { discardPendingGroupMessage, forwardGroupMessage, groupAttachmentPath, groupQuote, publishGroup, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat'
import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat'
const props = defineProps<{ group: GroupDetail }>()
const session = useSession()
@@ -22,6 +23,8 @@ const favoritesOnly = ref(false)
const replying = ref<GroupLine>()
const editing = ref<GroupLine>()
const recalling = ref<GroupLine>()
const forwarding = ref<GroupLine>()
const forwardStatus = ref('')
const file = ref<File>()
const pendingVoice = ref<{ file: File; epoch: string }>()
const busy = ref(false)
@@ -158,6 +161,20 @@ function favorite(line: GroupLine) {
})
}
function beginForward(line: GroupLine) {
forwardStatus.value = ''
forwarding.value = line
}
function forward(destination: ForwardDestination) {
const identity = session.identity
const source = forwarding.value
if (identity && source) void run(async () => {
forwardStatus.value = await forwardGroupMessage(identity, props.group, source, destination, session.authorized)
forwarding.value = undefined
})
}
function discard() {
const identity = session.identity
if (identity) void run(async () => {
@@ -197,6 +214,7 @@ onBeforeUnmount(() => clearInterval(timer))
<section class="group-chat" aria-label="群消息">
<h3>群消息</h3>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<p v-if="forwardStatus" role="status">{{ forwardStatus }}</p>
<button v-if="!code" class="primary" :disabled="busy" @click="enable">启用本机群聊</button>
<template v-else>
<p v-if="view?.warning" class="muted" role="status">{{ view.warning }}</p>
@@ -248,6 +266,7 @@ onBeforeUnmount(() => clearInterval(timer))
<small v-if="line.edited && !line.recalled" class="muted">已编辑</small>
<div v-if="!line.recalled" class="message-actions">
<button type="button" class="plain" :disabled="busy" @click="favorite(line)">{{ line.favorite ? '取消收藏' : '收藏' }}</button>
<button type="button" class="plain" :disabled="busy" @click="beginForward(line)">转发</button>
<template v-if="currentEpoch && line.epoch === currentEpoch">
<button type="button" class="plain" :disabled="busy || view?.hasPending || !!editing" @click="replying = line">引用</button>
<template v-if="line.sender === session.identity?.device.id">
@@ -258,6 +277,8 @@ onBeforeUnmount(() => clearInterval(timer))
</div>
</li>
</ul>
<GroupForward v-if="forwarding && view" :key="[forwarding.epoch, forwarding.sender, forwarding.id].join('/')"
:group-id="group.id" :pinned="view.pinned" :busy="busy" @confirm="forward" @cancel="forwarding = undefined" />
<div v-if="ready && recalling" class="confirmation">
<p>撤回后,群成员的聊天界面会更新。成员可能已保存副本。</p>
<button type="button" class="plain" :disabled="busy || view?.hasPending" @click="recall">确认撤回</button>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useSession } from '../session'
import { directory } from './chat'
import type { Peer } from './chat'
import type { Contact } from '../contacts'
import type { ForwardDestination, GroupSummary } from './group-chat'
const props = defineProps<{ groupId: string; pinned: Record<string, string>; busy: boolean }>()
const emit = defineEmits<{ cancel: []; confirm: [destination: ForwardDestination] }>()
const session = useSession()
const groups = ref<GroupSummary[]>([])
const contacts = ref<Contact[]>([])
const destination = ref('')
const devices = ref<Peer[]>([])
const deviceId = ref('')
const loading = ref(true)
const error = ref('')
const isContact = computed(() => destination.value.startsWith('user:'))
const selectedDevice = computed(() => devices.value.find((item) => item.id === deviceId.value && props.pinned[item.id] === item.publicKey))
const target = computed<ForwardDestination | undefined>(() => {
const id = destination.value.split(':')[1]
if (!id) return
if (isContact.value && selectedDevice.value) return { user: id, device: selectedDevice.value }
if (groups.value.some((group) => group.id === id && destination.value === 'group:' + id)) return { group: id }
})
onMounted(async () => {
try {
const [allGroups, allContacts] = await Promise.all([session.authorized<GroupSummary[]>('/groups'), session.contacts()])
groups.value = allGroups.filter((group) => group.state === 'active' && group.id !== props.groupId)
contacts.value = allContacts.filter((contact) => contact.state === 'friend')
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '无法读取转发目标'
} finally {
loading.value = false
}
})
watch(destination, async (value, _previous, onCleanup) => {
devices.value = []
deviceId.value = ''
error.value = ''
if (!value.startsWith('user:')) return
let current = true
onCleanup(() => { current = false })
try {
const candidates = await directory(session.authorized, value.slice('user:'.length))
if (!current) return
devices.value = candidates.filter((item) => item.mls && props.pinned[item.id] === item.publicKey)
deviceId.value = devices.value[0]?.id ?? ''
if (!devices.value.length) error.value = '请先在私聊中核验该联系人的设备'
} catch (cause) {
if (current) error.value = cause instanceof Error ? cause.message : '无法读取联系人设备'
}
})
</script>
<template>
<form class="confirmation group-forward" aria-label="转发群消息" @submit.prevent="target && emit('confirm', target)">
<p v-if="error" class="error" role="alert">{{ error }}</p>
<label>转发给
<select v-model="destination" :disabled="busy || loading">
<option value="">选择群聊或联系人</option>
<optgroup v-if="groups.length" label="群聊">
<option v-for="group in groups" :key="group.id" :value="'group:' + group.id">{{ group.name }}</option>
</optgroup>
<optgroup v-if="contacts.length" label="联系人">
<option v-for="contact in contacts" :key="contact.id" :value="'user:' + contact.id">{{ contact.alias || contact.username }}</option>
</optgroup>
</select>
</label>
<label v-if="devices.length">目标设备
<select v-model="deviceId" :disabled="busy">
<option v-for="item in devices" :key="item.id" :value="item.id">{{ item.name }} · {{ item.id.slice(0, 8) }}</option>
</select>
</label>
<div class="message-actions">
<button type="submit" class="primary" :disabled="busy || !target">确认转发</button>
<button type="button" class="plain" :disabled="busy" @click="emit('cancel')">取消</button>
</div>
</form>
</template>
<style scoped>
.group-forward { display: grid; gap: .65rem; }
</style>
+5
View File
@@ -162,3 +162,8 @@ export async function downloadAttachment(attachment: Attachment, call: Call, pat
link.click()
setTimeout(() => URL.revokeObjectURL(url), 30_000)
}
export async function readForwardedFile(attachment: Attachment, call: Call, path?: string) {
const bytes = await readAttachment(attachment, call, path)
return attachment.voice ? voiceFile([bytes]) : new File([bytes], attachment.name, { type: attachment.media })
}
+2 -5
View File
@@ -3,7 +3,7 @@ import { mlsBinding, signMls } from '../identity'
import { base64, decode, fingerprint, loadEngine } from './engine'
import type { DeviceMls } from './engine'
import { withVault } from './vault'
import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readAttachment, sealAttachment, uploadAttachment, voiceFile } from './attachments'
import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readForwardedFile, sealAttachment, uploadAttachment } from './attachments'
import type { Attachment, Mutation } from './attachments'
import type { GroupChatState } from './group-chat'
@@ -278,10 +278,7 @@ export function localMessageAction(identity: ChatIdentity, line: ChatLine, actio
export async function forwardMessage(identity: ChatIdentity, line: ChatLine, recipient: string, device: Peer, call: Call) {
if (line.recalled) throw new Error('撤回的消息无法转发')
const attachment = line.attachment
const bytes = attachment ? await readAttachment(attachment, call) : undefined
const content = attachment && bytes ? attachment.voice ? voiceFile([bytes]) :
new File([bytes], attachment.name, { type: attachment.media }) : line.text
const content = line.attachment ? await readForwardedFile(line.attachment, call) : line.text
await send(identity, recipient, device, content, call)
}
+33 -3
View File
@@ -1,12 +1,13 @@
import { APIError } from '../api'
import { base64, decode } from './engine'
import { applyMutation, replenishPackages, update, verifiedPeer, verify } from './chat'
import { applyMutation, replenishPackages, send, update, verifiedPeer, verify } from './chat'
import type { Call, ChatIdentity, Package, Peer } from './chat'
import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, sealAttachment } from './attachments'
import { decodeMessage, encodeAttachment, encodeMutation, encodeReply, readForwardedFile, 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'] }
export type GroupSummary = Omit<GroupDetail, 'members'> & { name: string; state: GroupMember['state'] }
export type GroupDevice = Peer & { user: string }
type Epoch = { id: string; creatorDevice: string; membershipVersion: string; welcome?: string; current: boolean; roster: string[] }
type Publishing = { id: string; membershipVersion: string; devices: { device: string; wire?: string }[] }
@@ -17,6 +18,7 @@ export type GroupLine = {
attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean; favorite?: boolean
}
type LineRef = Pick<GroupLine, 'id' | 'sender' | 'epoch'>
export type ForwardDestination = { group: string } | { user: string; device: Peer }
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> }
@@ -281,6 +283,34 @@ export function discardPendingGroupMessage(identity: ChatIdentity, group: GroupD
})
}
export async function forwardGroupMessage(identity: ChatIdentity, source: GroupDetail, message: LineRef, destination: ForwardDestination, call: Call) {
const content = await update(identity, async (state) => {
const item = state.groupChats?.[source.id]?.lines.find((entry) => entry.id === message.id &&
entry.epoch === message.epoch && entry.sender === message.sender)
if (!item || item.recalled) throw new Error('此群消息无法转发')
return item.attachment ? readForwardedFile(item.attachment, call, groupAttachmentPath(source, item.attachment.id)) : item.text
})
if ('user' in destination) {
await send(identity, destination.user, destination.device, content, call)
return '已提交转发'
}
const target = await call<GroupDetail & { state: GroupMember['state'] }>('/groups/' + encodeURIComponent(destination.group))
if (target.state !== 'active') throw new Error('请先接受目标群的邀请')
const view = await synchronizeGroup(identity, target, call)
if (!view.ready || !view.current) throw new Error('请先在目标群加入加密会话')
if (view.hasPending) throw new Error('目标群还有待处理的消息,请先打开目标群')
await sendGroupMessage(identity, target, content, call, view.current.id)
// At this point the outbox is durable. The target can retry after a network failure.
try {
const result = await synchronizeGroup(identity, target, call)
if (!result.hasPending) return '已转发到群聊'
} catch {
// The encrypted outbox remains available on the target group page.
}
return '转发待投递,请打开目标群重试'
}
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 : message instanceof File ? '' : message.text ?? '').trim()
@@ -291,7 +321,7 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, mes
const epochs = await call<Epoch[]>(path(group) + '/epochs')
const epoch = epochs.find((item) => item.current && item.membershipVersion === group.membershipVersion)
if (!epoch || !matchesEpoch(chat.epochs[epoch.id], epoch, group)) throw new Error('群成员或设备已变更,请先建立新世代')
if (expectedEpoch && epoch.id !== expectedEpoch) throw new Error('群加密会话已变更,请重新录音')
if (expectedEpoch && epoch.id !== expectedEpoch) throw new Error('群加密会话已变更,请重试')
if (chat.pendingMessage) throw new Error('请先刷新以重试待发消息')
const id = crypto.randomUUID()
const own = chat.epochs[epoch.id]!.roster[identity.device.id]
+2 -1
View File
@@ -4,8 +4,9 @@ import { useRoute, useRouter } from 'vue-router'
import { useSession } from '../session'
import type { Contact } from '../contacts'
import GroupChat from '../chat/GroupChat.vue'
import type { GroupSummary } from '../chat/group-chat'
type Group = { id: string; name: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member'; membershipVersion: string }
type Group = GroupSummary
type Detail = Group & { members: { id: string; username: string; state: Group['state']; role: Group['role'] }[] }
const session = useSession()