增加加密群公告和群主转让

This commit is contained in:
xhgit committed 2026-11-15 17:20:18 +08:00
1 parent 52c0e52ffd
commit 47b76080c6
10 files changed
+163 -22

No files matched your search

+34
View File
@@ -20,6 +20,7 @@ const code = ref('')
const codes = ref<Record<string, string>>({})
const selected = ref<Record<string, string>>({})
const draft = ref('')
const announcementDraft = ref<string>()
const search = ref('')
const favoritesOnly = ref(false)
const historyViews = [
@@ -146,6 +147,17 @@ function establish() {
})
}
function saveAnnouncement() {
const identity = session.identity
const announcement = announcementDraft.value
if (!identity || announcement === undefined) return
void run(async () => {
await sendGroupMessage(identity, props.group, { announcement }, session.authorized)
announcementDraft.value = undefined
await refresh()
})
}
function send() {
const identity = session.identity
if (identity) void run(async () => {
@@ -239,6 +251,7 @@ watch(() => session.groupChange, (event) => { if (event?.groupId === props.group
watch(() => session.connection, (connection) => { if (connection === '实时连接已建立') queueRefresh() })
watch(currentEpoch, (epoch, previous) => {
if (!previous || epoch === previous) return
announcementDraft.value = undefined
if (editing.value || replying.value) draft.value = ''
editing.value = undefined
replying.value = undefined
@@ -283,6 +296,24 @@ onBeforeUnmount(() => {
<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>
<section v-if="view && (view.announcement || (ready && group.role === 'owner'))" class="group-announcement" aria-label="群公告">
<h4>群公告</h4>
<p v-if="view.announcement" class="announcement-text">{{ view.announcement }}</p>
<p v-else class="muted">暂无群公告。</p>
<template v-if="ready && group.role === 'owner'">
<button v-if="announcementDraft === undefined" type="button" class="plain" :disabled="busy || view.hasPending"
@click="announcementDraft = view.announcement ?? ''">{{ view.announcement ? '编辑群公告' : '写群公告' }}</button>
<form v-else class="group-chat-composer" @submit.prevent="saveAnnouncement">
<label>公告内容<textarea v-model="announcementDraft" rows="3" maxlength="2000" /></label>
<div class="message-actions">
<button class="primary" :disabled="busy || view.hasPending || announcementDraft.trim() === (view.announcement ?? '')">
{{ announcementDraft.trim() ? '发布公告' : '清除公告' }}
</button>
<button type="button" class="plain" @click="announcementDraft = undefined">取消</button>
</div>
</form>
</template>
</section>
<details :open="!ready">
<summary>群设备和安全码</summary>
<p>本机安全码 <code class="group-security-code">{{ code }}</code></p>
@@ -385,6 +416,9 @@ onBeforeUnmount(() => {
<style scoped>
.group-chat { display: grid; gap: .7rem; padding-block: 1rem; }
.group-chat p, .group-chat h3 { margin: 0; }
.group-announcement { display: grid; gap: .45rem; padding: .65rem .8rem; border: 1px solid var(--line); border-radius: .45rem; }
.group-announcement h4 { margin: 0; }
.announcement-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.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; }
+49 -17
View File
@@ -21,18 +21,22 @@ export type GroupLine = {
}
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 GroupContent = string | File | { text: string; reply: LineRef } | (Mutation & { epoch: string }) | { announcement: string }
type Verified = { user: string; key: string; name: string }
type VerifiedEpoch = { version: string; roster: Record<string, Verified> }
type VerifiedEpoch = { version: string; roster: Record<string, Verified>; ownerDevice?: string }
export type GroupChatState = {
cursor: string
lines: GroupLine[]
epochs: Record<string, VerifiedEpoch>
announcement?: { text: string; sequence: string }
pendingEpoch?: Publishing
pendingMessage?: Outgoing & { line: GroupLine; mutation?: Mutation }
pendingMessage?: Outgoing & { line: GroupLine; mutation?: Mutation; announcement?: string }
}
const encoder = new TextEncoder()
const decoder = new TextDecoder('utf-8', { fatal: true })
const announcementPrefix = [255, 5]
const maxAnnouncementBytes = 2000
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) =>
@@ -42,9 +46,14 @@ function local(chats: Record<string, GroupChatState>, group: string) {
return chats[group] ??= { cursor: '0', lines: [], epochs: {} }
}
function finishPending(chat: GroupChatState, pending: NonNullable<GroupChatState['pendingMessage']>) {
function applyAnnouncement(chat: GroupChatState, text: string, sequence: string) {
if (!chat.announcement || BigInt(sequence) > BigInt(chat.announcement.sequence)) chat.announcement = { text, sequence }
}
function finishPending(chat: GroupChatState, pending: NonNullable<GroupChatState['pendingMessage']>, sequence: string) {
pending.line.epoch ??= pending.epoch
if (pending.mutation) applyGroupMutation(chat, pending.epoch, pending.line.sender, pending.mutation)
if (pending.announcement !== undefined) applyAnnouncement(chat, pending.announcement, sequence)
else if (pending.mutation) applyGroupMutation(chat, pending.epoch, pending.line.sender, pending.mutation)
else chat.lines.push(pending.line)
delete chat.pendingMessage
}
@@ -86,9 +95,12 @@ function matchesEpoch(known: VerifiedEpoch | undefined, epoch: Epoch, group: Gro
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 &&
const owner = members.find((member) => member.role === 'owner')
return Boolean(owner && known.roster[epoch.creatorDevice]?.user === owner.id &&
(!known.ownerDevice || known.ownerDevice === epoch.creatorDevice) &&
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))
members.every((member) => Object.values(known.roster).some((device) => device.user === member.id)))
}
async function groupID(group: string, epoch: string) {
@@ -164,7 +176,7 @@ export function publishGroup(identity: ChatIdentity, group: GroupDetail, selecti
}
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.epochs[id] = { version: group.membershipVersion, roster, ownerDevice: identity.device.id }
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())
@@ -179,10 +191,10 @@ 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', {
const { sequence } = await call<{ sequence: string }>(path(group) + '/messages', 'POST', {
id: pending.id, epoch: pending.epoch, wire: pending.wire, attachmentId: pending.line.attachment?.id,
})
finishPending(chat, pending)
finishPending(chat, pending, sequence)
}
export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, call: Call) {
@@ -209,7 +221,7 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
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 }
chat.epochs[current.id] = { version: group.membershipVersion, roster, ownerDevice: current.creatorDevice }
state.packageChecked = 0
await save(state)
} finally {
@@ -220,6 +232,10 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
}
}
const ready = Boolean(current && matchesEpoch(chat.epochs[current.id], current, group))
if (ready && current && !chat.epochs[current.id]!.ownerDevice) {
chat.epochs[current.id]!.ownerDevice = current.creatorDevice
await save(state)
}
if (current && chat.epochs[current.id] && !ready) warning = '群设备名单与本机核验记录不匹配'
if (ready && chat.pendingMessage && chat.pendingMessage.epoch === current?.id) {
try {
@@ -236,7 +252,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) {
finishPending(chat, pending)
finishPending(chat, pending, item.sequence)
}
} else {
if (item.epoch === current?.id && !ready) break
@@ -247,6 +263,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())
if (bytes[0] === announcementPrefix[0] && bytes[1] === announcementPrefix[1]) {
if (item.attachmentId || bytes.length > maxAnnouncementBytes + 2 ||
chat.epochs[item.epoch]?.ownerDevice !== item.senderDevice) throw new Error('群公告身份或格式无效')
applyAnnouncement(chat, decoder.decode(bytes.subarray(2)), item.sequence)
chat.cursor = item.sequence
continue
}
const { text, attachment, quote, mutation } = decodeMessage(bytes)
if (attachment?.id !== item.attachmentId) throw new Error('群附件标识不匹配')
if (mutation) {
@@ -273,7 +296,7 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
try { await replenishPackages(identity, call, state, save, engine) } catch { warning ||= '密钥包补充失败' } finally { engine.free() }
}
const hasMore = packets.length === 64 && packets.at(-1)?.sequence === chat.cursor
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning, cursor: chat.cursor, hasMore,
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning, cursor: chat.cursor, hasMore, announcement: chat.announcement?.text,
hasPending: Boolean(chat.pendingMessage), stalePending: Boolean(chat.pendingMessage && chat.pendingMessage.epoch !== current?.id) }
})
}
@@ -319,9 +342,10 @@ export async function forwardContent(identity: ChatIdentity, destination: Forwar
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()
const announcement = typeof message === 'object' && 'announcement' in message ? message.announcement.trim() : undefined
const text = (typeof message === 'string' ? message : !(message instanceof File) && 'text' in message ? message.text ?? '' : '').trim()
let content: Uint8Array = encoder.encode(text)
if (!(message instanceof File) && !(typeof message === 'object' && 'action' in message && message.action === 'recall') &&
if (announcement === undefined && !(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')
@@ -346,17 +370,25 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, mes
if (!target || target.recalled) throw new Error('当前会话中没有可引用的消息')
quote = groupQuote(target)
content = encodeReply(text, quote)
} else if (typeof message === 'object') {
} else if (typeof message === 'object' && 'action' in message) {
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)
}
if (announcement !== undefined) {
if (group.role !== 'owner' || epoch.creatorDevice !== identity.device.id) throw new Error('请使用群主的会话设备发布公告')
const body = encoder.encode(announcement)
if (body.length > maxAnnouncementBytes) throw new Error('群公告不能超过 2,000 字节')
content = new Uint8Array(body.length + 2)
content.set(announcementPrefix)
content.set(body, 2)
}
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), mutation,
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire), mutation, announcement,
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())
+3
View File
@@ -203,6 +203,8 @@ onBeforeUnmount(() => {
@click="change(member.role === 'admin' ? 'demote' : 'promote', member.id)">
{{ member.role === 'admin' ? '取消管理员' : '设为管理员' }}
</button>
<button v-if="detail.role === 'owner' && member.state === 'active'" type="button" class="plain" :disabled="busy"
@click="confirmation = { action: 'transfer', target: member.id, label: '将群主转让给 ' + member.username }">转让群主</button>
<button v-if="detail.role === 'owner' || member.role === 'member'" class="plain" :disabled="busy"
@click="confirmation = { action: 'remove', target: member.id, label: member.state === 'invited' ? '撤销此邀请' : '移除此成员' }">
{{ member.state === 'invited' ? '撤销邀请' : '移除成员' }}
@@ -214,6 +216,7 @@ onBeforeUnmount(() => {
<button v-else class="plain" :disabled="busy" @click="confirmation = { action: 'leave', label: '退出群组' }">退出群组</button>
<div v-if="confirmation" class="confirmation">
<p>确认{{ confirmation.label }}?</p>
<p v-if="confirmation.action === 'transfer'" class="muted">转让完成后,你将成为普通成员,由新群主重新建立加密会话。</p>
<button class="plain" :disabled="busy" @click="change(confirmation.action, confirmation.target)">确认操作</button>
<button class="plain" @click="confirmation = undefined">取消</button>
</div>