import { pbkdf2Async } from "@noble/hashes/pbkdf2.js"; import { sha256 } from "@noble/hashes/sha2.js"; const prefix = "pbkdf2-sha256$600000$"; const encoder = new TextEncoder(); const base64 = (bytes) => btoa(String.fromCharCode(...bytes)); export async function hashPassword(password, salt) { const bytes = await pbkdf2Async( sha256, encoder.encode(password), encoder.encode(salt), { c: 6e5, dkLen: 32, asyncTick: 10 } ); return prefix + base64(bytes); } export async function verifyPassword(password, salt, stored) { if (stored.startsWith(prefix)) return equal(stored, await hashPassword(password, salt)); if (!/^[A-Za-z0-9+/]{43}=$/.test(stored)) return false; const key = await crypto.subtle.importKey( "raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"] ); const bytes = await crypto.subtle.deriveBits( { name: "PBKDF2", hash: "SHA-256", salt: encoder.encode(salt), iterations: 1e5 }, key, 256 ); return equal(stored, base64(new Uint8Array(bytes))); } async function equal(a, b) { const key = await crypto.subtle.importKey( "raw", encoder.encode(a), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"] ); return crypto.subtle.verify( "HMAC", key, await crypto.subtle.sign("HMAC", key, encoder.encode(a)), encoder.encode(b) ); } export const needsPasswordUpgrade = (stored) => !stored.startsWith(prefix);