@theokit/gateway-whatsapp 0.3.2 → 0.3.3

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,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 467af35: The unofficial (Web) bridge now exits on SIGTERM instead of hanging with Chromium still running.
8
+
9
+ Measured 2026-08-30: sending SIGTERM to the bridge did not stop it at all — the `exit` event never
10
+ fired and ten Chromium processes stayed up. puppeteer registers its own SIGTERM/SIGINT/SIGHUP
11
+ handlers by default, and registering any handler replaces Node's terminate-on-signal default; the
12
+ bridge installed none of its own, so it inherited a shutdown that waits on a browser close which
13
+ never arrives while WhatsApp Web is still loading.
14
+
15
+ Anything that supervises a process stops it with SIGTERM — systemd, Docker, pm2, a parent Node
16
+ process. Every such stop left a bridge that would not die and a leaked browser tree, recoverable
17
+ only with SIGKILL, which cannot close anything cleanly. Restarting therefore accumulated Chromium
18
+ processes and session directories.
19
+
20
+ The bridge now owns its termination signals and closes the browser under a five-second deadline,
21
+ then exits regardless. Re-measured on the same probe: the process exits in ~6s with code 0 and zero
22
+ Chromium processes survive.
23
+
3
24
  ## 0.3.2
4
25
 
5
26
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,84 @@
1
1
  # `@theokit/gateway-whatsapp`
2
2
 
3
- WhatsApp platform adapter for `@theokit/gateway`. Multi-backend (Meta WhatsApp Business Cloud API + `whatsapp-web.js` subprocess bridge).
3
+ WhatsApp platform adapter for `@theokit/gateway`. Three backends behind one
4
+ `WhatsAppBackend` interface: the Meta WhatsApp Business Cloud API, a `whatsapp-web.js`
5
+ subprocess bridge, and a `baileys` socket.
4
6
 
5
- Status: **v0.1.0 pre-release**. Pre-1.0 contract per ADR D314 — breaking changes allowed within 0.x.
7
+ Pre-1.0 contract per ADR D314 — breaking changes allowed within 0.x. (This line used to
8
+ pin a version number, and named 0.1.0 while the package shipped 0.3.2.)
9
+
10
+ ## Choosing a backend
11
+
12
+ | Backend | Needs | Exercised against real WhatsApp |
13
+ | --- | --- | --- |
14
+ | `WhatsAppCloudBackend` | a Meta Business account, an access token, a phone number id | **yes** — send accepted by Meta, `wamid` returned. Delivery status arrives by webhook and is not asserted here |
15
+ | `WhatsAppBaileysBackend` | a phone to scan a QR once, then a `sessionDir` | **yes** — paired against a real account 2026-08-30 and sent through it |
16
+ | `WhatsAppWebBackend` | a phone to scan a QR **and a Chrome/Chromium binary** | reaches WhatsApp and issues a QR, given a browser (see below) |
17
+
18
+ The Cloud API is the supported path — it is the one Meta documents, the one with no
19
+ phone tethered to a session, and the only one whose send this repository asserts in a
20
+ test. The other two speak WhatsApp's client protocol, which its terms do not sanction;
21
+ choosing one is a decision about your account, not about this package.
22
+
23
+ Measured 2026-08-29: Baileys produced a pairing QR **1441 ms** after `connect()`, then
24
+ returned `false` — not a throw, and with the reason stated — when the 45 s window closed
25
+ unscanned. The web bridge reached the same point with `PUPPETEER_EXECUTABLE_PATH` set.
26
+
27
+ Measured 2026-08-30: the Baileys backend was **paired against a real WhatsApp account** and sent
28
+ through it, returning a `wamid`. Two things that cost a session each are worth carrying:
29
+
30
+ - **Pairing is QR-only.** `requestPairingCode` exists in Baileys and WhatsApp refuses the codes
31
+ this backend asks for — three attempts, on both the 12- and 13-digit forms of a Brazilian
32
+ number. `WhatsAppBaileysBackend`'s docblock records what is and is not established about why.
33
+ - **A `wamid` is not delivery, and this one loses messages silently.** Two sends to the same
34
+ Brazilian line, one with the ninth digit and one without: both returned `ok: true` with a
35
+ `wamid`, and only `553598838687` — the form without it — arrived. `5535998838687` was accepted
36
+ and vanished. This backend does NOT normalise the Brazilian ninth digit; pass the JID form
37
+ WhatsApp knows, which the account itself reports (WhatsApp Web stores it under `last-wid-md`).
38
+ Tracked as a defect rather than a footnote: a send that reports success for a message nobody
39
+ receives is the swallowed failure `rules/error-handling.md` § 5 names first.
40
+
41
+ The web bridge has still never been paired, so it has no send anyone here can prove.
42
+
43
+ ### Showing the QR: `backend.pairing`
44
+
45
+ `onQr` is push — it fires when WhatsApp issues a code, at a moment the caller does not choose. A
46
+ screen is pull: it loads when someone opens it and has to ask what is true right now. So the
47
+ backend also answers:
48
+
49
+ ```ts
50
+ backend.pairing
51
+ // { status: "idle" | "awaiting_scan" | "connected" | "closed", qr?: string, qrAt?: number }
52
+ ```
53
+
54
+ `qr` is present only while `awaiting_scan`, and is dropped on `connected` and on `closed` —
55
+ WhatsApp reissues roughly every 20 seconds and a screen holding the previous square offers
56
+ something that cannot be scanned. `qrAt` lets a UI show the code's age rather than a stale image.
57
+
58
+ Rendering is the app's job. This package does not encode the image and will not: `qrcode` pulls a
59
+ CLI argument parser, and a consumer using only the Cloud API backend would carry it to pair
60
+ nothing. Two lines where the screen is:
61
+
62
+ ```ts
63
+ import { toDataURL } from "qrcode";
64
+ const src = await toDataURL(backend.pairing.qr);
65
+ ```
66
+
67
+ ### The web backend needs a browser you provide
68
+
69
+ `whatsapp-web.js` drives a real Chrome through Puppeteer, and **this package does not ship
70
+ one**: the repository leaves `puppeteer` out of `pnpm.onlyBuiltDependencies`, so its
71
+ postinstall never downloads a browser. Without one the bridge starts, fails to find Chrome,
72
+ and reports that failure in its own protocol — it does not crash, which is the fix from
73
+ B-002, but it does not connect either.
74
+
75
+ Point it at a browser you already have:
76
+
77
+ ```bash
78
+ PUPPETEER_EXECUTABLE_PATH=/usr/bin/google-chrome node your-app.js
79
+ ```
80
+
81
+ The bridge spawns without an explicit `env`, so it inherits yours and the variable
82
+ reaches Puppeteer. `WhatsAppBaileysBackend` needs no browser at all, which is the reason
83
+ it exists (B-001).
6
84
 
@@ -164,6 +164,42 @@ client.on("disconnected", (reason) => {
164
164
  emitError(`DISCONNECTED: ${reason}`);
165
165
  });
166
166
 
167
+ /**
168
+ * Close the browser and leave, under a deadline.
169
+ *
170
+ * The deadline is the point. `client.destroy()` closes Chromium, and while WhatsApp Web is still
171
+ * loading it can wait forever — so an unbounded shutdown is a process that never exits. Racing it
172
+ * against a timer means the browser is closed properly when that is possible and the bridge leaves
173
+ * regardless, which is what a supervisor waiting on the exit is owed.
174
+ */
175
+ let shuttingDown = false;
176
+ async function shutdown(code) {
177
+ if (shuttingDown) return;
178
+ shuttingDown = true;
179
+ await Promise.race([
180
+ client.destroy().catch(() => undefined),
181
+ new Promise((resolve) => setTimeout(resolve, 5_000)),
182
+ ]);
183
+ process.exit(code);
184
+ }
185
+
186
+ /**
187
+ * Own the termination signals.
188
+ *
189
+ * Measured 2026-08-30: without these, SIGTERM did not stop the bridge at all — the process stayed
190
+ * up and eleven Chromium processes with it. puppeteer registers its own SIGTERM/SIGINT/SIGHUP
191
+ * handlers by default, and registering ANY handler removes Node's terminate-on-signal default; the
192
+ * bridge then inherited a shutdown that could hang and had no deadline of its own.
193
+ *
194
+ * Registering last wins for the exit: puppeteer's handler still runs and closes what it can, and
195
+ * this one guarantees the process actually leaves.
196
+ */
197
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
198
+ process.on(signal, () => {
199
+ void shutdown(0);
200
+ });
201
+ }
202
+
167
203
  const rl = createInterface({ input: process.stdin });
168
204
  rl.on("line", async (line) => {
169
205
  let cmd;
@@ -173,12 +209,7 @@ rl.on("line", async (line) => {
173
209
  return;
174
210
  }
175
211
  if (cmd?.cmd === "shutdown") {
176
- try {
177
- await client.destroy();
178
- } catch {
179
- /* ignore */
180
- }
181
- process.exit(0);
212
+ await shutdown(0);
182
213
  }
183
214
  if (cmd?.cmd === "send") {
184
215
  const msgId = cmd.msgId;
package/dist/index.cjs CHANGED
@@ -103,18 +103,29 @@ function resolveParties(key, remoteJid) {
103
103
  if (fromPhone.length === 0 || channelId.length === 0) return void 0;
104
104
  return { fromPhone, channelId, isGroup };
105
105
  }
106
- function isDispatchable(key, remoteJid) {
107
- if (key.fromMe === true) return false;
108
- return remoteJid !== STATUS_BROADCAST_JID;
106
+ function isDispatchable(key, remoteJid, wamid, ctx) {
107
+ if (remoteJid === STATUS_BROADCAST_JID) return "no";
108
+ if (key.fromMe !== true) return "yes";
109
+ const selfJids = ctx?.selfJids;
110
+ if (selfJids === void 0 || selfJids.size === 0) return "no";
111
+ if (!selfJids.has(normalizeWhatsAppId(remoteJid))) return "no";
112
+ return ctx?.sentWamids?.has(wamid) === true ? "no" : "yes-from-self";
109
113
  }
110
- function normalizeBaileysMessage(raw) {
111
- const envelope = asObject(raw);
114
+ function addressingOf(envelope) {
112
115
  const key = envelope === void 0 ? void 0 : asObject(envelope.key);
113
116
  if (key === void 0) return void 0;
114
117
  const remoteJid = asText(key.remoteJid);
115
118
  const wamid = asText(key.id);
116
119
  if (remoteJid === void 0 || wamid === void 0) return void 0;
117
- if (!isDispatchable(key, remoteJid)) return void 0;
120
+ return { key, remoteJid, wamid };
121
+ }
122
+ function normalizeBaileysMessage(raw, ctx) {
123
+ const envelope = asObject(raw);
124
+ const addressed = addressingOf(envelope);
125
+ if (addressed === void 0) return void 0;
126
+ const { key, remoteJid, wamid } = addressed;
127
+ const verdict = isDispatchable(key, remoteJid, wamid, ctx);
128
+ if (verdict === "no") return void 0;
118
129
  const text = extractText(envelope?.message);
119
130
  if (text === void 0) return void 0;
120
131
  const parties = resolveParties(key, remoteJid);
@@ -131,6 +142,7 @@ function normalizeBaileysMessage(raw) {
131
142
  receivedAt: seconds * 1e3,
132
143
  backend: "baileys",
133
144
  raw,
145
+ ...verdict === "yes-from-self" ? { fromSelf: true } : {},
134
146
  ...contactName !== void 0 ? { contactName } : {}
135
147
  };
136
148
  }
@@ -300,6 +312,7 @@ function endQuietly(socket) {
300
312
  }
301
313
  var DEFAULT_CONNECT_TIMEOUT_MS = 6e4;
302
314
  var DEFAULT_SEND_TIMEOUT_MS = 3e4;
315
+ var SENT_WAMID_WINDOW = 256;
303
316
  var WhatsAppBaileysBackend = class {
304
317
  constructor(opts) {
305
318
  this.opts = opts;
@@ -334,6 +347,54 @@ var WhatsAppBaileysBackend = class {
334
347
  * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
335
348
  */
336
349
  lastCloseError;
350
+ /** The pairing, as a caller may ask for it. Never handed out mutable. */
351
+ pairingState = { status: "idle" };
352
+ /**
353
+ * The JIDs that ARE this account, normalised. Empty until a socket reports who it logged in as.
354
+ *
355
+ * Empty means "not learned yet", and `isDispatchable` reads that as refusing everything this
356
+ * account sent — the same behaviour as before self-chat support existed. A backend that
357
+ * guessed here would answer in a stranger's conversation.
358
+ */
359
+ selfJids = /* @__PURE__ */ new Set();
360
+ /**
361
+ * Ids this backend sent, most recent last. This is what stops the agent answering itself.
362
+ *
363
+ * Bounded because it is a loop guard, not a log: an unbounded set on a long-lived socket is a
364
+ * leak, and nothing needs to recognise an echo from an hour ago — WhatsApp delivers our own
365
+ * message back within seconds or not at all.
366
+ */
367
+ sentWamids = /* @__PURE__ */ new Set();
368
+ /** Record one id we sent, evicting the oldest once the window is full. @internal */
369
+ rememberSent(wamid) {
370
+ this.sentWamids.add(wamid);
371
+ while (this.sentWamids.size > SENT_WAMID_WINDOW) {
372
+ const oldest = this.sentWamids.values().next();
373
+ if (oldest.done === true) break;
374
+ this.sentWamids.delete(oldest.value);
375
+ }
376
+ }
377
+ /**
378
+ * Learn which JIDs are this account, from the socket that just logged in.
379
+ *
380
+ * Both forms are recorded: the phone JID and the LID. The self-chat is addressed by LID —
381
+ * measured on a real account, where a note-to-self arrived on `231116569108705@lid` while the
382
+ * account's phone JID was `553598838687` — so recording only one leaves the self-chat
383
+ * unrecognised and the feature silently off.
384
+ *
385
+ * @internal
386
+ */
387
+ learnSelfJids(socket) {
388
+ const user = socket.user;
389
+ const ids = [user?.id, user?.lid].filter((id) => typeof id === "string" && id.length > 0).map((id) => normalizeWhatsAppId(id)).filter((id) => id.length > 0);
390
+ this.selfJids = new Set(ids);
391
+ if (process.env.THEOKIT_WHATSAPP_TRACE === "1") {
392
+ process.stderr.write(
393
+ `[whatsapp-baileys][trace] selfJids learned: ${ids.length === 0 ? "(none)" : ids.join(", ")}
394
+ `
395
+ );
396
+ }
397
+ }
337
398
  inboundHandler;
338
399
  statusHandler;
339
400
  /**
@@ -390,20 +451,68 @@ var WhatsAppBaileysBackend = class {
390
451
  }
391
452
  if (this.socket !== void 0 && this.socket !== socket) endQuietly(this.socket);
392
453
  this.socket = socket;
454
+ this.learnSelfJids(socket);
393
455
  this.connected = true;
394
456
  return true;
395
457
  }
458
+ /**
459
+ * What the pairing is doing right now.
460
+ *
461
+ * Read it as often as a screen needs; it is a snapshot, not a subscription.
462
+ */
463
+ get pairing() {
464
+ return this.pairingState;
465
+ }
396
466
  /** Build a socket through the injected factory, or the real one. @internal */
397
467
  async buildSocket() {
398
468
  const factory = this.opts.socketFactory ?? createBaileysSocket;
399
469
  return factory({
400
470
  sessionDir: this.opts.sessionDir,
401
- ...this.opts.onQr !== void 0 ? { onQr: this.opts.onQr } : {}
471
+ // ALWAYS supplied, even when the caller wants none: a backend that only forwards cannot
472
+ // answer `pairing`, and the caller's own handler still runs, so wiring one costs nothing.
473
+ onQr: (qr) => {
474
+ this.pairingState = { status: "awaiting_scan", qr, qrAt: Date.now() };
475
+ this.opts.onQr?.(qr);
476
+ }
477
+ });
478
+ }
479
+ /**
480
+ * Trace one inbound batch BEFORE any filter, when `THEOKIT_WHATSAPP_TRACE=1`.
481
+ *
482
+ * Two independent filters can discard an envelope — the batch `type` here and `fromMe` inside
483
+ * `normalizeBaileysMessage` — and from outside, both look identical: nothing happens. Telling
484
+ * them apart by reading the code is guessing; this is how you find out which one fired.
485
+ *
486
+ * Deliberately content-free. A Baileys session pairs a REAL account carrying real
487
+ * conversations, so the trace records shape (type, direction, group, has-text) and the last
488
+ * four digits of the jid, never the message and never a full contact number.
489
+ *
490
+ * @internal
491
+ */
492
+ traceBatch(payload) {
493
+ if (process.env.THEOKIT_WHATSAPP_TRACE !== "1") return;
494
+ const messages = payload.messages ?? [];
495
+ const rows = messages.map((raw) => {
496
+ const key = raw?.key ?? {};
497
+ const jid = typeof key.remoteJid === "string" ? key.remoteJid : "";
498
+ const message = raw?.message;
499
+ return [
500
+ `fromMe=${String(key.fromMe === true)}`,
501
+ `jid=\u2026${jid.replace(/\D/g, "").slice(-4)}`,
502
+ `group=${String(jid.endsWith("@g.us"))}`,
503
+ `hasMessage=${String(message !== null && message !== void 0)}`
504
+ ].join(" ");
402
505
  });
506
+ process.stderr.write(
507
+ `[whatsapp-baileys][trace] upsert type=${payload.type ?? "(none)"} n=${messages.length}` + (rows.length === 0 ? "\n" : `
508
+ ${rows.join("\n ")}
509
+ `)
510
+ );
403
511
  }
404
512
  /** Route this socket's inbound batches into the handler, while it is still current. @internal */
405
513
  subscribeInbound(socket, isCurrent) {
406
514
  socket.ev.on("messages.upsert", (payload) => {
515
+ this.traceBatch(payload);
407
516
  if (payload.type !== void 0 && payload.type !== "notify") return;
408
517
  if (!isCurrent()) return;
409
518
  for (const raw of payload.messages ?? []) this.dispatchInbound(raw);
@@ -430,12 +539,14 @@ var WhatsAppBaileysBackend = class {
430
539
  socket.ev.on("connection.update", (update) => {
431
540
  if (!isCurrent()) return;
432
541
  if (update.connection === "open") {
542
+ this.pairingState = { status: "connected" };
433
543
  settle(true);
434
544
  return;
435
545
  }
436
546
  if (update.connection !== "close") return;
437
547
  this.lastCloseError = update.lastDisconnect?.error;
438
548
  this.connected = false;
549
+ this.pairingState = { status: "closed" };
439
550
  if (this.socket === socket) this.socket = void 0;
440
551
  endQuietly(socket);
441
552
  settle(false);
@@ -558,6 +669,7 @@ var WhatsAppBaileysBackend = class {
558
669
  };
559
670
  }
560
671
  const wamid = outcome?.key?.id;
672
+ if (wamid !== void 0) this.rememberSent(wamid);
561
673
  return wamid !== void 0 ? { ok: true, wamid } : { ok: true };
562
674
  }).catch((err) => ({
563
675
  ok: false,
@@ -601,7 +713,10 @@ var WhatsAppBaileysBackend = class {
601
713
  dispatchInbound(raw) {
602
714
  const handler = this.inboundHandler;
603
715
  if (handler === void 0) return;
604
- const event = normalizeBaileysMessage(raw);
716
+ const event = normalizeBaileysMessage(raw, {
717
+ selfJids: this.selfJids,
718
+ sentWamids: this.sentWamids
719
+ });
605
720
  if (event === void 0) return;
606
721
  void handler(event).catch((err) => {
607
722
  const message = err instanceof Error ? err.message : String(err);
@@ -1491,6 +1606,30 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1491
1606
  connected = false;
1492
1607
  handler;
1493
1608
  statusHandler;
1609
+ /** Whether the "this platform carries no format flag" warning has already been emitted. */
1610
+ warnedAboutFormat = false;
1611
+ /**
1612
+ * Say, once, that a declared `format` has nowhere to go on this platform.
1613
+ *
1614
+ * WhatsApp's emphasis is INLINE — `*bold*`, `_italic_` — carried in the message text itself,
1615
+ * with no field on the request to set and no escape sequence to suppress it. So a caller
1616
+ * declaring `markdown` has already put the syntax in the text, and one declaring `html` is
1617
+ * asking for something the platform does not have.
1618
+ *
1619
+ * Reading the field is what turns a silent discard into a stated one — the swallowed-error
1620
+ * shape `rules/error-handling.md` refuses.
1621
+ *
1622
+ * @internal
1623
+ */
1624
+ warnFormatUnsupported(format) {
1625
+ if (format === void 0 || format === "plain") return;
1626
+ if (this.warnedAboutFormat) return;
1627
+ this.warnedAboutFormat = true;
1628
+ process.stderr.write(
1629
+ `[whatsapp] format="${format}" was declared, and WhatsApp cannot carry it as a flag \u2014 its emphasis is inline in the text. Sending as-is; this is logged once.
1630
+ `
1631
+ );
1632
+ }
1494
1633
  // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
1495
1634
  inboundUnsubscribe;
1496
1635
  statusUnsubscribe;
@@ -1634,6 +1773,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1634
1773
  if (out.text.length === 0) {
1635
1774
  return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1636
1775
  }
1776
+ this.warnFormatUnsupported(out.format);
1637
1777
  const parts = splitForWhatsApp(out.text);
1638
1778
  if (parts.length === 0) {
1639
1779
  return {
@@ -1665,6 +1805,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter
1665
1805
  * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1666
1806
  */
1667
1807
  isRefusedBySenderAllowlist(inbound) {
1808
+ if (inbound.fromSelf === true) return false;
1668
1809
  if (this.allowedSenders === void 0) return false;
1669
1810
  if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1670
1811
  process.stderr.write(