-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-by-otpauth.js
101 lines (79 loc) · 1.96 KB
/
server-by-otpauth.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const express = require("express");
const otpauth = require("otpauth");
const cors = require("cors");
const app = express();
app.use(express.json());
app.use(cors());
const memoryBase32ByUserId = new Map();
const TOTP_PARAMS = {
issuer: "YOUR-CRM",
issuerInLabel: true,
label: "YOUR-CRM",
digits: 6,
period: 30,
algorithm: "SHA1",
};
app.post("/generate", async (req, res) => {
const { userId } = req.body;
const secret = new otpauth.Secret({
size: 20,
});
const totp = new otpauth.TOTP({
...TOTP_PARAMS,
secret,
});
const otpauthurl = totp.toString();
memoryBase32ByUserId.set(userId, {
secret: secret.base32,
});
res.json({ qrCodeData: otpauthurl });
///
console.debug({
secret: secret.base32,
otpauthurl,
});
});
app.post("/verify", (req, res) => {
const { userId, totpCode, window: maybeWindow } = req.body;
const userTemp = memoryBase32ByUserId.get(userId);
if (!userTemp) {
return res.sendStatus(401);
}
const { secret } = userTemp;
const totp = new otpauth.TOTP({
...TOTP_PARAMS,
secret,
});
const selectedWindow = maybeWindow ?? 1;
const validateWindow = totp.validate({
token: totpCode,
window: selectedWindow,
});
const validate =
typeof validateWindow === "number"
? /** MUST USED: validateWindow !== null */
validateWindow === selectedWindow
: false;
const remainingSeconds =
totp.period - (Math.floor(Date.now() / 1000) % totp.period);
{
console.debug({
userId,
totpCode,
suitableCode: totp.generate(),
suitableCodeWithWindow: totp.generate({
timestamp: Date.now() + selectedWindow * totp.period * 1000,
}),
validateWindow,
validate,
remainingSeconds,
secret: userTemp.secret,
window: selectedWindow,
});
}
if (!validate) {
return res.sendStatus(401);
}
res.sendStatus(200);
});
app.listen(3000, () => console.log("server started on port 3000"));