增加加密引用回复和本机消息管理

This commit is contained in:
xhgit committed 2026-11-13 19:17:13 +08:00
1 parent c24960d22a
commit c27ad52dab
7 files changed
+121 -8

No files matched your search

+18 -1
View File
@@ -53,8 +53,16 @@ export function encodeAttachment(attachment: Attachment) {
return message
}
export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment } {
export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment; quote?: string } {
if (message[0] !== 255) return { text: decoder.decode(message) }
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' ||
!value.quote.trim() || value.quote.length > 240 || encoder.encode(value.text).length > 8000) {
throw new Error('引用消息格式无效')
}
return { text: value.text, quote: value.quote }
}
if (message[1] !== 1 || message.length > 4096) throw new Error('附件描述格式无效')
const value = JSON.parse(decoder.decode(message.subarray(2))) as Attachment | null
if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) ||
@@ -67,6 +75,15 @@ export function decodeMessage(message: Uint8Array): { text: string; attachment?:
return { text: '', attachment: value }
}
export function encodeReply(text: string, quote: string) {
const body = encoder.encode(JSON.stringify({ text, quote }))
if (body.length + 2 > 18_000) throw new Error('引用消息过长')
const message = new Uint8Array(body.length + 2)
message.set([255, 2])
message.set(body, 2)
return message
}
export async function downloadAttachment(attachment: Attachment, call: Call) {
const ciphertext = await call<ArrayBuffer>(attachmentPath(attachment.id), 'GET', undefined, true)
if (ciphertext.byteLength !== attachment.size + 16) throw new Error('附件完整性校验失败')
+23 -3
View File
@@ -3,7 +3,7 @@ import { mlsBinding, signMls } from '../identity'
import { base64, decode, fingerprint, loadEngine } from './engine'
import type { DeviceMls } from './engine'
import { withVault } from './vault'
import { decodeMessage, encodeAttachment, sealAttachment, uploadAttachment } from './attachments'
import { decodeMessage, encodeAttachment, encodeReply, sealAttachment, uploadAttachment } from './attachments'
import type { Attachment } from './attachments'
export interface Peer {
@@ -27,6 +27,8 @@ export interface ChatLine {
peer: string
text: string
attachment?: Attachment
quote?: string
favorite?: boolean
time: string
own: boolean
}
@@ -149,7 +151,7 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
return unavailable
}
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call) {
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call, reply?: ChatLine) {
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('发送前请核验对方设备安全码')
@@ -162,6 +164,8 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
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
@@ -184,7 +188,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
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, text, attachment, time: new Date().toISOString(), own: true })
state.lines.push({ id, peer: current.id, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
state.engine = base64(engine.snapshot())
await save(state)
await flush(state, save, call)
@@ -194,6 +198,22 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
})
}
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.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 synchronize(identity: ChatIdentity, user: string, call: Call) {
return update(identity, async (state, save, factory) => {
const peers = await directory(call, user)
+7
View File
@@ -85,6 +85,13 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.chat-lines small { display: block; text-align: end; }
.chat-compose { display: grid; gap: 8px; }
.chat-compose button { justify-self: end; }
.chat-filters, .chat-quote, .message-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: end; }
.chat-filters label:first-child { flex: 1 1 180px; }
.chat-checkbox { display: flex; align-items: center; gap: 6px; padding: 10px 4px; }
.chat-checkbox input { width: auto; }
.chat-lines blockquote { border-left: 2px solid var(--line); margin: 0 0 4px; padding: 0 6px; color: var(--muted); font-size: .9em; }
.message-actions { margin-top: 5px; }
.message-actions .plain { font-size: .78em; padding: 2px 6px; }
.account-footer { display: grid; gap: 12px; margin-top: auto; }
.account-footer p { color: var(--muted); font-size: 13px; }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); margin: 0 8px 1px 4px; }
+53 -4
View File
@@ -2,7 +2,8 @@
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSession } from '../session'
import { enableChat, send, synchronize, trust } from '../chat/chat'
import { enableChat, localMessageAction, send, synchronize, trust } from '../chat/chat'
import type { ChatLine } from '../chat/chat'
import { downloadAttachment } from '../chat/attachments'
import type { Attachment } from '../chat/attachments'
@@ -12,6 +13,10 @@ const ownCode = ref('')
const code = ref('')
const selected = ref('')
const draft = ref('')
const search = ref('')
const favoritesOnly = ref(false)
const reply = ref<ChatLine>()
const deleting = ref<ChatLine>()
const error = ref('')
const busy = ref(false)
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
@@ -19,7 +24,12 @@ const target = computed(() => typeof route.params.user === 'string' ? route.para
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
const lines = computed(() => (view.value?.lines ?? []).filter((line) => line.peer === selected.value))
const lines = computed(() => {
const query = search.value.trim().toLowerCase()
return (view.value?.lines ?? []).filter((line) => line.peer === selected.value &&
(!favoritesOnly.value || line.favorite) &&
(!query || [line.text, line.attachment?.name, line.quote].some((part) => part?.toLowerCase().includes(query))))
})
let timer: ReturnType<typeof setInterval>
async function execute(action: () => Promise<void>) {
@@ -65,8 +75,9 @@ function confirm() {
function submit() {
void execute(async () => {
if (!session.identity || !peer.value) return
await send(session.identity, target.value, peer.value, draft.value, session.authorized)
await send(session.identity, target.value, peer.value, draft.value, session.authorized, reply.value)
draft.value = ''
reply.value = undefined
await refresh()
})
}
@@ -87,6 +98,16 @@ function saveAttachment(attachment: Attachment) {
void execute(() => downloadAttachment(attachment, session.authorized))
}
function localAction(line: ChatLine, action: 'favorite' | 'remove') {
void execute(async () => {
if (!session.identity) return
await localMessageAction(session.identity, line, action)
deleting.value = undefined
if (action === 'remove' && reply.value?.id === line.id) reply.value = undefined
await refresh()
})
}
function sync() {
if (ownCode.value) void execute(refresh)
}
@@ -98,6 +119,12 @@ watch(target, () => {
draft.value = ''
sync()
})
watch(selected, () => {
search.value = ''
favoritesOnly.value = false
reply.value = undefined
deleting.value = undefined
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
onMounted(() => { timer = setInterval(sync, 10_000) })
onBeforeUnmount(() => clearInterval(timer))
@@ -135,14 +162,36 @@ onBeforeUnmount(() => clearInterval(timer))
<p class="verified-label">设备已验证</p>
<p v-if="view?.deliveryError" class="error">{{ view.deliveryError }}</p>
<p v-if="view?.rejected" class="muted">已拒绝 {{ view.rejected }} 个无法验证的封包。</p>
<div class="chat-filters">
<label>搜索本机消息<input v-model="search" type="search" maxlength="120"></label>
<label class="chat-checkbox"><input v-model="favoritesOnly" type="checkbox">只看收藏</label>
</div>
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
<li v-for="line in lines" :key="line.id" :class="{ own: line.own }">
<li v-for="line in lines" :key="line.peer + ':' + line.own + ':' + line.id" :class="{ own: line.own }">
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<button v-if="line.attachment" type="button" class="plain" :disabled="busy"
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
<span v-else>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small>
<div class="message-actions">
<button type="button" class="plain" :disabled="busy" @click="reply = line">引用</button>
<button type="button" class="plain" :disabled="busy" @click="localAction(line, 'favorite')">
{{ line.favorite ? '取消收藏' : '收藏' }}
</button>
<button type="button" class="plain" :disabled="busy || view?.unsent.includes(line.id)" @click="deleting = line">本机删除</button>
</div>
</li>
</ol>
<p v-if="(search || favoritesOnly) && !lines.length" class="muted">没有匹配的消息。</p>
<div v-if="deleting" class="confirmation">
<p>从本机删除这条消息?</p>
<button type="button" class="plain" :disabled="busy" @click="localAction(deleting, 'remove')">确认删除</button>
<button type="button" class="plain" @click="deleting = undefined">取消</button>
</div>
<form class="chat-compose" @submit.prevent="submit">
<div v-if="reply" class="chat-quote">
<span>引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}</span>
<button type="button" class="plain" @click="reply = undefined">取消引用</button>
</div>
<label>发送附件<input type="file" :disabled="busy" @change="attach"></label>
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
<button class="primary" :disabled="busy || !draft.trim()">发送</button>