feat: Docker audit + Telegram bot service + send UI

Docker:
- Harden docker-compose.yml: parameterized DB creds, required AUTH_SECRET,
  health checks, resource limits, network isolation, removed exposed DB port
- Add profiles (telegram/bot/full) so base 'docker compose up' needs only AUTH_SECRET
- Fix docker-entrypoint.sh: AUTH_SECRET startup guard
- Fix Dockerfile: copy prisma.config.ts + dotenv into production image
- Update .env.example with all new variables
- Update .dockerignore

Telegram Bot Service (bot/):
- TDLib-based bot using bot token auth (not HTTP Bot API)
- Commands: /search, /latest, /package, /link, /unlink, /subscribe, /unsubscribe
- pg_notify listener for send requests (bot_send) and new packages (new_package)
- Subscription-based notifications when matching packages arrive
- Dockerfile with multi-stage build (bookworm-slim for glibc/TDLib)

API & Database:
- Prisma: TelegramLink, BotSendRequest, BotSubscription models + migration
- POST /api/telegram/bot/send - queue package delivery to linked TG account
- GET /api/telegram/bot/send/[id] - poll send request status
- Server actions: generateTelegramLinkCode, unlinkTelegram, getBotSendHistory
- Worker: emit pg_notify('new_package') after creating packages

Frontend:
- Settings: TelegramLinkCard for account linking via one-time code
- STL table + drawer: SendToTelegramButton with send dialog and status polling
- Telegram admin: Bot Sends tab with delivery history table
- Shared SendHistoryRow type

README: Updated with bot docs, profiles, config vars, project structure
This commit is contained in:
2026-03-03 21:36:57 +01:00
parent 4d0df6b1a4
commit 575ffdbc31
36 changed files with 4516 additions and 37 deletions

92
bot/src/index.ts Normal file
View File

@@ -0,0 +1,92 @@
import { config } from "./util/config.js";
import { logger } from "./util/logger.js";
import { db, pool } from "./db/client.js";
import { createBotClient, closeBotClient, onBotUpdate } from "./tdlib/client.js";
import { startSendListener, stopSendListener } from "./send-listener.js";
import { handleMessage } from "./commands.js";
import { mkdir } from "fs/promises";
const log = logger.child({ module: "main" });
async function main(): Promise<void> {
log.info("DragonsStash Telegram Bot starting");
if (!config.botToken) {
log.fatal("BOT_TOKEN environment variable is required");
process.exit(1);
}
if (!config.telegramApiId || !config.telegramApiHash) {
log.fatal("TELEGRAM_API_ID and TELEGRAM_API_HASH are required");
process.exit(1);
}
// Ensure TDLib state directory exists
await mkdir(config.tdlibStateDir, { recursive: true });
await mkdir(`${config.tdlibStateDir}/bot`, { recursive: true });
await mkdir(`${config.tdlibStateDir}/bot_files`, { recursive: true });
// Initialize TDLib bot client
await createBotClient();
// Start pg_notify listener for send requests and new package notifications
await startSendListener();
// Listen for incoming messages from Telegram users
onBotUpdate((update) => {
if (update._ === "updateNewMessage") {
const message = update.message as Record<string, unknown>;
const content = message.content as Record<string, unknown>;
const chatId = message.chat_id as number;
const senderId = message.sender_id as Record<string, unknown> | undefined;
// Only handle text messages from users (not channels or service messages)
if (
content?._ === "messageText" &&
senderId?._ === "messageSenderUser"
) {
const text = (content.text as Record<string, unknown>)?.text as string;
const userId = senderId.user_id as number;
if (text && userId) {
// Get user info for display name (async but fire-and-forget for perf)
handleMessage({
chatId: BigInt(chatId),
userId: BigInt(userId),
text,
firstName: "User", // TDLib provides this via a separate getUser call
username: undefined,
}).catch((err) => {
log.error({ err, chatId, userId }, "Failed to handle message");
});
}
}
}
});
log.info("Bot is running and listening for messages");
}
// Graceful shutdown
function shutdown(signal: string): void {
log.info({ signal }, "Shutdown signal received");
stopSendListener();
Promise.all([closeBotClient(), db.$disconnect(), pool.end()])
.then(() => {
log.info("Shutdown complete");
process.exit(0);
})
.catch((err) => {
log.error({ err }, "Error during shutdown");
process.exit(1);
});
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
main().catch((err) => {
log.fatal({ err }, "Bot failed to start");
process.exit(1);
});