import { base64, decode } from './engine' import type { Call } from './chat' const maxSize = 8 * 1024 * 1024 const encoder = new TextEncoder() const decoder = new TextDecoder('utf-8', { fatal: true }) export interface Attachment { id: string name: string size: number key: string iv: string } function attachmentPath(id: string) { return '/attachments/' + encodeURIComponent(id) } function authenticatedData(file: Pick) { return encoder.encode(JSON.stringify(['XHChat attachment v1', file.id, file.name, file.size])) } function safeName(name: string) { return name.replace(/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069<>:"/\\|?*]/g, '_').trim().slice(0, 180) || 'attachment' } 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) } 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()) return { attachment, ciphertext } } finally { key.fill(0) } } export function uploadAttachment(attachment: Attachment, ciphertext: ArrayBuffer, peer: string, call: Call) { return call(attachmentPath(attachment.id) + '?recipient=' + encodeURIComponent(peer), 'POST', ciphertext) } export function encodeAttachment(attachment: Attachment) { const body = encoder.encode(JSON.stringify(attachment)) const message = new Uint8Array(body.length + 2) // An invalid UTF-8 prefix keeps attachment messages distinct from older text payloads. message[0] = 255 message[1] = 1 message.set(body, 2) return message } export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment } { if (message[0] !== 255) return { text: decoder.decode(message) } 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) || typeof value.name !== 'string' || value.name !== safeName(value.name) || !Number.isInteger(value.size) || value.size < 0 || value.size > maxSize || typeof value.key !== 'string' || decode(value.key).length !== 32 || typeof value.iv !== 'string' || decode(value.iv).length !== 12) { throw new Error('附件描述格式无效') } return { text: '', attachment: value } } export async function downloadAttachment(attachment: Attachment, call: Call) { const ciphertext = await call(attachmentPath(attachment.id), 'GET', undefined, true) if (ciphertext.byteLength !== attachment.size + 16) throw new Error('附件完整性校验失败') const raw = decode(attachment.key) let bytes: ArrayBuffer try { const key = await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['decrypt']) bytes = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: decode(attachment.iv), additionalData: authenticatedData(attachment) }, key, ciphertext) } catch { throw new Error('附件完整性校验失败') } finally { raw.fill(0) } const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' })) const link = document.createElement('a') link.download = attachment.name link.href = url link.click() setTimeout(() => URL.revokeObjectURL(url), 30_000) }