aboutsummaryrefslogtreecommitdiffstats
path: root/src/helpers/password-helpers.ts
blob: a628ea51ee6941f65b1dad2cdb96756d55faf018 (plain) (blame)
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
import { type BinaryLike, createHash } from 'node:crypto';

export function hash(password: BinaryLike): string {
  return createHash('sha256').update(password).digest('base64');
}

export function scorePassword(password: string): number {
  let score = 0;
  if (!password) {
    return score;
  }

  // award every unique letter until 5 repetitions
  const letters = {};
  for (const letter of password) {
    letters[letter] = (letters[letter] || 0) + 1;
    score += 5 / letters[letter];
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(password),
    lower: /[a-z]/.test(password),
    upper: /[A-Z]/.test(password),
    nonWords: /\W/.test(password),
  };

  let variationCount = 0;
  for (const key of Object.keys(variations)) {
    variationCount += variations[key] === true ? 1 : 0;
  }

  score += (variationCount - 1) * 10;

  return Number.parseInt(score.toString(), 10);
}