import { APIError } from '../api' import { base64, decode } from './engine' import { applyMutation, replenishPackages, send, update, verifiedPeer, verify } from './chat' import type { Call, ChatIdentity, Package, Peer } from './chat' 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 & { 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 }[] } type Outgoing = { id: string; epoch: string; wire: string } type Packet = Outgoing & { sequence: string; senderDevice: string; createdAt: string; attachmentId?: string } export type GroupLine = { id: string; user: string; sender: string; name: string; text: string; time: string; epoch?: string attachment?: Attachment; quote?: string; edited?: boolean; recalled?: boolean; favorite?: boolean } type LineRef = Pick 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 } export type GroupChatState = { cursor: string lines: GroupLine[] epochs: Record pendingEpoch?: Publishing pendingMessage?: Outgoing & { line: GroupLine; mutation?: Mutation } } const encoder = new TextEncoder() 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')) function local(chats: Record, group: string) { return chats[group] ??= { cursor: '0', lines: [], epochs: {} } } function finishPending(chat: GroupChatState, pending: NonNullable) { pending.line.epoch ??= pending.epoch if (pending.mutation) applyGroupMutation(chat, pending.epoch, pending.line.sender, pending.mutation) else chat.lines.push(pending.line) delete chat.pendingMessage } function applyGroupMutation(chat: GroupChatState, epoch: string, sender: string, mutation: Mutation) { const target = chat.lines.find((line) => line.id === mutation.id && line.epoch === epoch && line.sender === sender) if (!target) return applyMutation(target, mutation) if (target.recalled) delete target.favorite } function trimHistory(chat: GroupChatState) { const cutoff = Math.max(0, chat.lines.length - 1000) chat.lines = [...chat.lines.slice(0, cutoff).filter((line) => line.favorite), ...chat.lines.slice(cutoff)] } export function setGroupFavorite(identity: ChatIdentity, group: GroupDetail, message: LineRef, favorite: boolean) { return update(identity, async (state, save) => { const chat = state.groupChats?.[group.id] const line = chat?.lines.find((item) => item.id === message.id && item.epoch === message.epoch && item.sender === message.sender) if (!chat || !line || line.recalled) throw new Error('此群消息无法收藏') if (favorite) line.favorite = true else delete line.favorite trimHistory(chat) await save(state) return chat.lines }) } export function groupQuote(line: GroupLine) { return (line.text || line.attachment?.name || '').slice(0, 240) } 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(path(group) + '/devices') } async function verifyRoster(identity: ChatIdentity, group: GroupDetail, selected: GroupDevice[], pinned: Record) { 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 = {} 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) { 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(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, 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(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(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, attachmentId: pending.line.attachment?.id, }) finishPending(chat, pending) } 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(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(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 && pending.line.attachment?.id === item.attachmentId) { finishPending(chat, pending) } } 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)) state.engine = base64(engine.snapshot()) const { text, attachment, quote, mutation } = decodeMessage(bytes) if (attachment?.id !== item.attachmentId) throw new Error('群附件标识不匹配') if (mutation) { applyGroupMutation(chat, item.epoch, item.senderDevice, mutation) } else if (attachment || quote || (text.length > 0 && bytes.length <= 8000)) { chat.lines.push({ id: item.id, epoch: item.epoch, user: sender.user, name: sender.name, sender: item.senderDevice, text, quote, attachment, time: item.createdAt }) } } catch { warning ||= '已跳过无法通过验证的群消息' } finally { engine.free() } } } chat.cursor = item.sequence } if (chat.cursor !== previousCursor) { trimHistory(chat) 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 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('/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() let content: Uint8Array = encoder.encode(text) if (!(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(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 (chat.pendingMessage) throw new Error('请先刷新以重试待发消息') const id = crypto.randomUUID() const own = chat.epochs[epoch.id]!.roster[identity.device.id] if (!own) throw new Error('当前设备未加入群加密世代') let attachment: Attachment | undefined let quote: string | undefined let mutation: Mutation | undefined if (message instanceof File) { 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) } else if (typeof message === 'object' && 'reply' in message) { const target = chat.lines.find((line) => line.epoch === epoch.id && line.epoch === message.reply.epoch && line.id === message.reply.id && line.sender === message.reply.sender) if (!target || target.recalled) throw new Error('当前会话中没有可引用的消息') quote = groupQuote(target) content = encodeReply(text, quote) } else if (typeof message === 'object') { 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) } 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, 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()) await save(state) } finally { engine.free() } }) }