-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
79 lines (69 loc) · 2.08 KB
/
index.mjs
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
/**
* TOTP 服务就是常见的一次性 6 位验证码验证
*/
import elysia from "https://esm.sh/elysia";
import * as OTPAuth from "https://deno.land/x/otpauth/dist/otpauth.esm.js";
const app = new elysia();
const kv = await Deno.openKv();
/**
* 生成一个新的密钥
* @todo 需要鉴权
*/
app.get("/generate-secret", async (ctx) => {
const username = ctx.query.username;
if (!username) {
return new Response("User ID is required", { status: 400 });
}
const secret = new OTPAuth.Secret();
await kv.set(["TOTP-secret", username], secret.base32);
// Create a new TOTP object.
let totp = new OTPAuth.TOTP({
secret,
});
return {
username,
secret: secret.base32,
uri: OTPAuth.URI.stringify(totp),
};
});
/**
* 生成 OTP
* @todo 需要鉴权
*/
app.get("/generate-otp", async (req) => {
const username = req.query.username;
if (!username) {
return new Response("Invalid User ID", { status: 400 });
}
const secretKv = await kv.get(["TOTP-secret", username]);
if (!secretKv.value)
return new Response(" User need to open TOTP first", { status: 400 });
const secret = OTPAuth.Secret.fromBase32(secretKv.value);
const totp = new OTPAuth.TOTP({
secret: secret,
digits: 6,
period: 30,
});
const token = totp.generate();
return { username, otp: token };
});
// 验证 OTP
app.get("/verify-otp", async (req) => {
const username = req.query.username;
const token = req.query.token;
if (!username || !token) {
return new Response("Invalid request", { status: 400 });
}
const secretKv = await kv.get(["TOTP-secret", username]);
if (!secretKv.value)
return new Response(" User need to open TOTP first", { status: 400 });
const secret = OTPAuth.Secret.fromBase32(secretKv.value);
const totp = new OTPAuth.TOTP({
secret: secret,
digits: 6,
period: 30,
});
const isValid = totp.validate({ token: token, window: 1 }) !== null;
return { username, isValid };
});
Deno.serve(app.fetch);