From c77d725864de5908bc0ad9ce98ec8be29311838a Mon Sep 17 00:00:00 2001
From: Tom Smeding <tom.smeding@gmail.com>
Date: Wed, 20 Nov 2019 15:01:33 +0100
Subject: Bcrypt -> Scrypt

The bcrypt module doesn't support the newest Node, so let's use the
built-in routines!
---
 modules/todo/todo.js | 35 ++++++++++++++++++++++++++++++-----
 1 file changed, 30 insertions(+), 5 deletions(-)

(limited to 'modules/todo')

diff --git a/modules/todo/todo.js b/modules/todo/todo.js
index 8fabc63..7f45263 100644
--- a/modules/todo/todo.js
+++ b/modules/todo/todo.js
@@ -2,12 +2,10 @@
 
 var cmn=require("../$common.js"),
     persist=require("node-persist"),
-    bcrypt=require("bcrypt"),
+    crypto=require("crypto"),
     basicAuth=require("basic-auth"),
     fs=require("fs");
 
-var bcryptHashRounds=10;
-
 var moddir=null;
 
 persist=persist.create({
@@ -63,6 +61,33 @@ function shiftDate(date,repweeks){
 	return new Date(Y,M,D+7*repweeks,h,m,s,ms);
 }
 
+function scryptHash(password,cb){
+	crypto.randomBytes(16,function(err,salt){
+		if(err){
+			cb(err,null);
+			return;
+		}
+		crypto.scrypt(password,salt,32,function(err,key){
+			if(err)cb(err,null);
+			else cb(null,salt.toString("hex")+"$"+key.toString("hex"));
+		});
+	});
+}
+
+function scryptCompare(password,hash,cb){
+	hash=hash.split("$");
+	if(hash.length!=2){
+		cb(new Error("Invalid hash in database"),null);
+		return;
+	}
+	var salt=Buffer.from(hash[0],"hex"),shash=hash[1];
+	crypto.scrypt(password,salt,32,function(err,key){
+		if(err)cb(err,null);
+		else if(key.toString("hex")==shash)cb(null,true);
+		else cb(null,false);
+	});
+}
+
 
 function sendUnauth(res){
 	res.set("WWW-Authenticate","Basic realm=Authorization required");
@@ -82,7 +107,7 @@ function authMiddleware(req,res,next){
 	}
 	req.authuser=user.name;
 	if(accounts[req.authuser]){
-		bcrypt.compare(user.pass,accounts[req.authuser],function(err,ok){
+		scryptCompare(user.pass,accounts[req.authuser],function(err,ok){
 			if(ok)next();
 			else sendUnauth(res);
 		});
@@ -130,7 +155,7 @@ module.exports=function(app,io,_moddir){
 			res.status(500).send("Too many accounts created, please contact Tom...");
 			return;
 		}
-		bcrypt.hash(user.pass,bcryptHashRounds,function(err,hash){
+		scryptHash(user.pass,function(err,hash){
 			if(!hash){
 				res.status(500).send("Something went wrong...");
 				console.log(err);
-- 
cgit v1.2.3-70-g09d2