Sven Slootweg 5 years ago
parent
commit
af0d0ae973
7 changed files with 327 additions and 0 deletions
  1. 137 0
      README.md
  2. 1 0
      index.coffee
  3. 1 0
      index.js
  4. 46 0
      lib/scrypt-for-humans.coffee
  5. 89 0
      lib/scrypt-for-humans.js
  6. 2 0
      package.json
  7. 51 0
      test.js

+ 137 - 0
README.md

@ -0,0 +1,137 @@
1
# scrypt-for-humans
2
3
A human-friendly API wrapper for the Node.js Scrypt bindings, because the default bindings kind of suck.
4
5
This module will change and do the following things for you:
6
7
* Input values (passwords, usually) are expected in utf-8.
8
* Output/hash values are base64-encoded, and can be stored directly in your data store of choice.
9
* Scrypt parameters are set to `scrypt.params(0.1)`, this can be overridden on a per-hash basis (see API documentation below).
10
* Scrypt errors, which are not proper Error types in the original library, are caught and rethrown as one of three correctly-inheriting Error types (see API documentation below). This means you can handle them like any other kind of Error.
11
12
The API supports both Promises and nodebacks.
13
14
## License
15
16
[WTFPL](http://www.wtfpl.net/txt/copying/) or [CC0](https://creativecommons.org/publicdomain/zero/1.0/), whichever you prefer.
17
18
## Donate
19
20
My income consists entirely of donations for my projects. If this module is useful to you, consider [making a donation](http://cryto.net/~joepie91/donate.html)!
21
22
You can donate using Bitcoin, PayPal, Gratipay, Flattr, cash-in-mail, SEPA transfers, and pretty much anything else.
23
24
## Contributing
25
26
Pull requests welcome. Please make sure your modifications are in line with the overall code style, and ensure that you're editing the `.coffee` files, not the `.js` files.
27
28
As this module could potentially deal with authentication, tests are needed; a pull request for those would be especially welcome.
29
30
Build tool of choice is `gulp`; simply run `gulp` while developing, and it will watch for changes.
31
32
## Usage
33
34
```javascript
35
scrypt = require("scrypt-for-humans");
36
Promise = require("bluebird");
37
38
/* Using Promises */
39
40
var theHash;
41
42
Promise.try(function(){
43
	return scrypt.hash("secretpassword");
44
}).then(function(hash){
45
	console.log("The hash is " + hash);
46
	theHash = hash;
47
48
	/* Now let's see if it verifies - number 1 is correct. */
49
	return scrypt.verifyHash("secretpassword", theHash);
50
}).then(function(){
51
	console.log("Number 1 was correct!");
52
}).catch(scrypt.PasswordError, function(err){
53
	console.log("Number 1 was wrong!");
54
}).then(function(){
55
	/* And let's see if it fails correctly - number 2 is wrong. */
56
	return scrypt.verifyHash("wrongpassword", theHash);
57
}).then(function(){
58
	console.log("Number 2 was correct!");
59
}).catch(scrypt.PasswordError, function(err){
60
	console.log("Number 2 was wrong!");
61
});
62
63
/* Using nodebacks */
64
65
scrypt.hash("secretpassword", {}, function(err, hash){
66
	console.log("The hash is " + hash);
67
68
	/* Now let's see if it verifies - number 1 is correct. */
69
	scrypt.verifyHash("secretpassword", hash, function(err, result){
70
		if(err) {
71
			console.log("Number 1 was wrong!", err);
72
		} else {
73
			console.log("Number 1 was correct!");
74
		}
75
76
		/* And let's see if it fails correctly - number 2 is wrong. */
77
		scrypt.verifyHash("wrongpassword", hash, function(err, result){
78
			if(err) {
79
				console.log("Number 2 was wrong!", err);
80
			} else {
81
				console.log("Number 2 was correct!");
82
			}
83
		});
84
	});
85
});
86
```
87
88
## API
89
90
### scrypt.hash(input, [options, [callback]])
91
92
Creates a hash.
93
94
* __input__: The input to hash, usually a password.
95
* __options__: *Optional.* Custom options.
96
	* __options.params__: Sets the Scrypt parameters to use. Defaults to `scrypt.params(0.1)`. If you want to change these, you'll probably need scrypt.scryptLib (documented below).
97
* __callback__: *Optional.* A nodeback to call upon completion. If omitted, the function will return a Promise.
98
99
If this is successful, the hash is returned as either the resolved Promise value or the second callback parameter, depending on the API you use.
100
101
If an error occurs, either the Promise will reject with it, or it will be passed as the first callback parameter, depending on the API you use. All errors correctly inherit from `Error`, and are documented below.
102
103
### scrypt.verifyHash(input, hash, [callback])
104
105
Creates a hash.
106
107
* __input__: The input to hash, usually a password.
108
* __hash__: The hash to verify against, in base64 encoding (the default output format of `scrypt.hash`).
109
* __callback__: *Optional.* A nodeback to call upon completion. If omitted, the function will return a Promise.
110
111
If the input is correct and matches the hash, the Promise will resolve or the callback will be called with `true` as the value.
112
113
__If the input does *not* match the hash, this is considered a PasswordError, *not* a `false` value!__
114
115
If an error occurs, either the Promise will reject with it, or it will be passed as the first callback parameter, depending on the API you use. All errors correctly inherit from `Error`, and are documented below.
116
117
### scrypt.PasswordError
118
119
This error is thrown if the input did not match the specified hash. The original error message is retained.
120
121
### scrypt.InputError
122
123
This error is thrown if there is a different problem with the input (either the to-be-hashed value, or the hash), such as a malformed hash. The original error message is retained.
124
125
### scrypt.OperationalError
126
127
This error is thrown when an internal error of some other kind occurs in the `scrypt` library. The original error message is retained.
128
129
### scrypt.scryptLib
130
131
Provides access to the underlying `scrypt` library that is used. Useful if you want to eg. specify custom Scrypt parameters.
132
133
## Changelog
134
135
### v1.0.0
136
137
Initial release.

+ 1 - 0
index.coffee

@ -0,0 +1 @@
1
module.exports = require "./lib/scrypt-for-humans"

+ 1 - 0
index.js

@ -0,0 +1 @@
1
module.exports = require("./lib/scrypt-for-humans");

+ 46 - 0
lib/scrypt-for-humans.coffee

@ -0,0 +1,46 @@
1
scrypt = require "scrypt"
2
errors = require "errors"
3
Promise = require "bluebird"
4
5
# Scrypt input/output format configuration
6
# FIXME: Figure out how to isolate this, so that there is a guarantee these changes won't affect any other `scrypt` imports outside of the module.
7
scrypt.hash.config.keyEncoding = "utf8"
8
scrypt.hash.config.outputEncoding = "base64"
9
scrypt.verify.config.keyEncoding = "utf8"
10
scrypt.verify.config.hashEncoding = "base64"
11
12
# Some custom error types, since the `scrypt` library doesn't have proper error handling
13
errors.create name: "ScryptError"
14
errors.create {name: "ScryptInputError", parents: errors.ScryptError}
15
errors.create {name: "ScryptPasswordError", parents: errors.ScryptError}
16
errors.create {name: "ScryptInternalError", parents: errors.ScryptError}
17
18
19
scryptHandler = (resolve, reject) ->
20
	# This is ridiculous, but `scrypt` doesn't have proper error-handling facilities...
21
	return (err, result) ->
22
		if err?
23
			errorObj = switch err.scrypt_err_code
24
				when 1, 2, 3, 4, 5, 6, 9, 10, 12, 13 then errors.ScryptInternalError
25
				when 7, 8 then errors.ScryptInputError
26
				when 11 then errors.ScryptPasswordError
27
			reject new errorObj(err.scrypt_err_message)
28
		else
29
			resolve result
30
31
32
module.exports =
33
	hash: (password, options = {}, callback) ->
34
		(new Promise (resolve, reject) ->
35
			options.params ?= scrypt.params(0.1)
36
			scrypt.hash password, options.params, scryptHandler(resolve, reject)
37
		).nodeify(callback)
38
	verifyHash: (password, hash, callback) ->
39
		(new Promise (resolve, reject) ->
40
			scrypt.verify hash, password, scryptHandler(resolve, reject)
41
		).nodeify(callback)
42
	ScryptError: errors.ScryptError
43
	InputError: errors.ScryptInputError
44
	PasswordError: errors.ScryptPasswordError
45
	InternalError: errors.ScryptInternalError
46
	scryptLib: scrypt

+ 89 - 0
lib/scrypt-for-humans.js

@ -0,0 +1,89 @@
1
var Promise, errors, scrypt, scryptHandler;
2
3
scrypt = require("scrypt");
4
5
errors = require("errors");
6
7
Promise = require("bluebird");
8
9
scrypt.hash.config.keyEncoding = "utf8";
10
11
scrypt.hash.config.outputEncoding = "base64";
12
13
scrypt.verify.config.keyEncoding = "utf8";
14
15
scrypt.verify.config.hashEncoding = "base64";
16
17
errors.create({
18
  name: "ScryptError"
19
});
20
21
errors.create({
22
  name: "ScryptInputError",
23
  parents: errors.ScryptError
24
});
25
26
errors.create({
27
  name: "ScryptPasswordError",
28
  parents: errors.ScryptError
29
});
30
31
errors.create({
32
  name: "ScryptInternalError",
33
  parents: errors.ScryptError
34
});
35
36
scryptHandler = function(resolve, reject) {
37
  return function(err, result) {
38
    var errorObj;
39
    if (err != null) {
40
      errorObj = (function() {
41
        switch (err.scrypt_err_code) {
42
          case 1:
43
          case 2:
44
          case 3:
45
          case 4:
46
          case 5:
47
          case 6:
48
          case 9:
49
          case 10:
50
          case 12:
51
          case 13:
52
            return errors.ScryptInternalError;
53
          case 7:
54
          case 8:
55
            return errors.ScryptInputError;
56
          case 11:
57
            return errors.ScryptPasswordError;
58
        }
59
      })();
60
      return reject(new errorObj(err.scrypt_err_message));
61
    } else {
62
      return resolve(result);
63
    }
64
  };
65
};
66
67
module.exports = {
68
  hash: function(password, options, callback) {
69
    if (options == null) {
70
      options = {};
71
    }
72
    return (new Promise(function(resolve, reject) {
73
      if (options.params == null) {
74
        options.params = scrypt.params(0.1);
75
      }
76
      return scrypt.hash(password, options.params, scryptHandler(resolve, reject));
77
    })).nodeify(callback);
78
  },
79
  verifyHash: function(password, hash, callback) {
80
    return (new Promise(function(resolve, reject) {
81
      return scrypt.verify(hash, password, scryptHandler(resolve, reject));
82
    })).nodeify(callback);
83
  },
84
  ScryptError: errors.ScryptError,
85
  InputError: errors.ScryptInputError,
86
  PasswordError: errors.ScryptPasswordError,
87
  InternalError: errors.ScryptInternalError,
88
  scryptLib: scrypt
89
};

+ 2 - 0
package.json

@ -29,6 +29,8 @@
29 29
    "gulp-util": "~2.2.17"
30 30
  },
31 31
  "dependencies": {
32
    "bluebird": "^2.6.4",
33
    "errors": "^0.2.0",
32 34
    "scrypt": "^3.0.1"
33 35
  }
34 36
}

+ 51 - 0
test.js

@ -0,0 +1,51 @@
1
scrypt = require("./");
2
Promise = require("bluebird");
3
4
/* Using Promises */
5
6
var theHash;
7
8
Promise.try(function(){
9
	return scrypt.hash("secretpassword");
10
}).then(function(hash){
11
	console.log("The hash is " + hash);
12
	theHash = hash;
13
14
	/* Now let's see if it verifies - number 1 is correct. */
15
	return scrypt.verifyHash("secretpassword", theHash);
16
}).then(function(){
17
	console.log("Number 1 was correct!");
18
}).catch(scrypt.PasswordError, function(err){
19
	console.log("Number 1 was wrong!");
20
}).then(function(){
21
	/* And let's see if it fails correctly - number 2 is wrong. */
22
	return scrypt.verifyHash("wrongpassword", theHash);
23
}).then(function(){
24
	console.log("Number 2 was correct!");
25
}).catch(scrypt.PasswordError, function(err){
26
	console.log("Number 2 was wrong!");
27
});
28
29
/* Using nodebacks */
30
31
scrypt.hash("secretpassword", {}, function(err, hash){
32
	console.log("The hash is " + hash);
33
34
	/* Now let's see if it verifies - number 1 is correct. */
35
	scrypt.verifyHash("secretpassword", hash, function(err, result){
36
		if(err) {
37
			console.log("Number 1 was wrong!", err);
38
		} else {
39
			console.log("Number 1 was correct!");
40
		}
41
42
		/* And let's see if it fails correctly - number 2 is wrong. */
43
		scrypt.verifyHash("wrongpassword", hash, function(err, result){
44
			if(err) {
45
				console.log("Number 2 was wrong!", err);
46
			} else {
47
				console.log("Number 2 was correct!");
48
			}
49
		});
50
	});
51
});