为双端群聊增加端到端加密附件
This commit is contained in:
1 parent
5988ad6ed6
commit
a95a007768
21 files changed
+405
-84
No files matched your search
@@ -1,8 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useSession } from '../session'
|
||||
import { downloadAttachment } from './attachments'
|
||||
import type { Attachment } from './attachments'
|
||||
import MediaPreview from './MediaPreview.vue'
|
||||
import { enableChat, trust } from './chat'
|
||||
import { discardPendingGroupMessage, publishGroup, sendGroupMessage, synchronizeGroup } from './group-chat'
|
||||
import { discardPendingGroupMessage, groupAttachmentPath, publishGroup, sendGroupMessage, synchronizeGroup } from './group-chat'
|
||||
import type { GroupDetail, GroupDevice } from './group-chat'
|
||||
|
||||
const props = defineProps<{ group: GroupDetail }>()
|
||||
@@ -12,6 +15,7 @@ const code = ref('')
|
||||
const codes = ref<Record<string, string>>({})
|
||||
const selected = ref<Record<string, string>>({})
|
||||
const draft = ref('')
|
||||
const file = ref<File>()
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
const ready = computed(() => view.value?.ready && view.value.current?.membershipVersion === props.group.membershipVersion)
|
||||
@@ -84,6 +88,26 @@ function send() {
|
||||
})
|
||||
}
|
||||
|
||||
function chooseFile(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
file.value = input.files?.[0]
|
||||
input.value = ''
|
||||
}
|
||||
|
||||
function sendFile() {
|
||||
const identity = session.identity
|
||||
const selectedFile = file.value
|
||||
if (identity && selectedFile) void run(async () => {
|
||||
await sendGroupMessage(identity, props.group, selectedFile, session.authorized)
|
||||
file.value = undefined
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function download(attachment: Attachment) {
|
||||
void run(() => downloadAttachment(attachment, session.authorized, groupAttachmentPath(props.group, attachment.id)))
|
||||
}
|
||||
|
||||
function discard() {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
@@ -135,7 +159,12 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
<ul v-if="view?.lines.length" class="group-chat-lines" aria-label="群消息记录">
|
||||
<li v-for="line in view.lines" :key="line.id">
|
||||
<small>{{ line.name }} · {{ new Date(line.time).toLocaleString() }}</small>
|
||||
<p>{{ line.text }}</p>
|
||||
<template v-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>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-if="view?.hasPending" role="status">
|
||||
@@ -146,6 +175,14 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
<label>群消息<textarea v-model="draft" rows="3" maxlength="8000" required /></label>
|
||||
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">发送群消息</button>
|
||||
</form>
|
||||
<div v-if="ready" class="group-chat-composer">
|
||||
<label>选择群附件 <input type="file" :disabled="busy || view?.hasPending" @change="chooseFile"></label>
|
||||
<div v-if="file" class="message-actions">
|
||||
<span>{{ file.name }}</span>
|
||||
<button type="button" class="plain" :disabled="busy || view?.hasPending" @click="sendFile">发送群附件</button>
|
||||
<button type="button" class="plain" :disabled="busy" @click="file = undefined">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -160,4 +197,5 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
.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; }
|
||||
.media-preview :deep(img), .media-preview :deep(video) { display: block; max-width: 100%; max-height: 18rem; }
|
||||
</style>
|
||||
@@ -4,7 +4,7 @@ import { readAttachment } from './attachments'
|
||||
import type { Attachment } from './attachments'
|
||||
import { useSession } from '../session'
|
||||
|
||||
const props = defineProps<{ attachment: Attachment }>()
|
||||
const props = defineProps<{ attachment: Attachment; path?: string }>()
|
||||
const session = useSession()
|
||||
const url = ref('')
|
||||
const busy = ref(false)
|
||||
@@ -21,7 +21,7 @@ async function open() {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const bytes = await readAttachment(props.attachment, session.authorized)
|
||||
const bytes = await readAttachment(props.attachment, session.authorized, props.path)
|
||||
if (active) url.value = URL.createObjectURL(new Blob([bytes], { type: props.attachment.media }))
|
||||
} catch (cause) {
|
||||
if (active) error.value = cause instanceof Error ? cause.message : '无法加载媒体预览'
|
||||
|
||||
@@ -137,8 +137,8 @@ function encodeContent(kind: number, value: object) {
|
||||
return message
|
||||
}
|
||||
|
||||
export async function readAttachment(attachment: Attachment, call: Call) {
|
||||
const ciphertext = await call<ArrayBuffer>(attachmentPath(attachment.id), 'GET', undefined, true)
|
||||
export async function readAttachment(attachment: Attachment, call: Call, path = attachmentPath(attachment.id)) {
|
||||
const ciphertext = await call<ArrayBuffer>(path, 'GET', undefined, true)
|
||||
if (ciphertext.byteLength !== attachment.size + 16) throw new Error('附件完整性校验失败')
|
||||
const raw = decode(attachment.key)
|
||||
let bytes: ArrayBuffer
|
||||
@@ -153,8 +153,8 @@ export async function readAttachment(attachment: Attachment, call: Call) {
|
||||
return bytes
|
||||
}
|
||||
|
||||
export async function downloadAttachment(attachment: Attachment, call: Call) {
|
||||
const bytes = await readAttachment(attachment, call)
|
||||
export async function downloadAttachment(attachment: Attachment, call: Call, path?: string) {
|
||||
const bytes = await readAttachment(attachment, call, path)
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }))
|
||||
const link = document.createElement('a')
|
||||
link.download = attachment.name
|
||||
|
||||
+27
-13
@@ -2,6 +2,8 @@ import { APIError } from '../api'
|
||||
import { base64, decode } from './engine'
|
||||
import { 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'
|
||||
|
||||
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'] }
|
||||
@@ -9,8 +11,8 @@ 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 }[] }
|
||||
type Outgoing = { id: string; epoch: string; wire: string }
|
||||
type Packet = Outgoing & { sequence: string; senderDevice: string; createdAt: string }
|
||||
type Line = { id: string; user: string; sender: string; name: string; text: string; time: 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 }
|
||||
type Verified = { user: string; key: string; name: string }
|
||||
type VerifiedEpoch = { version: string; roster: Record<string, Verified> }
|
||||
export type GroupChatState = {
|
||||
@@ -22,8 +24,8 @@ export type GroupChatState = {
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const decoder = new TextDecoder('utf-8', { fatal: true })
|
||||
const path = (group: GroupDetail) => '/groups/' + encodeURIComponent(group.id)
|
||||
export const groupAttachmentPath = (group: GroupDetail, id: string) => path(group) + '/attachments/' + encodeURIComponent(id)
|
||||
const aad = (group: string, epoch: string, id: string, sender: string) =>
|
||||
encoder.encode(['XHChat group message v1', group, epoch, id, sender].join('\n'))
|
||||
|
||||
@@ -132,7 +134,9 @@ export function publishGroup(identity: ChatIdentity, group: GroupDetail, selecti
|
||||
async function sendPending(group: GroupDetail, chat: GroupChatState, call: Call) {
|
||||
const pending = chat.pendingMessage
|
||||
if (!pending) return
|
||||
await call(path(group) + '/messages', 'POST', { id: pending.id, epoch: pending.epoch, wire: pending.wire })
|
||||
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
|
||||
}
|
||||
@@ -186,7 +190,8 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
for (const item of packets) {
|
||||
if (item.senderDevice === identity.device.id) {
|
||||
const pending = chat.pendingMessage
|
||||
if (pending && pending.id === item.id && pending.epoch === item.epoch && pending.wire === item.wire) {
|
||||
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
|
||||
}
|
||||
@@ -198,11 +203,12 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
try {
|
||||
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))
|
||||
const text = decoder.decode(bytes)
|
||||
if (text.length > 0 && bytes.length <= 8000) {
|
||||
chat.lines.push({ id: item.id, user: sender.user, name: sender.name, sender: item.senderDevice, text, time: item.createdAt })
|
||||
}
|
||||
state.engine = base64(engine.snapshot())
|
||||
const { text, attachment, quote } = 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 })
|
||||
}
|
||||
} catch {
|
||||
warning ||= '已跳过无法通过验证的群消息'
|
||||
} finally {
|
||||
@@ -233,10 +239,11 @@ export function discardPendingGroupMessage(identity: ChatIdentity, group: GroupD
|
||||
})
|
||||
}
|
||||
|
||||
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, text: string, call: Call) {
|
||||
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: string | File, call: Call) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const content = encoder.encode(text.trim())
|
||||
if (content.length === 0 || content.length > 8000) throw new Error('消息须为 1 至 8000 字节')
|
||||
const text = typeof message === 'string' ? message.trim() : ''
|
||||
let content: Uint8Array = encoder.encode(text)
|
||||
if (typeof message === 'string' && (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)
|
||||
@@ -245,11 +252,18 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, tex
|
||||
const id = crypto.randomUUID()
|
||||
const own = chat.epochs[epoch.id]!.roster[identity.device.id]
|
||||
if (!own) throw new Error('当前设备未加入群加密世代')
|
||||
let attachment: Attachment | undefined
|
||||
if (typeof message !== 'string') {
|
||||
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)
|
||||
}
|
||||
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: text.trim(), time: new Date().toISOString() } }
|
||||
line: { id, user: identity.user.id, name: own.name, sender: identity.device.id, text, attachment, time: new Date().toISOString() } }
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user