1 import { createAddressKeyRoute, createAddressKeyRouteV2 } from '../../api/keys';
2 import { DEFAULT_KEYGEN_TYPE, KEYGEN_CONFIGS } from '../../constants';
3 import type { ActiveKey, Address, Api, KeyGenConfig, KeyPair, KeyTransparencyVerify } from '../../interfaces';
4 import { generateAddressKey, getNewAddressKeyToken } from '../addressKeys';
5 import { getActiveKeyObject, getNormalizedActiveKeys } from '../getActiveKeys';
6 import { getDefaultKeyFlags } from '../keyFlags';
7 import { getSignedKeyListWithDeferredPublish } from '../signedKeyList';
9 interface CreateAddressKeyLegacyArguments {
11 keyGenConfig?: KeyGenConfig;
14 activeKeys: ActiveKey[];
15 keyTransparencyVerify: KeyTransparencyVerify;
16 addressForwardingID?: string;
19 export const removePrimary = (activeKey: ActiveKey): ActiveKey => {
20 if (activeKey.primary) {
29 export const createAddressKeyLegacy = async ({
32 keyGenConfig = KEYGEN_CONFIGS[DEFAULT_KEYGEN_TYPE],
35 keyTransparencyVerify,
36 addressForwardingID: AddressForwardingID,
37 }: CreateAddressKeyLegacyArguments) => {
38 const { privateKey, privateKeyArmored } = await generateAddressKey({
43 const newActiveKey = await getActiveKeyObject(privateKey, {
46 flags: getDefaultKeyFlags(address),
48 const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey, ...activeKeys.map(removePrimary)]);
49 const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
54 const { Key } = await api(
55 createAddressKeyRoute({
56 AddressID: address.ID,
57 Primary: newActiveKey.primary,
58 PrivateKey: privateKeyArmored,
63 await onSKLPublishSuccess();
64 newActiveKey.ID = Key.ID;
66 return [newActiveKey, updatedActiveKeys] as const;
69 interface CreateAddressKeyV2Arguments {
72 keyGenConfig?: KeyGenConfig;
74 activeKeys: ActiveKey[];
75 keyTransparencyVerify: KeyTransparencyVerify;
78 export const createAddressKeyV2 = async ({
81 keyGenConfig = KEYGEN_CONFIGS[DEFAULT_KEYGEN_TYPE],
84 keyTransparencyVerify,
85 }: CreateAddressKeyV2Arguments) => {
86 const { token, encryptedToken, signature } = await getNewAddressKeyToken({ address, userKeys });
87 const { privateKey, privateKeyArmored } = await generateAddressKey({
92 const newActiveKey = await getActiveKeyObject(privateKey, {
95 flags: getDefaultKeyFlags(address),
97 const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey, ...activeKeys.map(removePrimary)]);
98 const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish(
101 keyTransparencyVerify
103 const { Key } = await api(
104 createAddressKeyRouteV2({
105 AddressID: address.ID,
106 Primary: newActiveKey.primary,
107 PrivateKey: privateKeyArmored,
109 Signature: signature,
110 Token: encryptedToken,
113 // Only once the SKL is successfully posted we add it to the KT commit state.
114 await onSKLPublishSuccess();
115 newActiveKey.ID = Key.ID;
117 return [newActiveKey, updatedActiveKeys] as const;