const jwt = require('jsonwebtoken'); const argon2 = require('@node-rs/argon2'); // Only for checking passwords saved before 2.0 (they're re-hashed with Argon2id at the next sign-in). const bcrypt = require('bcryptjs'); // `extra` adds claims, e.g. { setup: true } for the first-run setup wizard's token. const generateToken = (userId, role, tokenVersion = 0, extra = {}) => { return jwt.sign( { ...extra, id: userId, role, tokenVersion }, process.env.JWT_SECRET, { expiresIn: '30d' } ); }; // Argon2id with OWASP's recommended minimum (19 MiB, 2 passes, 1 lane): about 20–40 ms a hash. const ARGON2 = { algorithm: 2 /* Argon2id (a const enum in the typings, so not on the module) */, memoryCost: 19456, timeCost: 2, parallelism: 1 }; const ARGON2_PREFIX = `$argon2id$v=19$m=${ARGON2.memoryCost},t=${ARGON2.timeCost},p=${ARGON2.parallelism}$`; const hashPassword = async (password) => argon2.hash(password, ARGON2); /** Whether `entered` is the password behind `stored` (an Argon2 hash, or a bcrypt one from before 2.0). */ const comparePassword = async (enteredPassword, storedPassword) => { if (typeof enteredPassword !== 'string' || typeof storedPassword !== 'string') return false; try { if (storedPassword.startsWith('$argon2')) return await argon2.verify(storedPassword, enteredPassword); if (/^\$2[aby]\$/.test(storedPassword)) return await bcrypt.compare(enteredPassword, storedPassword); } catch { // A malformed hash never matches. } return false; }; /** True for a hash that isn't Argon2id with today's settings (bcrypt, or weaker Argon2). */ const needsRehash = (storedPassword) => typeof storedPassword === 'string' && !storedPassword.startsWith(ARGON2_PREFIX); module.exports = { generateToken, hashPassword, comparePassword, needsRehash, };