session-desktop/ts/session/types/PubKey.ts

63 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-06-04 07:38:21 +02:00
export class PubKey {
2020-06-05 08:56:47 +02:00
public static readonly PUBKEY_LEN = 66;
public static readonly MOBILE_GROUP_PUBKEY_LEN = 32;
private static readonly regexForMobileGroupID = `__textsecure_group__![0-9a-fA-F]{${PubKey.MOBILE_GROUP_PUBKEY_LEN}}`;
// prettier-ignore
private static readonly regexForPubkeys = `((05)?[0-9a-fA-F]{${PubKey.PUBKEY_LEN - 2}})`;
2020-06-12 06:03:50 +02:00
private static readonly regex: RegExp = new RegExp(
`^${PubKey.regexForPubkeys}|${PubKey.regexForMobileGroupID}$`
2020-06-12 06:03:50 +02:00
);
2020-06-04 07:38:21 +02:00
public readonly key: string;
/**
* A PubKey object.
* If `pubKeyString` is not valid then this will throw an `Error`.
*
* @param pubkeyString The public key string.
*/
2020-06-04 08:11:50 +02:00
constructor(pubkeyString: string) {
if (!PubKey.validate(pubkeyString)) {
throw new Error(`Invalid pubkey string passed: ${pubkeyString}`);
}
2020-06-25 04:13:53 +02:00
this.key = pubkeyString.toLowerCase();
2020-06-04 07:38:21 +02:00
}
/**
* Cast a `value` to a `PubKey`.
* If `value` is not valid then this will throw.
*
* @param value The value to cast.
*/
public static cast(value: string | PubKey): PubKey {
return typeof value === 'string' ? new PubKey(value) : value;
}
/**
* Try convert `pubKeyString` to `PubKey`.
*
* @param pubkeyString The public key string.
* @returns `PubKey` if valid otherwise returns `undefined`.
*/
2020-06-04 07:38:21 +02:00
public static from(pubkeyString: string): PubKey | undefined {
// Returns a new instance if the pubkey is valid
if (PubKey.validate(pubkeyString)) {
return new PubKey(pubkeyString);
}
return undefined;
}
public static validate(pubkeyString: string): boolean {
return this.regex.test(pubkeyString);
2020-06-04 07:38:21 +02:00
}
2020-06-15 01:31:56 +02:00
2020-06-18 02:27:08 +02:00
public isEqual(comparator: PubKey | string) {
return comparator instanceof PubKey
? this.key === comparator.key
2020-06-25 04:13:53 +02:00
: this.key === comparator.toLowerCase();
2020-06-15 01:31:56 +02:00
}
2020-06-04 07:38:21 +02:00
}
2020-06-12 05:53:54 +02:00
export class PrimaryPubKey extends PubKey {}
export class SecondaryPubKey extends PubKey {}