Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / components / hooks / helpers / addressFlagsHelper.ts
blobc512d33563d69f964e20300e96b58844100a603e
1 import { getNewKeyFlags } from '@proton/components/containers/keys/shared/flags';
2 import { FlagAction } from '@proton/components/containers/keys/shared/interface';
3 import { updateAddressFlags } from '@proton/shared/lib/api/members';
4 import type {
5     ActiveKeyWithVersion,
6     Address,
7     Api,
8     DecryptedAddressKey,
9     KeyTransparencyVerify,
10 } from '@proton/shared/lib/interfaces';
11 import { getSignedKeyListWithDeferredPublish } from '@proton/shared/lib/keys';
12 import { getActiveAddressKeys, getNormalizedActiveAddressKeys } from '@proton/shared/lib/keys/getActiveKeys';
14 export const setAddressFlags = async ({
15     encryptionDisabled,
16     expectSignatureDisabled,
17     address,
18     keyTransparencyVerify,
19     api,
20     addressesKeys,
21 }: {
22     encryptionDisabled: boolean;
23     expectSignatureDisabled: boolean;
24     address: Address;
25     keyTransparencyVerify: KeyTransparencyVerify;
26     api: Api;
27     addressesKeys?: {
28         address: Address;
29         keys: DecryptedAddressKey[];
30     }[];
31 }): Promise<void> => {
32     const { ID: addressID, SignedKeyList: currentSignedKeyList, Keys: currentKeys } = address;
33     const addressWithKeys = addressesKeys?.find(({ address: { ID } }) => ID === addressID);
34     if (addressWithKeys === undefined) {
35         throw new Error('addressWithKeys is undefined!');
36     }
38     const { keys } = addressWithKeys;
40     const activeKeys = await getActiveAddressKeys(address, currentSignedKeyList, currentKeys, keys);
42     const setFlags = <V extends ActiveKeyWithVersion>(activeKey: V) => ({
43         ...activeKey,
44         flags: getNewKeyFlags(
45             getNewKeyFlags(
46                 activeKey.flags,
47                 encryptionDisabled ? FlagAction.DISABLE_ENCRYPTION : FlagAction.ENABLE_ENCRYPTION
48             ),
49             expectSignatureDisabled ? FlagAction.DISABLE_EXPECT_SIGNED : FlagAction.ENABLE_EXPECT_SIGNED
50         ),
51     });
52     const newActiveKeys = getNormalizedActiveAddressKeys(address, {
53         v4: activeKeys.v4.map(setFlags),
54         v6: activeKeys.v6.map(setFlags),
55     });
56     const [newSignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
57         newActiveKeys,
58         address,
59         keyTransparencyVerify
60     );
61     await api(updateAddressFlags(address.ID, !encryptionDisabled, !expectSignatureDisabled, newSignedKeyList));
62     await onSKLPublishSuccess();