1 import { stringToUtf8Array, utf8ArrayToString } from '@proton/crypto/lib/utils';
2 import { decryptData, encryptData } from '@proton/crypto/lib/subtle/aesGcm';
3 import { getClientKey } from '@proton/shared/lib/authentication/clientKey';
5 import type { DecryptedCache, EncryptedCache } from './db';
7 export const getEncryptedCache = async ({ clientKey, state }: { clientKey: string; state: string }) => {
8 const key = await getClientKey(clientKey);
9 return encryptData(key, stringToUtf8Array(state), stringToUtf8Array('cache'));
12 const decrypt = async <T>(options: { data: ArrayBuffer; key: CryptoKey }): Promise<T | undefined> => {
16 const decryptedData = await decryptData(options.key, new Uint8Array(options.data), stringToUtf8Array('cache'));
17 return JSON.parse(utf8ArrayToString(decryptedData)) as T;
20 export const getDecryptedCache = async <T>(
21 { state: encryptedState, eventID, appVersion }: Partial<EncryptedCache>,
22 { clientKey }: { clientKey: string }
23 ): Promise<DecryptedCache<T> | undefined> => {
24 if (!encryptedState || !eventID || !appVersion) {
27 const key = await getClientKey(clientKey);
29 const state = await decrypt<T>({ data: encryptedState, key });
35 return { state, eventID, appVersion };