交付双端基础、实时联系人和隔离浏览器
This commit is contained in:
1 parent
43687d5e7e
commit
67fef3ff87
59 files changed
+5094
-1
No files matched your search
@@ -0,0 +1,66 @@
|
||||
interface DeviceProof {
|
||||
publicKey: string
|
||||
signature: string
|
||||
}
|
||||
|
||||
interface DesktopBridge {
|
||||
apiBase: string
|
||||
signChallenge: (username: string, challenge: string) => Promise<DeviceProof>
|
||||
openBrowser?: () => Promise<void>
|
||||
}
|
||||
|
||||
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 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('无法使用本机设备密钥,请检查浏览器是否支持安全密钥存储')
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user