Merge pull request '支持加密图片与视频的本机预览' (#18) from xhgit/encrypted-media-preview into main

Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/18
This commit was merged in pull request #18.
This commit is contained in:
xhgit committed 2026-11-14 00:12:58 +00:00
commit a8c81beb4a
10 files changed
+94 -7

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@ async function start() {
url.pathname.endsWith('.wasm') ? 'application/wasm' : 'application/javascript'
return new Response(bytes, { headers: {
'Content-Type': type,
'Content-Security-Policy': browserAsset ? policy : policy + "; media-src blob:; connect-src 'self' " + api + ' ' + websocket,
'Content-Security-Policy': browserAsset ? policy : policy + "; img-src blob:; media-src blob:; connect-src 'self' " + api + ' ' + websocket,
'X-Content-Type-Options': 'nosniff',
} })
} catch {
+1 -1
View File
@@ -17,7 +17,7 @@
| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 |
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 |
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,并在本机预览图片和视频。 |
| 加密语音 | 两端可录制和播放最长 60 秒的语音消息。 |
| 消息管理 | 支持会话查找、可选加密已读回执、引用回复、编辑、撤回、转发、本机搜索和收藏。 |
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
+1 -1
View File
@@ -27,7 +27,7 @@ server {
proxy_set_header Host $http_host;
}
add_header Content-Security-Policy "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; connect-src 'self'; media-src blob:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; connect-src 'self'; img-src blob:; media-src blob:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'" always;
add_header Referrer-Policy no-referrer always;
add_header X-Content-Type-Options nosniff always;
add_header Permissions-Policy "camera=(), microphone=(self), geolocation=()" always;
+4
View File
@@ -84,3 +84,7 @@ Windows 浏览器新增可跨窗口保留的本地书签和历史,每类最多
## 加密语音消息
Windows 和 Web 使用 MediaRecorder 录制 Opus,支持取消、计时和最长 60 秒录音。录音经附件加密链路发送,收件方验证密文后本地播放、暂停或拖动进度。Windows 的通讯渲染层只在主动录音时获得短期麦克风请求权限,第三方浏览器仍使用独立的逐站权限。集成测试使用 Chromium 虚拟麦克风完成 Windows 录音到 Web 播放。语音转写、按住录音和未听提醒尚待实现。
## 加密图片和视频预览
两端支持在聊天内预览 JPEG、PNG、WebP、GIF、MP4 和 WebM 附件。预览需主动打开,先在本机验证完整性,再使用临时 Blob URL 加载。关闭预览或离开聊天会释放 URL。自动化验收覆盖 Web 发送 PNG 到 Windows 端实际解码和关闭预览。视频预览已构建,仍需独立验证不同编码格式。
+10
View File
@@ -195,6 +195,16 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
return audio && audio.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && audio.currentTime > 0
})
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jf2sAAAAASUVORK5CYII=', 'base64')
await web.locator('input[type=file]').setInputFiles({ name: '加密预览.png', mimeType: 'image/png', buffer: pixel })
await windows.getByRole('button', { name: '预览 加密预览.png' }).click()
const image = windows.getByRole('img', { name: '加密预览.png' })
await image.waitFor()
await windows.waitForFunction(() => document.querySelector('img[alt="加密预览.png"]')?.naturalWidth === 1)
assert.match(await image.getAttribute('src'), /^blob:/)
await windows.getByRole('button', { name: '关闭预览' }).click()
assert.equal(await image.count(), 0)
await windows.getByRole('button', { name: '退出登录' }).click()
await windows.getByRole('heading', { name: '登录 XHChat' }).waitFor()
const offline = '离线补拉 ' + randomBytes(8).toString('hex')
+56
View File
@@ -0,0 +1,56 @@
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { readAttachment } from './attachments'
import type { Attachment } from './attachments'
import { useSession } from '../session'
const props = defineProps<{ attachment: Attachment }>()
const session = useSession()
const url = ref('')
const busy = ref(false)
const error = ref('')
let active = true
function close() {
if (url.value) URL.revokeObjectURL(url.value)
url.value = ''
}
async function open() {
if (!props.attachment.media) return
busy.value = true
error.value = ''
try {
const bytes = await readAttachment(props.attachment, session.authorized)
if (active) url.value = URL.createObjectURL(new Blob([bytes], { type: props.attachment.media }))
} catch (cause) {
if (active) error.value = cause instanceof Error ? cause.message : '无法加载媒体预览'
} finally {
busy.value = false
}
}
function decodeError() {
close()
error.value = '客户端无法解码此媒体文件'
}
onBeforeUnmount(() => {
active = false
close()
})
</script>
<template>
<div class="media-preview">
<template v-if="url">
<img v-if="attachment.media?.startsWith('image/')" :src="url" :alt="attachment.name" @error="decodeError">
<video v-else :src="url" controls preload="metadata" :aria-label="attachment.name" @error="decodeError"></video>
<button type="button" class="plain" @click="close">关闭预览</button>
</template>
<button v-else type="button" class="plain" :disabled="busy" @click="open">
{{ busy ? '正在解密…' : '预览 ' + attachment.name }}
</button>
<small v-if="error" class="error" role="alert">{{ error }}</small>
</div>
</template>
+11 -1
View File
@@ -4,6 +4,12 @@ import type { Call } from './chat'
const maxSize = 8 * 1024 * 1024
const encoder = new TextEncoder()
const decoder = new TextDecoder('utf-8', { fatal: true })
const mediaTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'video/mp4', 'video/webm'] as const
type MediaType = typeof mediaTypes[number]
function mediaType(value: unknown): value is MediaType {
return mediaTypes.some((type) => type === value)
}
export interface Attachment {
id: string
@@ -12,6 +18,7 @@ export interface Attachment {
key: string
iv: string
voice?: true
media?: MediaType
}
const voiceRecordings = new WeakSet<File>()
@@ -25,9 +32,10 @@ function attachmentPath(id: string) {
return '/attachments/' + encodeURIComponent(id)
}
function authenticatedData(file: Pick<Attachment, 'id' | 'name' | 'size' | 'voice'>) {
function authenticatedData(file: Pick<Attachment, 'id' | 'name' | 'size' | 'voice' | 'media'>) {
const fields = ['XHChat attachment v1', file.id, file.name, file.size]
if (file.voice) fields.push('voice')
if (file.media) fields.push(file.media)
return encoder.encode(JSON.stringify(fields))
}
@@ -41,6 +49,7 @@ export async function sealAttachment(file: File) {
const iv = crypto.getRandomValues(new Uint8Array(12))
const attachment: Attachment = { id: crypto.randomUUID(), name: safeName(file.name), size: file.size, key: base64(key), iv: base64(iv) }
if (voiceRecordings.has(file)) attachment.voice = true
else if (mediaType(file.type)) attachment.media = file.type
try {
const imported = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt'])
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: authenticatedData(attachment) }, imported, await file.arrayBuffer())
@@ -99,6 +108,7 @@ export function decodeMessage(message: Uint8Array): ChatContent {
typeof value.name !== 'string' || value.name !== safeName(value.name) ||
!Number.isInteger(value.size) || value.size < 0 || value.size > maxSize ||
(value.voice !== undefined && value.voice !== true) ||
(value.media !== undefined && (!mediaType(value.media) || value.voice === true)) ||
typeof value.key !== 'string' || decode(value.key).length !== 32 ||
typeof value.iv !== 'string' || decode(value.iv).length !== 12) {
throw new Error('附件描述格式无效')
+2 -1
View File
@@ -266,7 +266,8 @@ export async function forwardMessage(identity: ChatIdentity, line: ChatLine, rec
if (line.recalled) throw new Error('撤回的消息无法转发')
const attachment = line.attachment
const bytes = attachment ? await readAttachment(attachment, call) : undefined
const content = attachment && bytes ? attachment.voice ? voiceFile([bytes]) : new File([bytes], attachment.name) : line.text
const content = attachment && bytes ? attachment.voice ? voiceFile([bytes]) :
new File([bytes], attachment.name, { type: attachment.media }) : line.text
await send(identity, recipient, device, content, call)
}
+2
View File
@@ -84,6 +84,8 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
.chat-lines li.own { align-self: end; background: var(--green-soft); }
.chat-lines small { display: block; text-align: end; }
.chat-lines audio { display: block; width: min(260px, 100%); }
.media-preview { display: grid; gap: 5px; justify-items: start; margin-bottom: 5px; }
.media-preview img, .media-preview video { display: block; max-width: min(300px, 100%); max-height: 220px; border-radius: 5px; }
.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; }
+6 -2
View File
@@ -9,6 +9,7 @@ import { downloadAttachment } from '../chat/attachments'
import type { Attachment } from '../chat/attachments'
import VoiceRecorder from '../chat/VoiceRecorder.vue'
import VoiceMessage from '../chat/VoiceMessage.vue'
import MediaPreview from '../chat/MediaPreview.vue'
const session = useSession()
const route = useRoute()
@@ -370,8 +371,11 @@ onBeforeUnmount(() => {
<blockquote v-if="line.quote">{{ line.quote }}</blockquote>
<span v-if="line.recalled" class="muted">消息已撤回</span>
<VoiceMessage v-else-if="line.attachment?.voice" :attachment="line.attachment" />
<button v-else-if="line.attachment" type="button" class="plain" :disabled="busy"
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
<template v-else-if="line.attachment">
<MediaPreview v-if="line.attachment.media" :attachment="line.attachment" />
<button type="button" class="plain" :disabled="busy"
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
</template>
<span v-else><template v-for="(part, index) in messageParts(line.text)" :key="index"><button v-if="part.url && internalBrowser"
type="button" class="chat-link" @click="openLink(part.url)">{{ part.text }}</button><a v-else-if="part.url"
class="chat-link" :href="part.url" target="_blank" rel="noopener noreferrer">{{ part.text }}</a><template v-else>{{ part.text }}</template></template></span>