CB2FA v2.0.0 - Matrix-Focused Release
BREAKING CHANGES: - Matrix-Only: Removed all other platforms to focus purely on Matrix - New Structure: Moved Matrix implementation from /matrix to project root - Simplified Architecture: Single-platform focus for better stability Added: - New Project Structure: Clean root-level organization (src/, middleware.ts) - Enhanced Documentation: Professional README following EasyProTech standards - Deno Tasks: Convenient task runner commands - TypeScript Improvements: @ts-ignore fixes for Deno imports Changed: - File Organization: Matrix code moved from /matrix/src/ to /src/ - Import Paths: Updated all imports for new structure - Documentation: Completely rewritten README for v2.0 focus - Version Tracking: Updated to v2.0.0 across all files Removed: - Multi-Platform Support: Removed planned Telegram, Discord, Slack - Core Abstractions: Removed /core and /docs directories - Complex Architecture: Simplified for single Matrix focus Company: EasyProTech LLC (www.easypro.tech) Dev: Brabus Location: London, UK Contact: mail.easypro.tech@gmail.com Telegram: https://t.me/easyprotech
This commit is contained in:
314
src/client.ts
Normal file
314
src/client.ts
Normal file
@@ -0,0 +1,314 @@
|
||||
// CB2FA - Community-Based Two-Factor Authentication v2.0.0
|
||||
// Company: EasyProTech LLC (www.easypro.tech)
|
||||
// Dev: Brabus
|
||||
// Created: 2025-08-10 21:40 MSK
|
||||
// Telegram: https://t.me/easyprotech
|
||||
|
||||
import { config } from "./config.ts";
|
||||
import { log } from "./logger.ts";
|
||||
import { t } from "./i18n.ts";
|
||||
|
||||
export class MatrixClient {
|
||||
private accessToken = "";
|
||||
private roomId = "";
|
||||
private currentRequest: any = null;
|
||||
|
||||
async login() {
|
||||
const response = await fetch(`${config.matrix.homeserverUrl}/_matrix/client/v3/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
type: "m.login.password",
|
||||
identifier: {
|
||||
type: "m.id.user",
|
||||
user: config.matrix.botUsername,
|
||||
},
|
||||
password: config.matrix.botPassword,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Login failed: ${await response.text()}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
this.accessToken = data.access_token;
|
||||
log.info(t("loggedIn"));
|
||||
|
||||
await this.setupRoom();
|
||||
}
|
||||
|
||||
async setupRoom() {
|
||||
// Get joined rooms
|
||||
const roomsResponse = await fetch(`${config.matrix.homeserverUrl}/_matrix/client/v3/joined_rooms`, {
|
||||
headers: { "Authorization": `Bearer ${this.accessToken}` },
|
||||
});
|
||||
|
||||
if (!roomsResponse.ok) {
|
||||
throw new Error("Failed to get rooms");
|
||||
}
|
||||
|
||||
const roomsData = await roomsResponse.json();
|
||||
|
||||
// Look for CB2FA room
|
||||
for (const roomId of roomsData.joined_rooms) {
|
||||
const stateResponse = await fetch(
|
||||
`${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${roomId}/state/m.room.name`,
|
||||
{ headers: { "Authorization": `Bearer ${this.accessToken}` } }
|
||||
);
|
||||
|
||||
if (stateResponse.ok) {
|
||||
const state = await stateResponse.json();
|
||||
if (state.name === config.cb2fa.roomName) {
|
||||
this.roomId = roomId;
|
||||
log.info(`${t("roomFound")}: ${roomId}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create room if not found
|
||||
const createResponse = await fetch(`${config.matrix.homeserverUrl}/_matrix/client/v3/createRoom`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${this.accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: config.cb2fa.roomName,
|
||||
topic: "CB2FA authorization - simple y/n commands",
|
||||
visibility: "private",
|
||||
preset: "private_chat",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!createResponse.ok) {
|
||||
throw new Error("Failed to create room");
|
||||
}
|
||||
|
||||
const createData = await createResponse.json();
|
||||
this.roomId = createData.room_id;
|
||||
log.info(`${t("roomCreated")}: ${this.roomId}`);
|
||||
|
||||
// Invite all configured users immediately
|
||||
for (const user of config.cb2fa.invitedUsers) {
|
||||
const userId = `@${user}:${config.matrix.domain}`;
|
||||
await this.inviteUser(userId);
|
||||
}
|
||||
}
|
||||
|
||||
async inviteUser(userId: string) {
|
||||
const response = await fetch(
|
||||
`${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${this.roomId}/invite`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${this.accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ user_id: userId }),
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
log.info(`Invited ${userId} to room`);
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(message: string) {
|
||||
const txnId = Date.now().toString();
|
||||
const response = await fetch(
|
||||
`${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${this.roomId}/send/m.room.message/${txnId}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${this.accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
msgtype: "m.text",
|
||||
body: message,
|
||||
format: "org.matrix.custom.html",
|
||||
formatted_body: message
|
||||
.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
|
||||
.replace(/`(.*?)`/g, "<code>$1</code>")
|
||||
.replace(/\n/g, "<br/>"),
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
log.error("Failed to send message:", await response.text());
|
||||
}
|
||||
}
|
||||
|
||||
async sendFormattedMessage(htmlContent: string, plainTextFallback: string) {
|
||||
const txnId = Date.now().toString();
|
||||
const response = await fetch(
|
||||
`${config.matrix.homeserverUrl}/_matrix/client/v3/rooms/${this.roomId}/send/m.room.message/${txnId}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Authorization": `Bearer ${this.accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
msgtype: "m.text",
|
||||
body: plainTextFallback,
|
||||
format: "org.matrix.custom.html",
|
||||
formatted_body: htmlContent,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
log.error("Failed to send formatted message:", await response.text());
|
||||
} else {
|
||||
log.info("✅ Sent table to Matrix");
|
||||
}
|
||||
}
|
||||
|
||||
async sendLoginRequest(username: string, ipAddress: string, deviceInfo?: string) {
|
||||
const requestId = crypto.randomUUID();
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
|
||||
this.currentRequest = {
|
||||
id: requestId,
|
||||
username,
|
||||
ipAddress,
|
||||
deviceInfo,
|
||||
timestamp,
|
||||
status: "pending",
|
||||
};
|
||||
|
||||
// Create clean table with HTML formatting
|
||||
const deviceRow = deviceInfo ? `
|
||||
<tr>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-weight: bold; background-color: #f8f9fa;">${t("device")}:</td>
|
||||
<td style="border: 1px solid #ddd; padding: 8px;">${deviceInfo}</td>
|
||||
</tr>` : "";
|
||||
|
||||
const htmlTable = `
|
||||
<h3>🔐 ${t("loginRequest")}</h3>
|
||||
<table style="border-collapse: collapse; width: 100%; max-width: 500px; margin: 10px 0;">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-weight: bold; background-color: #f8f9fa; width: 120px;">${t("user")}:</td>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-family: monospace; font-weight: bold;">${username}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-weight: bold; background-color: #f8f9fa;">${t("ip")}:</td>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-family: monospace;">${ipAddress}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-weight: bold; background-color: #f8f9fa;">${t("time")}:</td>
|
||||
<td style="border: 1px solid #ddd; padding: 8px; font-family: monospace;">${timestamp}</td>
|
||||
</tr>${deviceRow}
|
||||
</tbody>
|
||||
</table>
|
||||
<p style="background-color: #e8f4fd; padding: 10px; border-left: 4px solid #007acc; margin: 10px 0;">
|
||||
<strong>📋 ${t("replyInstructions")}</strong>
|
||||
</p>`;
|
||||
|
||||
const plainTextTable = `🔐 ${t("loginRequest")}
|
||||
|
||||
${t("user")}: ${username}
|
||||
${t("ip")}: ${ipAddress}
|
||||
${t("time")}: ${timestamp}
|
||||
${deviceInfo ? `${t("device")}: ${deviceInfo}` : ""}
|
||||
|
||||
📋 ${t("replyInstructions")}`;
|
||||
|
||||
await this.sendFormattedMessage(htmlTable, plainTextTable);
|
||||
|
||||
log.info(`${t("requestCreated")} ${username} (${requestId.substring(0, 8)})`);
|
||||
|
||||
return this.currentRequest;
|
||||
}
|
||||
|
||||
async startPolling() {
|
||||
let nextBatch = "";
|
||||
|
||||
// Get initial sync token
|
||||
const syncResponse = await fetch(
|
||||
`${config.matrix.homeserverUrl}/_matrix/client/v3/sync?timeout=0`,
|
||||
{ headers: { "Authorization": `Bearer ${this.accessToken}` } }
|
||||
);
|
||||
|
||||
if (syncResponse.ok) {
|
||||
const syncData = await syncResponse.json();
|
||||
nextBatch = syncData.next_batch;
|
||||
}
|
||||
|
||||
// Poll for new messages
|
||||
while (true) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${config.matrix.homeserverUrl}/_matrix/client/v3/sync?since=${nextBatch}&timeout=30000`,
|
||||
{ headers: { "Authorization": `Bearer ${this.accessToken}` } }
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
nextBatch = data.next_batch;
|
||||
|
||||
// Process room events
|
||||
if (data.rooms?.join?.[this.roomId]?.timeline?.events) {
|
||||
for (const event of data.rooms.join[this.roomId].timeline.events) {
|
||||
if (event.type === "m.room.message" && event.content?.msgtype === "m.text") {
|
||||
await this.processMessage(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Sync error:", error);
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async processMessage(event: any) {
|
||||
const sender = event.sender;
|
||||
const message = event.content?.body?.trim().toLowerCase();
|
||||
|
||||
if (!sender || !message) return;
|
||||
|
||||
// Skip bot's own messages
|
||||
if (sender === `@${config.matrix.botUsername}:${config.matrix.domain}`) {
|
||||
return;
|
||||
}
|
||||
|
||||
const username = sender.split(":")[0].replace("@", "");
|
||||
|
||||
// Handle y/n responses to current request
|
||||
if (this.currentRequest && (message === "y" || message === "n")) {
|
||||
if (message === "y") {
|
||||
this.currentRequest.status = "approved";
|
||||
this.currentRequest.approvedBy = username;
|
||||
await this.sendMessage(`${t("requestApproved")} by ${username}`);
|
||||
log.info(`Request approved by ${username}`);
|
||||
} else {
|
||||
this.currentRequest.status = "denied";
|
||||
this.currentRequest.deniedBy = username;
|
||||
await this.sendMessage(`${t("requestDenied")} by ${username}`);
|
||||
log.info(`Request denied by ${username}`);
|
||||
}
|
||||
|
||||
// Clear current request after decision
|
||||
setTimeout(() => {
|
||||
this.currentRequest = null;
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
getCurrentRequest() {
|
||||
return this.currentRequest;
|
||||
}
|
||||
|
||||
hasPendingRequest(): boolean {
|
||||
return this.currentRequest !== null;
|
||||
}
|
||||
}
|
||||
|
||||
export const matrixClient = new MatrixClient();
|
||||
29
src/config.ts
Normal file
29
src/config.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
// CB2FA - Community-Based Two-Factor Authentication v2.0.0
|
||||
// Company: EasyProTech LLC (www.easypro.tech)
|
||||
// Dev: Brabus
|
||||
// Created: 2025-08-10 21:40 MSK
|
||||
// Telegram: https://t.me/easyprotech
|
||||
|
||||
// @ts-ignore
|
||||
import { load } from "https://deno.land/std@0.208.0/dotenv/mod.ts";
|
||||
|
||||
await load({ export: true });
|
||||
|
||||
export const config = {
|
||||
matrix: {
|
||||
homeserverUrl: Deno.env.get("MATRIX_HOMESERVER_URL") || "http://localhost:8008",
|
||||
botUsername: Deno.env.get("MATRIX_BOT_USERNAME") || "cb2fa_bot",
|
||||
botPassword: Deno.env.get("MATRIX_BOT_PASSWORD") || "",
|
||||
domain: Deno.env.get("MATRIX_DOMAIN") || "localhost",
|
||||
adminForAuth: Deno.env.get("MATRIX_ADMIN_FOR_AUTH") || "admin",
|
||||
},
|
||||
cb2fa: {
|
||||
invitedUsers: (Deno.env.get("CB2FA_INVITED_USERS") || "admin").split(",").map(u => u.trim()),
|
||||
roomName: Deno.env.get("CB2FA_ROOM_NAME") || "CB2FA Authorization",
|
||||
timeoutMinutes: parseInt(Deno.env.get("CB2FA_TIMEOUT_MINUTES") || "15"),
|
||||
botPort: parseInt(Deno.env.get("CB2FA_BOT_PORT") || "10000"),
|
||||
middlewarePort: parseInt(Deno.env.get("CB2FA_MIDDLEWARE_PORT") || "9999"),
|
||||
},
|
||||
// Fix: TEST_LANG should override LANGUAGE for testing
|
||||
language: Deno.env.get("TEST_LANG") || Deno.env.get("LANGUAGE") || "en",
|
||||
};
|
||||
216
src/i18n.ts
Normal file
216
src/i18n.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
// CB2FA - Community-Based Two-Factor Authentication v2.0.0
|
||||
// Company: EasyProTech LLC (www.easypro.tech)
|
||||
// Dev: Brabus
|
||||
// Created: 2025-08-10 21:40 MSK
|
||||
// Telegram: https://t.me/easyprotech
|
||||
|
||||
import { config } from "./config.ts";
|
||||
|
||||
const messages = {
|
||||
en: {
|
||||
botStarting: "🚀 Starting CB2FA Matrix Bot...",
|
||||
loggedIn: "✅ Logged in to Matrix successfully",
|
||||
roomCreated: "✅ Created CB2FA room",
|
||||
roomFound: "✅ Found CB2FA room",
|
||||
botReady: "✅ CB2FA Bot ready",
|
||||
httpServerStarted: "🌐 HTTP server started on",
|
||||
botStarted: "🎯 CB2FA Bot started successfully!",
|
||||
|
||||
loginRequest: "🔐 Login Request",
|
||||
user: "User",
|
||||
ip: "IP",
|
||||
time: "Time",
|
||||
device: "Device",
|
||||
replyInstructions: "Reply: y (allow) / n (deny)",
|
||||
|
||||
requestApproved: "✅ Request APPROVED",
|
||||
requestDenied: "❌ Request DENIED",
|
||||
|
||||
botAuthRequest: "🤖 CB2FA bot requests verification. Reply 'y' to authorize this bot",
|
||||
botAuthorized: "✅ CB2FA bot authorized successfully",
|
||||
|
||||
loginAttempt: "🔐 Login attempt",
|
||||
loginFailed: "❌ Login failed",
|
||||
regularUser: "🔄 Regular user - creating CB2FA request",
|
||||
requestCreated: "📝 Created auth request for",
|
||||
},
|
||||
ru: {
|
||||
botStarting: "🚀 Запуск CB2FA Matrix Бота...",
|
||||
loggedIn: "✅ Успешный вход в Matrix",
|
||||
roomCreated: "✅ Создана CB2FA комната",
|
||||
roomFound: "✅ Найдена CB2FA комната",
|
||||
botReady: "✅ CB2FA Бот готов",
|
||||
httpServerStarted: "🌐 HTTP сервер запущен на",
|
||||
botStarted: "🎯 CB2FA Бот успешно запущен!",
|
||||
|
||||
loginRequest: "🔐 Запрос входа",
|
||||
user: "Пользователь",
|
||||
ip: "IP",
|
||||
time: "Время",
|
||||
device: "Устройство",
|
||||
replyInstructions: "Ответ: y (разрешить) / n (запретить)",
|
||||
|
||||
requestApproved: "✅ Запрос ОДОБРЕН",
|
||||
requestDenied: "❌ Запрос ОТКЛОНЕН",
|
||||
|
||||
botAuthRequest: "🤖 CB2FA бот запрашивает авторизацию. Ответьте 'y' чтобы авторизовать",
|
||||
botAuthorized: "✅ CB2FA бот успешно авторизован",
|
||||
|
||||
loginAttempt: "🔐 Попытка входа",
|
||||
loginFailed: "❌ Неудачный вход",
|
||||
regularUser: "🔄 Обычный пользователь - создаем CB2FA запрос",
|
||||
requestCreated: "📝 Создан запрос авторизации для",
|
||||
},
|
||||
de: {
|
||||
botStarting: "🚀 CB2FA Matrix Bot wird gestartet...",
|
||||
loggedIn: "✅ Erfolgreich in Matrix eingeloggt",
|
||||
roomCreated: "✅ CB2FA Raum erstellt",
|
||||
roomFound: "✅ CB2FA Raum gefunden",
|
||||
botReady: "✅ CB2FA Bot bereit",
|
||||
httpServerStarted: "🌐 HTTP Server gestartet auf",
|
||||
botStarted: "🎯 CB2FA Bot erfolgreich gestartet!",
|
||||
|
||||
loginRequest: "🔐 Anmeldeanfrage",
|
||||
user: "Benutzer",
|
||||
ip: "IP",
|
||||
time: "Zeit",
|
||||
device: "Gerät",
|
||||
replyInstructions: "Antwort: y (erlauben) / n (verweigern)",
|
||||
|
||||
requestApproved: "✅ Anfrage GENEHMIGT",
|
||||
requestDenied: "❌ Anfrage ABGELEHNT",
|
||||
|
||||
botAuthRequest: "🤖 CB2FA Bot bittet um Verifizierung. Antworten Sie 'y' um diesen Bot zu autorisieren",
|
||||
botAuthorized: "✅ CB2FA Bot erfolgreich autorisiert",
|
||||
|
||||
loginAttempt: "🔐 Anmeldeversuch",
|
||||
loginFailed: "❌ Anmeldung fehlgeschlagen",
|
||||
regularUser: "🔄 Regulärer Benutzer - erstelle CB2FA Anfrage",
|
||||
requestCreated: "📝 Autorisierungsanfrage erstellt für",
|
||||
},
|
||||
"zh-cn": {
|
||||
botStarting: "🚀 正在启动CB2FA Matrix机器人...",
|
||||
loggedIn: "✅ 成功登录Matrix",
|
||||
roomCreated: "✅ 已创建CB2FA房间",
|
||||
roomFound: "✅ 找到CB2FA房间",
|
||||
botReady: "✅ CB2FA机器人已就绪",
|
||||
httpServerStarted: "🌐 HTTP服务器已启动在",
|
||||
botStarted: "🎯 CB2FA机器人启动成功!",
|
||||
|
||||
loginRequest: "🔐 登录请求",
|
||||
user: "用户",
|
||||
ip: "IP地址",
|
||||
time: "时间",
|
||||
device: "设备",
|
||||
replyInstructions: "回复: y (允许) / n (拒绝)",
|
||||
|
||||
requestApproved: "✅ 请求已批准",
|
||||
requestDenied: "❌ 请求已拒绝",
|
||||
|
||||
botAuthRequest: "🤖 CB2FA机器人请求验证。回复'y'以授权此机器人",
|
||||
botAuthorized: "✅ CB2FA机器人授权成功",
|
||||
|
||||
loginAttempt: "🔐 登录尝试",
|
||||
loginFailed: "❌ 登录失败",
|
||||
regularUser: "🔄 普通用户 - 创建CB2FA请求",
|
||||
requestCreated: "📝 已为以下用户创建授权请求",
|
||||
},
|
||||
fr: {
|
||||
botStarting: "🚀 Démarrage du bot CB2FA Matrix...",
|
||||
loggedIn: "✅ Connexion à Matrix réussie",
|
||||
roomCreated: "✅ Salon CB2FA créé",
|
||||
roomFound: "✅ Salon CB2FA trouvé",
|
||||
botReady: "✅ Bot CB2FA prêt",
|
||||
httpServerStarted: "🌐 Serveur HTTP démarré sur",
|
||||
botStarted: "🎯 Bot CB2FA démarré avec succès!",
|
||||
|
||||
loginRequest: "🔐 Demande de connexion",
|
||||
user: "Utilisateur",
|
||||
ip: "IP",
|
||||
time: "Heure",
|
||||
device: "Appareil",
|
||||
replyInstructions: "Réponse: y (autoriser) / n (refuser)",
|
||||
|
||||
requestApproved: "✅ Demande APPROUVÉE",
|
||||
requestDenied: "❌ Demande REFUSÉE",
|
||||
|
||||
botAuthRequest: "🤖 Le bot CB2FA demande une vérification. Répondez 'y' pour autoriser ce bot",
|
||||
botAuthorized: "✅ Bot CB2FA autorisé avec succès",
|
||||
|
||||
loginAttempt: "🔐 Tentative de connexion",
|
||||
loginFailed: "❌ Échec de la connexion",
|
||||
regularUser: "🔄 Utilisateur régulier - création d'une demande CB2FA",
|
||||
requestCreated: "📝 Demande d'autorisation créée pour",
|
||||
},
|
||||
es: {
|
||||
botStarting: "🚀 Iniciando bot CB2FA Matrix...",
|
||||
loggedIn: "✅ Sesión iniciada en Matrix correctamente",
|
||||
roomCreated: "✅ Sala CB2FA creada",
|
||||
roomFound: "✅ Sala CB2FA encontrada",
|
||||
botReady: "✅ Bot CB2FA listo",
|
||||
httpServerStarted: "🌐 Servidor HTTP iniciado en",
|
||||
botStarted: "🎯 ¡Bot CB2FA iniciado correctamente!",
|
||||
|
||||
loginRequest: "🔐 Solicitud de inicio de sesión",
|
||||
user: "Usuario",
|
||||
ip: "IP",
|
||||
time: "Hora",
|
||||
device: "Dispositivo",
|
||||
replyInstructions: "Respuesta: y (permitir) / n (denegar)",
|
||||
|
||||
requestApproved: "✅ Solicitud APROBADA",
|
||||
requestDenied: "❌ Solicitud DENEGADA",
|
||||
|
||||
botAuthRequest: "🤖 El bot CB2FA solicita verificación. Responda 'y' para autorizar este bot",
|
||||
botAuthorized: "✅ Bot CB2FA autorizado correctamente",
|
||||
|
||||
loginAttempt: "🔐 Intento de inicio de sesión",
|
||||
loginFailed: "❌ Fallo en el inicio de sesión",
|
||||
regularUser: "🔄 Usuario regular - creando solicitud CB2FA",
|
||||
requestCreated: "📝 Solicitud de autorización creada para",
|
||||
},
|
||||
tr: {
|
||||
botStarting: "🚀 CB2FA Matrix botu başlatılıyor...",
|
||||
loggedIn: "✅ Matrix'e başarıyla giriş yapıldı",
|
||||
roomCreated: "✅ CB2FA odası oluşturuldu",
|
||||
roomFound: "✅ CB2FA odası bulundu",
|
||||
botReady: "✅ CB2FA botu hazır",
|
||||
httpServerStarted: "🌐 HTTP sunucusu başlatıldı",
|
||||
botStarted: "🎯 CB2FA botu başarıyla başlatıldı!",
|
||||
|
||||
loginRequest: "🔐 Giriş talebi",
|
||||
user: "Kullanıcı",
|
||||
ip: "IP",
|
||||
time: "Zaman",
|
||||
device: "Cihaz",
|
||||
replyInstructions: "Yanıt: y (izin ver) / n (reddet)",
|
||||
|
||||
requestApproved: "✅ Talep ONAYLANDI",
|
||||
requestDenied: "❌ Talep REDDEDİLDİ",
|
||||
|
||||
botAuthRequest: "🤖 CB2FA botu doğrulama talep ediyor. Bu botu yetkilendirmek için 'y' yanıtlayın",
|
||||
botAuthorized: "✅ CB2FA botu başarıyla yetkilendirildi",
|
||||
|
||||
loginAttempt: "🔐 Giriş denemesi",
|
||||
loginFailed: "❌ Giriş başarısız",
|
||||
regularUser: "🔄 Normal kullanıcı - CB2FA talebi oluşturuluyor",
|
||||
requestCreated: "📝 Yetkilendirme talebi oluşturuldu:",
|
||||
}
|
||||
};
|
||||
|
||||
export const t = (key: string): string => {
|
||||
const lang = config.language as keyof typeof messages;
|
||||
const langMessages = messages[lang] || messages.en;
|
||||
return (langMessages as any)[key] || key;
|
||||
};
|
||||
|
||||
// Export available languages for documentation
|
||||
export const availableLanguages = {
|
||||
"en": "🇬🇧 English",
|
||||
"ru": "🇷🇺 Русский",
|
||||
"de": "🇩🇪 Deutsch",
|
||||
"zh-cn": "🇨🇳 中文 (简体)",
|
||||
"fr": "🇫🇷 Français",
|
||||
"es": "🇪🇸 Español",
|
||||
"tr": "🇹🇷 Türkçe"
|
||||
};
|
||||
12
src/logger.ts
Normal file
12
src/logger.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
// CB2FA - Community-Based Two-Factor Authentication v2.0.0
|
||||
// Company: EasyProTech LLC (www.easypro.tech)
|
||||
// Dev: Brabus
|
||||
// Created: 2025-08-10 21:40 MSK
|
||||
// Telegram: https://t.me/easyprotech
|
||||
|
||||
export const log = {
|
||||
info: (message: string, ...args: unknown[]) => console.log(`[INFO] ${message}`, ...args),
|
||||
warn: (message: string, ...args: unknown[]) => console.warn(`[WARN] ${message}`, ...args),
|
||||
error: (message: string, ...args: unknown[]) => console.error(`[ERROR] ${message}`, ...args),
|
||||
debug: (message: string, ...args: unknown[]) => console.debug(`[DEBUG] ${message}`, ...args),
|
||||
};
|
||||
101
src/main.ts
Normal file
101
src/main.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
// CB2FA - Community-Based Two-Factor Authentication v2.0.0
|
||||
// Company: EasyProTech LLC (www.easypro.tech)
|
||||
// Dev: Brabus
|
||||
// Created: 2025-08-10 21:40 MSK
|
||||
// Telegram: https://t.me/easyprotech
|
||||
|
||||
// @ts-ignore
|
||||
import { serve } from "https://deno.land/std@0.208.0/http/server.ts";
|
||||
import { config } from "./config.ts";
|
||||
import { log } from "./logger.ts";
|
||||
import { t, availableLanguages } from "./i18n.ts";
|
||||
import { matrixClient } from "./client.ts";
|
||||
|
||||
log.info(t("botStarting"));
|
||||
log.info(`Invited users: ${config.cb2fa.invitedUsers.join(", ")}`);
|
||||
log.info(`Admin for auth: ${config.matrix.adminForAuth}`);
|
||||
log.info(`Language: ${config.language} (${availableLanguages[config.language as keyof typeof availableLanguages] || config.language})`);
|
||||
log.info(`Matrix domain: ${config.matrix.domain}`);
|
||||
|
||||
// Start Matrix client
|
||||
await matrixClient.login();
|
||||
|
||||
// Start polling for messages
|
||||
matrixClient.startPolling();
|
||||
|
||||
// HTTP server for CB2FA API
|
||||
const handler = async (req: Request): Promise<Response> => {
|
||||
const url = new URL(req.url);
|
||||
|
||||
if (url.pathname === "/health") {
|
||||
return new Response(JSON.stringify({
|
||||
status: "healthy",
|
||||
language: config.language,
|
||||
domain: config.matrix.domain,
|
||||
version: "2.0.0",
|
||||
supportedLanguages: availableLanguages
|
||||
}), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname === "/cb2fa/has-pending" && req.method === "GET") {
|
||||
return new Response(JSON.stringify({
|
||||
hasPending: matrixClient.hasPendingRequest(),
|
||||
}), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname === "/cb2fa/create" && req.method === "POST") {
|
||||
try {
|
||||
const data = await req.json();
|
||||
|
||||
const request = await matrixClient.sendLoginRequest(
|
||||
data.username,
|
||||
data.ip_address,
|
||||
data.device_info
|
||||
);
|
||||
|
||||
return new Response(JSON.stringify(request), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error) {
|
||||
log.error("Error creating CB2FA request:", error);
|
||||
return new Response(JSON.stringify({
|
||||
error: "Failed to create request",
|
||||
}), {
|
||||
status: 500,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === "/cb2fa/status" && req.method === "GET") {
|
||||
const currentRequest = matrixClient.getCurrentRequest();
|
||||
|
||||
if (!currentRequest) {
|
||||
return new Response(JSON.stringify({
|
||||
error: "No pending request",
|
||||
}), {
|
||||
status: 404,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify(currentRequest), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
return new Response("Not Found", { status: 404 });
|
||||
};
|
||||
|
||||
await serve(handler, {
|
||||
port: config.cb2fa.botPort,
|
||||
hostname: "127.0.0.1",
|
||||
});
|
||||
|
||||
log.info(`${t("httpServerStarted")} http://127.0.0.1:${config.cb2fa.botPort}`);
|
||||
log.info(t("botStarted"));
|
||||
log.info("🔑 Bot is ready for CB2FA requests!");
|
||||
Reference in New Issue
Block a user