near-api-js
near-api-js copied to clipboard
Get correct publicKey from biometric getKeys using indexer
Have you read the Contributing Guidelines?
- [X] I have read the Contributing Guidelines on issues.
Description
As the nature of Elliptic Curve crypto, getKeys
return with two possible public key pairs. In order to select the correct public key pair out of two pairs, one can either implement a logic to preserve the public key pair created from createKey
and retrieve them after calling getKeys
and find the right one or alternatively, opt for the following approach that utilizes a public indexer
import { getKeys, getCorrectPublicKey } from "@near-js/biometric-ed25519";
const keys = await getKeys(userName);
const correctKey = getCorrectPublicKey(keys, userName);
Has this been requested on GitHub Discussions?
No response
Motivation
As an avid user of this library I can say its easy to get into situations where it becomes hard to find the correct public key from the pair returned. This solution offers worst case a fallback and best case a new way to use this library without having to necessarily store keys or usernames.
This method makes it possible to abstract away the management of keys by returning the correct key regardless of knowing the username or not
API design
import { accountsByPublicKey } from '@mintbase-js/data';
/**
* Finds the correct public key from the pair returned in getKeys based on the associated username or if not provided any account data.
* @param keys - An array of KeyPair objects.
* @param username - The username to match against the associated data.
* @returns The correct public key as a string.
* @throws Error if no account is found for the key.
*/
export const getCorrectPublicKey = async (keys: [KeyPair, KeyPair], username?: string): Promise<string> => {
for (const key of keys) {
const publicKeyString = key.getPublicKey()?.toString();
const { data } = await accountsByPublicKey(publicKeyString);
const isValidKey = username ? data.some((id) => id === username) : data.length > 0;
if (isValidKey) {
return publicKeyString;
}
}
throw new Error("No account found for key");
};
Self-service
- [X] I'd be willing to contribute and develop this feature myself.
This sounds good as a feature. However, our team will propose to completely rewrite the biometric module. The reason is that there are some issues with it and not a single test or doc about why the module has been designed in such a way.
Either way PR will be appreciated