passphrase prompt

This commit is contained in:
2023-05-23 00:44:51 +02:00
parent 029893830f
commit aa77296d00
6 changed files with 110 additions and 27 deletions

View File

@@ -2,7 +2,7 @@ import { doc, getDoc } from 'firebase/firestore'
import { user, db } from '@/composables/useFirebase'
import { decrypt, calculateClientKey } from '@/utils/crypto'
function getClientKeysFromLocalStorage() {
function getClientKeysFromLocalStorage(): { [uid: string]: string } {
try {
return JSON.parse(localStorage.getItem('clientKeys') || '{}')
} catch (e) {
@@ -10,24 +10,58 @@ function getClientKeysFromLocalStorage() {
}
}
export const getClientKey = (): ClientKey | void => {
export const clientKey = ref<ClientKey>()
export const getClientKey = () => {
if (!user.value) return
const clientKeys = getClientKeysFromLocalStorage()
const clientKey = clientKeys[user.value?.uid] || calculateClientKey('test')
return clientKey
clientKey.value = clientKeys[user.value?.uid]
}
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
export const setClientKey = (passphrase: string) => {
const calculatedClientKey = calculateClientKey(passphrase)
const verified = verifyClientKey(calculatedClientKey)
if (!user.value || !verified) return
const clientKeys = getClientKeysFromLocalStorage()
clientKeys[user.value.uid] = calculatedClientKey
localStorage.setItem('clientKeys', JSON.stringify(clientKeys))
clientKey.value = calculatedClientKey
getEncryptionKey()
return true
}
export const verifyClientKey = (clientKey: ClientKey) => {
try {
if (!encryptedEncryptionKey.value) throw new Error('Encryption key is null')
if (!clientKey) throw new Error('Client key is null')
decrypt(encryptedEncryptionKey.value, clientKey)
return true
} catch (e) {
console.log(e)
return false
}
}
const encryptedEncryptionKey = ref<EncryptedEncryptionKey>()
async function getEncryptedEncryptionKey(): Promise<EncryptedEncryptionKey | void> {
if (!user.value || !db.value) return
const data = (await getDoc(doc(db.value, 'encryptionKeys', user.value?.uid || ''))).data()
return data?.key
}
export const encryptionKey = ref<EncryptionKey | null>()
export async function getEncryptionKey() {
encryptedEncryptionKey.value = (await getEncryptedEncryptionKey()) || undefined
if (!encryptedEncryptionKey.value || !clientKey.value) return
encryptionKey.value = decrypt(encryptedEncryptionKey.value, clientKey.value)
}
export const passphraseRequired = computed(() => {
return Boolean(encryptedEncryptionKey.value && !clientKey.value)
})
const decryptNote = (note: BaseNote, key: EncryptionKey) => {
return {
...note,