|
| 1 | +import { vValidator } from "@hono/valibot-validator"; |
| 2 | +import { captureException } from "@sentry/node"; |
| 3 | +import { Hono } from "hono"; |
| 4 | +import { validator } from "hono/validator"; |
| 5 | +import { createHmac, timingSafeEqual } from "node:crypto"; |
| 6 | +import * as v from "valibot"; |
| 7 | + |
| 8 | +import { own } from "../supervise"; |
| 9 | +import validatorHook from "../utils/validatorHook"; |
| 10 | +import createQueue from "../workers/chat/queue"; |
| 11 | + |
| 12 | +import type { Redis } from "ioredis"; |
| 13 | + |
| 14 | +export default function chat({ |
| 15 | + bullmq, |
| 16 | + whatsappFrom, |
| 17 | + whatsappSecret, |
| 18 | + whatsappVerifyToken, |
| 19 | +}: { |
| 20 | + bullmq: Redis; |
| 21 | + whatsappFrom: string; |
| 22 | + whatsappSecret?: string; |
| 23 | + whatsappVerifyToken?: string; |
| 24 | +}) { |
| 25 | + bullmq.on("error", (error: unknown) => captureException(error)); |
| 26 | + const queue = createQueue(bullmq); |
| 27 | + const app = new Hono() |
| 28 | + .get( |
| 29 | + "/", |
| 30 | + vValidator( |
| 31 | + "query", |
| 32 | + v.object({ |
| 33 | + "hub.mode": v.literal("subscribe"), |
| 34 | + "hub.verify_token": v.string(), |
| 35 | + "hub.challenge": v.string(), |
| 36 | + }), |
| 37 | + validatorHook({ code: "bad verification" }), |
| 38 | + ), |
| 39 | + (c) => |
| 40 | + c.req.valid("query")["hub.verify_token"] === whatsappVerifyToken |
| 41 | + ? c.text(c.req.valid("query")["hub.challenge"]) |
| 42 | + : c.json({ code: "invalid verify token" }, 403), |
| 43 | + ) |
| 44 | + .post( |
| 45 | + "/", |
| 46 | + validator("header", async ({ "x-hub-signature-256": signature }, c) => { |
| 47 | + if (!verify(await c.req.text(), signature, whatsappSecret)) return c.json({ code: "invalid signature" }, 401); |
| 48 | + }), |
| 49 | + vValidator("json", event, validatorHook({ code: "bad chat" })), |
| 50 | + async (c) => { |
| 51 | + const delivered = parse(c.req.valid("json")); |
| 52 | + const foreign = [...new Set(delivered.map(({ phoneNumberId }) => phoneNumberId))].filter( |
| 53 | + (phoneNumberId) => phoneNumberId !== whatsappFrom, |
| 54 | + ); |
| 55 | + if (foreign.length > 0) { |
| 56 | + captureException(new Error("chat delivered to another business number"), { |
| 57 | + level: "error", |
| 58 | + extra: { expected: whatsappFrom, foreign }, |
| 59 | + }); |
| 60 | + } |
| 61 | + const messages = new Map( |
| 62 | + delivered |
| 63 | + .filter(({ phoneNumberId }) => phoneNumberId === whatsappFrom) |
| 64 | + .map((message) => [message.id, message] as const), |
| 65 | + ); |
| 66 | + const threads = new Map<string, [(typeof delivered)[number], ...(typeof delivered)[number][]]>(); |
| 67 | + for (const message of messages.values()) { |
| 68 | + const key = `${message.phoneNumberId}/${message.from}`; |
| 69 | + const thread = threads.get(key); |
| 70 | + if (thread) thread.push(message); |
| 71 | + else threads.set(key, [message]); |
| 72 | + } |
| 73 | + await Promise.all( |
| 74 | + [...threads.values()].map(([sender, ...tail]) => |
| 75 | + queue |
| 76 | + .enqueue({ |
| 77 | + id: sender.id, |
| 78 | + contact: sender.contact, |
| 79 | + from: sender.from, |
| 80 | + text: [sender, ...tail].map(({ text }) => text).join("\n"), |
| 81 | + }) |
| 82 | + .catch((error: unknown) => { |
| 83 | + captureException(error, { extra: { sender }, tags: { job: "chat", queue: "chat" } }); |
| 84 | + throw error; |
| 85 | + }), |
| 86 | + ), |
| 87 | + ); |
| 88 | + return c.json({ code: "ok" }); |
| 89 | + }, |
| 90 | + ); |
| 91 | + return own({ app, ready: Promise.resolve() }, () => queue.close()); |
| 92 | +} |
| 93 | + |
| 94 | +function verify(body: string, signature?: string, secret?: string) { |
| 95 | + if (!secret) return true; |
| 96 | + if (!signature) return false; |
| 97 | + const expected = Buffer.from(`sha256=${createHmac("sha256", secret).update(body).digest("hex")}`); |
| 98 | + const received = Buffer.from(signature); |
| 99 | + return received.length === expected.length && timingSafeEqual(received, expected); |
| 100 | +} |
| 101 | + |
| 102 | +function parse({ entry }: v.InferOutput<typeof event>) { |
| 103 | + return entry.flatMap(({ changes }) => |
| 104 | + changes.flatMap(({ value: { contacts, messages, metadata } }) => |
| 105 | + (messages ?? []).flatMap((message) => |
| 106 | + message.text |
| 107 | + ? [ |
| 108 | + { |
| 109 | + id: message.id, |
| 110 | + from: message.from_user_id, |
| 111 | + text: message.text.body, |
| 112 | + contact: contacts?.find(({ user_id }) => user_id === message.from_user_id)?.profile?.name, |
| 113 | + phoneNumberId: metadata.phone_number_id, |
| 114 | + }, |
| 115 | + ] |
| 116 | + : [], |
| 117 | + ), |
| 118 | + ), |
| 119 | + ); |
| 120 | +} |
| 121 | + |
| 122 | +const event = v.object({ |
| 123 | + entry: v.array( |
| 124 | + v.object({ |
| 125 | + changes: v.array( |
| 126 | + v.object({ |
| 127 | + value: v.object({ |
| 128 | + metadata: v.object({ phone_number_id: v.string() }), |
| 129 | + contacts: v.optional( |
| 130 | + v.array( |
| 131 | + v.object({ |
| 132 | + user_id: v.string(), |
| 133 | + profile: v.optional(v.object({ name: v.optional(v.string()) })), |
| 134 | + }), |
| 135 | + ), |
| 136 | + ), |
| 137 | + messages: v.optional( |
| 138 | + v.array( |
| 139 | + v.object({ |
| 140 | + id: v.string(), |
| 141 | + from_user_id: v.string(), |
| 142 | + type: v.string(), |
| 143 | + text: v.optional(v.object({ body: v.string() })), |
| 144 | + }), |
| 145 | + ), |
| 146 | + ), |
| 147 | + }), |
| 148 | + }), |
| 149 | + ), |
| 150 | + }), |
| 151 | + ), |
| 152 | +}); |
0 commit comments