auth-vir
Version:
Auth made easy and secure via JWT cookies, CSRF tokens, and password hashing helpers.
51 lines (50 loc) • 1.42 kB
JavaScript
import { mergeDefinedProperties, } from '@augment-vir/common';
import { argon2id, argon2Verify } from 'hash-wasm';
/**
* Default value for {@link HashPasswordOptions}.
*
* @category Internal
*/
export const defaultHashOptions = {
hashLength: 32,
iterations: 256,
memorySize: 512,
parallelism: 1,
};
/**
* Hashes a password using the Argon2id algorithm so passwords don't need to be stored in plain
* text. The output of this function is safe to store in a database for future credential
* comparisons.
*
* @category Auth : Host
* @returns The hashed password.
* @see https://en.wikipedia.org/wiki/Argon2
*/
export async function hashPassword(password, options = {}) {
const salt = globalThis.crypto.getRandomValues(new Uint8Array(16));
return await argon2id(mergeDefinedProperties(defaultHashOptions, options, {
outputType: 'encoded',
password: password.normalize(),
salt,
}));
}
/**
* A utility that provides more accurate string byte size than doing `string.length`.
*
* @category Internal
*/
export function getByteLength(input) {
return new Blob([input]).size;
}
/**
* Checks if the given password is a match by comparing it to the previously computed and stored
* hash.
*
* @category Auth : Host
*/
export async function doesPasswordMatchHash({ password, hash, }) {
return await argon2Verify({
hash,
password,
});
}