decrypt notes

This commit is contained in:
2023-05-22 20:48:53 +02:00
parent 55a281581e
commit 7ca2b25e8f
11 changed files with 152 additions and 24 deletions

View File

@@ -0,0 +1,44 @@
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
}