接通 Windows 与 Web 设备间加密文字聊天
This commit is contained in:
1 parent
b04034ee89
commit
d1efdedc57
27 files changed
+880
-22
No files matched your search
@@ -0,0 +1,233 @@
|
||||
import { APIError } from '../api'
|
||||
import { mlsBinding, signMls } from '../identity'
|
||||
import { base64, decode, fingerprint, loadEngine } from './engine'
|
||||
import type { DeviceMls } from './engine'
|
||||
import { withVault } from './vault'
|
||||
|
||||
export interface Peer {
|
||||
id: string
|
||||
name: string
|
||||
publicKey: string
|
||||
mls?: { publicKey: string; signature: string }
|
||||
}
|
||||
|
||||
export interface ChatIdentity {
|
||||
user: { id: string; username: string }
|
||||
device: { id: string }
|
||||
}
|
||||
|
||||
interface Package { package: string; signature: string }
|
||||
interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string }
|
||||
interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string }
|
||||
|
||||
export interface ChatLine {
|
||||
id: string
|
||||
peer: string
|
||||
text: string
|
||||
time: string
|
||||
own: boolean
|
||||
}
|
||||
|
||||
interface ChatState {
|
||||
engine: string
|
||||
cursor: string
|
||||
pending: Incoming[]
|
||||
outbox: Outgoing[]
|
||||
lines: ChatLine[]
|
||||
pinned: Record<string, string>
|
||||
groups: Record<string, string>
|
||||
package?: { lastPublished: number; item: Package }
|
||||
rejected: number
|
||||
}
|
||||
|
||||
export type Call = <T>(path: string, method?: string, body?: object) => Promise<T>
|
||||
const encoder = new TextEncoder()
|
||||
|
||||
function aad(id: string, sender: string, recipient: string) {
|
||||
return encoder.encode('XHChat message v1\n' + id + '\n' + sender + '\n' + recipient)
|
||||
}
|
||||
|
||||
async function verify(peer: Peer, user: string, type: 'credential' | 'KeyPackage', value: Uint8Array, signature: string) {
|
||||
const key = await crypto.subtle.importKey('raw', decode(peer.publicKey), 'Ed25519', false, ['verify'])
|
||||
if (!await crypto.subtle.verify('Ed25519', key, decode(signature), mlsBinding(type, user, peer.id, value))) {
|
||||
throw new Error('对方设备签名验证失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function verifiedPeer(peer: Peer, user: string) {
|
||||
if (!peer.mls) throw new Error('此设备尚未启用加密聊天')
|
||||
const key = decode(peer.mls.publicKey)
|
||||
await verify(peer, user, 'credential', key, peer.mls.signature)
|
||||
return key
|
||||
}
|
||||
|
||||
export function directory(call: Call, user: string) {
|
||||
return call<Peer[]>('/contacts/' + user + '/devices')
|
||||
}
|
||||
|
||||
function update<R>(identity: ChatIdentity, operation: (s: ChatState, save: (s: ChatState) => Promise<void>, factory: Awaited<ReturnType<typeof loadEngine>>) => Promise<R>) {
|
||||
return withVault<ChatState, R>(identity.device.id, async (state, save) => {
|
||||
const factory = await loadEngine()
|
||||
if (!state) {
|
||||
const engine = new factory.DeviceMls(identity.device.id)
|
||||
try {
|
||||
state = { engine: base64(engine.snapshot()), cursor: '0', pending: [], outbox: [], lines: [], pinned: {}, groups: {}, rejected: 0 }
|
||||
await save(state)
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
}
|
||||
return operation(state, save, factory)
|
||||
})
|
||||
}
|
||||
|
||||
async function signed(identity: ChatIdentity, kind: 'credential' | 'KeyPackage', value: Uint8Array<ArrayBuffer>) {
|
||||
return base64(await signMls(identity.user.username, kind, identity.user.id, identity.device.id, value))
|
||||
}
|
||||
|
||||
export async function enableChat(identity: ChatIdentity, call: Call) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
if (engine.device() !== identity.device.id) throw new Error('本机加密状态属于其他设备')
|
||||
const key = engine.public_key()
|
||||
await call('/mls-credential', 'POST', { publicKey: base64(key), signature: await signed(identity, 'credential', key) })
|
||||
if (!state.package || Date.now() - state.package.lastPublished >= 6 * 3600_000) {
|
||||
if (!state.package || state.package.lastPublished) {
|
||||
const pack = engine.key_package()
|
||||
state.package = { lastPublished: 0, item: { package: base64(pack), signature: await signed(identity, 'KeyPackage', pack) } }
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
}
|
||||
await call('/key-packages', 'POST', state.package.item)
|
||||
state.package.lastPublished = Date.now()
|
||||
await save(state)
|
||||
}
|
||||
return fingerprint(decode(await localIdentityKey(identity, call)))
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function localIdentityKey(identity: ChatIdentity, call: Call) {
|
||||
const { publicKey } = await call<{ publicKey: string }>('/mls-local-key')
|
||||
const credential = decode(publicKey)
|
||||
const proof = await signed(identity, 'credential', credential)
|
||||
await verify({ id: identity.device.id, name: '', publicKey }, identity.user.id, 'credential', credential, proof)
|
||||
return publicKey
|
||||
}
|
||||
|
||||
export async function trust(identity: ChatIdentity, user: string, peer: Peer, code: string) {
|
||||
await verifiedPeer(peer, user)
|
||||
const expected = await fingerprint(decode(peer.publicKey))
|
||||
if (code.replace(/\s+/g, '').toLowerCase() !== expected) throw new Error('安全码不匹配')
|
||||
await update(identity, async (state, save) => {
|
||||
const previous = state.pinned[peer.id]
|
||||
if (previous && previous !== peer.publicKey) throw new Error('该设备身份已变更,请使用新设备重新建立会话')
|
||||
state.pinned[peer.id] = peer.publicKey
|
||||
await save(state)
|
||||
})
|
||||
}
|
||||
|
||||
async function flush(state: ChatState, save: (state: ChatState) => Promise<void>, call: Call) {
|
||||
const unavailable = new Set<string>()
|
||||
for (const item of [...state.outbox]) {
|
||||
if (unavailable.has(item.recipientDevice)) continue
|
||||
try {
|
||||
await call('/inbox', 'POST', item)
|
||||
state.outbox = state.outbox.filter((pending) => pending.messageId !== item.messageId)
|
||||
await save(state)
|
||||
} catch (error) {
|
||||
if (!(error instanceof APIError) || error.status !== 404) throw error
|
||||
unavailable.add(item.recipientDevice)
|
||||
}
|
||||
}
|
||||
return unavailable
|
||||
}
|
||||
|
||||
export function send(identity: ChatIdentity, user: string, peer: Peer, text: string, 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 字节')
|
||||
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
|
||||
if (!group) {
|
||||
const pack = await call<Package>('/contacts/' + user + '/devices/' + current.id + '/claim', 'POST')
|
||||
const wire = decode(pack.package)
|
||||
await verify(current, user, 'KeyPackage', wire, pack.signature)
|
||||
group = crypto.getRandomValues(new Uint8Array(32))
|
||||
const welcome = engine.start(group, current.id, key, wire)
|
||||
state.groups[current.id] = base64(group)
|
||||
state.outbox.push({ messageId: crypto.randomUUID(), recipientDevice: current.id, ciphertext: base64(welcome) })
|
||||
}
|
||||
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.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
await flush(state, save, call)
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function synchronize(identity: ChatIdentity, user: string, call: Call) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const peers = await directory(call, user)
|
||||
for (let page = 0; page < 4; page++) {
|
||||
const inbox = await call<Incoming[]>('/inbox?after=' + state.cursor)
|
||||
if (!inbox.length) break
|
||||
if (state.pending.length + inbox.length > 512) throw new Error('待验证消息已达上限,请先打开相应联系人的聊天')
|
||||
state.pending.push(...inbox)
|
||||
state.cursor = inbox.at(-1)!.sequence
|
||||
await save(state)
|
||||
if (inbox.length < 64) break
|
||||
}
|
||||
for (const item of [...state.pending]) {
|
||||
const peer = peers.find((device) => device.id === item.senderDevice)
|
||||
if (!peer || !peer.mls || state.pinned[peer.id] !== peer.publicKey) continue
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
const key = await verifiedPeer(peer, user)
|
||||
const wire = decode(item.ciphertext)
|
||||
if (wire[3] === 3) {
|
||||
const group = base64(engine.join(peer.id, key, wire))
|
||||
const previous = state.groups[peer.id]
|
||||
if (!previous || group < previous) state.groups[peer.id] = group
|
||||
} 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),
|
||||
time: item.createdAt, own: false,
|
||||
})
|
||||
}
|
||||
state.engine = base64(engine.snapshot())
|
||||
} catch {
|
||||
state.rejected++
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
state.pending = state.pending.filter((pending) => pending.sequence !== item.sequence)
|
||||
await save(state)
|
||||
}
|
||||
let deliveryError = ''
|
||||
try {
|
||||
const unavailable = await flush(state, save, call)
|
||||
if (unavailable.size) deliveryError = '部分待发消息的设备已不可用'
|
||||
} catch (cause) {
|
||||
deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试'
|
||||
}
|
||||
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError,
|
||||
unsent: state.outbox.map((item) => item.messageId) }
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user