aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/walletEntropy.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/walletEntropy.ts')
-rw-r--r--src/lib/walletEntropy.ts67
1 files changed, 67 insertions, 0 deletions
diff --git a/src/lib/walletEntropy.ts b/src/lib/walletEntropy.ts
new file mode 100644
index 00000000..f022a2cc
--- /dev/null
+++ b/src/lib/walletEntropy.ts
@@ -0,0 +1,67 @@
+import { browser } from "$app/environment";
+import { getCachedPrfKey, rememberPrfKey, defaultRememberForMs } from "$lib/passwordCache";
+
+const DERIVATION_EVENT = {
+ kind: 1,
+ created_at: 0,
+ content: "coinos-wallet-key-derivation",
+ tags: [],
+};
+
+async function hashSignature(sig: string): Promise<ArrayBuffer> {
+ const sigBytes = new Uint8Array(sig.length / 2);
+ for (let i = 0; i < sig.length; i += 2)
+ sigBytes[i / 2] = parseInt(sig.slice(i, i + 2), 16);
+ return crypto.subtle.digest("SHA-256", sigBytes);
+}
+
+/**
+ * Silent helper. Checks localStorage for nsec, signs fixed event locally,
+ * caches and returns entropy. Returns null if no nsec stored.
+ */
+export async function tryDeriveFromNsec(): Promise<ArrayBuffer | null> {
+ if (!browser) return null;
+ const nsec = localStorage.getItem("nsec");
+ if (!nsec) return null;
+
+ try {
+ const { nip19, finalizeEvent } = await import("nostr-tools");
+ const sk = nip19.decode(nsec).data as Uint8Array;
+ const signed = finalizeEvent({ ...DERIVATION_EVENT } as any, sk);
+ const entropy = await hashSignature(signed.sig);
+ rememberPrfKey(entropy, defaultRememberForMs);
+ return entropy;
+ } catch (e) {
+ console.log("nsec entropy derivation failed", e);
+ return null;
+ }
+}
+
+/**
+ * Non-interactive. Checks cached prfKey, then tries silent nsec derivation.
+ * Returns null if neither available. Use in onMount and auto-provisioning.
+ */
+export async function getWalletEntropy(): Promise<ArrayBuffer | null> {
+ const cached = getCachedPrfKey();
+ if (cached) return cached;
+ return tryDeriveFromNsec();
+}
+
+/**
+ * Interactive. Tries silent nsec first, then calls sign() from $lib/nostr
+ * which shows Nostr.svelte modal if signer isn't ready. Caches result.
+ * Use for "Unlock" buttons.
+ */
+export async function deriveNostrEntropy(): Promise<ArrayBuffer> {
+ const cached = getCachedPrfKey();
+ if (cached) return cached;
+
+ const fromNsec = await tryDeriveFromNsec();
+ if (fromNsec) return fromNsec;
+
+ const { sign } = await import("$lib/nostr");
+ const signed = await sign({ ...DERIVATION_EVENT });
+ const entropy = await hashSignature(signed.sig);
+ rememberPrfKey(entropy, defaultRememberForMs);
+ return entropy;
+}