1 import { getAddressKeyPassword, getDecryptedAddressKey } from '@proton/shared/lib/keys/addressKeys';
2 import isTruthy from '@proton/utils/isTruthy';
3 import noop from '@proton/utils/noop';
5 import type { DecryptedAddressKey, KeyPair, User, AddressKey as tsAddressKey } from '../interfaces';
6 import { getDecryptedOrganizationKey } from './getDecryptedOrganizationKey';
7 import { splitKeys } from './keys';
9 export const getDecryptedAddressKeys = async (
10 addressKeys: tsAddressKey[] = [],
11 userKeys: KeyPair[] = [],
13 organizationKey?: KeyPair
14 ): Promise<DecryptedAddressKey[]> => {
15 if (!addressKeys.length || !userKeys.length) {
19 const userKeysPair = splitKeys(userKeys);
21 const [primaryKey, ...restKeys] = addressKeys;
23 const primaryKeyResult = await getAddressKeyPassword(primaryKey, userKeysPair, keyPassword, organizationKey)
24 .then((password) => getDecryptedAddressKey(primaryKey, password))
27 // In case the primary key fails to decrypt, something is broken, so don't even try to decrypt the rest of the keys.
28 if (!primaryKeyResult) {
32 const restKeyResults = await Promise.all(
33 restKeys.map((restKey) => {
34 return getAddressKeyPassword(restKey, userKeysPair, keyPassword, organizationKey)
35 .then((password) => getDecryptedAddressKey(restKey, password))
40 return [primaryKeyResult, ...restKeyResults].filter(isTruthy);
42 export const getDecryptedAddressKeysHelper = async (
43 addressKeys: tsAddressKey[] = [],
45 userKeys: KeyPair[] = [],
47 ): Promise<DecryptedAddressKey[]> => {
48 if (!user.OrganizationPrivateKey) {
49 return getDecryptedAddressKeys(addressKeys, userKeys, keyPassword);
52 const { OrganizationPrivateKey } = user;
54 const organizationKey = OrganizationPrivateKey
55 ? await getDecryptedOrganizationKey(OrganizationPrivateKey, keyPassword).catch(noop)
57 // When signed into a non-private member, if the organization key can't be decrypted, the rest
58 // of the keys won't be able to get decrypted
59 if (!organizationKey) {
62 return getDecryptedAddressKeys(addressKeys, userKeys, keyPassword, organizationKey);