Path: blob/master/src/packages/backend/auth/password-hash.ts
1447 views
import { generate, verify } from "password-hash";1import LRU from "lru-cache";23// We cache computation of the hash, since e.g., api keys have the4// hash computed for every single api call, and it's always the same key,5// so that's expensive.6const cache = new LRU<string, string>({7max: 1000,8ttl: 1000 * 60 * 5, // 5 minutes9});1011// You can change the parameters at any time and no existing passwords12// or cookies should break. This will only impact newly created13// passwords and cookies. Old ones can be read just fine (with the old14// parameters).15const HASH_ALGORITHM = "sha512";16const HASH_ITERATIONS = 1000;17const HASH_SALT_LENGTH = 32;1819export default function passwordHash(password: string): string {20// This blocks the server for around 5ms.21// There are newer async libraries as explained at https://www.npmjs.com/package/password-hash22// that do NOT block, which maybe we should be using instead....23if (cache.has(password)) {24return cache.get(password)!;25}2627const hash = generate(password, {28algorithm: HASH_ALGORITHM,29saltLength: HASH_SALT_LENGTH,30iterations: HASH_ITERATIONS,31});32cache.set(password, hash);33return hash;34}3536export { verify as verifyPassword };373839