mic-bot/bot/normal_mode/captcha.ts
2024-10-25 19:35:12 +02:00

129 lines
4.4 KiB
TypeScript

import { Filter } from "https://deno.land/x/grammy/mod.ts";
import { BotConfig } from "../../cfg/config.ts";
import { Ctx } from "../ctx.ts";
import { LangManager } from "../lang/export.ts";
import { Kysely } from 'npm:kysely';
import { Database } from "../../repo/exports.ts";
import { checkUserRestrictions, getActiveInviteLink } from "../../core/users.ts";
import { CheckUserOut, type CheckUserOnStartOut } from "./user_managment.ts";
const CAPTCHA_FAILS_LIMIT = 3
const TIMEOUT_AFTER_FAIL_MINS = 5
export interface CaptchaSessionData {
message_id: number,
tries_failed: number,
generated_at: number,
// Captcha can be changed from a simple matematical ones
// to a more complicated images or even science-related questions
solution: string,
}
const randInt = (min: number, max: number): number =>
Math.floor(Math.random() * (max - min) + min)
class Captcha {
// ! READ ONLY ! Initialized by the constructor
public _generated_at = Date.now()
// ! READ ONLY ! Initialized by the constructor
public _solution: number
// ! READ ONLY ! Initialized by the constructor
public _text: string
constructor() {
const number1 = randInt(-100, 100)
const number2 = randInt(-100, 100)
this._solution = number1 + number2
this._text = `Captcha: ${number1}+${number2}=?`
}
}
// User captcha response sanitizer/parser/validator
const isSolutionCorrect = (expectSolution: string, solution: string): boolean => {
solution = solution.replace(' ','').replace('\t','') // Sanitizing
return parseInt(solution, 10) == parseInt(expectSolution, 10) ? true : false
}
const captchaPassed = async (ctx: Ctx, db: Kysely<Database>, cfg: BotConfig) => {
if (ctx.chatId && ctx.session.captcha_data) {
await ctx.api.deleteMessage(
ctx.chatId, ctx.session.captcha_data.message_id
)
}
ctx.session.captcha_data = undefined
const linkValidUntil = new Date()
linkValidUntil.setHours(linkValidUntil.getHours() + 12)
const link = await ctx.api.createChatInviteLink(cfg.chat_id, {
member_limit: 1,
expire_date: Math.floor(linkValidUntil.getTime() / 1000),
})
await db.transaction().execute(async trx => {
await trx.updateTable('users').where('tg_id', '=', ctx.from!.id)
.set({ is_captcha_passed: true }).execute()
await trx.insertInto('invite_links').values({
link: link.invite_link,
expect_user_tg_id: ctx.from!.id,
valid_until: linkValidUntil
}).execute()
})
ctx.reply(LangManager.getLang(ctx.from!.language_code)
.replies.captcha.passed(link.invite_link))
ctx.session.captcha_data = undefined
}
const initUserCaptcha = async (ctx: Ctx, db: Kysely<Database>, user: CheckUserOnStartOut, cfg: BotConfig) => {
if (user.isChatParticipant) {
ctx.reply(LangManager.getLang(ctx.from!.language_code)
.replies.captcha.already_in_chat)
} else if (user.activeInviteLink) {
await ctx.reply(user.activeInviteLink)
} else if (user.isCaptchaSolved) {
await captchaPassed(ctx, db, cfg)
} else {
const captcha = new Captcha()
const msg = await ctx.reply(captcha._text)
ctx.session.captcha_data = {
message_id: msg.message_id,
tries_failed: 0,
generated_at: captcha._generated_at,
solution: captcha._solution.toString(),
}
}
}
// returns true if captcha is response to a captcha; else -- returns false
const checkCaptchaSolution = async (ctx: Filter<Ctx, "message:text">, db: Kysely<Database>, cfg: BotConfig) => {
if (!ctx.msg) return
const users = await db.selectFrom('users').selectAll().where('tg_id', '=', ctx.msg.from.id).execute()
if (users.length < 1) return // TODO: Maybe create new user here, idk
const user = users[0]
const userRestrictions = await checkUserRestrictions(db, user)
if (userRestrictions.isBlocked || userRestrictions.isTimeout) return
if (isSolutionCorrect(ctx.session.captcha_data!.solution, ctx.message.text)) {
await captchaPassed(ctx, db, cfg)
} else {
ctx.session.captcha_data!.tries_failed++
await ctx.api.deleteMessage(ctx.chatId, ctx.msg.message_id)
if (ctx.session.captcha_data!.tries_failed > CAPTCHA_FAILS_LIMIT) {
ctx.reply(LangManager.getLang(ctx.msg.from.language_code)
.replies.captcha.failed(TIMEOUT_AFTER_FAIL_MINS))
await ctx.api.deleteMessage(ctx.chatId, ctx.session.captcha_data!.message_id)
// TODO: Add timeout
}
}
return
}
export { checkCaptchaSolution, initUserCaptcha }