实现 Windows 与 Web 加密文字群聊预览
This commit is contained in:
1 parent
709e6aa6a6
commit
ea6aec3323
19 files changed
+809
-31
No files matched your search
@@ -0,0 +1,163 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useSession } from '../session'
|
||||
import { enableChat, trust } from './chat'
|
||||
import { discardPendingGroupMessage, publishGroup, sendGroupMessage, synchronizeGroup } from './group-chat'
|
||||
import type { GroupDetail, GroupDevice } from './group-chat'
|
||||
|
||||
const props = defineProps<{ group: GroupDetail }>()
|
||||
const session = useSession()
|
||||
const view = ref<Awaited<ReturnType<typeof synchronizeGroup>>>()
|
||||
const code = ref('')
|
||||
const codes = ref<Record<string, string>>({})
|
||||
const selected = ref<Record<string, string>>({})
|
||||
const draft = ref('')
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
const ready = computed(() => view.value?.ready && view.value.current?.membershipVersion === props.group.membershipVersion)
|
||||
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)))))
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
|
||||
function pinned(device: GroupDevice) {
|
||||
return view.value?.pinned[device.id] === device.publicKey
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const identity = session.identity
|
||||
if (!code.value || !identity) return
|
||||
view.value = await synchronizeGroup(identity, props.group, session.authorized)
|
||||
for (const member of members.value) {
|
||||
const devices = view.value.devices.filter((device) => device.user === member.id)
|
||||
if (!devices.some((device) => device.id === selected.value[member.id] && pinned(device))) {
|
||||
selected.value[member.id] = devices.find(pinned)?.id ?? ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function run(action: () => Promise<void>, manual = true) {
|
||||
if (busy.value) return
|
||||
busy.value = true
|
||||
if (manual) error.value = ''
|
||||
try {
|
||||
await action()
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '群消息操作失败'
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function enable() {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
code.value = await enableChat(identity, session.authorized)
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function verifyDevice(device: GroupDevice) {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
await trust(identity, device.user, device, codes.value[device.id] ?? '')
|
||||
delete codes.value[device.id]
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function establish() {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
await publishGroup(identity, props.group, selected.value, session.authorized)
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function send() {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
const text = draft.value
|
||||
await sendGroupMessage(identity, props.group, text, session.authorized)
|
||||
if (draft.value === text) draft.value = ''
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function discard() {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
await discardPendingGroupMessage(identity, props.group)
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
watch(() => props.group.membershipVersion, () => void run(refresh))
|
||||
onMounted(() => { timer = setInterval(() => { if (code.value) void run(refresh, false) }, 2500) })
|
||||
onBeforeUnmount(() => clearInterval(timer))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="group-chat" aria-label="群消息">
|
||||
<h3>群消息</h3>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</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>
|
||||
<p v-if="ready" role="status">群加密已建立</p>
|
||||
<p v-else-if="view?.current && !view.current.welcome">当前设备未获分配群密钥。</p>
|
||||
<p v-else-if="!view?.current && group.role !== 'owner'">等待群主建立群加密会话。</p>
|
||||
<details :open="!ready">
|
||||
<summary>群设备和安全码</summary>
|
||||
<p>本机安全码 <code class="group-security-code">{{ code }}</code></p>
|
||||
<p class="muted">请通过线下或可信渠道与群成员核对各自设备的安全码。每位成员在一个群加密会话中使用一台设备。</p>
|
||||
<div v-for="member in members" :key="member.id" class="group-device-member">
|
||||
<strong>{{ member.username }}</strong>
|
||||
<p v-if="!view?.devices.some((device) => device.user === member.id)" class="muted">该成员尚未启用加密。</p>
|
||||
<div v-for="device in view?.devices.filter((item) => item.user === member.id)" :key="device.id">
|
||||
<p>{{ device.name }} · {{ device.id.slice(0, 8) }}<span v-if="pinned(device)"> · 已核验</span></p>
|
||||
<form v-if="!pinned(device)" class="contact-preferences" @submit.prevent="verifyDevice(device)">
|
||||
<label>{{ member.username }} · {{ device.id.slice(0, 8) }} 安全码<input v-model="codes[device.id]" autocomplete="off" maxlength="96" required></label>
|
||||
<button class="plain" :disabled="busy">核验设备</button>
|
||||
</form>
|
||||
</div>
|
||||
<label v-if="group.role === 'owner' && !view?.current">{{ member.username }} 的群设备
|
||||
<select v-model="selected[member.id]">
|
||||
<option value="">选择已核验设备</option>
|
||||
<option v-for="device in view?.devices.filter((item) => item.user === member.id && pinned(item))" :key="device.id" :value="device.id">
|
||||
{{ device.name }} · {{ device.id.slice(0, 8) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<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">
|
||||
<small>{{ line.name }} · {{ new Date(line.time).toLocaleString() }}</small>
|
||||
<p>{{ line.text }}</p>
|
||||
</li>
|
||||
</ul>
|
||||
<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">
|
||||
<label>群消息<textarea v-model="draft" rows="3" maxlength="8000" required /></label>
|
||||
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">发送群消息</button>
|
||||
</form>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.group-chat { display: grid; gap: .7rem; padding-block: 1rem; }
|
||||
.group-chat p, .group-chat h3 { margin: 0; }
|
||||
.group-security-code { overflow-wrap: anywhere; }
|
||||
.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-composer { display: grid; gap: .55rem; }
|
||||
.group-chat-composer textarea { display: block; width: 100%; resize: vertical; font: inherit; }
|
||||
.group-chat button { justify-self: start; }
|
||||
</style>
|
||||
@@ -5,6 +5,7 @@ import type { DeviceMls } from './engine'
|
||||
import { withVault } from './vault'
|
||||
import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readAttachment, sealAttachment, uploadAttachment, voiceFile } from './attachments'
|
||||
import type { Attachment, Mutation } from './attachments'
|
||||
import type { GroupChatState } from './group-chat'
|
||||
|
||||
export interface Peer {
|
||||
id: string
|
||||
@@ -18,7 +19,7 @@ export interface ChatIdentity {
|
||||
device: { id: string }
|
||||
}
|
||||
|
||||
interface Package { package: string; signature: string }
|
||||
export interface Package { package: string; signature: string }
|
||||
interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string; mutationTarget?: string }
|
||||
interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string }
|
||||
|
||||
@@ -49,6 +50,7 @@ interface ChatState {
|
||||
packageChecked?: number
|
||||
rejected: number
|
||||
shareRead?: boolean
|
||||
groupChats?: Record<string, GroupChatState>
|
||||
}
|
||||
|
||||
export type Call = <T>(path: string, method?: string, body?: object, binary?: boolean) => Promise<T>
|
||||
@@ -58,14 +60,14 @@ function aad(id: string, sender: string, recipient: string) {
|
||||
return encoder.encode('XHChat message v1\n' + id + '\n' + sender + '\n' + recipient)
|
||||
}
|
||||
|
||||
async function verify(peer: Peer, user: string, type: 'credential' | 'KeyPackage', value: Uint8Array, signature: string) {
|
||||
export async function verify(peer: Peer, user: string, type: 'credential' | 'KeyPackage', value: Uint8Array, signature: string) {
|
||||
const key = await crypto.subtle.importKey('raw', decode(peer.publicKey), 'Ed25519', false, ['verify'])
|
||||
if (!await crypto.subtle.verify('Ed25519', key, decode(signature), mlsBinding(type, user, peer.id, value))) {
|
||||
throw new Error('对方设备签名验证失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function verifiedPeer(peer: Peer, user: string) {
|
||||
export async function verifiedPeer(peer: Peer, user: string) {
|
||||
if (!peer.mls) throw new Error('此设备尚未启用加密聊天')
|
||||
const key = decode(peer.mls.publicKey)
|
||||
await verify(peer, user, 'credential', key, peer.mls.signature)
|
||||
@@ -76,7 +78,7 @@ export function directory(call: Call, user: string) {
|
||||
return call<Peer[]>('/contacts/' + user + '/devices')
|
||||
}
|
||||
|
||||
function update<R>(identity: ChatIdentity, operation: (s: ChatState, save: (s: ChatState) => Promise<void>, factory: Awaited<ReturnType<typeof loadEngine>>) => Promise<R>) {
|
||||
export function update<R>(identity: ChatIdentity, operation: (s: ChatState, save: (s: ChatState) => Promise<void>, factory: Awaited<ReturnType<typeof loadEngine>>) => Promise<R>) {
|
||||
return withVault<ChatState, R>(identity.device.id, async (state, save) => {
|
||||
const factory = await loadEngine()
|
||||
if (!state) {
|
||||
@@ -111,7 +113,7 @@ export async function enableChat(identity: ChatIdentity, call: Call) {
|
||||
})
|
||||
}
|
||||
|
||||
async function replenishPackages(identity: ChatIdentity, call: Call, state: ChatState, save: (s: ChatState) => Promise<void>, engine: DeviceMls) {
|
||||
export async function replenishPackages(identity: ChatIdentity, call: Call, state: ChatState, save: (s: ChatState) => Promise<void>, engine: DeviceMls) {
|
||||
// Persist generated private material before sending any public package.
|
||||
if (state.package && state.package.lastPublished === 0) {
|
||||
await call('/key-packages', 'POST', state.package.item)
|
||||
|
||||
@@ -6,8 +6,11 @@ export interface DeviceMls {
|
||||
key_package(): Uint8Array<ArrayBuffer>
|
||||
start(id: Uint8Array, peer: string, key: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
join(peer: string, key: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
start_group(id: Uint8Array, roster: string): Uint8Array<ArrayBuffer>
|
||||
join_group(id: Uint8Array, owner: string, roster: string, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
encrypt(id: Uint8Array, aad: Uint8Array, value: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
decrypt(peer: string, key: Uint8Array, aad: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
decrypt_group(id: Uint8Array, peer: string, key: Uint8Array, aad: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
}
|
||||
|
||||
interface Module {
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import { APIError } from '../api'
|
||||
import { base64, decode } from './engine'
|
||||
import { replenishPackages, update, verifiedPeer, verify } from './chat'
|
||||
import type { Call, ChatIdentity, Package, Peer } from './chat'
|
||||
|
||||
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 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 Verified = { user: string; key: string; name: string }
|
||||
type VerifiedEpoch = { version: string; roster: Record<string, Verified> }
|
||||
export type GroupChatState = {
|
||||
cursor: string
|
||||
lines: Line[]
|
||||
epochs: Record<string, VerifiedEpoch>
|
||||
pendingEpoch?: Publishing
|
||||
pendingMessage?: Pick<Packet, 'id' | 'epoch' | 'wire'> & { line: Line }
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const decoder = new TextDecoder('utf-8', { fatal: true })
|
||||
const path = (group: GroupDetail) => '/groups/' + encodeURIComponent(group.id)
|
||||
const aad = (group: string, epoch: string, id: string, sender: string) =>
|
||||
encoder.encode(['XHChat group message v1', group, epoch, id, sender].join('\n'))
|
||||
|
||||
function local(chats: Record<string, GroupChatState>, group: string) {
|
||||
return chats[group] ??= { cursor: '0', lines: [], epochs: {} }
|
||||
}
|
||||
|
||||
function activeMembers(group: GroupDetail) {
|
||||
return group.members.filter((member) => member.state === 'active')
|
||||
}
|
||||
|
||||
function matchesEpoch(known: VerifiedEpoch | undefined, epoch: Epoch, group: GroupDetail) {
|
||||
if (!known || known.version !== epoch.membershipVersion) return false
|
||||
const members = activeMembers(group)
|
||||
const expected = Object.keys(known.roster)
|
||||
return expected.length === members.length && epoch.roster.length === expected.length &&
|
||||
expected.every((id) => epoch.roster.includes(id)) &&
|
||||
members.every((member) => Object.values(known.roster).some((device) => device.user === member.id))
|
||||
}
|
||||
|
||||
async function groupID(group: string, epoch: string) {
|
||||
return new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode('XHChat group v1\n' + group + '\n' + epoch)))
|
||||
}
|
||||
|
||||
export function groupDevices(group: GroupDetail, call: Call) {
|
||||
return call<GroupDevice[]>(path(group) + '/devices')
|
||||
}
|
||||
|
||||
async function verifyRoster(identity: ChatIdentity, group: GroupDetail, selected: GroupDevice[], pinned: Record<string, string>) {
|
||||
const members = activeMembers(group)
|
||||
if (selected.length !== members.length || new Set(selected.map((device) => device.user)).size !== members.length) {
|
||||
throw new Error('每位有效成员须选定一台已核验设备')
|
||||
}
|
||||
const checked: Record<string, Verified> = {}
|
||||
for (const device of selected) {
|
||||
const member = members.find((item) => item.id === device.user)
|
||||
if (!member || (device.id !== identity.device.id && pinned[device.id] !== device.publicKey)) {
|
||||
throw new Error('请先核验名单内每台设备的安全码')
|
||||
}
|
||||
if ((device.user === identity.user.id) !== (device.id === identity.device.id)) {
|
||||
throw new Error('当前账号须使用本机设备')
|
||||
}
|
||||
const key = await verifiedPeer(device, device.user)
|
||||
checked[device.id] = { user: device.user, key: base64(key), name: member.username }
|
||||
}
|
||||
return checked
|
||||
}
|
||||
|
||||
async function publishPending(group: GroupDetail, chat: GroupChatState, call: Call, persist: () => Promise<void>) {
|
||||
if (!chat.pendingEpoch) return
|
||||
const pending = chat.pendingEpoch
|
||||
try {
|
||||
await call(path(group) + '/epochs', 'POST', pending)
|
||||
} catch (error) {
|
||||
if (!(error instanceof APIError) || error.status !== 409) throw error
|
||||
const epochs = await call<Epoch[]>(path(group) + '/epochs')
|
||||
if (!epochs.some((item) => item.id === pending.id)) {
|
||||
delete chat.epochs[pending.id]
|
||||
delete chat.pendingEpoch
|
||||
await persist()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
delete chat.pendingEpoch
|
||||
await persist()
|
||||
}
|
||||
|
||||
export function publishGroup(identity: ChatIdentity, group: GroupDetail, selections: Record<string, string>, call: Call) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const chat = local(state.groupChats ??= {}, group.id)
|
||||
if (chat.pendingEpoch) return publishPending(group, chat, call, () => save(state))
|
||||
const devices = await groupDevices(group, call)
|
||||
const selection = activeMembers(group).map((member) => {
|
||||
const id = member.id === identity.user.id ? identity.device.id : selections[member.id]
|
||||
const device = devices.find((item) => item.id === id && item.user === member.id)
|
||||
if (!device) throw new Error('请为每位成员选择一台设备')
|
||||
return device
|
||||
})
|
||||
const roster = await verifyRoster(identity, group, selection, state.pinned)
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
if (base64(engine.public_key()) !== roster[identity.device.id]?.key) throw new Error('本机群凭据不匹配')
|
||||
const existing = await call<Epoch[]>(path(group) + '/epochs')
|
||||
if (existing.some((item) => item.current)) throw new Error('当前群加密世代已建立')
|
||||
const enrollments = []
|
||||
for (const device of selection.filter((item) => item.id !== identity.device.id)) {
|
||||
const pack = await call<Package>(path(group) + '/devices/' + device.id + '/claim', 'POST')
|
||||
const wire = decode(pack.package)
|
||||
await verify(device, device.user, 'KeyPackage', wire, pack.signature)
|
||||
enrollments.push({ device: device.id, key: Array.from(decode(roster[device.id]!.key)), package: Array.from(wire) })
|
||||
}
|
||||
const id = crypto.randomUUID()
|
||||
const welcome = base64(engine.start_group(await groupID(group.id, id), JSON.stringify(enrollments)))
|
||||
chat.epochs[id] = { version: group.membershipVersion, roster }
|
||||
chat.pendingEpoch = { id, membershipVersion: group.membershipVersion,
|
||||
devices: selection.map((device) => ({ device: device.id, wire: device.id === identity.device.id ? undefined : welcome })) }
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
await publishPending(group, chat, call, () => save(state))
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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 })
|
||||
chat.lines.push(pending.line)
|
||||
delete chat.pendingMessage
|
||||
}
|
||||
|
||||
export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, call: Call) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const chat = local(state.groupChats ??= {}, group.id)
|
||||
const devices = await groupDevices(group, call)
|
||||
if (chat.pendingEpoch) await publishPending(group, chat, call, () => save(state))
|
||||
const epochs = await call<Epoch[]>(path(group) + '/epochs')
|
||||
const current = epochs.find((item) => item.current && item.membershipVersion === group.membershipVersion)
|
||||
let warning = ''
|
||||
if (current && !chat.epochs[current.id] && current.welcome) {
|
||||
try {
|
||||
const selected = current.roster.map((id) => {
|
||||
const device = devices.find((item) => item.id === id)
|
||||
if (!device) throw new Error('群设备名单已变更')
|
||||
return device
|
||||
})
|
||||
const roster = await verifyRoster(identity, group, selected, state.pinned)
|
||||
if (roster[current.creatorDevice]?.user !== activeMembers(group).find((member) => member.role === 'owner')?.id) {
|
||||
throw new Error('无法验证此群的创建设备')
|
||||
}
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
const members = Object.entries(roster).map(([device, { key }]) => ({ device, key: Array.from(decode(key)) }))
|
||||
engine.join_group(await groupID(group.id, current.id), current.creatorDevice, JSON.stringify(members), decode(current.welcome))
|
||||
state.engine = base64(engine.snapshot())
|
||||
chat.epochs[current.id] = { version: group.membershipVersion, roster }
|
||||
state.packageChecked = 0
|
||||
await save(state)
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
} catch (error) {
|
||||
warning = error instanceof Error ? error.message : '群加密会话尚未核验'
|
||||
}
|
||||
}
|
||||
const ready = Boolean(current && matchesEpoch(chat.epochs[current.id], current, group))
|
||||
if (current && chat.epochs[current.id] && !ready) warning = '群设备名单与本机核验记录不匹配'
|
||||
if (ready && chat.pendingMessage && chat.pendingMessage.epoch === current?.id) {
|
||||
try {
|
||||
await sendPending(group, chat, call)
|
||||
await save(state)
|
||||
} catch (error) {
|
||||
warning ||= error instanceof Error ? error.message : '暂时无法投递群消息'
|
||||
}
|
||||
}
|
||||
const packets = await call<Packet[]>(path(group) + '/messages?after=' + chat.cursor)
|
||||
const previousCursor = chat.cursor
|
||||
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) {
|
||||
chat.lines.push(pending.line)
|
||||
delete chat.pendingMessage
|
||||
}
|
||||
} else {
|
||||
if (item.epoch === current?.id && !ready) break
|
||||
const sender = chat.epochs[item.epoch]?.roster[item.senderDevice]
|
||||
if (sender) {
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
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())
|
||||
} catch {
|
||||
warning ||= '已跳过无法通过验证的群消息'
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
}
|
||||
}
|
||||
chat.cursor = item.sequence
|
||||
}
|
||||
if (chat.cursor !== previousCursor) {
|
||||
chat.lines = chat.lines.slice(-1000)
|
||||
await save(state)
|
||||
}
|
||||
if (Date.now() - (state.packageChecked ?? 0) >= 60_000) {
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try { await replenishPackages(identity, call, state, save, engine) } catch { warning ||= '密钥包补充失败' } finally { engine.free() }
|
||||
}
|
||||
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning,
|
||||
hasPending: Boolean(chat.pendingMessage), stalePending: Boolean(chat.pendingMessage && chat.pendingMessage.epoch !== current?.id) }
|
||||
})
|
||||
}
|
||||
|
||||
export function discardPendingGroupMessage(identity: ChatIdentity, group: GroupDetail) {
|
||||
return update(identity, async (state, save) => {
|
||||
const chat = local(state.groupChats ??= {}, group.id)
|
||||
delete chat.pendingMessage
|
||||
await save(state)
|
||||
})
|
||||
}
|
||||
|
||||
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, text: string, 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 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)
|
||||
if (!epoch || !matchesEpoch(chat.epochs[epoch.id], epoch, group)) throw new Error('群成员或设备已变更,请先建立新世代')
|
||||
if (chat.pendingMessage) throw new Error('请先刷新以重试待发消息')
|
||||
const id = crypto.randomUUID()
|
||||
const own = chat.epochs[epoch.id]!.roster[identity.device.id]
|
||||
if (!own) throw new Error('当前设备未加入群加密世代')
|
||||
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() } }
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useSession } from '../session'
|
||||
import type { Contact } from '../contacts'
|
||||
import GroupChat from '../chat/GroupChat.vue'
|
||||
|
||||
type Group = { id: string; name: string; state: 'active' | 'invited'; role: 'owner' | 'admin' | 'member'; membershipVersion: string }
|
||||
type Detail = Group & { members: { id: string; username: string; state: Group['state']; role: Group['role'] }[] }
|
||||
@@ -121,7 +122,7 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="muted">群消息尚未开放。</p>
|
||||
<GroupChat v-if="session.identity" :key="detail.id" :group="detail" />
|
||||
<form v-if="manage" class="contact-preferences" @submit.prevent="change('rename', undefined, nextName)">
|
||||
<label>修改群名称<input v-model="nextName" required maxlength="64"></label>
|
||||
<button class="plain" :disabled="busy || !nextName.trim() || nextName.trim() === detail.name">保存群名称</button>
|
||||
|
||||
Reference in new issue
Block a user