authenticator.test.js
1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Created by lintry on 2017/5/19.
*/
const TOTP = require('../lib/totp');
const chalk = require('chalk');
const fs = require('fs-extra');
const path = require('path');
//使用外部生成的密钥
// let secret = 'vH6OdbUEjSukTqlDvW3TYdusjiOIkxRnAHNTjJewfZa5yNueG9wx1N9pJMFOmPAV';
let secret = 'acnahbfX3bKa+EuhD7sR+MToc8d5rZ8Db7xh68ZUnBX3SPfhlHS/GeJ7SKEfcLTI';
let authenticator = new TOTP({algorithm: 'sha1'}).parse(secret);
console.log(chalk.cyan('totp的secret'));
console.log(secret, authenticator.totp_options);
//外部传入的token参数
let token = process.argv[2];
if (!token) {
token = authenticator.totp();
console.error(chalk.red('none token found, we generate a new token instead'), token);
return;
}
console.log(chalk.green('token is'), token);
//精确验证token
let verify = authenticator.verify(token);
console.log(chalk.magenta('verify is '), (verify ? chalk.green : chalk.red)(verify));
//允许误差验证token
console.log(chalk.blue('verifyDelta is '), authenticator.verifyDelta(token, 2));
//生成密钥二维码图片
let img_path = path.resolve(process.cwd(), 'img');
let qr = path.resolve(img_path, 'qr.svg');
fs.ensureDir(img_path, function (err, added_root) {
if (err) {
return console.error(chalk.red('create folder error'), chalk.red(JSON.stringify(err, null, 4)));
}
added_root && console.log(chalk.green(img_path + ' is created'));
let fd = fs.openSync(qr, 'w');
fs.writeSync(fd, authenticator.getQR('totp@gitlab.kmlab.com', '通行密钥'));
fs.closeSync(fd);
console.log(chalk.green('密钥字符串'), chalk.yellow(authenticator.getOtpAuth('totp@gitlab.kmlab.com', '通行密钥')))
});
console.log('QR SVG output is', img_path, qr);