diff --git a/lib/shared/device-list-utils.js b/lib/shared/device-list-utils.js --- a/lib/shared/device-list-utils.js +++ b/lib/shared/device-list-utils.js @@ -214,11 +214,41 @@ await updateDeviceList(signedDeviceList); } +async function replaceDeviceInDeviceList( + identityClient: IdentityServiceClient, + userID: string, + deviceIDToRemove: string, + newDeviceID: string, +): Promise { + const { updateDeviceList } = identityClient; + invariant( + updateDeviceList, + 'updateDeviceList() should be defined on native. ' + + 'Are you calling it on a non-primary device?', + ); + + const { devices } = await fetchLatestDeviceList(identityClient, userID); + + // If the device to remove is not on the list and the new device is already on + // the list, return + if (!devices.includes(deviceIDToRemove) && devices.includes(newDeviceID)) { + return; + } + + const newDevices = devices.filter(it => it !== deviceIDToRemove); + newDevices.push(newDeviceID); + + const newDeviceList = composeRawDeviceList(newDevices); + const signedDeviceList = await signDeviceListUpdate(newDeviceList); + await updateDeviceList(signedDeviceList); +} + export { verifyAndGetDeviceList, createAndSignSingletonDeviceList, fetchLatestDeviceList, addDeviceToDeviceList, removeDeviceFromDeviceList, + replaceDeviceInDeviceList, signDeviceListUpdate, };