@theokit/gateway-whatsapp 0.2.0 → 0.3.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,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e0330fe: **The `WhatsAppBackend` contract now says what it requires, and all three implementations are held to it at once.**
8
+
9
+ The interface declared bare signatures with no prose, so each backend answered the unasked questions its own way — and they diverged. `send()` on a disconnected backend refused in web (`"Bridge not connected."`) and in Baileys (`"Baileys backend is not connected."`), and **posted anyway** in Cloud. A consumer swapping backends, which is the single thing this seam exists to allow, would have found their unconnected sends leaving the process: for Cloud, a real request carrying a credential nothing had verified, or one `connect()` had already rejected.
10
+
11
+ Three changes, in the order that matters:
12
+
13
+ - **The contract is written down.** `connect()` is idempotent and returns `false` rather than throwing; `disconnect()` is idempotent and safe on a backend that never connected; `send()` requires a successful `connect()` and refuses without one, without touching the transport.
14
+ - **`not_connected` is its own error code.** Two backends called this state `server_error` and one had no opinion. A caller branches on the code, and a conformance test can only assert on one — so three descriptions of one state is the divergence, not a detail. **This widens the error union**, so an exhaustive `switch` stops compiling until the case is handled.
15
+ - **A conformance suite runs the contract against every implementation.** A per-backend test proves one implementation does something; only a shared one proves they do the _same_ thing, and the substitutability is the product. A fourth backend inherits it by being added to the table, which is where someone decides whether it complies rather than discovering later that it does not.
16
+
17
+ Verified by mutation: making any one of the three diverge fails the suite.
18
+
19
+ - b1e5dd3: **Meta's `131030` gets its own error code: `recipient_not_allowlisted`.** It used to collapse into the generic `invalid_request`, which sends a developer to re-read a payload that was correct. The remedy is a console step — register the recipient against the phone number — and it travels with the message now, exactly as `session_window_expired` already does for `131047`.
20
+
21
+ This is the error most Cloud API integrations meet first. Every app starts on a free test number whose recipients must be registered one at a time, so it is both the commonest failure and the one where a wrong diagnosis costs the most: the request is fine, so nothing in it explains the refusal.
22
+
23
+ **This widens `WhatsAppSendResult["error"]["code"]`**, so an exhaustive `switch` over it stops compiling until the new case is handled. No call site in this repository switches on it.
24
+
25
+ The WhatsApp live suite now distinguishes the two, and does so without giving itself a hiding place. An unregistered recipient is incomplete configuration — the same category as a missing credential, which this suite already skips whole platforms for — so it skips, naming the number and the console step. But a recipient _we_ mangled would be refused identically, so the skip is only reached after asserting that the recipient which actually left the process, captured through the `fetch` seam, is the one configured.
26
+
27
+ That guard took two attempts. The first compared `digitsOnly(configured)` against `configured` — which reads as a check on our own bytes and is not one, because `digitsOnly` is not on the send path at all. It asserted that the env var contains digits, and was satisfied unconditionally. A reviewer substituted the adapter's own `botPhoneId` for the recipient — a one-token regression, one line away in the same class — and watched a total outbound-routing failure skip as a provisioning gap. The current guard fails that mutation, which was verified by performing it.
28
+
29
+ ### Patch Changes
30
+
31
+ - 038fa86: **`WhatsAppCloudBackend.connect()` now asks Meta before reporting success.** It was `return true`, unconditionally — no request, no validation, no error path. A consumer with a wrong, expired or revoked token got success at startup and found out from messages that silently never arrived: no error, no log, nothing to alert on, which is the worst way for a message gateway to fail.
32
+
33
+ It verifies against the phone number itself rather than `/me`, and that choice is the point: a token can be perfectly valid and still have no access to _this_ phone number id, which is the likelier of the two misconfigurations. Checking only the token would wave it through.
34
+
35
+ The reason survives. `connect()` still returns a boolean — every sibling adapter is tested against "returns false rather than **throwing**", because a throw at startup takes the whole runner down — but it writes the mapped cause to stderr first. Told only `false`, a supervisor cannot tell a revoked token, which needs a human, from a rate limit, which needs a wait.
36
+
37
+ Verification happens once and is cached, like every sibling: re-asking on each call would turn a health check into a rate-limit source against Meta.
38
+
39
+ **How it was found is worth more than the fix.** 209 unit tests in this package passed throughout, and none of them could have caught it — the fake backend always accepts, so `return true` is indistinguishable from a successful check. It surfaced on the _first ever_ execution of `integration/tests/whatsapp/live.test.ts`, a file whose own header read `NEVER EXECUTED`, minutes after real Cloud API credentials existed for the first time. Measured across the ten adapters: the seven with live coverage all authenticate inside `connect()` and all pass the equivalent assertion. WhatsApp Cloud was the only one that did not.
40
+
41
+ A cross-adapter gate now fails when any `connect()` body invokes nothing at all. It is deliberately weak — it cannot tell a real check from a pointless one, only that the function does work before claiming the work succeeded — and that is precisely the shape that was missing.
42
+
43
+ `WhatsAppError` is now a named export, extracted from the inline type inside `WhatsAppSendResult` rather than duplicated beside it: a credential check and a send fail for the same reasons, and two declarations of one vocabulary drift the moment somebody adds a code to one of them. `WhatsAppCredentialCheck` is new. Neither changes an existing shape.
44
+
45
+ - 5d40a95: **`connect()` now checks that the credential resolves to the configured phone number, not merely that the request succeeded.** The first version read only the HTTP status, which meant three ways to report a working credential that does not work:
46
+
47
+ - a `200` carrying an error envelope, which Meta does send;
48
+ - an empty or unreadable `200`, which a captive portal or proxy sends;
49
+ - a `200` describing a **different node** — and this is the live one. Pasting a WhatsApp Business Account id where the phone number id belongs is the commonest Cloud API misconfiguration, and `GET /{waba_id}` with a management-scoped token answers `200`. The check said yes; every send then failed.
50
+
51
+ That last case is exactly what the method's own docblock claimed to catch — _"a token can be valid and still have no access to this phone number id"_ — while the code checked access and not identity. The response names the node it reached, so the fix is to compare it, and the refusal now says which node it got and which it expected.
52
+
53
+ Also fixed: a `disconnect()` arriving while a verification was in flight left `connected` set to `true` when that verification resolved, so every later `connect()` short-circuited on a flag no live check stood behind — despite the field's own comment promising `disconnect()` cleared it. A generation counter retires the abandoned attempt, the same guard the Baileys backend carries.
54
+
55
+ - 878c0ee: Five findings from an independent review of the credential-check and conformance work, all closed:
56
+
57
+ - **`verifyCredentials()` threw on a `null` body.** `response.json()` resolves `null` for the JSON literal, which is neither `undefined` nor an object, so the guard let it through and the next line dereferenced it — and the throw escaped `connect()` unwrapped. That is precisely the clause this series exists to defend: a throw at startup takes the host down with it. Arrays, strings and numbers were equally unguarded and now are.
58
+ - **`sendTemplate()` still posted an unverified credential.** The guard went on `send()` and stopped there. Being off the `WhatsAppBackend` interface — WhatsApp Web has no templates — is why the conformance suite structurally cannot see this method, which is a reason it needs its own guard, not a reason to be exempt from the rule.
59
+ - **The conformance suite asserted three of the five clauses it was written to enforce.** `connect()` idempotency and its failure contract were unasserted, which is exactly why the `null`-body throw above was invisible to the suite added to catch that class. Both are covered now — and writing them exposed that the contract itself was wrong: it demanded `false` absolutely, and two backends "failed" by throwing on a missing browser and a missing peer. They were right. **Misconfiguration throws; operational failure returns `false`**, and the interface says so.
60
+ - **The `web` conformance row observed nothing.** It carried `reachedNetwork: undefined` and a comment naming the elapsed-time check as its coverage — which a reviewer disproved by mutation, in about a millisecond. It uses the backend's documented `spawnFactory` seam now, so the row counts spawns like the others, and stops writing `.wwebjs_auth` into the package as a side effect.
61
+ - **A numeric `id` produced a refusal that contradicted itself**: _"resolves to node 12345, not the configured phoneNumberId 12345"_. Compared as strings.
62
+
3
63
  ## 0.2.0
4
64
 
5
65
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -170,10 +170,12 @@ var UNDELIVERABLE_CODES = /* @__PURE__ */ new Set([
170
170
  // no WhatsApp account, terms not accepted, or an outdated client
171
171
  ]);
172
172
  var SESSION_WINDOW_EXPIRED_CODE = 131047;
173
+ var RECIPIENT_NOT_ALLOWLISTED_CODE = 131030;
173
174
  function cloudErrorCode(status, errCode) {
174
175
  if (errCode === 190 || status === 401) return "auth_failed";
175
176
  if (RATE_LIMIT_CODES.has(errCode) || status === 429) return "rate_limit";
176
177
  if (errCode === SESSION_WINDOW_EXPIRED_CODE) return "session_window_expired";
178
+ if (errCode === RECIPIENT_NOT_ALLOWLISTED_CODE) return "recipient_not_allowlisted";
177
179
  if (UNDELIVERABLE_CODES.has(errCode)) return "undeliverable";
178
180
  if (status === 400 || errCode === 100) return "invalid_request";
179
181
  if (status >= 500) return "server_error";
@@ -186,6 +188,12 @@ function mapWhatsAppCloudError(status, body) {
186
188
  const code = cloudErrorCode(status, errCode);
187
189
  if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
188
190
  if (code === "rate_limit") return { code, message: `Throttled: ${errMsg}` };
191
+ if (code === "recipient_not_allowlisted") {
192
+ return {
193
+ code,
194
+ message: `Recipient is not on this number's allowed list \u2014 register it under the phone number in the app's WhatsApp API setup before sending: ${errMsg}`
195
+ };
196
+ }
189
197
  if (code === "session_window_expired") {
190
198
  return {
191
199
  code,
@@ -531,7 +539,7 @@ var WhatsAppBaileysBackend = class {
531
539
  return {
532
540
  result: Promise.resolve({
533
541
  ok: false,
534
- error: { code: "server_error", message: "Baileys backend is not connected." }
542
+ error: { code: "not_connected", message: "Baileys backend is not connected." }
535
543
  }),
536
544
  inFlight: Promise.resolve()
537
545
  };
@@ -659,6 +667,66 @@ var WhatsAppCloudClient = class {
659
667
  };
660
668
  return this.postMessage(req);
661
669
  }
670
+ /**
671
+ * Ask Meta whether this credential can actually act as this phone number.
672
+ *
673
+ * `connect()` used to answer that question with `return true`, so a wrong, expired or revoked
674
+ * token reported success at startup and surfaced as messages that silently never arrived —
675
+ * the worst failure mode a gateway has, because there is nothing in a log to see. The first
676
+ * live run of the WhatsApp suite caught it (#58); 209 unit tests could not, because a fake
677
+ * backend always accepts.
678
+ *
679
+ * It reads the phone number itself rather than `/me`, and that choice is the point: a token
680
+ * can be perfectly valid and still have no access to THIS phone number id, which is the
681
+ * likelier misconfiguration of the two. Checking only the token would wave it through.
682
+ *
683
+ * Returns a result rather than a boolean, and never throws — `connect()` is specified to
684
+ * return false rather than throw, and the reason has to survive the trip: `auth_failed` and
685
+ * `rate_limit` ask a supervisor for opposite responses.
686
+ */
687
+ async verifyCredentials() {
688
+ let response;
689
+ try {
690
+ response = await this.fetchImpl(this.baseUrl, {
691
+ method: "GET",
692
+ headers: { authorization: `Bearer ${this.opts.accessToken}` }
693
+ });
694
+ } catch (cause) {
695
+ return {
696
+ ok: false,
697
+ error: {
698
+ code: "server_error",
699
+ message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`
700
+ }
701
+ };
702
+ }
703
+ const body = await response.json().catch(() => void 0);
704
+ if (!response.ok) {
705
+ return { ok: false, error: mapWhatsAppCloudError(response.status, body ?? {}) };
706
+ }
707
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
708
+ return {
709
+ ok: false,
710
+ error: {
711
+ code: "unknown",
712
+ message: `Meta answered ${response.status} with a body this client could not read.`
713
+ }
714
+ };
715
+ }
716
+ if (body.error !== void 0) {
717
+ return { ok: false, error: mapWhatsAppCloudError(response.status, body) };
718
+ }
719
+ if (String(body.id) !== this.opts.phoneNumberId) {
720
+ return {
721
+ ok: false,
722
+ error: {
723
+ code: "invalid_request",
724
+ message: `Credential is valid but resolves to node ${String(body.id)}, not the configured phoneNumberId ${this.opts.phoneNumberId}. A WhatsApp Business Account id in place of a phone number id looks exactly like this.`
725
+ }
726
+ };
727
+ }
728
+ return { ok: true };
729
+ }
662
730
  /**
663
731
  * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.
664
732
  *
@@ -817,6 +885,28 @@ function metaStatusToReceipt(s) {
817
885
  var WhatsAppCloudBackend = class {
818
886
  kind = "cloud";
819
887
  client;
888
+ /** Verified once by `connect()`; cleared by `disconnect()`. */
889
+ connected = false;
890
+ /**
891
+ * The verification currently in flight, shared by every caller that arrives during it.
892
+ *
893
+ * A flag alone only guards callers that arrive AFTER one finished — two simultaneous
894
+ * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a
895
+ * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it
896
+ * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay
897
+ * distinguishable from a revoked token.
898
+ */
899
+ connecting;
900
+ /**
901
+ * Which connection attempt is current.
902
+ *
903
+ * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in
904
+ * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every
905
+ * later `connect()` would short-circuit on a flag no live check stands behind — the field's own
906
+ * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend
907
+ * carries, for the same reason.
908
+ */
909
+ generation = 0;
820
910
  appSecret;
821
911
  inboundHandler;
822
912
  statusHandler;
@@ -830,14 +920,64 @@ var WhatsAppCloudBackend = class {
830
920
  this.appSecret = opts.appSecret;
831
921
  }
832
922
  // Cloud has no persistent connection — webhook is push, send is HTTP.
923
+ /**
924
+ * Confirm with Meta that this credential can act as this phone number.
925
+ *
926
+ * This used to be `return true`. A consumer with a wrong, expired or revoked token got success
927
+ * at startup and found out from messages that silently never arrived — no error, no log,
928
+ * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the
929
+ * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.
930
+ *
931
+ * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would
932
+ * turn a supervisor's health check into a rate-limit source against Meta.
933
+ *
934
+ * Returns false rather than throwing — the contract each sibling adapter is tested against,
935
+ * because a throw at startup takes the whole runner down with it. The reason goes to stderr
936
+ * first: told only "false", a supervisor cannot tell a revoked token, which needs a human,
937
+ * from a rate limit, which needs a wait.
938
+ */
833
939
  async connect() {
940
+ if (this.connected) return true;
941
+ if (this.connecting !== void 0) return this.connecting;
942
+ const attempt = this.verifyOnce(++this.generation);
943
+ this.connecting = attempt;
944
+ try {
945
+ return await attempt;
946
+ } finally {
947
+ if (this.connecting === attempt) this.connecting = void 0;
948
+ }
949
+ }
950
+ /** One credential check, mapped to the boolean `connect()` is contracted to return. @internal */
951
+ async verifyOnce(generation) {
952
+ const check = await this.client.verifyCredentials();
953
+ if (!check.ok) {
954
+ process.stderr.write(
955
+ `[whatsapp-cloud] connect failed: ${check.error?.code ?? "unknown"} \u2014 ${check.error?.message ?? "no reason given"}
956
+ `
957
+ );
958
+ return false;
959
+ }
960
+ if (this.generation !== generation) return false;
961
+ this.connected = true;
834
962
  return true;
835
963
  }
836
964
  async disconnect() {
965
+ this.generation += 1;
966
+ this.connected = false;
967
+ this.connecting = void 0;
837
968
  this.inboundHandler = void 0;
838
969
  this.statusHandler = void 0;
839
970
  }
840
971
  async send(message) {
972
+ if (!this.connected) {
973
+ return {
974
+ ok: false,
975
+ error: {
976
+ code: "not_connected",
977
+ message: "Cloud backend is not connected \u2014 call connect()."
978
+ }
979
+ };
980
+ }
841
981
  return this.client.sendText(message.to, message.text, message.isGroup);
842
982
  }
843
983
  /**
@@ -856,6 +996,15 @@ var WhatsAppCloudBackend = class {
856
996
  * @param components Values for the template's variables; omit for a template that takes none.
857
997
  */
858
998
  async sendTemplate(to, templateName, languageCode, components) {
999
+ if (!this.connected) {
1000
+ return {
1001
+ ok: false,
1002
+ error: {
1003
+ code: "not_connected",
1004
+ message: "Cloud backend is not connected \u2014 call connect()."
1005
+ }
1006
+ };
1007
+ }
859
1008
  return this.client.sendTemplate(to, templateName, languageCode, components);
860
1009
  }
861
1010
  onInbound(handler) {
@@ -1162,7 +1311,7 @@ var WhatsAppWebBackend = class {
1162
1311
  }
1163
1312
  async send(message) {
1164
1313
  if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
1165
- return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
1314
+ return { ok: false, error: { code: "not_connected", message: "Bridge not connected." } };
1166
1315
  }
1167
1316
  const msgId = `out-${++this.msgIdCounter}`;
1168
1317
  const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS2;