mirror of
https://github.com/xCyanGrizzly/DragonsStash.git
synced 2026-05-11 06:11:15 +00:00
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:
209
src/app/(app)/settings/_components/telegram-link-card.tsx
Normal file
209
src/app/(app)/settings/_components/telegram-link-card.tsx
Normal file
@@ -0,0 +1,209 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { Send, Link2, Unlink, Copy, Loader2, CheckCircle2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
generateTelegramLinkCode,
|
||||
unlinkTelegram,
|
||||
} from "../telegram-actions";
|
||||
|
||||
interface TelegramLinkCardProps {
|
||||
linked: boolean;
|
||||
telegramName: string | null;
|
||||
telegramUserId: string | null;
|
||||
linkedAt: string | null;
|
||||
botUsername?: string | null;
|
||||
}
|
||||
|
||||
export function TelegramLinkCard({
|
||||
linked: initialLinked,
|
||||
telegramName: initialName,
|
||||
telegramUserId: initialUserId,
|
||||
linkedAt: initialLinkedAt,
|
||||
botUsername,
|
||||
}: TelegramLinkCardProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [linked, setLinked] = useState(initialLinked);
|
||||
const [telegramName, setTelegramName] = useState(initialName);
|
||||
const [telegramUserId, setTelegramUserId] = useState(initialUserId);
|
||||
const [linkedAt, setLinkedAt] = useState(initialLinkedAt);
|
||||
const [linkCode, setLinkCode] = useState<string | null>(null);
|
||||
const [codeExpiresAt, setCodeExpiresAt] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
function handleGenerateCode() {
|
||||
startTransition(async () => {
|
||||
const result = await generateTelegramLinkCode();
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
setLinkCode(result.data.code);
|
||||
setCodeExpiresAt(result.data.expiresAt);
|
||||
toast.success("Link code generated! Send it to the bot within 10 minutes.");
|
||||
});
|
||||
}
|
||||
|
||||
function handleUnlink() {
|
||||
startTransition(async () => {
|
||||
const result = await unlinkTelegram();
|
||||
if (!result.success) {
|
||||
toast.error(result.error);
|
||||
return;
|
||||
}
|
||||
setLinked(false);
|
||||
setTelegramName(null);
|
||||
setTelegramUserId(null);
|
||||
setLinkedAt(null);
|
||||
setLinkCode(null);
|
||||
toast.success("Telegram account unlinked");
|
||||
});
|
||||
}
|
||||
|
||||
async function handleCopy() {
|
||||
if (!linkCode) return;
|
||||
const command = `/link ${linkCode}`;
|
||||
await navigator.clipboard.writeText(command);
|
||||
setCopied(true);
|
||||
toast.success("Copied to clipboard");
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
|
||||
const botLink = botUsername
|
||||
? `https://t.me/${botUsername}?start=link_${linkCode}`
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Send className="h-5 w-5 text-primary" />
|
||||
<CardTitle>Telegram Link</CardTitle>
|
||||
{linked ? (
|
||||
<Badge variant="default" className="ml-auto">
|
||||
Linked
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="ml-auto">
|
||||
Not linked
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardDescription>
|
||||
Link your account to receive packages via the Telegram bot.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{linked ? (
|
||||
<>
|
||||
<div className="rounded-lg border p-4 space-y-2 bg-muted/30">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground">Telegram:</span>
|
||||
<span className="font-medium">
|
||||
{telegramName ?? `User ${telegramUserId}`}
|
||||
</span>
|
||||
</div>
|
||||
{linkedAt && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>Linked:</span>
|
||||
<span>{new Date(linkedAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={handleUnlink}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-1" />
|
||||
) : (
|
||||
<Unlink className="h-4 w-4 mr-1" />
|
||||
)}
|
||||
Unlink Account
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{linkCode ? (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border p-4 space-y-2 bg-muted/30">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Send this command to the bot:
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 rounded bg-background px-3 py-2 text-sm font-mono border">
|
||||
/link {linkCode}
|
||||
</code>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
onClick={handleCopy}
|
||||
>
|
||||
{copied ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{codeExpiresAt && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Expires:{" "}
|
||||
{new Date(codeExpiresAt).toLocaleTimeString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{botLink && (
|
||||
<a
|
||||
href={botLink}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
|
||||
>
|
||||
<Send className="h-3.5 w-3.5" />
|
||||
Or click here to open the bot directly
|
||||
</a>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleGenerateCode}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending && <Loader2 className="h-4 w-4 animate-spin mr-1" />}
|
||||
Generate New Code
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={handleGenerateCode}
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-1" />
|
||||
) : (
|
||||
<Link2 className="h-4 w-4 mr-1" />
|
||||
)}
|
||||
Generate Link Code
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -3,12 +3,19 @@ import { redirect } from "next/navigation";
|
||||
import { getUserSettings } from "@/data/settings.queries";
|
||||
import { PageHeader } from "@/components/shared/page-header";
|
||||
import { SettingsForm } from "./_components/settings-form";
|
||||
import { TelegramLinkCard } from "./_components/telegram-link-card";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export default async function SettingsPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) redirect("/login");
|
||||
|
||||
const settings = await getUserSettings(session.user.id);
|
||||
const [settings, telegramLink] = await Promise.all([
|
||||
getUserSettings(session.user.id),
|
||||
prisma.telegramLink.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
}),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -16,10 +23,17 @@ export default async function SettingsPage() {
|
||||
title="Settings"
|
||||
description="Manage your application preferences"
|
||||
/>
|
||||
<div className="max-w-2xl">
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<SettingsForm
|
||||
settings={JSON.parse(JSON.stringify(settings))}
|
||||
/>
|
||||
<TelegramLinkCard
|
||||
linked={!!telegramLink}
|
||||
telegramName={telegramLink?.telegramName ?? null}
|
||||
telegramUserId={telegramLink?.telegramUserId?.toString() ?? null}
|
||||
linkedAt={telegramLink?.createdAt?.toISOString() ?? null}
|
||||
botUsername={process.env.BOT_USERNAME ?? null}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
171
src/app/(app)/settings/telegram-actions.ts
Normal file
171
src/app/(app)/settings/telegram-actions.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
"use server";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { ActionResult } from "@/types/api.types";
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
/**
|
||||
* Generate a one-time link code for the current user.
|
||||
* The user sends `/link <code>` to the bot to complete the link.
|
||||
* Code is stored in GlobalSetting as `link_code:<code>` → userId.
|
||||
* Codes expire after 10 minutes (checked by the bot).
|
||||
*/
|
||||
export async function generateTelegramLinkCode(): Promise<
|
||||
ActionResult<{ code: string; expiresAt: string }>
|
||||
> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
// Check if user already has a link
|
||||
const existing = await prisma.telegramLink.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
});
|
||||
if (existing) {
|
||||
return {
|
||||
success: false,
|
||||
error: "You already have a linked Telegram account. Unlink first to generate a new code.",
|
||||
};
|
||||
}
|
||||
|
||||
// Generate a short random code
|
||||
const code = randomBytes(4).toString("hex"); // 8 hex chars
|
||||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
|
||||
|
||||
// Store in GlobalSetting — overwrites any previous code for this user
|
||||
// First, clean up any previous codes for this user
|
||||
const existingCodes = await prisma.globalSetting.findMany({
|
||||
where: { key: { startsWith: "link_code:" } },
|
||||
});
|
||||
for (const setting of existingCodes) {
|
||||
try {
|
||||
const parsed = JSON.parse(setting.value);
|
||||
if (parsed.userId === session.user.id) {
|
||||
await prisma.globalSetting.delete({ where: { key: setting.key } });
|
||||
}
|
||||
} catch {
|
||||
// Skip malformed entries
|
||||
}
|
||||
}
|
||||
|
||||
// Store the new code
|
||||
await prisma.globalSetting.upsert({
|
||||
where: { key: `link_code:${code}` },
|
||||
update: {
|
||||
value: JSON.stringify({
|
||||
userId: session.user.id,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
}),
|
||||
},
|
||||
create: {
|
||||
key: `link_code:${code}`,
|
||||
value: JSON.stringify({
|
||||
userId: session.user.id,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { code, expiresAt: expiresAt.toISOString() },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current user's Telegram link status.
|
||||
*/
|
||||
export async function getTelegramLinkStatus(): Promise<
|
||||
ActionResult<{
|
||||
linked: boolean;
|
||||
telegramName: string | null;
|
||||
telegramUserId: string | null;
|
||||
linkedAt: string | null;
|
||||
}>
|
||||
> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const link = await prisma.telegramLink.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
linked: !!link,
|
||||
telegramName: link?.telegramName ?? null,
|
||||
telegramUserId: link?.telegramUserId?.toString() ?? null,
|
||||
linkedAt: link?.createdAt?.toISOString() ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlink the current user's Telegram account.
|
||||
*/
|
||||
export async function unlinkTelegram(): Promise<ActionResult> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const link = await prisma.telegramLink.findUnique({
|
||||
where: { userId: session.user.id },
|
||||
});
|
||||
|
||||
if (!link) {
|
||||
return { success: false, error: "No linked Telegram account found" };
|
||||
}
|
||||
|
||||
await prisma.telegramLink.delete({ where: { id: link.id } });
|
||||
|
||||
revalidatePath("/settings");
|
||||
return { success: true, data: undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent bot send requests for the current user (or all for admins).
|
||||
*/
|
||||
export async function getBotSendHistory(
|
||||
limit = 20
|
||||
): Promise<
|
||||
ActionResult<
|
||||
Array<{
|
||||
id: string;
|
||||
packageName: string;
|
||||
recipientName: string | null;
|
||||
status: string;
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
completedAt: string | null;
|
||||
}>
|
||||
>
|
||||
> {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
|
||||
|
||||
const isAdmin = session.user.role === "ADMIN";
|
||||
|
||||
const requests = await prisma.botSendRequest.findMany({
|
||||
where: isAdmin ? {} : { requestedByUserId: session.user.id },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit,
|
||||
include: {
|
||||
package: { select: { fileName: true } },
|
||||
telegramLink: { select: { telegramName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: requests.map((r: typeof requests[number]) => ({
|
||||
id: r.id,
|
||||
packageName: r.package.fileName,
|
||||
recipientName: r.telegramLink.telegramName,
|
||||
status: r.status,
|
||||
error: r.error,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
completedAt: r.completedAt?.toISOString() ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user