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'] } 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 } 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 } export type GroupChatState = { cursor: string lines: Line[] epochs: Record pendingEpoch?: Publishing pendingMessage?: Pick & { line: Line } } 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 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, }) 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(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) { 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)) 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 { 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, message: string | File, call: Call, expectedEpoch?: string) { return update(identity, async (state, save, factory) => { 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(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 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, attachment, time: new Date().toISOString() } } state.engine = base64(engine.snapshot()) await save(state) } finally { engine.free() } }) }