支持跨端加密消息编辑与撤回

This commit is contained in:
xhgit committed 2026-11-13 19:26:17 +08:00
1 parent 9b8c2026ea
commit f5f116a266
6 files changed
+140 -23

No files matched your search

+22 -4
View File
@@ -53,8 +53,18 @@ export function encodeAttachment(attachment: Attachment) {
return message
}
export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment; quote?: string } {
export type Mutation = { action: 'edit' | 'recall'; id: string; text?: string }
type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation }
export function decodeMessage(message: Uint8Array): ChatContent {
if (message[0] !== 255) return { text: decoder.decode(message) }
if (message[1] === 3 && message.length <= 18_000) {
const value = JSON.parse(decoder.decode(message.subarray(2))) as Mutation | null
if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) ||
!(value.action === 'recall' || value.action === 'edit' && typeof value.text === 'string' &&
value.text.trim() && encoder.encode(value.text).length <= 8000)) throw new Error('消息更新格式无效')
return { text: '', mutation: value }
}
if (message[1] === 2 && message.length <= 18_000) {
const value = JSON.parse(decoder.decode(message.subarray(2))) as { text?: unknown; quote?: unknown } | null
if (!value || typeof value.text !== 'string' || !value.text.trim() || typeof value.quote !== 'string' ||
@@ -76,10 +86,18 @@ export function decodeMessage(message: Uint8Array): { text: string; attachment?:
}
export function encodeReply(text: string, quote: string) {
const body = encoder.encode(JSON.stringify({ text, quote }))
if (body.length + 2 > 18_000) throw new Error('引用消息过长')
return encodeContent(2, { text, quote })
}
export function encodeMutation(mutation: Mutation) {
return encodeContent(3, mutation)
}
function encodeContent(kind: number, value: object) {
const body = encoder.encode(JSON.stringify(value))
if (body.length + 2 > 18_000) throw new Error('消息内容过长')
const message = new Uint8Array(body.length + 2)
message.set([255, 2])
message.set([255, kind])
message.set(body, 2)
return message
}