Spaces:
Starting
Starting
File size: 5,798 Bytes
170b9b6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | /**
* Telegram webhook controller (POST /api/webhooks/telegram).
*
* Steps:
* 1. Optionally verify X-Telegram-Bot-Api-Secret-Token header.
* 2. Dedupe by provider_event_id in webhook_events (onConflictDoNothing).
* 3. Normalize the Telegram update to NormalizedInboundMessage.
* 4. Call ConversationsService.ingestInbound.
* 5. Emit Inngest events (message.received + evidence.uploaded per item).
*
* Day 2 is INBOUND ONLY β no messages are sent back (CLAUDE.md #2, #3).
*/
import { Controller, Headers, HttpCode, HttpException, HttpStatus, Inject, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { eq } from "drizzle-orm";
import { type Database, webhookEvents } from "@courtmitra/db";
import type { NormalizedInboundMessage } from "@courtmitra/contracts";
import { DB } from "../db/db.module.js";
import { ConversationsService } from "../conversations/conversations.service.js";
import { WorkflowService } from "../workflow/inngest.module.js";
// ---- Telegram update shape (minimal, only what we need) -------------------
interface TgPhotoSize {
file_id: string;
file_size?: number;
width: number;
height: number;
}
interface TgDocument {
file_id: string;
mime_type?: string;
file_name?: string;
}
interface TgMessage {
message_id: number;
chat: { id: number };
from?: { id: number; username?: string; first_name?: string };
text?: string;
photo?: TgPhotoSize[];
document?: TgDocument;
}
interface TgUpdate {
update_id: number;
message?: TgMessage;
}
function pickLargestPhoto(photos: TgPhotoSize[]): TgPhotoSize | undefined {
return photos.reduce<TgPhotoSize | undefined>((best, p) => {
if (!best) return p;
return (p.file_size ?? 0) > (best.file_size ?? 0) ? p : best;
}, undefined);
}
function normalizeTelegramUpdate(update: TgUpdate): NormalizedInboundMessage | null {
const msg = update.message;
if (!msg) return null; // e.g. edited_message, callback_query β ignore for now
const chatId = String(msg.chat.id);
const fromId = String(msg.from?.id ?? chatId);
const media: NormalizedInboundMessage["media"] = [];
if (msg.photo) {
const largest = pickLargestPhoto(msg.photo);
if (largest) {
media.push({ kind: "photo", providerFileId: largest.file_id, mimeType: "image/jpeg", filename: null });
}
}
if (msg.document) {
media.push({
kind: "document",
providerFileId: msg.document.file_id,
mimeType: msg.document.mime_type ?? null,
filename: msg.document.file_name ?? null,
});
}
return {
channel: "telegram",
externalThreadId: chatId,
providerMessageId: String(msg.message_id),
fromSubject: fromId,
text: msg.text ?? null,
media,
rawPayloadRef: update,
};
}
// ---------------------------------------------------------------------------
@Controller("webhooks/telegram")
export class TelegramWebhookController {
constructor(
@Inject(DB) private readonly db: Database,
@Inject(ConversationsService) private readonly conversations: ConversationsService,
@Inject(WorkflowService) private readonly workflow: WorkflowService,
) {}
@Post()
@HttpCode(200)
async handleUpdate(
@Req() req: FastifyRequest,
@Headers("x-telegram-bot-api-secret-token") secretToken?: string,
) {
// 1. Secret token verification.
// Fix 13: in production, reject requests if the secret is unset.
const expectedSecret = process.env["TELEGRAM_WEBHOOK_SECRET"];
if (!expectedSecret && process.env["NODE_ENV"] === "production") {
throw new HttpException("Forbidden: TELEGRAM_WEBHOOK_SECRET not configured", HttpStatus.FORBIDDEN);
}
if (expectedSecret && secretToken !== expectedSecret) {
throw new HttpException("Forbidden", HttpStatus.FORBIDDEN);
}
const update = req.body as TgUpdate;
if (!update || typeof update.update_id !== "number") {
return { ok: true, skipped: "no update_id" };
}
const providerEventId = `telegram:${update.update_id}`;
// 2. Dedupe insert β if already processed, return early
const [inserted] = await this.db
.insert(webhookEvents)
.values({
provider: "telegram",
providerEventId,
payload: update as unknown as Record<string, unknown>,
})
.onConflictDoNothing()
.returning();
if (!inserted) {
return { ok: true, deduped: true };
}
// 3. Normalize
const normalized = normalizeTelegramUpdate(update);
if (!normalized) {
// Mark as processed but nothing to ingest
await this.db
.update(webhookEvents)
.set({ processedAt: new Date() })
.where(eq(webhookEvents.id, inserted.id));
return { ok: true, skipped: "unsupported update type" };
}
// 4. Ingest
const result = await this.conversations.ingestInbound(normalized, {});
// 5. Emit Inngest events
try {
// Emit message.received unconditionally β photo-only messages must also trigger intake.
await this.workflow.send("message.received", {
missionId: result.missionId,
conversationId: result.conversationId,
messageId: result.messageId,
});
for (const evidenceItemId of result.evidenceItemIds) {
await this.workflow.send("evidence.uploaded", {
missionId: result.missionId,
evidenceItemId,
});
}
} catch (err) {
// Inngest dev server may not be running β log but don't fail the webhook
console.warn("[telegram webhook] Inngest send failed (non-fatal):", String(err));
}
// Mark webhook event as processed
await this.db
.update(webhookEvents)
.set({ processedAt: new Date() })
.where(eq(webhookEvents.id, inserted.id));
return { ok: true };
}
}
|