交付 Windows 与 Web 端到端加密附件预览
This commit is contained in:
1 parent
d1efdedc57
commit
c24960d22a
19 files changed
+421
-58
No files matched your search
+23
-4
@@ -6,20 +6,39 @@ export class APIError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, method = 'GET', token = '', body?: object): Promise<T> {
|
||||
export async function request<T>(path: string, method = 'GET', token = '', body?: object, binary = false): Promise<T> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (token) headers.Authorization = 'Bearer ' + token
|
||||
if (body) headers['Content-Type'] = 'application/json'
|
||||
const bytes = body instanceof ArrayBuffer
|
||||
if (body) headers['Content-Type'] = bytes ? 'application/octet-stream' : 'application/json'
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(base + '/api/v1' + path, {
|
||||
method, headers, body: body ? JSON.stringify(body) : undefined,
|
||||
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(12000),
|
||||
method, headers, body: bytes ? body : body ? JSON.stringify(body) : undefined,
|
||||
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(binary || bytes ? 60_000 : 12_000),
|
||||
})
|
||||
} catch {
|
||||
throw new Error('无法连接 XHChat 服务,请检查网络后重试')
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
if (binary && response.ok) {
|
||||
if (Number(response.headers.get('Content-Length')) > 8 * 1024 * 1024 + 16) throw new Error('附件超过大小限制')
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) throw new Error('附件下载失败')
|
||||
const chunks: Uint8Array<ArrayBuffer>[] = []
|
||||
let length = 0
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
length += value.byteLength
|
||||
if (length > 8 * 1024 * 1024 + 16) {
|
||||
await reader.cancel()
|
||||
throw new Error('附件超过大小限制')
|
||||
}
|
||||
chunks.push(value)
|
||||
}
|
||||
return await new Blob(chunks).arrayBuffer() as T
|
||||
}
|
||||
const data = await response.json().catch(() => null)
|
||||
if (!response.ok) throw new APIError(response.status, data?.error?.message ?? '请求失败,请稍后重试')
|
||||
return data as T
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
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 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<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)
|
||||
}
|
||||
+19
-6
@@ -3,6 +3,8 @@ import { mlsBinding, signMls } from '../identity'
|
||||
import { base64, decode, fingerprint, loadEngine } from './engine'
|
||||
import type { DeviceMls } from './engine'
|
||||
import { withVault } from './vault'
|
||||
import { decodeMessage, encodeAttachment, sealAttachment, uploadAttachment } from './attachments'
|
||||
import type { Attachment } from './attachments'
|
||||
|
||||
export interface Peer {
|
||||
id: string
|
||||
@@ -24,6 +26,7 @@ export interface ChatLine {
|
||||
id: string
|
||||
peer: string
|
||||
text: string
|
||||
attachment?: Attachment
|
||||
time: string
|
||||
own: boolean
|
||||
}
|
||||
@@ -40,7 +43,7 @@ interface ChatState {
|
||||
rejected: number
|
||||
}
|
||||
|
||||
export type Call = <T>(path: string, method?: string, body?: object) => Promise<T>
|
||||
export type Call = <T>(path: string, method?: string, body?: object, binary?: boolean) => Promise<T>
|
||||
const encoder = new TextEncoder()
|
||||
|
||||
function aad(id: string, sender: string, recipient: string) {
|
||||
@@ -146,19 +149,29 @@ async function flush(state: ChatState, save: (state: ChatState) => Promise<void>
|
||||
return unavailable
|
||||
}
|
||||
|
||||
export function send(identity: ChatIdentity, user: string, peer: Peer, text: string, call: Call) {
|
||||
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const current = (await directory(call, user)).find((item) => item.id === peer.id)
|
||||
if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码')
|
||||
const key = await verifiedPeer(current, user)
|
||||
const unavailable = await flush(state, save, call)
|
||||
if (unavailable.has(current.id)) throw new Error('该设备暂不可接收消息')
|
||||
const plaintext = encoder.encode(text.trim())
|
||||
if (!plaintext.length || plaintext.length > 8000) throw new Error('消息须为 1 至 8000 字节')
|
||||
const text = typeof content === 'string' ? content.trim() : ''
|
||||
let plaintext = encoder.encode(text)
|
||||
if (typeof content === 'string' && (!plaintext.length || plaintext.length > 8000)) {
|
||||
throw new Error('消息须为 1 至 8000 字节')
|
||||
}
|
||||
if (state.lines.length >= 1000) throw new Error('本机预览版消息容量已达上限')
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
let group = state.groups[current.id] ? decode(state.groups[current.id]) : undefined
|
||||
let attachment: Attachment | undefined
|
||||
if (typeof content !== 'string') {
|
||||
const sealed = await sealAttachment(content)
|
||||
attachment = sealed.attachment
|
||||
await uploadAttachment(attachment, sealed.ciphertext, current.id, call)
|
||||
plaintext = encodeAttachment(attachment)
|
||||
}
|
||||
if (!group) {
|
||||
const pack = await call<Package>('/contacts/' + user + '/devices/' + current.id + '/claim', 'POST')
|
||||
const wire = decode(pack.package)
|
||||
@@ -171,7 +184,7 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, text: str
|
||||
const id = crypto.randomUUID()
|
||||
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.lines.push({ id, peer: current.id, text: text.trim(), time: new Date().toISOString(), own: true })
|
||||
state.lines.push({ id, peer: current.id, text, attachment, time: new Date().toISOString(), own: true })
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
await flush(state, save, call)
|
||||
@@ -207,7 +220,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
|
||||
} else {
|
||||
const plaintext = engine.decrypt(peer.id, key, aad(item.messageId, peer.id, identity.device.id), wire)
|
||||
if (state.lines.length < 1000) state.lines.push({
|
||||
id: item.messageId, peer: peer.id, text: new TextDecoder('utf-8', { fatal: true }).decode(plaintext),
|
||||
id: item.messageId, peer: peer.id, ...decodeMessage(plaintext),
|
||||
time: item.createdAt, own: false,
|
||||
})
|
||||
}
|
||||
|
||||
+2
-2
@@ -91,10 +91,10 @@ export const useSession = defineStore('session', () => {
|
||||
void connect(token)
|
||||
}
|
||||
|
||||
async function authorized<T>(path: string, method = 'GET', body?: object) {
|
||||
async function authorized<T>(path: string, method = 'GET', body?: object, binary = false) {
|
||||
const current = token
|
||||
try {
|
||||
const response = await request<T>(path, method, current, body)
|
||||
const response = await request<T>(path, method, current, body, binary)
|
||||
if (token !== current) throw new Error('登录会话已变更')
|
||||
return response
|
||||
} catch (error) {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useSession } from '../session'
|
||||
import { enableChat, send, synchronize, trust } from '../chat/chat'
|
||||
import { downloadAttachment } from '../chat/attachments'
|
||||
import type { Attachment } from '../chat/attachments'
|
||||
|
||||
const session = useSession()
|
||||
const route = useRoute()
|
||||
@@ -69,6 +71,22 @@ function submit() {
|
||||
})
|
||||
}
|
||||
|
||||
function attach(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
void execute(async () => {
|
||||
if (!session.identity || !peer.value) return
|
||||
await send(session.identity, target.value, peer.value, file, session.authorized)
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function saveAttachment(attachment: Attachment) {
|
||||
void execute(() => downloadAttachment(attachment, session.authorized))
|
||||
}
|
||||
|
||||
function sync() {
|
||||
if (ownCode.value) void execute(refresh)
|
||||
}
|
||||
@@ -119,10 +137,13 @@ onBeforeUnmount(() => clearInterval(timer))
|
||||
<p v-if="view?.rejected" class="muted">已拒绝 {{ view.rejected }} 个无法验证的封包。</p>
|
||||
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
|
||||
<li v-for="line in lines" :key="line.id" :class="{ own: line.own }">
|
||||
<span>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small>
|
||||
<button v-if="line.attachment" type="button" class="plain" :disabled="busy"
|
||||
@click="saveAttachment(line.attachment)">下载 {{ line.attachment.name }}</button>
|
||||
<span v-else>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small>
|
||||
</li>
|
||||
</ol>
|
||||
<form class="chat-compose" @submit.prevent="submit">
|
||||
<label>发送附件<input type="file" :disabled="busy" @change="attach"></label>
|
||||
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
|
||||
<button class="primary" :disabled="busy || !draft.trim()">发送</button>
|
||||
</form>
|
||||
|
||||
Reference in new issue
Block a user