peppa/packages/core/src/telegram.ts
2026-11-16 09:52:35 +05:00

248 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.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<string> {
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<User | null> {
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<void> {
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<User | null> {
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<User[]> {
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<number>(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<boolean> {
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<void> {
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<void> {
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<void> {
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<UserBot[]> {
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<string, unknown>; questionId?: number; chatMessageId?: number },
): Promise<boolean> {
const rows = await db.insert(telegramOutbox).values(m).onConflictDoNothing().returning();
return rows.length > 0;
}
export async function getOutbox(db: Db, dedupeKey: string): Promise<OutboxRow | null> {
const [row] = await db.select().from(telegramOutbox).where(eq(telegramOutbox.dedupeKey, dedupeKey));
return row ?? null;
}
export async function dueOutbox(db: Db, limit = 20): Promise<OutboxRow[]> {
return db
.select()
.from(telegramOutbox)
.where(and(eq(telegramOutbox.status, "pending"), lte(telegramOutbox.nextAttemptAt, new Date())))
.orderBy(asc(telegramOutbox.id))
.limit(limit);
}
export async function markOutboxSent(db: Db, row: OutboxRow, telegramMessageId: number | null): Promise<void> {
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<void> {
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;
}
/** 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)));
}