import { APIError } from '../api' import { mlsBinding, signMls } from '../identity' import { base64, decode, fingerprint, loadEngine } from './engine' import type { DeviceMls } from './engine' import { withVault } from './vault' import { decodeMessage, encodeAttachment, encodeMutation, encodeRead, encodeReply, readForwardedFile, sealAttachment, uploadAttachment } from './attachments' import type { Attachment, Mutation } from './attachments' import type { GroupChatState } from './group-chat' export interface Peer { id: string name: string publicKey: string mls?: { publicKey: string; signature: string } } export interface ChatIdentity { user: { id: string; username: string } device: { id: string } } export interface Package { package: string; signature: string } interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string; mutationTarget?: string; silent?: boolean } interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string } export interface ChatLine { id: string peer: string text: string attachment?: Attachment quote?: string favorite?: boolean recalled?: boolean edited?: boolean read?: boolean contact?: string time: string own: boolean } interface ChatState { engine: string cursor: string pending: Incoming[] received?: Record outbox: Outgoing[] lines: ChatLine[] pinned: Record groups: Record package?: { lastPublished: number; item: Package } packageChecked?: number rejected: number shareRead?: boolean groupChats?: Record } export type Call = (path: string, method?: string, body?: object, binary?: boolean) => Promise const encoder = new TextEncoder() function aad(id: string, sender: string, recipient: string) { return encoder.encode('XHChat message v1\n' + id + '\n' + sender + '\n' + recipient) } 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('对方设备签名验证失败') } } 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) return key } export function directory(call: Call, user: string) { return call('/contacts/' + user + '/devices') } export function update(identity: ChatIdentity, operation: (s: ChatState, save: (s: ChatState) => Promise, factory: Awaited>) => Promise) { return withVault(identity.device.id, async (state, save) => { const factory = await loadEngine() if (!state) { const engine = new factory.DeviceMls(identity.device.id) try { state = { engine: base64(engine.snapshot()), cursor: '0', pending: [], outbox: [], lines: [], pinned: {}, groups: {}, rejected: 0 } await save(state) } finally { engine.free() } } return operation(state, save, factory) }) } async function signed(identity: ChatIdentity, kind: 'credential' | 'KeyPackage', value: Uint8Array) { return base64(await signMls(identity.user.username, kind, identity.user.id, identity.device.id, value)) } export async function enableChat(identity: ChatIdentity, call: Call) { return update(identity, async (state, save, factory) => { const engine = factory.DeviceMls.restore(decode(state.engine)) try { if (engine.device() !== identity.device.id) throw new Error('本机加密状态属于其他设备') const key = engine.public_key() await call('/mls-credential', 'POST', { publicKey: base64(key), signature: await signed(identity, 'credential', key) }) await replenishPackages(identity, call, state, save, engine) return fingerprint(decode(await localIdentityKey(identity, call))) } finally { engine.free() } }) } export async function replenishPackages(identity: ChatIdentity, call: Call, state: ChatState, save: (s: ChatState) => Promise, 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) delete state.package await save(state) } const { available } = await call<{ available: number }>('/key-packages') for (let count = available; count < 4; count++) { const pack = engine.key_package() state.package = { lastPublished: 0, item: { package: base64(pack), signature: await signed(identity, 'KeyPackage', pack) } } state.engine = base64(engine.snapshot()) await save(state) await call('/key-packages', 'POST', state.package.item) delete state.package await save(state) } state.packageChecked = Date.now() await save(state) } async function localIdentityKey(identity: ChatIdentity, call: Call) { const { publicKey } = await call<{ publicKey: string }>('/mls-local-key') const credential = decode(publicKey) const proof = await signed(identity, 'credential', credential) await verify({ id: identity.device.id, name: '', publicKey }, identity.user.id, 'credential', credential, proof) return publicKey } export async function trust(identity: ChatIdentity, user: string, peer: Peer, code: string) { await verifiedPeer(peer, user) const expected = await fingerprint(decode(peer.publicKey)) if (code.replace(/\s+/g, '').toLowerCase() !== expected) throw new Error('安全码不匹配') await update(identity, async (state, save) => { const previous = state.pinned[peer.id] if (previous && previous !== peer.publicKey) throw new Error('该设备身份已变更,请使用新设备重新建立会话') state.pinned[peer.id] = peer.publicKey await save(state) }) } async function flush(state: ChatState, save: (state: ChatState) => Promise, call: Call) { const unavailable = new Set() for (const item of [...state.outbox]) { if (unavailable.has(item.recipientDevice)) continue try { await call('/inbox', 'POST', { messageId: item.messageId, recipientDevice: item.recipientDevice, ciphertext: item.ciphertext, ...(item.silent || item.mutationTarget ? { silent: true } : {}), }) state.outbox = state.outbox.filter((pending) => pending.messageId !== item.messageId) await save(state) } catch (error) { if (!(error instanceof APIError) || error.status !== 404) throw error unavailable.add(item.recipientDevice) } } return unavailable } export function applyMutation(line: Pick, mutation: Mutation) { if (line.recalled) return if (mutation.action === 'recall') { line.recalled = true line.text = '' delete line.attachment delete line.quote } else if (!line.attachment && mutation.text) { line.text = mutation.text line.edited = true } } export function mutateMessage(identity: ChatIdentity, user: string, peer: Peer, mutation: Mutation, call: Call) { return update(identity, async (state, save, factory) => { const current = (await directory(call, user)).find((item) => item.id === peer.id) if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('请核验对方设备安全码') await verifiedPeer(current, user) const unavailable = await flush(state, save, call) if (unavailable.has(current.id)) throw new Error('该设备暂不可接收消息') const line = state.lines.find((item) => item.id === mutation.id && item.peer === current.id && item.own) if (!line || line.recalled || (mutation.action === 'edit' && line.attachment)) throw new Error('此消息无法更新') if (mutation.action === 'edit') { mutation = { ...mutation, text: mutation.text?.trim() } if (!mutation.text || encoder.encode(mutation.text).length > 8000) throw new Error('消息须为 1 至 8000 字节') } const group = state.groups[current.id] if (!group) throw new Error('会话尚未建立') const engine = factory.DeviceMls.restore(decode(state.engine)) try { const id = crypto.randomUUID() const ciphertext = engine.encrypt(decode(group), aad(id, identity.device.id, current.id), encodeMutation(mutation)) state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext), mutationTarget: line.id }) applyMutation(line, mutation) state.engine = base64(engine.snapshot()) await save(state) await flush(state, save, call) } finally { engine.free() } }) } export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call, { reply, onQueued }: { reply?: ChatLine; onQueued?: () => void } = {}) { return update(identity, async (state, save, factory) => { const current = (await directory(call, user)).find((item) => item.id === peer.id) if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码') const key = await verifiedPeer(current, user) const unavailable = await flush(state, save, call) if (unavailable.has(current.id)) throw new Error('该设备暂不可接收消息') const text = typeof content === 'string' ? content.trim() : '' let plaintext = encoder.encode(text) if (typeof content === 'string' && (!plaintext.length || plaintext.length > 8000)) { throw new Error('消息须为 1 至 8000 字节') } if (state.lines.length >= 1000) throw new Error('本机预览版消息容量已达上限') const quote = reply && reply.peer === current.id ? (reply.text || reply.attachment?.name || '').slice(0, 240) : undefined if (quote && typeof content === 'string') plaintext = encodeReply(text, quote) const engine = factory.DeviceMls.restore(decode(state.engine)) try { let group = state.groups[current.id] ? decode(state.groups[current.id]) : undefined let attachment: Attachment | undefined if (typeof content !== 'string') { const sealed = await sealAttachment(content) attachment = sealed.attachment await uploadAttachment(attachment, sealed.ciphertext, current.id, call) plaintext = encodeAttachment(attachment) } if (!group) { const pack = await call('/contacts/' + user + '/devices/' + current.id + '/claim', 'POST') const wire = decode(pack.package) await verify(current, user, 'KeyPackage', wire, pack.signature) group = crypto.getRandomValues(new Uint8Array(32)) const welcome = engine.start(group, current.id, key, wire) state.groups[current.id] = base64(group) state.outbox.push({ messageId: crypto.randomUUID(), recipientDevice: current.id, ciphertext: base64(welcome) }) } const id = crypto.randomUUID() const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext) state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext) }) state.lines.push({ id, peer: current.id, contact: user, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true }) state.engine = base64(engine.snapshot()) await save(state) onQueued?.() await flush(state, save, call) } finally { engine.free() } }) } export function localMessageAction(identity: ChatIdentity, line: ChatLine, action: 'favorite' | 'remove') { return update(identity, async (state, save) => { const index = state.lines.findIndex((item) => item.id === line.id && item.peer === line.peer && item.own === line.own) if (index < 0) return if (action === 'remove') { if (state.outbox.some((item) => (item.mutationTarget ?? item.messageId) === line.id && item.recipientDevice === line.peer)) { throw new Error('待发送消息暂不能删除') } state.lines.splice(index, 1) } else { state.lines[index]!.favorite = !state.lines[index]!.favorite } await save(state) }) } export function readPrivateForward(identity: ChatIdentity, message: Pick, call: Call) { return update(identity, async (state) => { const line = state.lines.find((item) => item.id === message.id && item.peer === message.peer && item.own === message.own) if (!line || line.recalled) throw new Error('此私聊消息无法转发') return line.attachment ? readForwardedFile(line.attachment, call) : line.text }) } export function recentConversations(identity: ChatIdentity) { return withVault>(identity.device.id, async (state) => { const recent: Record = {} for (const line of state?.lines ?? []) { if (line.contact && (!recent[line.contact] || recent[line.contact] < line.time)) recent[line.contact] = line.time } return recent }, true) } export function markRead(identity: ChatIdentity, user: string, peer: Peer, visible: string[], call: Call) { return update(identity, async (state, save, factory) => { if (!state.shareRead) return const selected = new Set(visible) const lines = state.lines.filter((line) => line.peer === peer.id && !line.own && !line.read && !line.recalled && selected.has(line.id)).slice(0, 64) const group = state.groups[peer.id] if (!lines.length || !group || state.pinned[peer.id] !== peer.publicKey) return const current = (await directory(call, user)).find((device) => device.id === peer.id) if (!current || current.publicKey !== peer.publicKey) return await verifiedPeer(current, user) const engine = factory.DeviceMls.restore(decode(state.engine)) try { const id = crypto.randomUUID() const bytes = engine.encrypt(decode(group), aad(id, identity.device.id, peer.id), encodeRead(lines.map((line) => line.id))) state.outbox.push({ messageId: id, recipientDevice: peer.id, ciphertext: base64(bytes), silent: true }) for (const line of lines) line.read = true state.engine = base64(engine.snapshot()) await save(state) await flush(state, save, call) } finally { engine.free() } }) } export function setReadReceipts(identity: ChatIdentity, enabled: boolean) { return update(identity, async (state, save) => { state.shareRead = enabled await save(state) }) } export function synchronize(identity: ChatIdentity, user: string, call: Call) { return update(identity, async (state, save, factory) => { const received = state.received ??= {} const peers = await directory(call, user) const peerIDs = new Set(peers.map((peer) => peer.id)) let backfilled = false for (const line of state.lines) { if (!line.contact && peerIDs.has(line.peer)) { line.contact = user backfilled = true } } if (backfilled) await save(state) for (let page = 0; page < 4; page++) { const inbox = await call('/inbox?after=' + state.cursor) if (!inbox.length) break if (state.pending.length + inbox.length > 512) throw new Error('待验证消息已达上限,请先打开相应联系人的聊天') state.pending.push(...inbox) state.cursor = inbox.at(-1)!.sequence await save(state) if (inbox.length < 64) break } for (const item of [...state.pending]) { const peer = peers.find((device) => device.id === item.senderDevice) if (!peer || !peer.mls || state.pinned[peer.id] !== peer.publicKey) continue const engine = factory.DeviceMls.restore(decode(state.engine)) try { const key = await verifiedPeer(peer, user) const wire = decode(item.ciphertext) if (wire[3] === 3) { const group = base64(engine.join(peer.id, key, wire)) state.packageChecked = 0 const previous = state.groups[peer.id] if (!previous || group < previous) state.groups[peer.id] = group } else { const plaintext = engine.decrypt(peer.id, key, aad(item.messageId, peer.id, identity.device.id), wire) const content = decodeMessage(plaintext) if (content.read) { const ids = new Set(content.read) for (const line of state.lines) { if (line.own && line.peer === peer.id && ids.has(line.id)) line.read = true } } else if (content.mutation) { const mutation = content.mutation const changed = state.lines.find((line) => !line.own && line.peer === peer.id && line.id === mutation.id) if (changed) applyMutation(changed, mutation) } else if (state.lines.length < 1000) { state.lines.push({ id: item.messageId, peer: peer.id, contact: user, text: content.text, attachment: content.attachment, quote: content.quote, time: item.createdAt, own: false }) } } state.engine = base64(engine.snapshot()) } catch { state.rejected++ } finally { engine.free() } received[peer.id] = item.sequence state.pending = state.pending.filter((pending) => pending.sequence !== item.sequence) await save(state) } let deliveryError = '' try { const unavailable = await flush(state, save, call) if (unavailable.size) deliveryError = '部分待发消息的设备已不可用' } catch (cause) { deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试' } 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 { deliveryError ||= '密钥包补充失败,将自动重试' } finally { engine.free() } } return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, received, shareRead: state.shareRead === true, unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) } }) }