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

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

+1
View File
@@ -18,6 +18,7 @@
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 | | 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | | 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 | | 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 |
| 消息管理 | 支持引用回复、搜索本机历史、收藏和本机删除。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索和隐私窗口,网页运行在独立会话中。 | | Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索和隐私窗口,网页运行在独立会话中。 |
当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) 当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
+4
View File
@@ -54,3 +54,7 @@ Edge 与 Electron 集成测试覆盖错误安全码、双向文字、网络封
## 端到端加密附件预览 ## 端到端加密附件预览
Windows 与 Web 支持发送和下载最多 8 MiB 的附件。文件名、长度、密钥和 IV 位于 MLS 消息中,附件服务只存密文。下载先验证认证标签,再提供本地保存。跨端用例覆盖上传密文、篡改拒绝和下载字节一致性。对象存储、分片断点续传和媒体专用界面仍待完成。 Windows 与 Web 支持发送和下载最多 8 MiB 的附件。文件名、长度、密钥和 IV 位于 MLS 消息中,附件服务只存密文。下载先验证认证标签,再提供本地保存。跨端用例覆盖上传密文、篡改拒绝和下载字节一致性。对象存储、分片断点续传和媒体专用界面仍待完成。
## 消息管理
Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按正文、引用和文件名搜索本机历史,以及收藏和本机删除。收藏标记与历史保存在加密本地记录中。集成测试覆盖引用跨端显示、收藏筛选、搜索及删除后另一端仍可读取原消息。远程撤回、编辑、转发与跨设备收藏同步待后续交付。
+15
View File
@@ -103,8 +103,23 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice']) assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice'])
await windows.getByText(text, { exact: true }).waitFor() await windows.getByText(text, { exact: true }).waitFor()
const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex') const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex')
await windows.getByRole('listitem').filter({ hasText: text }).getByRole('button', { name: '引用', exact: true }).click()
await send(windows, reply) await send(windows, reply)
await web.getByText(reply, { exact: true }).waitFor() await web.getByText(reply, { exact: true }).waitFor()
await web.getByRole('listitem').filter({ hasText: reply }).locator('blockquote').getByText(text, { exact: true }).waitFor()
const original = web.getByRole('listitem').filter({ has: web.getByText(text, { exact: true }) }).filter({ hasNot: web.locator('blockquote') })
await original.getByRole('button', { name: '收藏', exact: true }).click()
await original.getByRole('button', { name: '取消收藏' }).waitFor()
await web.getByLabel('只看收藏').check()
assert.equal(await web.getByRole('listitem').count(), 1)
await web.getByLabel('搜索本机消息').fill('无匹配的搜索词')
await web.getByText('没有匹配的消息。').waitFor()
await web.getByLabel('搜索本机消息').clear()
await web.getByLabel('只看收藏').uncheck()
await original.getByRole('button', { name: '本机删除' }).click()
await web.getByRole('button', { name: '确认删除' }).click()
await original.waitFor({ state: 'detached' })
await windows.getByRole('listitem').filter({ hasText: text }).filter({ hasNot: windows.locator('blockquote') }).waitFor()
const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex')) const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex'))
const fileName = '跨端验收.txt' const fileName = '跨端验收.txt'
+18 -1
View File
@@ -53,8 +53,16 @@ export function encodeAttachment(attachment: Attachment) {
return message 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[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('附件描述格式无效') if (message[1] !== 1 || message.length > 4096) throw new Error('附件描述格式无效')
const value = JSON.parse(decoder.decode(message.subarray(2))) as Attachment | null 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) || 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 } 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) { export async function downloadAttachment(attachment: Attachment, call: Call) {
const ciphertext = await call<ArrayBuffer>(attachmentPath(attachment.id), 'GET', undefined, true) const ciphertext = await call<ArrayBuffer>(attachmentPath(attachment.id), 'GET', undefined, true)
if (ciphertext.byteLength !== attachment.size + 16) throw new Error('附件完整性校验失败') 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 { base64, decode, fingerprint, loadEngine } from './engine'
import type { DeviceMls } from './engine' import type { DeviceMls } from './engine'
import { withVault } from './vault' import { withVault } from './vault'
import { decodeMessage, encodeAttachment, sealAttachment, uploadAttachment } from './attachments' import { decodeMessage, encodeAttachment, encodeReply, sealAttachment, uploadAttachment } from './attachments'
import type { Attachment } from './attachments' import type { Attachment } from './attachments'
export interface Peer { export interface Peer {
@@ -27,6 +27,8 @@ export interface ChatLine {
peer: string peer: string
text: string text: string
attachment?: Attachment attachment?: Attachment
quote?: string
favorite?: boolean
time: string time: string
own: boolean own: boolean
} }
@@ -149,7 +151,7 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
return unavailable 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) => { return update(identity, async (state, save, factory) => {
const current = (await directory(call, user)).find((item) => item.id === peer.id) const current = (await directory(call, user)).find((item) => item.id === peer.id)
if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码') 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 字节') throw new Error('消息须为 1 至 8000 字节')
} }
if (state.lines.length >= 1000) throw new Error('本机预览版消息容量已达上限') 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)) const engine = factory.DeviceMls.restore(decode(state.engine))
try { try {
let group = state.groups[current.id] ? decode(state.groups[current.id]) : undefined 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 id = crypto.randomUUID()
const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext) 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.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()) state.engine = base64(engine.snapshot())
await save(state) await save(state)
await flush(state, save, call) 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) { export function synchronize(identity: ChatIdentity, user: string, call: Call) {
return update(identity, async (state, save, factory) => { return update(identity, async (state, save, factory) => {
const peers = await directory(call, user) 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-lines small { display: block; text-align: end; }
.chat-compose { display: grid; gap: 8px; } .chat-compose { display: grid; gap: 8px; }
.chat-compose button { justify-self: end; } .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 { display: grid; gap: 12px; margin-top: auto; }
.account-footer p { color: var(--muted); font-size: 13px; } .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; } .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 { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { useSession } from '../session' 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 { downloadAttachment } from '../chat/attachments'
import type { Attachment } from '../chat/attachments' import type { Attachment } from '../chat/attachments'
@@ -12,6 +13,10 @@ const ownCode = ref('')
const code = ref('') const code = ref('')
const selected = ref('') const selected = ref('')
const draft = ref('') const draft = ref('')
const search = ref('')
const favoritesOnly = ref(false)
const reply = ref<ChatLine>()
const deleting = ref<ChatLine>()
const error = ref('') const error = ref('')
const busy = ref(false) const busy = ref(false)
const view = ref<Awaited<ReturnType<typeof synchronize>>>() 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 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 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 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> let timer: ReturnType<typeof setInterval>
async function execute(action: () => Promise<void>) { async function execute(action: () => Promise<void>) {
@@ -65,8 +75,9 @@ function confirm() {
function submit() { function submit() {
void execute(async () => { void execute(async () => {
if (!session.identity || !peer.value) return 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 = '' draft.value = ''
reply.value = undefined
await refresh() await refresh()
}) })
} }
@@ -87,6 +98,16 @@ function saveAttachment(attachment: Attachment) {
void execute(() => downloadAttachment(attachment, session.authorized)) 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() { function sync() {
if (ownCode.value) void execute(refresh) if (ownCode.value) void execute(refresh)
} }
@@ -98,6 +119,12 @@ watch(target, () => {
draft.value = '' draft.value = ''
sync() sync()
}) })
watch(selected, () => {
search.value = ''
favoritesOnly.value = false
reply.value = undefined
deleting.value = undefined
})
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync) watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
onMounted(() => { timer = setInterval(sync, 10_000) }) onMounted(() => { timer = setInterval(sync, 10_000) })
onBeforeUnmount(() => clearInterval(timer)) onBeforeUnmount(() => clearInterval(timer))
@@ -135,14 +162,36 @@ onBeforeUnmount(() => clearInterval(timer))
<p class="verified-label">设备已验证</p> <p class="verified-label">设备已验证</p>
<p v-if="view?.deliveryError" class="error">{{ view.deliveryError }}</p> <p v-if="view?.deliveryError" class="error">{{ view.deliveryError }}</p>
<p v-if="view?.rejected" class="muted">已拒绝 {{ view.rejected }} 个无法验证的封包。</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"> <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" <button v-if="line.attachment" type="button" class="plain" :disabled="busy"
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button> @click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
<span v-else>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small> <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> </li>
</ol> </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"> <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>发送附件<input type="file" :disabled="busy" @change="attach"></label>
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label> <label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
<button class="primary" :disabled="busy || !draft.trim()">发送</button> <button class="primary" :disabled="busy || !draft.trim()">发送</button>