Initial commit: page-manager Next.js app with Coolify deploy support
Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents for deployment to Coolify: in-container cron scheduler (scripts/cron-runner.mjs) and disk-based upload storage served via /api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health for container health checks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { FacebookApiError } from "@/lib/facebook/client";
|
||||
import { getPageCredentialsByFbId, type PageCredentials } from "@/lib/facebook/tokens";
|
||||
import { replyToComment, sendImageMessage, sendPrivateReply, sendSenderAction, sendTextMessage } from "@/lib/facebook/inbox";
|
||||
import { claimReplySlot, matchRule, releaseReplySlot, typingDelayMs } from "@/lib/inbox/autoReply";
|
||||
|
||||
// Meta calls this with no session: GET proves ownership via the verify token,
|
||||
// POST proves authenticity via the X-Hub-Signature-256 HMAC. Listed in
|
||||
// SELF_AUTH_PREFIXES in src/proxy.ts. node:crypto needs the Node runtime.
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
export function GET(req: Request) {
|
||||
const url = new URL(req.url);
|
||||
const expected = process.env.META_WEBHOOK_VERIFY_TOKEN;
|
||||
if (
|
||||
!expected ||
|
||||
url.searchParams.get("hub.mode") !== "subscribe" ||
|
||||
url.searchParams.get("hub.verify_token") !== expected ||
|
||||
!url.searchParams.get("hub.challenge")
|
||||
) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
return new NextResponse(url.searchParams.get("hub.challenge"), { status: 200 });
|
||||
}
|
||||
|
||||
function isValidSignature(rawBody: string, header: string | null): boolean {
|
||||
const secret = process.env.META_APP_SECRET;
|
||||
if (!secret || !header?.startsWith("sha256=")) return false;
|
||||
const expected = Buffer.from(createHmac("sha256", secret).update(rawBody).digest("hex"), "hex");
|
||||
const provided = Buffer.from(header.slice("sha256=".length), "hex");
|
||||
return expected.length === provided.length && timingSafeEqual(expected, provided);
|
||||
}
|
||||
|
||||
interface MessagingEvent {
|
||||
sender?: { id?: string };
|
||||
message?: { mid?: string; text?: string; is_echo?: boolean };
|
||||
}
|
||||
interface ChangeValue {
|
||||
// Facebook "feed"
|
||||
item?: string;
|
||||
verb?: string;
|
||||
comment_id?: string;
|
||||
post_id?: string;
|
||||
message?: string;
|
||||
from?: { id?: string };
|
||||
// Instagram "comments": id / text / media.id
|
||||
id?: string;
|
||||
text?: string;
|
||||
media?: { id?: string };
|
||||
}
|
||||
interface Entry {
|
||||
id?: string;
|
||||
messaging?: MessagingEvent[];
|
||||
changes?: { field?: string; value?: ChangeValue }[];
|
||||
}
|
||||
|
||||
function extractComment(field: string, v: ChangeValue) {
|
||||
if (field === "feed") {
|
||||
if (v.item !== "comment" || v.verb !== "add") return null;
|
||||
if (!v.from?.id || !v.comment_id || !v.message) return null;
|
||||
return { platform: "facebook" as const, commenterId: v.from.id, commentId: v.comment_id, text: v.message };
|
||||
}
|
||||
if (field === "comments") {
|
||||
if (!v.from?.id || !v.id || !v.text) return null;
|
||||
return { platform: "instagram" as const, commenterId: v.from.id, commentId: v.id, text: v.text };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleComment(page: PageCredentials, field: string, value: ChangeValue) {
|
||||
const c = extractComment(field, value);
|
||||
if (!c) return;
|
||||
if (c.commenterId === page.fbPageId || c.commenterId === page.igUserId) return; // the page's own reply
|
||||
|
||||
const rule = await matchRule(page.id, "COMMENT", c.text);
|
||||
if (!rule) return;
|
||||
if (!(await claimReplySlot(rule.id, c.commenterId, c.commentId))) return;
|
||||
|
||||
try {
|
||||
await sendPrivateReply(page, c.commentId, rule.reply);
|
||||
if (rule.publicAck) {
|
||||
await replyToComment(page, c.commentId, rule.publicAck, c.platform).catch((e) =>
|
||||
console.error(`[webhook:comment] public ack failed comment=${c.commentId}`, e)
|
||||
);
|
||||
}
|
||||
console.info(`[webhook:comment] page=${page.fbPageId} rule=${rule.id} to=${c.commenterId}`);
|
||||
} catch (e) {
|
||||
// (#100) subcode 33: private replies only exist for comments on the page's
|
||||
// own posts — a Group comment fails identically on every retry, so keep the slot.
|
||||
if (e instanceof FacebookApiError && e.code === 100 && e.subcode === 33) {
|
||||
console.info(`[webhook:comment] private reply unsupported (likely a Group post) comment=${c.commentId}`);
|
||||
return;
|
||||
}
|
||||
console.error(`[webhook:comment] private reply failed rule=${rule.id}`, e);
|
||||
await releaseReplySlot(rule.id, c.commenterId);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMessage(page: PageCredentials, platform: "FACEBOOK" | "INSTAGRAM", event: MessagingEvent) {
|
||||
if (event.message?.is_echo) return;
|
||||
const psid = event.sender?.id;
|
||||
if (!psid || psid === page.fbPageId || psid === page.igUserId) return;
|
||||
|
||||
const convo = await prisma.conversation.upsert({
|
||||
where: { pageId_platform_psid: { pageId: page.id, platform, psid } },
|
||||
create: { pageId: page.id, platform, psid, lastInboundAt: new Date() },
|
||||
update: { lastInboundAt: new Date() },
|
||||
});
|
||||
|
||||
const text = event.message?.text;
|
||||
// Message text is matched in memory only — never logged or stored.
|
||||
console.info(`[webhook:dm] page=${page.fbPageId} platform=${platform} from=${psid} hasText=${Boolean(text)}`);
|
||||
if (!text || !convo.botEnabled) return;
|
||||
|
||||
const rule = await matchRule(page.id, "DM", text);
|
||||
if (!rule) return;
|
||||
if (!(await claimReplySlot(rule.id, psid, event.message?.mid ?? `dm-${Date.now()}`))) return;
|
||||
|
||||
try {
|
||||
if (platform === "FACEBOOK") {
|
||||
await sendSenderAction(page, psid, "mark_seen");
|
||||
await sendSenderAction(page, psid, "typing_on");
|
||||
await sleep(typingDelayMs(rule.reply));
|
||||
}
|
||||
await sendTextMessage(page, psid, rule.reply);
|
||||
if (rule.imageUrl) await sendImageMessage(page, psid, rule.imageUrl);
|
||||
} catch (e) {
|
||||
console.error(`[webhook:dm] auto-reply failed rule=${rule.id}`, e);
|
||||
await releaseReplySlot(rule.id, psid);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const rawBody = await req.text();
|
||||
if (!isValidSignature(rawBody, req.headers.get("x-hub-signature-256"))) {
|
||||
return new NextResponse("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
let body: { object?: string; entry?: Entry[] };
|
||||
try {
|
||||
body = JSON.parse(rawBody);
|
||||
} catch {
|
||||
return NextResponse.json({ received: true });
|
||||
}
|
||||
|
||||
const platform = body.object === "instagram" ? "INSTAGRAM" : "FACEBOOK";
|
||||
|
||||
for (const entry of body.entry ?? []) {
|
||||
if (!entry.id) continue;
|
||||
try {
|
||||
// Instagram entries carry the IG user id; map it back to the owning page.
|
||||
const page =
|
||||
platform === "INSTAGRAM"
|
||||
? await prisma.page
|
||||
.findFirst({ where: { igUserId: entry.id, status: { not: "DISCONNECTED" } }, select: { fbPageId: true } })
|
||||
.then((p) => (p ? getPageCredentialsByFbId(p.fbPageId) : null))
|
||||
: await getPageCredentialsByFbId(entry.id);
|
||||
if (!page) continue; // not a page we manage
|
||||
|
||||
for (const change of entry.changes ?? []) {
|
||||
if (change.value) await handleComment(page, change.field ?? "", change.value);
|
||||
}
|
||||
for (const event of entry.messaging ?? []) {
|
||||
await handleMessage(page, platform, event);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[webhook] entry ${entry.id} failed`, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Always 200 once the signature is valid: a non-200 makes Meta redeliver repeatedly.
|
||||
return NextResponse.json({ received: true });
|
||||
}
|
||||
Reference in New Issue
Block a user