Files
NodeBB/src/password.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

2014-08-12 21:41:23 -04:00
'use strict';
2019-08-30 16:16:56 -04:00
const path = require('path');
const crypto = require('crypto');
2019-08-30 16:16:56 -04:00
const util = require('util');
2014-08-12 21:41:23 -04:00
const bcrypt = require('bcryptjs');
2019-08-30 16:16:56 -04:00
const fork = require('./meta/debugFork');
2017-05-27 01:44:26 -04:00
function forkChild(message, callback) {
2019-08-30 16:16:56 -04:00
const child = fork(path.join(__dirname, 'password'));
2014-10-07 19:49:18 -04:00
2021-02-04 00:01:39 -07:00
child.on('message', (msg) => {
2018-10-31 15:10:45 -04:00
callback(msg.err ? new Error(msg.err) : null, msg.result);
2017-05-27 01:44:26 -04:00
});
child.on('error', (err) => {
console.error(err.stack);
callback(err);
});
2014-08-12 21:41:23 -04:00
2017-05-27 01:44:26 -04:00
child.send(message);
}
2018-10-31 15:10:45 -04:00
2019-08-30 16:16:56 -04:00
const forkChildAsync = util.promisify(forkChild);
exports.hash = async function (rounds, password) {
password = crypto.createHash('sha512').update(password).digest('hex');
2019-08-30 16:16:56 -04:00
return await forkChildAsync({ type: 'hash', rounds: rounds, password: password });
};
exports.compare = async function (password, hash, shaWrapped) {
2019-08-30 16:16:56 -04:00
const fakeHash = await getFakeHash();
if (shaWrapped) {
password = crypto.createHash('sha512').update(password).digest('hex');
}
2019-08-30 16:16:56 -04:00
return await forkChildAsync({ type: 'compare', password: password, hash: hash || fakeHash });
};
let fakeHashCache;
async function getFakeHash() {
if (fakeHashCache) {
return fakeHashCache;
}
fakeHashCache = await exports.hash(12, Math.random().toString());
return fakeHashCache;
}
2018-10-31 15:10:45 -04:00
// child process
2021-02-04 00:01:39 -07:00
process.on('message', (msg) => {
2018-10-31 15:10:45 -04:00
if (msg.type === 'hash') {
2019-08-30 16:16:56 -04:00
tryMethod(hashPassword, msg);
2018-10-31 15:10:45 -04:00
} else if (msg.type === 'compare') {
2019-08-30 16:16:56 -04:00
tryMethod(compare, msg);
2018-10-31 15:10:45 -04:00
}
});
2019-08-30 16:16:56 -04:00
async function tryMethod(method, msg) {
try {
const result = await method(msg);
process.send({ result: result });
} catch (err) {
process.send({ err: err.message });
} finally {
process.disconnect();
}
2018-10-31 15:10:45 -04:00
}
2019-08-30 16:16:56 -04:00
async function hashPassword(msg) {
const salt = await bcrypt.genSalt(parseInt(msg.rounds, 10));
const hash = await bcrypt.hash(msg.password, salt);
return hash;
2018-10-31 15:10:45 -04:00
}
2019-07-16 14:17:10 -04:00
2019-08-30 16:16:56 -04:00
async function compare(msg) {
return await bcrypt.compare(String(msg.password || ''), String(msg.hash || ''));
}
2019-07-16 14:17:10 -04:00
require('./promisify')(exports);