Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132import { createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
export interface RandomSource { (size: number): Uint8Array; }export const secureRandom: RandomSource = (size) => randomBytes(size);
export function hashOpaque(value: string): string { return createHash('sha256').update(value, 'utf8').digest('hex');}
/** Password-like credentials are never persisted in plaintext. */export function hashCredential(value: string, random: RandomSource = secureRandom): string { if (!value) throw new Error('credential must not be empty'); const salt = Buffer.from(random(16)); const digest = scryptSync(value, salt, 32, { N: 16_384, r: 8, p: 1 }); return `scrypt$${salt.toString('base64url')}$${digest.toString('base64url')}`;}
export function verifyCredential(value: string, encoded: string): boolean { try { const [algorithm, saltText, digestText] = encoded.split('$'); if (algorithm !== 'scrypt' || !saltText || !digestText) return false; const expected = Buffer.from(digestText, 'base64url'); const actual = scryptSync(value, Buffer.from(saltText, 'base64url'), expected.length, { N: 16_384, r: 8, p: 1 }); return expected.length === actual.length && timingSafeEqual(expected, actual); } catch { return false; }}
export function constantTimeEqual(left: string, right: string): boolean { const a = Buffer.from(left); const b = Buffer.from(right); return a.length === b.length && timingSafeEqual(a, b);}