Files
XHChat/web/src/identity.ts
T

89 lines
3.5 KiB
TypeScript

interface DeviceProof {
publicKey: string
signature: string
}
interface DesktopBridge {
apiBase: string
signChallenge: (username: string, challenge: string) => Promise<DeviceProof>
openBrowser?: (url?: string) => Promise<void>
messageNotificationsSupported: () => Promise<boolean>
showMessageNotification: (kind: 'group' | 'private') => Promise<void>
closeMessageNotification: () => Promise<void>
allowVoiceRecording: () => Promise<void>
endVoiceRecording: () => Promise<void>
signMls: (username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array<ArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>>
protectMls: (key: string) => Promise<string>
unprotectMls: (key: string) => Promise<string>
}
declare global {
interface Window { xhchat?: DesktopBridge }
}
const prefix = 'XHChat device authentication v1\n'
function base64url(bytes: ArrayBuffer) {
return btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
}
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open('xhchat-device', 1)
request.onupgradeneeded = () => request.result.createObjectStore('keys')
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
request.onblocked = () => reject(new Error('请关闭其他 XHChat 页面后重试'))
})
}
async function browserKey(username: string): Promise<CryptoKeyPair> {
const candidate = await crypto.subtle.generateKey('Ed25519', false, ['sign', 'verify'])
const db = await openDatabase()
try {
return await new Promise((resolve, reject) => {
const transaction = db.transaction('keys', 'readwrite')
const keys = transaction.objectStore('keys')
const read = keys.get(username)
let result = candidate
read.onsuccess = () => {
if (read.result) result = read.result
else keys.add(candidate, username)
}
transaction.oncomplete = () => resolve(result)
transaction.onabort = () => reject(transaction.error)
})
} finally {
db.close()
}
}
export const platform = window.xhchat ? 'windows' : 'web'
export function mlsBinding(kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array) {
const prefix = new TextEncoder().encode('XHChat MLS ' + kind + ' v1\n' + user + '\n' + device + '\n')
const bytes = new Uint8Array(prefix.length + value.length)
bytes.set(prefix)
bytes.set(value, prefix.length)
return bytes
}
export async function signMls(username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array<ArrayBuffer>) {
if (window.xhchat) return window.xhchat.signMls(username, kind, user, device, value)
const pair = await browserKey(username)
return new Uint8Array(await crypto.subtle.sign('Ed25519', pair.privateKey, mlsBinding(kind, user, device, value)))
}
export async function signChallenge(username: string, challenge: string): Promise<DeviceProof> {
if (window.xhchat) return window.xhchat.signChallenge(username, challenge)
try {
const pair = await browserKey(username)
const publicKey = await crypto.subtle.exportKey('raw', pair.publicKey)
const signature = await crypto.subtle.sign('Ed25519', pair.privateKey, new TextEncoder().encode(prefix + challenge))
return { publicKey: base64url(publicKey), signature: base64url(signature) }
} catch {
throw new Error('无法使用本机设备密钥,请检查浏览器是否支持安全密钥存储')
}
}