All files / lib/encryption encryption.lib.ts

80.95% Statements 17/21
33.33% Branches 2/6
75% Functions 6/8
82.35% Lines 14/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 382x 2x 2x 2x                     2x   2x 2x     3x 3x     3x 3x     3x     3x     2x      
import bcrypt from "bcrypt";
import crypto from "crypto";
import uniqid from "uniqid";
import base64 from "urlsafe-base64";
 
// Please change depends on your application security level
// rounds=8 : ~40 hashes/sec
// rounds=9 : ~20 hashes/sec
// rounds=10: ~10 hashes/sec
// rounds=11: ~5  hashes/sec
// rounds=12: 2-3 hashes/sec
// rounds=13: ~1 sec/hash
// rounds=14: ~1.5 sec/hash
// rounds=15: ~3 sec/hash
const BCRYPT_ROUND = 10;
 
export const hashPassword = async (password: string): Promise<string> => {
  return bcrypt.hash(password, BCRYPT_ROUND);
};
 
export const comparePassword = async (password: string, hash: string): Promise<boolean> => {
  return bcrypt.compare(password, hash);
};
 
export const uniqueString = async (bytes = 32): Promise<string> => {
  Iif (bytes - 18 < 0) {
    throw new Error("not enough bytes to ensure uniqueness");
  }
  Iif (bytes === 18) {
    return uniqid();
  }
  return base64.encode(crypto.randomBytes(bytes - 18)) + uniqid();
};
 
export const randomString = async (bytes = 32): Promise<string> => {
  return base64.encode(crypto.randomBytes(bytes));
};