增加群消息跨会话加密转发
This commit is contained in:
1 parent
2e51827a07
commit
c36e94fd1c
9 files changed
+212
-13
No files matched your search
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user