aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/keyWrapping.ts
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-02-27 14:46:27 -0800
committerAdam Soltys <[email protected]>2026-02-27 14:46:27 -0800
commit8ffcf769052461e03a2c69220392cb37a623f3f4 (patch)
tree5b0b16269a729fbe9db44c65b3a0da3d95c11b78 /src/lib/keyWrapping.ts
parent6ba952f16fc60fc56f0834e5b1d08671885618c5 (diff)
downloadcoinos-ui-8ffcf769052461e03a2c69220392cb37a623f3f4.tar.gz
coinos-ui-8ffcf769052461e03a2c69220392cb37a623f3f4.zip
2 step register
Diffstat (limited to 'src/lib/keyWrapping.ts')
-rw-r--r--src/lib/keyWrapping.ts61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/lib/keyWrapping.ts b/src/lib/keyWrapping.ts
new file mode 100644
index 00000000..b176e741
--- /dev/null
+++ b/src/lib/keyWrapping.ts
@@ -0,0 +1,61 @@
+import { prfEncrypt, prfDecrypt } from "$lib/crypto";
+import { rememberPrfKey, defaultRememberForMs, getCachedPrfKey } from "$lib/passwordCache";
+import { post } from "$lib/utils";
+
+export function generateCanonicalKey(): ArrayBuffer {
+ return crypto.getRandomValues(new Uint8Array(32)).buffer as ArrayBuffer;
+}
+
+export async function wrapCanonicalKey(
+ wrappingKey: ArrayBuffer,
+ canonicalKey: ArrayBuffer,
+): Promise<string> {
+ return prfEncrypt(wrappingKey, new Uint8Array(canonicalKey));
+}
+
+export async function unwrapCanonicalKey(
+ wrappingKey: ArrayBuffer,
+ encrypted: string,
+): Promise<ArrayBuffer> {
+ const bytes = await prfDecrypt(wrappingKey, encrypted);
+ return bytes.buffer as ArrayBuffer;
+}
+
+export async function resolveCanonicalKey(
+ methodId: string,
+ wrappingKey: ArrayBuffer,
+ encryptedKeys: Record<string, string> | null | undefined,
+ oldPrfKey: ArrayBuffer,
+): Promise<{ canonicalKey: ArrayBuffer; encryptedKeys: Record<string, string> }> {
+ if (encryptedKeys && encryptedKeys[methodId]) {
+ const canonicalKey = await unwrapCanonicalKey(wrappingKey, encryptedKeys[methodId]);
+ rememberPrfKey(canonicalKey, defaultRememberForMs);
+ return { canonicalKey, encryptedKeys };
+ }
+
+ // Migration: old PRF key becomes canonical key
+ const canonicalKey = oldPrfKey;
+ const wrapped = await wrapCanonicalKey(wrappingKey, canonicalKey);
+ const updated = { ...(encryptedKeys || {}), [methodId]: wrapped };
+ await saveEncryptedKeys(updated);
+ rememberPrfKey(canonicalKey, defaultRememberForMs);
+ return { canonicalKey, encryptedKeys: updated };
+}
+
+export async function saveEncryptedKeys(
+ encryptedKeys: Record<string, string>,
+): Promise<void> {
+ await post("/post/user", { encryptedKeys });
+}
+
+export function passwordMethodId(): string {
+ return "password";
+}
+
+export function passkeyMethodId(credentialId: string): string {
+ return `passkey:${credentialId}`;
+}
+
+export function nostrMethodId(pubkey: string): string {
+ return `nostr:${pubkey}`;
+}