UNPKG

2.04 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3"use strict";
4
5const yargs = require("yargs");
6// TESTABILITY: makes yargs throws instead of exiting.
7yargs.fail(function(msg) {
8 let help = yargs.help();
9
10 if (msg) {
11 help += "\n" + msg;
12 }
13
14 throw help;
15});
16
17// --------------------------------------------------------------------
18
19const hashy = require("./");
20
21// ====================================================================
22
23function main(argv) {
24 const options = yargs
25 .usage("Usage: hashy [<option>...]")
26 .example("hashy [ -a <algorithm> ] <secret>", "hash the secret")
27 .example("hashy <secret> <hash>", "verify the secret using the hash")
28 .options({
29 a: {
30 default: hashy.DEFAULT_ALGO,
31 describe: "algorithm to use for hashing",
32 },
33 h: {
34 alias: "help",
35 boolean: true,
36 describe: "display this help message",
37 },
38 v: {
39 alias: "version",
40 boolean: true,
41 describe: "display the version number",
42 },
43 c: {
44 alias: "cost",
45 describe: "cost for Bcrypt",
46 },
47 })
48 .parse(argv);
49
50 if (options.help) {
51 return yargs.help();
52 }
53
54 if (options.version) {
55 const pkg = require("./package");
56 return "Hashy version " + pkg.version;
57 }
58
59 if (options.cost) {
60 hashy.options.bcrypt.cost = +options.cost;
61 }
62
63 const args = options._;
64
65 if (args.length === 1) {
66 return hashy.hash(args[0], options.a).then(console.log);
67 }
68
69 if (args.length === 2) {
70 const password = args[0];
71 const hash = args[1];
72
73 return hashy.verify(password, hash).then(function(success) {
74 if (success) {
75 if (hashy.needsRehash(hash, options.a)) {
76 return "ok but password should be rehashed";
77 }
78
79 return "ok";
80 }
81
82 throw new Error("not ok");
83 });
84 }
85
86 throw new Error("incorrect number of arguments");
87}
88exports = module.exports = main;
89
90// ====================================================================
91
92if (!module.parent) {
93 require("exec-promise")(main);
94}