Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

1.3 KB
Raw Blame
import type { Context } from 'hono';
import { bodyLimit } from 'hono/body-limit';
import { z } from 'zod';

import { getServerDB } from '@/database/core/db-adaptor';
import {
  INBOUND_WEBHOOK_MAX_BODY_BYTES,
  receiveInboundWebhook,
} from '@/server/services/inboundWebhook/receiver';
import { scheduleInboundWebhookSweep } from '@/server/services/inboundWebhook/sweep';

export const inboundWebhookBodyLimit = bodyLimit({
  maxSize: INBOUND_WEBHOOK_MAX_BODY_BYTES,
  onError: (c) => c.json({ error: 'Payload too large' }, 413),
});

/** `POST /inbound/:id`: signed (MCP Events) or with `Authorization: Bearer <key>` (generic). */
export async function inboundWebhook(c: Context) {
  const id = c.req.param('id');
  if (!z.uuid().safeParse(id).success) return c.json({ error: 'Webhook is gone' }, 410);
  try {
    const result = await receiveInboundWebhook(await getServerDB(), {
      body: await c.req.text(),
      headers: c.req.raw.headers,
      id: id!,
      query: new URL(c.req.url).searchParams,
    });
    scheduleInboundWebhookSweep();
    if (result.retryAfter) c.header('Retry-After', String(result.retryAfter));
    return c.json(result.body, result.status);
  } catch {
    console.error('[inboundWebhook:route] Delivery failed');
    return c.json({ error: 'Delivery temporarily unavailable' }, 503);
  }
}