-
Notifications
You must be signed in to change notification settings - Fork 0
/
captcha.js
73 lines (58 loc) · 2.43 KB
/
captcha.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
const fs = require("fs");
const fig = require("figlet");
const sql = require("better-sqlite3");
const db = new sql("captcha_sessions.db");
const randm = str => str.split("\n").map(i => i.split("").map(i => (Math.random() * 12) > (9 + Math.floor(Math.random() * 2)) ? "." : i).join("")).join("\n");
let tim = new Map();
db.unsafeMode(true); // Nothing important here. So if corrupted then let it be.
db.exec("DROP TABLE IF EXISTS verification_sessions;");
db.exec("CREATE TABLE IF NOT EXISTS verification_sessions (sess TEXT, stage INT, question TEXT, answer TEXT, body TEXT, onid TEXT);");
module.exports.newCaptchaSession = function (q, s, onid) {
const sess = db.prepare("INSERT INTO verification_sessions VALUES (@sess, @stage, @question, @answer, @body, @onid)");
const sessID = Buffer.from(q.ip + Date.now() + Math.random().toString(36), "base64").toString("hex");
sess.run({
sess: sessID,
stage: 1,
question: "null",
answer: "null",
body: JSON.stringify(q.body),
onid
});
s.writeHead(302, {
"Set-Cookie": `verify_sess=${sessID}; SameSite=Strict; Path=/verify`,
"Location": "/verify"
}).end();
return tim.set(sessID, setTimeout(() => {
db.exec(`DELETE FROM verification_sessions WHERE sess = '${sessID}';`);
if (q.body.furl) fs.rm(__dirname + "/__uploads/" + q.body.furl, _ => null);
}, 60000 * 1));
}
module.exports.getCaptchaSession = function (sessid) {
const sessdb = db.prepare("SELECT * FROM verification_sessions WHERE sess = ?");
return sessdb.get(sessid);
}
module.exports.getNewQuestion = function (sess) {
const updateSession = db.prepare(`UPDATE verification_sessions SET question = ?, answer = ? WHERE sess = ?;`);
switch (sess.stage) {
case 1: {
const mathquestion = `${Math.floor(Math.random() * 50)}+${Math.floor(Math.random() * 50)}`
const question = randm(fig.textSync(mathquestion.split("").join(" ")));
updateSession.run(question, eval(mathquestion).toString(), sess.sess);
return {
q: question,
t: "Solve the math."
};
break;
}
}
}
module.exports.verifyCaptchaAnswer = function (sess, answer) {
if (sess.answer !== answer) {
db.prepare(`UPDATE verification_sessions SET answer = ? WHERE sess = ?;`).run(Math.random().toString(36), sess.sess);
return false;
}
db.exec(`DELETE FROM verification_sessions WHERE sess = '${sess.sess}';`);
clearTimeout(tim.get(sess.sess));
tim.delete(sess.sess);
return true;
}