@theokit/gateway-whatsapp 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3158f63: The `whatsappChannel` Cloud variant and `smsChannel` descriptors now declare `transport: "webhook"` with a `webhook.handle`, so a host mounts them with `createWebhookHandler`. WhatsApp answers Meta's subscription check and verifies `x-hub-signature-256`; SMS verifies Twilio's signature against the configured `publicUrl`. The Express listeners are unchanged.
8
+
3
9
  ## 0.8.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -228,8 +228,25 @@ descriptor itself is the `cloud` shape.
228
228
  | `baileys` | `botPhoneId` | `WHATSAPP_BOT_PHONE_ID` | no | no |
229
229
  | both | `requireMention` | `WHATSAPP_REQUIRE_MENTION` | no | no |
230
230
 
231
- `verifyToken` is not an adapter option: it is kept so the webhook half can answer Meta's
232
- subscription check.
231
+ `verifyToken` is not an adapter option: the webhook half uses it to answer Meta's subscription
232
+ check. The `cloud` descriptor declares `transport: "webhook"` with `methods: ["GET", "POST"]`;
233
+ `baileys` stays `"socket"`.
234
+
235
+ ### Mounting the route
236
+
237
+ GET answers the subscription check (200 with `hub.challenge` as `text/plain`, else 403). POST checks
238
+ `x-hub-signature-256` with `appSecret` (401 on a mismatch), answers 400 for a body that is not JSON,
239
+ delivers each event and answers 200 (500 or 503 when the handler threw or none is subscribed).
240
+
241
+ ```ts
242
+ import { createChannels, createWebhookHandler, selectVariant } from "@theokit/gateway";
243
+ import { whatsappChannel } from "@theokit/gateway-whatsapp";
244
+
245
+ const descriptor = selectVariant(whatsappChannel, "cloud");
246
+ const { channels } = createChannels([{ descriptor, config }]);
247
+ const handle = createWebhookHandler({ channels, isStarted: () => true });
248
+ // GET and POST /webhooks/whatsapp -> handle(request)
249
+ ```
233
250
 
234
251
  ```ts
235
252
  import { configFromEnv, createChannels, selectVariant } from "@theokit/gateway";
package/dist/index.cjs CHANGED
@@ -2193,6 +2193,122 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
2193
2193
  async deliver(event) {
2194
2194
  return this.runHandler(this.handler, event);
2195
2195
  }
2196
+ /**
2197
+ * Deliver like {@link deliver}, but a throwing handler is logged by name only: its message can
2198
+ * carry the inbound text, which the webhook route must not write to a log line.
2199
+ *
2200
+ * @internal
2201
+ */
2202
+ async deliverQuietly(event) {
2203
+ const handler = this.handler;
2204
+ if (handler === void 0) return "no_handler";
2205
+ try {
2206
+ await handler(event);
2207
+ } catch {
2208
+ process.stderr.write(`[whatsapp] handler threw
2209
+ `);
2210
+ return "handler_threw";
2211
+ }
2212
+ return "ok";
2213
+ }
2214
+ };
2215
+ var configs = /* @__PURE__ */ new WeakMap();
2216
+ function rememberWebhookConfig(adapter, config) {
2217
+ configs.set(adapter, config);
2218
+ }
2219
+ function headerValue(headers, name) {
2220
+ for (const [key, value] of Object.entries(headers)) {
2221
+ if (key.toLowerCase() === name) return value;
2222
+ }
2223
+ return void 0;
2224
+ }
2225
+ function safeEqual(a, b) {
2226
+ const ha = crypto.createHash("sha256").update(a).digest();
2227
+ const hb = crypto.createHash("sha256").update(b).digest();
2228
+ return crypto.timingSafeEqual(ha, hb);
2229
+ }
2230
+ function statusFor(outcomes) {
2231
+ let status = 200;
2232
+ for (const outcome of outcomes) {
2233
+ if (outcome === "handler_threw") status = 500;
2234
+ else if (outcome === "no_handler" && status === 200) status = 503;
2235
+ }
2236
+ return status;
2237
+ }
2238
+ function signatureValid(adapter, request) {
2239
+ const config = configs.get(adapter);
2240
+ if (config === void 0 || config.appSecret.trim().length === 0) return false;
2241
+ const header = headerValue(request.headers, "x-hub-signature-256");
2242
+ return verifyWebhookSignature(request.rawBody, header, config.appSecret);
2243
+ }
2244
+ function subscriptionChallenge(adapter, request) {
2245
+ const expected = configs.get(adapter)?.verifyToken;
2246
+ if (expected === void 0 || expected.length === 0 || request.url === void 0) {
2247
+ return void 0;
2248
+ }
2249
+ let params;
2250
+ try {
2251
+ params = new URL(request.url).searchParams;
2252
+ } catch {
2253
+ return void 0;
2254
+ }
2255
+ const token = params.get("hub.verify_token");
2256
+ const challenge = params.get("hub.challenge");
2257
+ if (params.get("hub.mode") !== "subscribe" || token === null || !safeEqual(token, expected)) {
2258
+ return void 0;
2259
+ }
2260
+ return challenge === null || challenge.length === 0 ? void 0 : challenge;
2261
+ }
2262
+ function requestValid(adapter, request) {
2263
+ const method = request.method?.toUpperCase();
2264
+ if (method === "GET") return subscriptionChallenge(adapter, request) !== void 0;
2265
+ if (method === "POST") return signatureValid(adapter, request);
2266
+ return false;
2267
+ }
2268
+ function isEnvelope(payload) {
2269
+ return payload !== null && typeof payload === "object" && !Array.isArray(payload);
2270
+ }
2271
+ async function deliverEnvelope(adapter, payload) {
2272
+ const outcomes = await deliverAll(adapter, payload);
2273
+ if (outcomes === void 0) return "malformed";
2274
+ return statusFor(outcomes) === 200 ? "delivered" : "no_handler";
2275
+ }
2276
+ async function deliverAll(adapter, payload) {
2277
+ if (!isEnvelope(payload)) return void 0;
2278
+ const outcomes = [];
2279
+ for (const event of adapter.toDeliverableEvents(payload)) {
2280
+ outcomes.push(await adapter.deliverQuietly(event));
2281
+ }
2282
+ return outcomes;
2283
+ }
2284
+ var cloudWebhook = {
2285
+ methods: ["GET", "POST"],
2286
+ verify(adapter, request) {
2287
+ return requestValid(adapter, request);
2288
+ },
2289
+ async ingest(adapter, payload) {
2290
+ return deliverEnvelope(adapter, payload);
2291
+ },
2292
+ async handle(adapter, request) {
2293
+ const isGet = request.method?.toUpperCase() === "GET";
2294
+ if (!requestValid(adapter, request)) return { status: isGet ? 403 : 401 };
2295
+ if (isGet) {
2296
+ return {
2297
+ status: 200,
2298
+ body: subscriptionChallenge(adapter, request),
2299
+ contentType: "text/plain"
2300
+ };
2301
+ }
2302
+ let payload;
2303
+ try {
2304
+ payload = JSON.parse(request.rawBody);
2305
+ } catch {
2306
+ return { status: 400 };
2307
+ }
2308
+ const outcomes = await deliverAll(adapter, payload);
2309
+ if (outcomes === void 0) return { status: 400 };
2310
+ return { status: statusFor(outcomes) };
2311
+ }
2196
2312
  };
2197
2313
 
2198
2314
  // src/channel.ts
@@ -2250,7 +2366,7 @@ var CLOUD_CONFIG = [
2250
2366
  required: false,
2251
2367
  secret: true,
2252
2368
  env: "WHATSAPP_VERIFY_TOKEN",
2253
- description: "The token Meta's webhook subscription check sends; not an adapter option, kept so the webhook half can answer it."
2369
+ description: "The token Meta's webhook subscription check sends; the webhook's GET answers 403 without it."
2254
2370
  },
2255
2371
  REQUIRE_MENTION
2256
2372
  ];
@@ -2283,12 +2399,17 @@ function createCloud(config) {
2283
2399
  const accessToken = requiredString(config, "accessToken");
2284
2400
  const phoneNumberId = requiredString(config, "phoneNumberId");
2285
2401
  const appSecret = requiredString(config, "appSecret");
2286
- read(config, "verifyToken", "string");
2402
+ const verifyToken = read(config, "verifyToken", "string");
2287
2403
  const opts = common(config);
2288
- return WhatsAppAdapter.from(
2404
+ const adapter = WhatsAppAdapter.from(
2289
2405
  { backend: "cloud", cloud: { accessToken, phoneNumberId, appSecret } },
2290
2406
  opts
2291
2407
  );
2408
+ rememberWebhookConfig(adapter, {
2409
+ appSecret,
2410
+ ...verifyToken === void 0 ? {} : { verifyToken }
2411
+ });
2412
+ return adapter;
2292
2413
  }
2293
2414
  function createBaileys(config) {
2294
2415
  const sessionDir = requiredString(config, "sessionDir");
@@ -2297,7 +2418,8 @@ function createBaileys(config) {
2297
2418
  }
2298
2419
  var cloudChannel = {
2299
2420
  platform: "whatsapp",
2300
- transport: "socket",
2421
+ transport: "webhook",
2422
+ webhook: cloudWebhook,
2301
2423
  senderIdentity: "authenticated",
2302
2424
  config: CLOUD_CONFIG,
2303
2425
  create: createCloud