@withstudiocms/auth-kit
Version:
Utilities for managing authentication
54 lines (53 loc) • 1.61 kB
JavaScript
import { randomBytes } from "node:crypto";
import { Effect } from "@withstudiocms/effect";
import {
breakSecurePassword,
buildSecurePassword,
checkPwnedDB,
constantTimeEqual,
PASS_GEN1_0_PREFIX,
verifyPasswordLength,
verifySafe
} from "../utils/password.js";
const Password = (Scrypt) => Effect.gen(function* () {
const scrypt = yield* Scrypt;
const hashPassword = Effect.fn("@withstudiocms/AuthKit/modules/password.hashPassword")(
function* (password, _salt) {
const salt = _salt || randomBytes(16).toString("hex");
const hash = yield* scrypt.run(password + salt);
return yield* buildSecurePassword({
generation: PASS_GEN1_0_PREFIX,
salt,
hash: hash.toString("hex")
});
}
);
const verifyPasswordHash = Effect.fn(
"@withstudiocms/AuthKit/modules/password.verifyPasswordHash"
)(function* (hash, password) {
const { salt } = yield* breakSecurePassword(hash);
const newHash = yield* hashPassword(password, salt);
return constantTimeEqual(hash, newHash);
});
const verifyPasswordStrength = Effect.fn(
"@withstudiocms/AuthKit/modules/password.verifyPasswordStrength"
)(function* (pass) {
const [lengthCheck, unsafeCheck, pwnedCheck] = yield* Effect.all([
verifyPasswordLength(pass),
verifySafe(pass),
checkPwnedDB(pass)
]);
if (lengthCheck) return lengthCheck;
if (unsafeCheck) return unsafeCheck;
if (pwnedCheck) return pwnedCheck;
return true;
});
return {
hashPassword,
verifyPasswordHash,
verifyPasswordStrength
};
});
export {
Password
};