import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';

/** Hashes a password into the `scrypt$salt$hex` format (matches the seed). */
export function hashPassword(plain: string): string {
  const salt = randomBytes(16).toString('hex');
  const hash = scryptSync(plain, salt, 64).toString('hex');
  return `scrypt$${salt}$${hash}`;
}

/** Verifies a password against the `scrypt$salt$hex` format used by the seed. */
export function verifyPassword(plain: string, stored: string): boolean {
  const [scheme, salt, hash] = stored.split('$');
  if (scheme !== 'scrypt' || !salt || !hash) return false;
  const expected = Buffer.from(hash, 'hex');
  const actual = scryptSync(plain, salt, expected.length);
  return expected.length === actual.length && timingSafeEqual(expected, actual);
}
