45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import { doc, getDoc } from 'firebase/firestore'
|
|
import { user, db } from '@/composables/useFirebase'
|
|
import { decrypt, calculateClientKey } from '@/utils/crypto'
|
|
|
|
function getClientKeysFromLocalStorage() {
|
|
try {
|
|
return JSON.parse(localStorage.getItem('clientKeys') || '{}')
|
|
} catch (e) {
|
|
return {}
|
|
}
|
|
}
|
|
|
|
export const getClientKey = (): ClientKey | void => {
|
|
if (!user.value) return
|
|
const clientKeys = getClientKeysFromLocalStorage()
|
|
const clientKey = clientKeys[user.value?.uid] || calculateClientKey('test')
|
|
return clientKey
|
|
}
|
|
|
|
export async function getEncryptionKey(): Promise<EncryptionKey | void> {
|
|
if (!user.value) return
|
|
const clientKey = getClientKey()
|
|
if (!db.value || !clientKey) return
|
|
const data = (await getDoc(doc(db.value, 'encryptionKeys', user.value?.uid || ''))).data()
|
|
if (!data) return
|
|
const { key } = data
|
|
const encryptionKey: EncryptionKey = decrypt(key, clientKey)
|
|
return encryptionKey
|
|
}
|
|
|
|
const decryptNote = (note: BaseNote, key: EncryptionKey) => {
|
|
return {
|
|
...note,
|
|
title: decrypt(note.title, key),
|
|
content: decrypt(note.content, key)
|
|
}
|
|
}
|
|
|
|
export const decryptNotes = (notes: BaseNotes, encryptionKey: EncryptionKey) => {
|
|
const decryptedNotes = Object.fromEntries(
|
|
Object.entries(notes).map(([noteId, note]) => [noteId, { ...decryptNote(note, encryptionKey) }])
|
|
)
|
|
return decryptedNotes
|
|
}
|