1- import { parse as parseCookies } from 'cookie-es'
1+ import { parse as parseCookies , serialize } from 'cookie-es'
2+ import crypto , { randomBytes } from 'crypto'
3+ import { promisify } from 'util'
24
3- function setCookie ( headers : Record < string , string > | undefined , name : string , value : string ) {
5+ const scrypt = promisify ( crypto . scrypt )
6+
7+ function setCookie (
8+ headers : Record < string , string > | undefined ,
9+ name : string ,
10+ value : string ,
11+ options : { expires ?: Date } = { expires : new Date ( Date . now ( ) + 1000 * 60 * 60 * 24 ) } // Default to 1 day expiration
12+ ) {
13+ serialize
414 if ( ! headers ) return
5- headers [ 'Set-Cookie' ] = ` ${ name } = ${ value } ; Path=/; HttpOnly; SameSite=Strict`
15+ headers [ 'Set-Cookie' ] = serialize ( name , value , options )
616}
717
8- function deleteCookie ( headers : Record < string , string > | undefined , name : string ) {
18+ function deleteCookie ( headers : Record < string , string > | undefined , name : string , expiresAt ?: Date ) {
919 if ( ! headers ) return
1020 headers [ 'Set-Cookie' ] = `${ name } =; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`
1121}
@@ -24,3 +34,16 @@ export function setSessionCookie(headers: Record<string, string> | undefined, va
2434export function deleteSessionCookie ( headers ?: Record < string , string > ) {
2535 deleteCookie ( headers , SESSION_COOKIE_NAME )
2636}
37+
38+ export async function hashPassword ( password : string ) : Promise < string > {
39+ const salt = randomBytes ( 8 ) . toString ( 'hex' )
40+ const derivedKey = await scrypt ( password , salt , 64 )
41+ return salt + ':' + ( derivedKey as Buffer ) . toString ( 'hex' )
42+ }
43+
44+ export async function verifyPassword ( password : string , hashedPassword : string ) : Promise < boolean > {
45+ const [ salt , key ] = hashedPassword . split ( ':' )
46+ const keyBuffer = Buffer . from ( key , 'hex' )
47+ const derivedKey = await scrypt ( password , salt , 64 )
48+ return crypto . timingSafeEqual ( keyBuffer , derivedKey as any )
49+ }
0 commit comments