Hashing
Hash hashes passwords and other secrets one way, and checks a value against a hash. It has three drivers:
| Driver | Package | Notes |
|---|---|---|
scrypt (default) | none, built into Node.js | N = 2^17, r = 8, p = 1 (OWASP) |
bcrypt | bcrypt (native) or bcryptjs | 12 rounds. Values over 72 bytes are refused |
argon2 | argon2 | argon2id, 19 MiB, 2 iterations, 1 lane (OWASP) |
scrypt needs no install, so it's the default. For the others, install the package; without it, Hash throws [Megh] argon2 is not installed. Run: npm install argon2.
npm i argon2 # argon2
npm i bcrypt # bcrypt, native
npm i bcryptjs # bcrypt, pure JavaScriptWith both bcrypt and bcryptjs installed, Megh uses bcrypt.
Hashing and checking
Inject Hash like any service:
import { AppService, Hash } from '@meghjs/core';
@AppService
export class AccountService {
constructor(private readonly hash: Hash) {}
async register(email: string, password: string) {
return User.create({ email, password: await this.hash.make(password) });
}
async signIn(email: string, password: string) {
const user = await User.findBy('email', email);
if (!user || !(await this.hash.check(password, user.password))) {
throw new UnauthorizedException('Invalid email or password.');
}
return user;
}
}Outside a class, call the same methods on Hash itself, or on the hash helper:
import { Hash, hash } from '@meghjs/core';
const hashed = await Hash.make('secret');
await hash.check('secret', hashed); // truemake(value, options?)hashesvaluewith the default driver and a new random salt, so the same value gives a different hash each time.check(value, hashed)returnstruewhen they match. It reads the algorithm from the hash, so it checks scrypt, bcrypt and argon2 hashes whatever the default driver is. A wrong value, an empty or malformed hash, or one Megh doesn't know returnsfalse. It only throws when the hash needs a package that isn't installed.needsRehash(hashed, options?)returnstruewhenhashedwas made by another driver or with other settings than the current ones.driver(name)gives one driver with its configured settings:hash.driver('bcrypt').make(value).
Comparisons run in constant time. Megh never logs the values it hashes.
Settings
Pick the driver and its settings with app.useHashing():
app.useHashing({
driver: 'argon2',
argon2: { memoryCost: 19456, timeCost: 2, parallelism: 1 },
});Or with an @AppConfig class, the same way as other use* settings:
import { AppConfig, MeghConfig, type HashingConfig } from '@meghjs/core';
@AppConfig
export class HashingSettings extends MeghConfig<HashingConfig> {
config(): HashingConfig {
return { driver: 'bcrypt', bcrypt: { rounds: 12 } };
}
}app.useHashing(HashingSettings);| Setting | Default | |
|---|---|---|
driver | scrypt | scrypt, bcrypt or argon2 |
scrypt.cost | 131072 | N, a power of two |
scrypt.blockSize | 8 | r |
scrypt.parallelization | 1 | p |
scrypt.saltLength | 16 | Bytes, at least 16 |
scrypt.keyLength | 64 | Bytes |
bcrypt.rounds | 12 | 4 to 31; each step doubles the time |
argon2.memoryCost | 19456 | KiB |
argon2.timeCost | 2 | Iterations |
argon2.parallelism | 1 | Lanes |
An unknown driver or an invalid setting throws when useHashing() runs. Without useHashing(), Hash uses scrypt with the defaults.
scrypt hashes look like scrypt$<N>$<r>$<p>$<salt>$<hash> (base64). bcrypt and argon2 hashes use their usual formats ($2b$12$..., $argon2id$v=19$...).
bcrypt and long passwords
bcrypt only reads the first 72 bytes of a value. Instead of hashing a cut-off value, make() throws a HashingError for anything longer (and for values containing a NUL character). Bytes, not characters: é is two bytes. Limit password length in your DTO, or use argon2 or scrypt.
Upgrading old hashes
When you change the driver or raise the cost, existing hashes keep working, because check() reads the algorithm from each hash. Rehash a user's password the next time they sign in:
if (await this.hash.check(password, user.password)) {
if (this.hash.needsRehash(user.password)) {
user.password = await this.hash.make(password);
await user.save();
}
}megh scaffold:auth writes this into AuthService.login(). Hashes from earlier versions of scaffold:auth (scrypt$<salt hex>$<hash hex>) still check, and needsRehash() returns true for them.
Tests
Hashing is slow on purpose. In tests, make it cheap:
import { Hash } from '@meghjs/core';
beforeAll(() =>
Hash.configure({
scrypt: { cost: 1024 },
bcrypt: { rounds: 4 },
argon2: { memoryCost: 1024, timeCost: 1 },
}),
);
afterAll(() => Hash.reset());Hash.configure() takes the same options as useHashing(), and Hash.reset() goes back to scrypt with the defaults. Don't use these settings outside tests.
From the command line
megh make:hash prints a hash, for example for a seeder, or checks a value against one:
megh make:hash < password.txt
megh make:hash --bcrypt --rounds 10 < password.txt
megh make:hash --verify '$2b$12$...' < password.txt # prints match or no matchSee CLI: Hashing a value.