接通双端加密语音录制与播放

This commit is contained in:
xhgit committed 2026-11-13 23:39:13 +08:00
1 parent 149028267e
commit 87676ae983
13 files changed
+217 -10

No files matched your search

+15 -3
View File
@@ -11,14 +11,24 @@ export interface Attachment {
size: number
key: string
iv: string
voice?: true
}
const voiceRecordings = new WeakSet<File>()
export function voiceFile(parts: BlobPart[]) {
const file = new File(parts, '语音消息.webm', { type: 'audio/webm;codecs=opus' })
voiceRecordings.add(file)
return file
}
function attachmentPath(id: string) {
return '/attachments/' + encodeURIComponent(id)
}
function authenticatedData(file: Pick<Attachment, 'id' | 'name' | 'size'>) {
return encoder.encode(JSON.stringify(['XHChat attachment v1', file.id, file.name, file.size]))
function authenticatedData(file: Pick<Attachment, 'id' | 'name' | 'size' | 'voice'>) {
const fields = ['XHChat attachment v1', file.id, file.name, file.size]
if (file.voice) fields.push('voice')
return encoder.encode(JSON.stringify(fields))
}
function safeName(name: string) {
@@ -29,7 +39,8 @@ export async function sealAttachment(file: File) {
if (file.size > maxSize) throw new Error('附件超过 8 MiB')
const key = crypto.getRandomValues(new Uint8Array(32))
const iv = crypto.getRandomValues(new Uint8Array(12))
const attachment = { id: crypto.randomUUID(), name: safeName(file.name), size: file.size, key: base64(key), iv: base64(iv) }
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
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())
@@ -87,6 +98,7 @@ export function decodeMessage(message: Uint8Array): ChatContent {
if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) ||
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) ||
typeof value.key !== 'string' || decode(value.key).length !== 32 ||
typeof value.iv !== 'string' || decode(value.iv).length !== 12) {
throw new Error('附件描述格式无效')