fix multiple password prompt bug

This commit is contained in:
hzrd149
2024-03-05 16:34:30 +00:00
parent e053e5dc0c
commit b4acac74df

View File

@@ -8,7 +8,7 @@ import amberSignerService from "./amber-signer";
import nostrConnectService from "./nostr-connect"; import nostrConnectService from "./nostr-connect";
import { hexToBytes } from "@noble/hashes/utils"; import { hexToBytes } from "@noble/hashes/utils";
const decryptedKeys = new Map<string, string>(); const decryptedKeys = new Map<string, string | Promise<string>>();
class SigningService { class SigningService {
private async getSalt() { private async getSalt() {
@@ -28,7 +28,10 @@ class SigningService {
); );
if (!password) throw new Error("Password required"); if (!password) throw new Error("Password required");
const enc = new TextEncoder(); const enc = new TextEncoder();
return window.crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits", "deriveKey"]); return await window.crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, [
"deriveBits",
"deriveKey",
]);
} }
private async getEncryptionKey() { private async getEncryptionKey() {
const salt = await this.getSalt(); const salt = await this.getSalt();
@@ -67,8 +70,10 @@ class SigningService {
if (account.type !== "local") throw new Error("Account dose not have a secret key"); if (account.type !== "local") throw new Error("Account dose not have a secret key");
const cache = decryptedKeys.get(account.pubkey); const cache = decryptedKeys.get(account.pubkey);
if (cache) return cache; if (cache) return await cache;
// create a promise to decrypt the key
const p = (async () => {
const key = await this.getEncryptionKey(); const key = await this.getEncryptionKey();
const decode = new TextDecoder(); const decode = new TextDecoder();
@@ -78,8 +83,16 @@ class SigningService {
decryptedKeys.set(account.pubkey, secKey); decryptedKeys.set(account.pubkey, secKey);
return secKey; return secKey;
} catch (e) { } catch (e) {
console.log(e);
throw new Error("Failed to decrypt secret key"); throw new Error("Failed to decrypt secret key");
} }
})();
// cache the promise so its only called once
decryptedKeys.set(account.pubkey, p);
// await, return key
return await p;
} }
async requestSignature(draft: DraftNostrEvent, account: Account) { async requestSignature(draft: DraftNostrEvent, account: Account) {