import { m as tr } from "@peppa/shared/i18n"; import { createHmac, randomBytes } from "node:crypto"; import { chats, projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db"; import { and, asc, desc, eq, gt, inArray, isNotNull, like, lte, sql } from "drizzle-orm"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { decrypt, encrypt } from "./crypto.ts"; import { PeppaError } from "./errors.ts"; import { inNightQuiet } from "./night-quiet.ts"; import type { User } from "./users.ts"; export type OutboxRow = typeof telegramOutbox.$inferSelect; const OFFSET = "telegram.offset"; const PAIRING_TTL_MS = 10 * 60_000; // Only a keyed hash of the pairing code is stored. const pairKey = (code: string, secret: string) => `telegram.pair:${createHmac("sha256", secret).update(code).digest("hex")}`; /** One-time /start code that binds a Telegram chat to this Peppa user (valid 10 minutes). */ export async function createPairingCode(db: Db, secret: string, userId: number): Promise { const code = randomBytes(18).toString("base64url"); await setSetting(db, pairKey(code, secret), { userId, expiresAt: Date.now() + PAIRING_TTL_MS }); return code; } /** Binds the chat to the user the code was issued for. A chat belongs to one user at a time. */ export async function acceptPairing( db: Db, secret: string, code: string, who: { chatId: number; userId: number; username?: string | null; /** PEP-85: the owner of the bot the code came through (absent = the shared bot). */ botUserId?: number }, ): Promise { const key = pairKey(code, secret); const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key); if (!saved) return null; await deleteSetting(db, key); if (Date.now() >= saved.expiresAt) return null; // A user's own bot pairs only its owner; the shared bot never pairs someone who has their own. if (who.botUserId != null && who.botUserId !== saved.userId) return null; if (who.botUserId == null) { const [owner] = await db.select({ own: users.telegramBotTokenEnc }).from(users).where(eq(users.id, saved.userId)); if (owner?.own) return null; } await db .update(users) .set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) .where(eq(users.telegramChatId, who.chatId)); const [u] = await db .update(users) .set({ telegramChatId: who.chatId, telegramUserId: who.userId, telegramUsername: who.username ?? null, telegramPairedAt: new Date() }) .where(eq(users.id, saved.userId)) .returning(); return u ?? null; } export async function unpairTelegram(db: Db, userId: number): Promise { await db .update(users) .set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) .where(eq(users.id, userId)); } /** The Peppa user paired with this chat (and Telegram account), if any. */ export async function telegramUser(db: Db, chatId: number, fromId: number): Promise { const [u] = await db.select().from(users).where(and(eq(users.telegramChatId, chatId), eq(users.telegramUserId, fromId))); return u ?? null; } /** Owner and members of a project who paired Telegram: they get its agents' questions. */ export async function questionRecipients(db: Db, projectId: number): Promise { const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId)); const members = await db.select({ id: projectMembers.userId }).from(projectMembers).where(eq(projectMembers.projectId, projectId)); const ids = [...new Set([p?.ownerId, ...members.map((m) => m.id)].filter((x): x is number => x != null))]; if (!ids.length) return []; return db.select().from(users).where(and(inArray(users.id, ids), isNotNull(users.telegramChatId))); } // PEP-85: every bot has its own update ids and offset. `botUserId` = the owner of a user's bot; // absent = the platform's shared bot (ids and the offset key as before). const offsetKey = (botUserId?: number) => (botUserId ? `${OFFSET}:u${botUserId}` : OFFSET); export const getOffset = async (db: Db, botUserId?: number) => (await getSetting(db, offsetKey(botUserId))) ?? 0; export const setOffset = (db: Db, offset: number, botUserId?: number) => setSetting(db, offsetKey(botUserId), offset); /** Update ids of different bots must not collide in `telegram_updates`. */ const updateKey = (updateId: number, botUserId?: number) => (botUserId ? botUserId * 2 ** 36 + updateId : updateId); /** Claims an update before acting on it. False = already taken (don't replay). */ export async function claimUpdate(db: Db, updateId: number, botUserId?: number): Promise { const rows = await db .insert(telegramUpdates) .values({ updateId: updateKey(updateId, botUserId), status: "dispatching" }) .onConflictDoNothing() .returning(); return rows.length > 0; } export async function finishUpdate(db: Db, updateId: number, status: "done" | "ignored" | "failed", botUserId?: number): Promise { await db.update(telegramUpdates).set({ status }).where(eq(telegramUpdates.updateId, updateKey(updateId, botUserId))); } // ── PEP-85: the user's own bot ─────────────────────────────────────────────────── export const BOT_TOKEN_RE = /^\d{5,15}:[A-Za-z0-9_-]{30,60}$/; export interface UserBot { userId: number; token: string; username: string; /** The chat the owner started the bot in (null until they press Start). */ chatId: number | null; } /** Asks Telegram who the token belongs to (`TELEGRAM_API_URL` for the mock). */ export async function verifyBotToken(token: string): Promise<{ id: number; username: string }> { const t = token.trim(); // glossary-ignore: «токен» — так эту строку называет сам BotFather, иначе человек не найдёт, что копировать if (!BOT_TOKEN_RE.test(t)) throw new PeppaError(tr("Это не похоже на токен бота. Он выглядит так: 1234567890:AAH… — скопируйте его целиком из сообщения BotFather")); let body: { ok?: boolean; result?: { id: number; username?: string; is_bot?: boolean }; description?: string }; try { const res = await fetch(`${process.env.TELEGRAM_API_URL ?? "https://api.telegram.org"}/bot${t}/getMe`, { signal: AbortSignal.timeout(15_000) }); body = (await res.json()) as typeof body; } catch { throw new PeppaError(tr("Telegram не ответил — попробуйте ещё раз через минуту")); } // glossary-ignore: «токен» — так эту строку называет сам BotFather, иначе человек не найдёт, что копировать if (!body.ok || !body.result?.username) throw new PeppaError(tr("Telegram не принял этот токен — проверьте, что скопировали его целиком, или получите новый в BotFather (/token)")); return { id: body.result.id, username: body.result.username }; } /** Connects the user's own bot. The chat pairing is dropped: the owner presses Start in the new bot. */ export async function setUserBot(db: Db, userId: number, token: string): Promise<{ username: string }> { const me = await verifyBotToken(token); const taken = (await db.select({ id: users.id, username: users.telegramBotUsername }).from(users).where(isNotNull(users.telegramBotUsername))).find((u) => u.id !== userId && u.username?.toLowerCase() === me.username.toLowerCase()); if (taken) throw new PeppaError(tr("Этот бот уже подключён другим пользователем — создайте своего в BotFather")); const [before] = await db.select({ username: users.telegramBotUsername }).from(users).where(eq(users.id, userId)); // PEP-109: another bot is not a member of the groups linked through the old one. if (before?.username && before.username.toLowerCase() !== me.username.toLowerCase()) await unlinkBotGroups(db, userId); await db .update(users) .set({ telegramBotTokenEnc: encrypt(token.trim()), telegramBotUsername: me.username, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) .where(eq(users.id, userId)); return { username: me.username }; } /** PEP-109: groups linked through this user's bot lose the link together with the bot. */ async function unlinkBotGroups(db: Db, userId: number): Promise { await db.update(chats).set({ tgChatId: null, tgTitle: null, tgLinkedAt: null, tgLinkedBy: null, tgBotUserId: null }).where(eq(chats.tgBotUserId, userId)); } /** Back to the platform's shared bot (the chat pairing and the groups of the bot are dropped too). */ export async function clearUserBot(db: Db, userId: number): Promise { await unlinkBotGroups(db, userId); await db .update(users) .set({ telegramBotTokenEnc: null, telegramBotUsername: null, telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null }) .where(eq(users.id, userId)); } /** Every connected own bot (the bot process polls them and sends through them). */ export async function userBots(db: Db): Promise { const rows = await db.select().from(users).where(isNotNull(users.telegramBotTokenEnc)); const out: UserBot[] = []; for (const u of rows) { if (u.disabledAt) continue; try { out.push({ userId: u.id, token: decrypt(u.telegramBotTokenEnc!), username: u.telegramBotUsername ?? "", chatId: u.telegramChatId }); } catch { // Unreadable after a key rotation gone wrong: skipped, the secrets audit shows it. } } return out; } /** Queues a Bot API call; a no-op if `dedupeKey` was queued before. */ export async function enqueueTelegram( db: Db, m: { dedupeKey: string; method: OutboxRow["method"]; params: Record; questionId?: number; chatMessageId?: number }, ): Promise { const rows = await db.insert(telegramOutbox).values(m).onConflictDoNothing().returning(); return rows.length > 0; } export async function getOutbox(db: Db, dedupeKey: string): Promise { const [row] = await db.select().from(telegramOutbox).where(eq(telegramOutbox.dedupeKey, dedupeKey)); return row ?? null; } /** Due rows; PEP-208: in the night silence only edits of messages already sent. */ export async function dueOutbox(db: Db, limit = 20, now = new Date()): Promise { return db .select() .from(telegramOutbox) .where(and(eq(telegramOutbox.status, "pending"), lte(telegramOutbox.nextAttemptAt, now), inNightQuiet(now) ? eq(telegramOutbox.method, "editMessageText") : undefined)) .orderBy(asc(telegramOutbox.id)) .limit(limit); } export async function markOutboxSent(db: Db, row: OutboxRow, telegramMessageId: number | null): Promise { await db .update(telegramOutbox) .set({ status: "sent", sentAt: new Date(), telegramMessageId, attempts: row.attempts + 1, error: null }) .where(eq(telegramOutbox.id, row.id)); if (row.method === "sendMessage" && row.questionId && telegramMessageId) { await db.update(questions).set({ telegramMessageId }).where(eq(questions.id, row.questionId)); } } const MAX_ATTEMPTS = 8; /** Schedules a retry (honouring Telegram's retry_after), or gives up after MAX_ATTEMPTS. */ export async function markOutboxRetry(db: Db, row: OutboxRow, error: string, retryAfterSec?: number): Promise { const attempts = row.attempts + 1; const delayMs = retryAfterSec != null ? retryAfterSec * 1000 : Math.min(60_000, 1000 * 2 ** attempts); await db .update(telegramOutbox) .set({ attempts, error, status: attempts >= MAX_ATTEMPTS ? "failed" : "pending", nextAttemptAt: new Date(Date.now() + delayMs), }) .where(eq(telegramOutbox.id, row.id)); } /** The question a bot message in this chat is about (message ids are per chat). */ export async function questionByTelegramMessage(db: Db, chatId: number, messageId: number) { const [row] = await db .select({ q: questions }) .from(telegramOutbox) .innerJoin(questions, eq(telegramOutbox.questionId, questions.id)) .where( and( eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.telegramMessageId, messageId), // json_extract, not ->>: chat_id may be stored as a number or a string. sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`, ), ); return row?.q ?? null; } /** PEP-151: the Telegram messages a question was delivered as (personal chats and linked groups). */ export async function sentQuestionMessages(db: Db, questionId: number): Promise { return db .select() .from(telegramOutbox) .where(and(eq(telegramOutbox.questionId, questionId), eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId))); } /** Key of the edit that refreshes a delivered message when its question's state came again. */ export const repeatEditKey = (outboxId: number, repeats: number) => `qe:${outboxId}:${repeats}`; export const isRepeatEdit = (row: Pick) => row.method === "editMessageText" && row.dedupeKey.startsWith("qe:"); /** When a delivered message was last queued for such a refresh (edits are rate-limited). */ export async function lastRepeatEdit(db: Db, outboxId: number): Promise { const [row] = await db.select({ at: telegramOutbox.createdAt }).from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `qe:${outboxId}:%`)).orderBy(desc(telegramOutbox.id)).limit(1); return row?.at ?? null; } /** Delivered question messages whose question got answered since `since` (to close them). */ export async function answeredQuestionMessages(db: Db, since: Date) { return db .select({ sent: telegramOutbox, q: questions }) .from(telegramOutbox) .innerJoin(questions, eq(telegramOutbox.questionId, questions.id)) .where(and(eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), gt(questions.answeredAt, since))); }