session-desktop/ts/util/user.ts

69 lines
2.1 KiB
TypeScript
Raw Normal View History

import { getItemById } from '../../js/modules/data';
2020-06-09 08:18:02 +02:00
import { KeyPair } from '../../libtextsecure/libsignal-protocol';
import { StringUtils } from '../session/utils';
import _ from 'lodash';
2021-01-20 06:58:59 +01:00
import { PubKey } from '../session/types';
import { UserUtil } from '.';
export type HexKeyPair = {
pubKey: string;
privKey: string;
};
/**
2021-01-20 06:58:59 +01:00
* Returns the public key of this current device as a string
*/
export async function getCurrentDevicePubKey(): Promise<string | undefined> {
const item = await getItemById('number_id');
if (!item || !item.value) {
return undefined;
}
return item.value.split('.')[0];
}
2021-01-20 06:58:59 +01:00
export async function getOurNumber(): Promise<PubKey> {
const ourNumber = await UserUtil.getCurrentDevicePubKey();
if(!ourNumber) {
throw new Error('ourNumber is not set');
}
return PubKey.cast(ourNumber);
}
export async function isUs(pubKey: string | PubKey | undefined): Promise<boolean> {
if(!pubKey) {
throw new Error('pubKey is not set');
}
const ourNumber = await UserUtil.getCurrentDevicePubKey();
if(!ourNumber) {
throw new Error('ourNumber is not set');
}
const pubKeyStr = pubKey instanceof PubKey ? pubKey.key : pubKey;
return pubKeyStr === ourNumber;
}
/**
* This return the stored x25519 identity keypair for the current logged in user
*/
export async function getIdentityKeyPair(): Promise<KeyPair | undefined> {
const item = await getItemById('identityKey');
return item?.value;
}
export async function getUserED25519KeyPair(): Promise<HexKeyPair | undefined> {
// 'identityKey' keeps the ed25519KeyPair under a ed25519KeyPair field.
// it is only set if the user migrated to the ed25519 way of generating a key
const item = await getItemById('identityKey');
const ed25519KeyPair = item?.value?.ed25519KeyPair;
if (ed25519KeyPair?.publicKey && ed25519KeyPair?.privateKey) {
const pubKeyAsArray = _.map(ed25519KeyPair.publicKey, a => a);
const privKeyAsArray = _.map(ed25519KeyPair.privateKey, a => a);
return {
pubKey: StringUtils.toHex(new Uint8Array(pubKeyAsArray)),
privKey: StringUtils.toHex(new Uint8Array(privKeyAsArray)),
};
}
return undefined;
}