Merge branch 'DRVDOC-1260' into 'main'
[ProtonMail-WebClient.git] / packages / components / containers / keyTransparency / useResignSKLWithPrimaryKey.ts
blob49dbdac2c1c51ebf084d28599b4a92b9a8af4e05
1 import useKTActivation from '@proton/components/containers/keyTransparency/useKTActivation';
2 import useApi from '@proton/components/hooks/useApi';
3 import {
4     fetchSignedKeyLists,
5     fetchVerifiedEpoch,
6     ktSentryReportError,
7     updateSignedKeyListSignature,
8     verifySKLSignature,
9 } from '@proton/key-transparency/lib';
10 import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig';
11 import type { ResignSKLWithPrimaryKey, ResignSKLWithPrimaryKeyArguments } from '@proton/shared/lib/interfaces';
12 import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces';
13 import { getSignedKeyListSignature } from '@proton/shared/lib/keys';
15 const useResignSKLWithPrimaryKey = (): ResignSKLWithPrimaryKey => {
16     const api = getSilentApi(useApi());
17     const ktActivation = useKTActivation();
19     const resignSKLWithPrimaryKey = async ({
20         address,
21         newPrimaryKey,
22         formerPrimaryKey,
23         userKeys,
24     }: ResignSKLWithPrimaryKeyArguments) => {
25         try {
26             if (ktActivation === KeyTransparencyActivation.DISABLED) {
27                 return;
28             }
29             const userVerificationKeys = userKeys.map((key) => key.publicKey);
30             const verifiedEpoch = await fetchVerifiedEpoch(address, api, userVerificationKeys);
31             const skls = await fetchSignedKeyLists(api, verifiedEpoch?.Revision ?? 0, address.Email);
32             await Promise.all(
33                 skls.map(async (skl) => {
34                     if (skl.Data && skl.Signature) {
35                         const timestamp = await verifySKLSignature([formerPrimaryKey], skl.Data, skl.Signature);
36                         if (!timestamp) {
37                             return;
38                         }
39                         const newSignature = await getSignedKeyListSignature(skl.Data, newPrimaryKey, timestamp);
40                         await updateSignedKeyListSignature(address.ID, skl.Revision, newSignature, api);
41                     }
42                 })
43             );
44         } catch (error: any) {
45             ktSentryReportError(error, { context: 'resignSKLWithPrimaryKey' });
46         }
47     };
49     return resignSKLWithPrimaryKey;
52 export default useResignSKLWithPrimaryKey;