Files
XHChat/web/src/chat/attachments.ts
T

125 lines
5.3 KiB
TypeScript

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<Attachment, 'id' | 'name' | 'size'>) {
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<void>(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 type Mutation = { action: 'edit' | 'recall'; id: string; text?: string }
type ChatContent = { text: string; attachment?: Attachment; quote?: string; mutation?: Mutation }
export function decodeMessage(message: Uint8Array): ChatContent {
if (message[0] !== 255) return { text: decoder.decode(message) }
if (message[1] === 3 && message.length <= 18_000) {
const value = JSON.parse(decoder.decode(message.subarray(2))) as Mutation | null
if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) ||
!(value.action === 'recall' || value.action === 'edit' && typeof value.text === 'string' &&
value.text.trim() && encoder.encode(value.text).length <= 8000)) throw new Error('消息更新格式无效')
return { text: '', mutation: value }
}
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) ||
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 function encodeReply(text: string, quote: string) {
return encodeContent(2, { text, quote })
}
export function encodeMutation(mutation: Mutation) {
return encodeContent(3, mutation)
}
function encodeContent(kind: number, value: object) {
const body = encoder.encode(JSON.stringify(value))
if (body.length + 2 > 18_000) throw new Error('消息内容过长')
const message = new Uint8Array(body.length + 2)
message.set([255, kind])
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('附件完整性校验失败')
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)
}