1 import { CryptoProxy } from '@proton/crypto';
2 import { getDefaultKeyFlags } from '@proton/shared/lib/keys';
4 import { createAddressKeyRoute } from '../../api/keys';
5 import type { Address, Api, DecryptedKey, KeyTransparencyVerify } from '../../interfaces';
9 getNormalizedActiveAddressKeys,
11 } from '../getActiveKeys';
12 import { getInactiveKeys } from '../getInactiveKeys';
13 import reactivateKeysProcessLegacy from '../reactivation/reactivateKeysProcessLegacy';
14 import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
15 import { getFilteredImportRecords } from './helper';
16 import type { KeyImportData, OnKeyImportCallback } from './interface';
18 export interface ImportKeysProcessLegacyArguments {
20 keyImportRecords: KeyImportData[];
21 onImport: OnKeyImportCallback;
24 addressKeys: DecryptedKey[];
25 keyTransparencyVerify: KeyTransparencyVerify;
28 // handles import with non-migrated keys
29 const importKeysProcessLegacy = async ({
36 keyTransparencyVerify,
37 }: ImportKeysProcessLegacyArguments) => {
38 const activeKeys = await getActiveAddressKeys(address, address.SignedKeyList, address.Keys, addressKeys);
39 const inactiveKeys = await getInactiveKeys(address.Keys, activeKeys.v4); // v6 keys not present for non-migrated users
41 const [keysToReactivate, keysToImport, existingKeys] = getFilteredImportRecords(
47 existingKeys.forEach((keyImportRecord) => {
48 onImport(keyImportRecord.id, new Error('Key already active'));
51 let mutableActiveKeys = activeKeys;
53 for (const keyImportRecord of keysToImport) {
55 const { privateKey } = keyImportRecord;
56 if (!privateKey.isPrivateKeyV4()) {
57 throw new Error('v6 keys not supported with non-migrated keys');
59 const privateKeyArmored = await CryptoProxy.exportPrivateKey({
61 passphrase: keyPassword,
64 const newActiveKey = await getActiveKeyObject(privateKey, {
66 primary: getPrimaryFlag(mutableActiveKeys.v4),
67 flags: getDefaultKeyFlags(address),
69 const updatedActiveKeys = getNormalizedActiveAddressKeys(address, {
70 v4: [...mutableActiveKeys.v4, newActiveKey],
73 const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
79 const { Key } = await api(
80 createAddressKeyRoute({
81 AddressID: address.ID,
82 Primary: newActiveKey.primary,
83 PrivateKey: privateKeyArmored,
87 // Only once the SKL is successfully posted we add it to the KT commit state.
88 await onSKLPublishSuccess();
89 // Mutably update the key with the latest value from the real ID.
90 newActiveKey.ID = Key.ID;
92 mutableActiveKeys = updatedActiveKeys;
94 onImport(keyImportRecord.id, 'ok');
96 onImport(keyImportRecord.id, e);
100 await reactivateKeysProcessLegacy({
107 keys: mutableActiveKeys.v4,
110 keyReactivationRecords: [
116 onReactivation: onImport,
117 keyTransparencyVerify,
121 export default importKeysProcessLegacy;