Cleanup - unused files / unused exports / duplicate exports
[ProtonMail-WebClient.git] / packages / shared / lib / keys / getDecryptedOrganizationKey.ts
blobc905d4c2dbea28826e66eec79f464857ca5e0629
1 import { CryptoProxy } from '@proton/crypto';
2 import { decryptAddressKeyToken } from '@proton/shared/lib/keys/addressKeys';
3 import { splitKeys } from '@proton/shared/lib/keys/keys';
4 import { ORGANIZATION_SIGNATURE_CONTEXT, getIsPasswordless } from '@proton/shared/lib/keys/organizationKeys';
6 import type { CachedOrganizationKey, DecryptedKey, KeyPair, OrganizationKey } from '../interfaces';
8 export const getDecryptedOrganizationKey = async (armoredKey: string, passphrase: string) => {
9     const privateKey = await CryptoProxy.importPrivateKey({
10         armoredKey,
11         passphrase,
12     });
13     const publicKey = await CryptoProxy.importPublicKey({
14         binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }),
15     });
16     return {
17         privateKey,
18         publicKey,
19     };
22 export const getOrganizationKeyToken = async ({
23     userKeys,
24     Key,
25     keyPassword,
26 }: {
27     userKeys: KeyPair[];
28     Key?: OrganizationKey;
29     keyPassword: string;
30 }) => {
31     if (getIsPasswordless(Key)) {
32         const { privateKeys, publicKeys } = splitKeys(userKeys);
33         return decryptAddressKeyToken({
34             publicKeys,
35             privateKeys,
36             Token: Key.Token,
37             Signature: Key.Signature,
38             context: { value: ORGANIZATION_SIGNATURE_CONTEXT.SHARE_ORGANIZATION_KEY_TOKEN, required: true },
39         });
40     }
41     return keyPassword;
44 export const getDecryptedOrganizationKeyHelper = async ({
45     userKeys,
46     Key,
47     keyPassword,
48 }: {
49     userKeys: KeyPair[];
50     Key: OrganizationKey;
51     keyPassword: string;
52 }) => {
53     if (!Key.PrivateKey) {
54         throw new Error('Missing key');
55     }
56     if (Key.LegacyPrivateKey) {
57         return getDecryptedOrganizationKey(Key.LegacyPrivateKey, keyPassword);
58     }
59     return getDecryptedOrganizationKey(Key.PrivateKey, await getOrganizationKeyToken({ userKeys, Key, keyPassword }));
62 export const getCachedOrganizationKey = async ({
63     userKeys,
64     keyPassword,
65     Key,
66 }: {
67     userKeys: DecryptedKey[];
68     keyPassword: string;
69     Key: OrganizationKey;
70 }): Promise<CachedOrganizationKey> => {
71     if (!Key.PrivateKey) {
72         return {
73             Key,
74         };
75     }
76     try {
77         const { privateKey, publicKey } = await getDecryptedOrganizationKeyHelper({
78             Key,
79             keyPassword,
80             userKeys,
81         });
82         return {
83             Key,
84             privateKey,
85             publicKey,
86         };
87     } catch (e: any) {
88         return {
89             Key,
90             error: e,
91         };
92     }