Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initialize the CAPTCHA module with emoji CAPTCHA #25

Merged
merged 26 commits into from Sep 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 57 additions & 0 deletions database/operations/kv.ts
@@ -0,0 +1,57 @@
/**
* This file is part of Moderent.
*
* Moderent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Moderent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Afferto General Public License
* along with Moderent. If not, see <https://www.gnu.org/licenses/>.
*/

import { database } from "../database.ts";
import { Collection } from "mongo";

export interface Kv<T = unknown> {
key: string;
value: T;
}

let collection: Collection<Kv>;
// deno-lint-ignore no-explicit-any
const cache = new Map<string, any>();

export function initializeKv() {
collection = database.collection("kv");
collection.createIndexes({
indexes: [
{
key: { "key": 1 },
name: "key",
unique: true,
},
],
});
}

export async function get<T = unknown>(key: string): Promise<T | null> {
let value = cache.get(key);
if (!value) {
value = (await collection.findOne({ key }))?.value ?? null;
}
return value;
}

export async function set<T = unknown>(key: string, value: T) {
const result = await collection.updateOne({ key }, { $set: { value } }, {
upsert: true,
});
cache.set(key, value);
return result.modifiedCount + result.upsertedCount != 0;
}
72 changes: 0 additions & 72 deletions database/operations/log_chats.ts

This file was deleted.

8 changes: 5 additions & 3 deletions database/operations/mod.ts
Expand Up @@ -15,10 +15,12 @@
* along with Moderent. If not, see <https://www.gnu.org/licenses/>.
*/

import { initializeLogChats } from "./log_chats.ts";
import { initializeSettings } from "./settings.ts";
import { initializeKv } from "./kv.ts";

export function initialize() {
return Promise.all([initializeLogChats()]);
return Promise.all([initializeSettings(), initializeKv()]);
}

export * from "./log_chats.ts";
export * from "./settings.ts";
export * from "./kv.ts";
66 changes: 66 additions & 0 deletions database/operations/settings.ts
@@ -0,0 +1,66 @@
/**
* This file is part of Moderent.
*
* Moderent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Moderent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Afferto General Public License
* along with Moderent. If not, see <https://www.gnu.org/licenses/>.
*/

import { database } from "../database.ts";
import { Collection } from "mongo";

export enum Captcha {
Emoji = "emoji",
}

export interface Settings {
logChat?: number | null;
captcha?: Captcha | null;
}

let collection: Collection<Settings & { id: number }>;
const cache = new Map<number, Settings>();

export function initializeSettings() {
collection = database.collection("chats");
collection.createIndexes({
indexes: [
{
key: { "id": 1 },
name: "id",
unique: true,
},
{
key: { "logChat": 1 },
name: "logChat",
unique: true,
},
],
});
}

export async function getSettings(id: number): Promise<Settings> {
let settings = cache.get(id);
if (typeof settings === "undefined") {
settings = await collection.findOne({ id }) ?? {};
cache.set(id, settings);
}
return settings ?? {};
}

export async function updateSettings(id: number, settings: Settings) {
const result = await collection.updateOne({ id }, { $set: { ...settings } }, {
upsert: true,
});
cache.set(id, settings);
return result.modifiedCount + result.upsertedCount != 0;
}
5 changes: 3 additions & 2 deletions env.ts
Expand Up @@ -16,7 +16,7 @@
*/

import { config } from "dotenv";
import { bool, cleanEnv, host, port, str } from "envalid";
import { bool, cleanEnv, host, port, str, url } from "envalid";

await config({ export: true });

Expand All @@ -25,5 +25,6 @@ export default cleanEnv(Deno.env.toObject(), {
WEBHOOK_HOST: host({ default: "127.0.0.1" }),
WEBHOOK_PORT: port({ default: 3000 }),
BOT_TOKEN: str(),
MONGODB_URI: str(),
MONGODB_URI: url(),
EMOJI_CAPTCHA_API_URL: url({ default: "" }),
});
153 changes: 153 additions & 0 deletions handlers/captcha/emoji.ts
@@ -0,0 +1,153 @@
/**
* This file is part of Moderent.
*
* Moderent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Moderent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Afferto General Public License
* along with Moderent. If not, see <https://www.gnu.org/licenses/>.
*/

import env from "$env";
import {
base64DecryptAesCbcWithIv,
base64EncryptAesCbcWithIv,
Context,
} from "$utilities";
import {
CallbackQueryContext,
Composer,
InlineKeyboard,
InputFile,
} from "grammy";
import { InlineKeyboardButton } from "grammy/types.ts";

const composer = new Composer<Context>();

const BUTTONS_PER_ROW = 5;
const EMOJI_CORRECT = "✅";
const EMOJI_WRONG = "❌";

const getEmojis = (string: string) =>
string.split(";").map((v) => v.split("-").map((v) => parseInt(v, 16))).map((
v,
) => String.fromCodePoint(...v.filter((v) => !isNaN(v))));

const replaceEmoji = (
buttons: InlineKeyboardButton.CallbackButton[][],
emoji: string,
replacement: string,
) =>
buttons.map((v) =>
v.map((v) => {
const slices = (v as InlineKeyboardButton.CallbackButton)
.callback_data.split(":");
slices[1] = slices[1] == emoji ? replacement : slices[1];
return {
...v,
text: slices[1] == emoji ? replacement : slices[1],
callback_data: slices.join(":"),
};
})
);

composer.callbackQuery(/^emoji-captcha:([^:]+):/, async (ctx) => {
await ctx.answerCallbackQuery();
const emoji = ctx.match![1];
if ([EMOJI_CORRECT, EMOJI_WRONG].includes(emoji)) {
return;
}
const chatId = Number(
(ctx.msg?.reply_to_message?.reply_markup
?.inline_keyboard[0][0] as InlineKeyboardButton.CallbackButton)
.callback_data,
);
const buttons = ctx.msg?.reply_markup
?.inline_keyboard as InlineKeyboardButton.CallbackButton[][];
const correctEmojis = (await base64DecryptAesCbcWithIv(
buttons.flat().map((v) => v.callback_data.split(":")[2] ?? "").join(""),
))
.split(";");
const attempts = buttons.flat().filter((v) =>
[EMOJI_CORRECT, EMOJI_WRONG].includes(v.text)
).length + 1;
const previousWrongAttempts = buttons.flat().filter((v) =>
v.text == EMOJI_WRONG
).length;
if (emoji == EMOJI_WRONG || emoji == EMOJI_CORRECT) {
return;
}
if (correctEmojis.includes(emoji)) {
await ctx.editMessageReplyMarkup({
reply_markup: {
inline_keyboard: replaceEmoji(buttons, emoji, EMOJI_CORRECT),
},
});
if (attempts == 6) {
await ctx.deleteMessage();
await ctx.api.approveChatJoinRequest(chatId, ctx.chat?.id!);
await ctx.api.editMessageText(
ctx.chat?.id!,
ctx.msg?.reply_to_message?.message_id!,
"Your request to join " +
// see ./mod.ts:57
ctx.msg?.reply_to_message?.text!.slice(47).slice(0, -1) +
" was accepted.",
);
}
} else {
await ctx.editMessageReplyMarkup({
reply_markup: {
inline_keyboard: replaceEmoji(buttons, emoji, EMOJI_WRONG),
},
});
if (previousWrongAttempts == 2) {
await ctx.deleteMessage();
await ctx.api.editMessageText(
ctx.chat?.id!,
ctx.msg?.reply_to_message?.message_id!,
"You couldn't make it. Try again later.",
);
}
}
});

export async function emoji(
ctx: CallbackQueryContext<Context>,
) {
const url = env.EMOJI_CAPTCHA_API_URL;
if (!url) {
return;
}
const res = await fetch(url);
const emojis = getEmojis(res.headers.get("x-emojis") ?? "");
const correctEmojis = getEmojis(res.headers.get("x-correct-emojis") ?? "");
if (emojis.length == 0 || correctEmojis.length == 0) {
return;
}
let encrypted = await base64EncryptAesCbcWithIv(correctEmojis.join(";"));
const keyboard = new InlineKeyboard();
for (const [i, emoji] of emojis.entries()) {
let data = `emoji-captcha:${emoji}:`;
const available = 64 - new TextEncoder().encode(data).length;
data += encrypted.slice(0, available);
encrypted = encrypted.slice(available);
keyboard.text(emoji, data);
if (i % BUTTONS_PER_ROW === (BUTTONS_PER_ROW - 1)) {
keyboard.row();
}
}
await ctx.replyWithPhoto(new InputFile(new Blob([await res.arrayBuffer()])), {
caption: "Which emojis do you see in the photo?",
reply_markup: keyboard,
});
}

export default composer;