import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' import { promisify } from 'node:util' /** * 密码哈希/校验(scrypt,盐 + 哈希以冒号分隔存储)。 * 独立于 Nuxt/Nitro 依赖,便于单元测试。 */ const scryptAsync = promisify(scrypt) as ( password: string, salt: string, keylen: number, ) => Promise export async function hashPassword(password: string): Promise { const salt = randomBytes(16).toString('hex') const key = await scryptAsync(password, salt, 64) return `${salt}:${key.toString('hex')}` } export async function verifyPassword(password: string, stored: string): Promise { const [salt, hash] = stored.split(':') if (!salt || !hash) return false const key = await scryptAsync(password, salt, 64) const expected = Buffer.from(hash, 'hex') return key.length === expected.length && timingSafeEqual(key, expected) }