@theokit/gateway-whatsapp 0.8.0 → 0.9.1

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/dist/index.d.cts CHANGED
@@ -1290,17 +1290,30 @@ declare class LineBuffer {
1290
1290
  }
1291
1291
 
1292
1292
  /**
1293
- * `whatsappChannel` — the WhatsApp channel described as data.
1293
+ * The Cloud half of the WhatsApp descriptor's webhook: Meta's GET subscription check and the signed
1294
+ * POST, answered through `ChannelWebhook.handle` so a host mounts it with `createWebhookHandler`.
1294
1295
  *
1295
- * Typed locally on purpose: this package declares `@theokit/gateway` as a peer, and a published
1296
- * `.d.ts` naming a core type an older release lacks would break a consumer on that floor. The object
1297
- * is structurally a `ChannelDescriptor`; the integration package assigns it to one.
1296
+ * The credentials the route needs (`appSecret`, `verifyToken`) are not adapter options, so the
1297
+ * descriptor's `create` records them here, keyed by the adapter it built, never on a public field.
1298
+ * An adapter not built by the descriptor has none and every request to it is refused.
1298
1299
  *
1299
- * Two variants pick the backend: `cloud` (Meta Cloud API) and `baileys` (WhatsApp Web multi-device).
1300
- * The parent descriptor itself describes the cloud shape; `selectVariant(whatsappChannel, "baileys")`
1301
- * picks the other.
1300
+ * No secret, signature or body text is logged or answered.
1302
1301
  */
1303
1302
 
1303
+ /** The request shape `handle` receives (structural; the core type is not imported). */
1304
+ interface WebhookRequestShape {
1305
+ readonly rawBody: string;
1306
+ readonly headers: Readonly<Record<string, string | undefined>>;
1307
+ readonly method?: string;
1308
+ readonly url?: string;
1309
+ }
1310
+ /** What `handle` answers. */
1311
+ interface WebhookAnswerShape {
1312
+ readonly status: number;
1313
+ readonly body?: string;
1314
+ readonly contentType?: string;
1315
+ }
1316
+
1304
1317
  type Config = Readonly<Record<string, unknown>>;
1305
1318
  /** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
1306
1319
  interface ConfigField {
@@ -1325,7 +1338,13 @@ declare const whatsappChannel: {
1325
1338
  variants: {
1326
1339
  cloud: {
1327
1340
  platform: "whatsapp";
1328
- transport: "socket";
1341
+ transport: "webhook";
1342
+ webhook: {
1343
+ methods: readonly ["GET", "POST"];
1344
+ verify(adapter: WhatsAppAdapter, request: WebhookRequestShape): boolean;
1345
+ ingest(adapter: WhatsAppAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
1346
+ handle(adapter: WhatsAppAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape>;
1347
+ };
1329
1348
  senderIdentity: "authenticated";
1330
1349
  config: readonly ConfigField[];
1331
1350
  create: typeof createCloud;
@@ -1339,7 +1358,13 @@ declare const whatsappChannel: {
1339
1358
  };
1340
1359
  };
1341
1360
  platform: "whatsapp";
1342
- transport: "socket";
1361
+ transport: "webhook";
1362
+ webhook: {
1363
+ methods: readonly ["GET", "POST"];
1364
+ verify(adapter: WhatsAppAdapter, request: WebhookRequestShape): boolean;
1365
+ ingest(adapter: WhatsAppAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
1366
+ handle(adapter: WhatsAppAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape>;
1367
+ };
1343
1368
  senderIdentity: "authenticated";
1344
1369
  config: readonly ConfigField[];
1345
1370
  create: typeof createCloud;
package/dist/index.d.ts CHANGED
@@ -1290,17 +1290,30 @@ declare class LineBuffer {
1290
1290
  }
1291
1291
 
1292
1292
  /**
1293
- * `whatsappChannel` — the WhatsApp channel described as data.
1293
+ * The Cloud half of the WhatsApp descriptor's webhook: Meta's GET subscription check and the signed
1294
+ * POST, answered through `ChannelWebhook.handle` so a host mounts it with `createWebhookHandler`.
1294
1295
  *
1295
- * Typed locally on purpose: this package declares `@theokit/gateway` as a peer, and a published
1296
- * `.d.ts` naming a core type an older release lacks would break a consumer on that floor. The object
1297
- * is structurally a `ChannelDescriptor`; the integration package assigns it to one.
1296
+ * The credentials the route needs (`appSecret`, `verifyToken`) are not adapter options, so the
1297
+ * descriptor's `create` records them here, keyed by the adapter it built, never on a public field.
1298
+ * An adapter not built by the descriptor has none and every request to it is refused.
1298
1299
  *
1299
- * Two variants pick the backend: `cloud` (Meta Cloud API) and `baileys` (WhatsApp Web multi-device).
1300
- * The parent descriptor itself describes the cloud shape; `selectVariant(whatsappChannel, "baileys")`
1301
- * picks the other.
1300
+ * No secret, signature or body text is logged or answered.
1302
1301
  */
1303
1302
 
1303
+ /** The request shape `handle` receives (structural; the core type is not imported). */
1304
+ interface WebhookRequestShape {
1305
+ readonly rawBody: string;
1306
+ readonly headers: Readonly<Record<string, string | undefined>>;
1307
+ readonly method?: string;
1308
+ readonly url?: string;
1309
+ }
1310
+ /** What `handle` answers. */
1311
+ interface WebhookAnswerShape {
1312
+ readonly status: number;
1313
+ readonly body?: string;
1314
+ readonly contentType?: string;
1315
+ }
1316
+
1304
1317
  type Config = Readonly<Record<string, unknown>>;
1305
1318
  /** One configuration field, shaped like the core's `ChannelConfigField` (typed locally). */
1306
1319
  interface ConfigField {
@@ -1325,7 +1338,13 @@ declare const whatsappChannel: {
1325
1338
  variants: {
1326
1339
  cloud: {
1327
1340
  platform: "whatsapp";
1328
- transport: "socket";
1341
+ transport: "webhook";
1342
+ webhook: {
1343
+ methods: readonly ["GET", "POST"];
1344
+ verify(adapter: WhatsAppAdapter, request: WebhookRequestShape): boolean;
1345
+ ingest(adapter: WhatsAppAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
1346
+ handle(adapter: WhatsAppAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape>;
1347
+ };
1329
1348
  senderIdentity: "authenticated";
1330
1349
  config: readonly ConfigField[];
1331
1350
  create: typeof createCloud;
@@ -1339,7 +1358,13 @@ declare const whatsappChannel: {
1339
1358
  };
1340
1359
  };
1341
1360
  platform: "whatsapp";
1342
- transport: "socket";
1361
+ transport: "webhook";
1362
+ webhook: {
1363
+ methods: readonly ["GET", "POST"];
1364
+ verify(adapter: WhatsAppAdapter, request: WebhookRequestShape): boolean;
1365
+ ingest(adapter: WhatsAppAdapter, payload: unknown): Promise<"delivered" | "malformed" | "no_handler">;
1366
+ handle(adapter: WhatsAppAdapter, request: WebhookRequestShape): Promise<WebhookAnswerShape>;
1367
+ };
1343
1368
  senderIdentity: "authenticated";
1344
1369
  config: readonly ConfigField[];
1345
1370
  create: typeof createCloud;
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { GatewayConfigurationError, chunkText, BasePlatformAdapter } from '@theokit/gateway';
2
2
  import * as crypto from 'crypto';
3
+ import { createHash, timingSafeEqual } from 'crypto';
3
4
  import * as fs from 'fs';
4
5
  import { existsSync } from 'fs';
5
6
  import * as path2 from 'path';
@@ -2169,6 +2170,122 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
2169
2170
  async deliver(event) {
2170
2171
  return this.runHandler(this.handler, event);
2171
2172
  }
2173
+ /**
2174
+ * Deliver like {@link deliver}, but a throwing handler is logged by name only: its message can
2175
+ * carry the inbound text, which the webhook route must not write to a log line.
2176
+ *
2177
+ * @internal
2178
+ */
2179
+ async deliverQuietly(event) {
2180
+ const handler = this.handler;
2181
+ if (handler === void 0) return "no_handler";
2182
+ try {
2183
+ await handler(event);
2184
+ } catch {
2185
+ process.stderr.write(`[whatsapp] handler threw
2186
+ `);
2187
+ return "handler_threw";
2188
+ }
2189
+ return "ok";
2190
+ }
2191
+ };
2192
+ var configs = /* @__PURE__ */ new WeakMap();
2193
+ function rememberWebhookConfig(adapter, config) {
2194
+ configs.set(adapter, config);
2195
+ }
2196
+ function headerValue(headers, name) {
2197
+ for (const [key, value] of Object.entries(headers)) {
2198
+ if (key.toLowerCase() === name) return value;
2199
+ }
2200
+ return void 0;
2201
+ }
2202
+ function safeEqual(a, b) {
2203
+ const ha = createHash("sha256").update(a).digest();
2204
+ const hb = createHash("sha256").update(b).digest();
2205
+ return timingSafeEqual(ha, hb);
2206
+ }
2207
+ function statusFor(outcomes) {
2208
+ let status = 200;
2209
+ for (const outcome of outcomes) {
2210
+ if (outcome === "handler_threw") status = 500;
2211
+ else if (outcome === "no_handler" && status === 200) status = 503;
2212
+ }
2213
+ return status;
2214
+ }
2215
+ function signatureValid(adapter, request) {
2216
+ const config = configs.get(adapter);
2217
+ if (config === void 0 || config.appSecret.trim().length === 0) return false;
2218
+ const header = headerValue(request.headers, "x-hub-signature-256");
2219
+ return verifyWebhookSignature(request.rawBody, header, config.appSecret);
2220
+ }
2221
+ function subscriptionChallenge(adapter, request) {
2222
+ const expected = configs.get(adapter)?.verifyToken;
2223
+ if (expected === void 0 || expected.length === 0 || request.url === void 0) {
2224
+ return void 0;
2225
+ }
2226
+ let params;
2227
+ try {
2228
+ params = new URL(request.url).searchParams;
2229
+ } catch {
2230
+ return void 0;
2231
+ }
2232
+ const token = params.get("hub.verify_token");
2233
+ const challenge = params.get("hub.challenge");
2234
+ if (params.get("hub.mode") !== "subscribe" || token === null || !safeEqual(token, expected)) {
2235
+ return void 0;
2236
+ }
2237
+ return challenge === null || challenge.length === 0 ? void 0 : challenge;
2238
+ }
2239
+ function requestValid(adapter, request) {
2240
+ const method = request.method?.toUpperCase();
2241
+ if (method === "GET") return subscriptionChallenge(adapter, request) !== void 0;
2242
+ if (method === "POST") return signatureValid(adapter, request);
2243
+ return false;
2244
+ }
2245
+ function isEnvelope(payload) {
2246
+ return payload !== null && typeof payload === "object" && !Array.isArray(payload);
2247
+ }
2248
+ async function deliverEnvelope(adapter, payload) {
2249
+ const outcomes = await deliverAll(adapter, payload);
2250
+ if (outcomes === void 0) return "malformed";
2251
+ return statusFor(outcomes) === 200 ? "delivered" : "no_handler";
2252
+ }
2253
+ async function deliverAll(adapter, payload) {
2254
+ if (!isEnvelope(payload)) return void 0;
2255
+ const outcomes = [];
2256
+ for (const event of adapter.toDeliverableEvents(payload)) {
2257
+ outcomes.push(await adapter.deliverQuietly(event));
2258
+ }
2259
+ return outcomes;
2260
+ }
2261
+ var cloudWebhook = {
2262
+ methods: ["GET", "POST"],
2263
+ verify(adapter, request) {
2264
+ return requestValid(adapter, request);
2265
+ },
2266
+ async ingest(adapter, payload) {
2267
+ return deliverEnvelope(adapter, payload);
2268
+ },
2269
+ async handle(adapter, request) {
2270
+ const isGet = request.method?.toUpperCase() === "GET";
2271
+ if (!requestValid(adapter, request)) return { status: isGet ? 403 : 401 };
2272
+ if (isGet) {
2273
+ return {
2274
+ status: 200,
2275
+ body: subscriptionChallenge(adapter, request),
2276
+ contentType: "text/plain"
2277
+ };
2278
+ }
2279
+ let payload;
2280
+ try {
2281
+ payload = JSON.parse(request.rawBody);
2282
+ } catch {
2283
+ return { status: 400 };
2284
+ }
2285
+ const outcomes = await deliverAll(adapter, payload);
2286
+ if (outcomes === void 0) return { status: 400 };
2287
+ return { status: statusFor(outcomes) };
2288
+ }
2172
2289
  };
2173
2290
 
2174
2291
  // src/channel.ts
@@ -2226,7 +2343,7 @@ var CLOUD_CONFIG = [
2226
2343
  required: false,
2227
2344
  secret: true,
2228
2345
  env: "WHATSAPP_VERIFY_TOKEN",
2229
- description: "The token Meta's webhook subscription check sends; not an adapter option, kept so the webhook half can answer it."
2346
+ description: "The token Meta's webhook subscription check sends; the webhook's GET answers 403 without it."
2230
2347
  },
2231
2348
  REQUIRE_MENTION
2232
2349
  ];
@@ -2259,12 +2376,17 @@ function createCloud(config) {
2259
2376
  const accessToken = requiredString(config, "accessToken");
2260
2377
  const phoneNumberId = requiredString(config, "phoneNumberId");
2261
2378
  const appSecret = requiredString(config, "appSecret");
2262
- read(config, "verifyToken", "string");
2379
+ const verifyToken = read(config, "verifyToken", "string");
2263
2380
  const opts = common(config);
2264
- return WhatsAppAdapter.from(
2381
+ const adapter = WhatsAppAdapter.from(
2265
2382
  { backend: "cloud", cloud: { accessToken, phoneNumberId, appSecret } },
2266
2383
  opts
2267
2384
  );
2385
+ rememberWebhookConfig(adapter, {
2386
+ appSecret,
2387
+ ...verifyToken === void 0 ? {} : { verifyToken }
2388
+ });
2389
+ return adapter;
2268
2390
  }
2269
2391
  function createBaileys(config) {
2270
2392
  const sessionDir = requiredString(config, "sessionDir");
@@ -2273,7 +2395,8 @@ function createBaileys(config) {
2273
2395
  }
2274
2396
  var cloudChannel = {
2275
2397
  platform: "whatsapp",
2276
- transport: "socket",
2398
+ transport: "webhook",
2399
+ webhook: cloudWebhook,
2277
2400
  senderIdentity: "authenticated",
2278
2401
  config: CLOUD_CONFIG,
2279
2402
  create: createCloud