73 lines
3.0 KiB
TypeScript
73 lines
3.0 KiB
TypeScript
import { base64, decode } from './engine'
|
|
|
|
interface VaultRecord {
|
|
key: CryptoKey | string
|
|
iv?: Uint8Array<ArrayBuffer>
|
|
sealed?: ArrayBuffer
|
|
}
|
|
|
|
function database(): Promise<IDBDatabase> {
|
|
return new Promise((resolve, reject) => {
|
|
const request = indexedDB.open('xhchat-encrypted-chat', 1)
|
|
request.onupgradeneeded = () => request.result.createObjectStore('vaults')
|
|
request.onsuccess = () => resolve(request.result)
|
|
request.onerror = () => reject(request.error)
|
|
request.onblocked = () => reject(new Error('请关闭其他 XHChat 页面后重试'))
|
|
})
|
|
}
|
|
|
|
function record(db: IDBDatabase, scope: string, value?: VaultRecord): Promise<VaultRecord | undefined> {
|
|
return new Promise((resolve, reject) => {
|
|
const transaction = db.transaction('vaults', value ? 'readwrite' : 'readonly')
|
|
const store = transaction.objectStore('vaults')
|
|
const request = value ? store.put(value, scope) : store.get(scope)
|
|
transaction.oncomplete = () => resolve(value ?? request.result)
|
|
transaction.onabort = () => reject(transaction.error)
|
|
})
|
|
}
|
|
|
|
async function newKey(): Promise<VaultRecord['key']> {
|
|
if (!window.xhchat) return crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
const raw = crypto.getRandomValues(new Uint8Array(32))
|
|
try {
|
|
return await window.xhchat.protectMls(base64(raw))
|
|
} finally {
|
|
raw.fill(0)
|
|
}
|
|
}
|
|
|
|
async function unsealKey(value: VaultRecord['key']) {
|
|
if (!window.xhchat && typeof value !== 'string') return value
|
|
if (!window.xhchat || typeof value !== 'string') throw new Error('会话存储密钥无效')
|
|
const raw = decode(await window.xhchat.unprotectMls(value))
|
|
try {
|
|
return await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt'])
|
|
} finally {
|
|
raw.fill(0)
|
|
}
|
|
}
|
|
|
|
export async function withVault<T, R>(device: string, update: (state: T | undefined, save: (state: T) => Promise<void>) => Promise<R>, readOnly = false) {
|
|
const scope = (window.xhchat?.apiBase ?? location.origin) + '/' + device
|
|
const additionalData = new TextEncoder().encode(scope)
|
|
return navigator.locks.request('xhchat-chat:' + scope, async () => {
|
|
const db = await database()
|
|
try {
|
|
const stored = await record(db, scope)
|
|
if (!stored && readOnly) return await update(undefined, async () => { throw new Error('会话尚未启用') })
|
|
const wrapped = stored?.key ?? await newKey()
|
|
const key = await unsealKey(wrapped)
|
|
const state = stored?.iv && stored.sealed
|
|
? JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: stored.iv, additionalData }, key, stored.sealed))) as T
|
|
: undefined
|
|
return await update(state, async (next) => {
|
|
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData }, key, new TextEncoder().encode(JSON.stringify(next)))
|
|
await record(db, scope, { key: wrapped, iv, sealed })
|
|
})
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
}
|