@theokit/gateway 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,98 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b38172b: **The peer floor on `@theokit/gateway` rises with this release.** Every adapter now implements
8
+ `deliver` over `runHandler`, and neither exists in an older core — an adapter installed against one
9
+ does not build. `dep-check` caught that by building the whole workspace against the floor each
10
+ package claimed, which is the one thing a version range cannot tell you by reading it.
11
+
12
+ The floor is set in the version commit rather than here, because a range cannot name a version that
13
+ does not exist yet: raised in the workspace, the same gate then fails the other way round — every
14
+ adapter declaring a floor above the core installed beside it. That is the shape `fa70153` used when
15
+ these ranges were first written.
16
+
17
+ `deliver(event)` — every adapter can now be handed an event that arrived out of band (#83).
18
+
19
+ `onInbound` was the seam every adapter implemented and it had no public counterpart. Six platforms
20
+ self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync loop, IMAP — so
21
+ the asymmetry stayed invisible: `GatewayRunner` worked for eight platforms and silently did nothing
22
+ for LINE and WhatsApp Cloud, whose payloads arrive on an HTTP route the application owns. Every app
23
+ wired those two by hand, beside the runner rather than through it.
24
+
25
+ ```ts
26
+ const outcome = await adapter.deliver(event); // "ok" | "no_handler" | "handler_threw"
27
+ ```
28
+
29
+ The three outcomes are distinguished because a caller acts on them differently: answering a webhook
30
+ 200 when nobody was subscribed tells the provider to stop retrying a message nothing received.
31
+
32
+ `BasePlatformAdapter.runHandler` holds the containment once, where ten copies of it used to live —
33
+ a handler is user code, its throw is named as the handler's failure rather than the platform's, and
34
+ delivery continues. Each adapter's `deliver` is one line over it.
35
+
36
+ Also: `gateway-sms`'s `createWebhookServer` now signs against the configured `publicUrl` (#90).
37
+ Twilio verifies against the URL it POSTed to, and behind a proxy that rewrites `host` — a tunnel, an
38
+ ingress, a load balancer terminating TLS — the reconstruction from headers yields the internal
39
+ address, so a correct signature fails on every delivery. `publicUrl` is required by all three
40
+ backend option shapes and documented as "used by signature verifier"; until now no source file read
41
+ it. The header reconstruction stays as the fallback for an app served directly.
42
+
43
+ - 4b1d4bb: The half of an Express webhook server that is the same everywhere now lives in one place (#89).
44
+
45
+ `gateway-line` and `gateway-sms` each shipped one and shared 101 of ~170 lines: the lazy `express`
46
+ load, the raw-body capture with the hang it documents, and the start/stop lifecycle. What differs —
47
+ signature verification, body parsing, routing — stayed where it belongs.
48
+
49
+ It had already been paid for. A write-once latch made `start()` after `stop()` return without
50
+ creating a listener, which is a port nothing answers on with no error and no log, and the fix had to
51
+ be applied to both files by one commit because the latch lived in the copied half.
52
+
53
+ `@theokit/gateway` now exports `loadPeer`, `rawBodyCapture` and `listenerLifecycle`. **This does not
54
+ make express a dependency of the core**: nothing in that module imports it. Every shape is
55
+ structural — a request is whatever has `readableEnded` and `on`, a listener is whatever has `listen`
56
+ and `close` — so the two packages that use express keep declaring it and the core never learns the
57
+ name.
58
+
59
+ Every adapter README now states how inbound reaches it (#91): a webhook the application must
60
+ authenticate, a WebSocket, a sync loop, or an SDK that owns its own HTTP server. The three that have
61
+ no webhook say so with the reason, because an absence that is a decision should not read as a gap.
62
+
63
+ - 348bc02: WhatsApp: send to the address that routes, and answer where the message came from (#82, #84).
64
+
65
+ **A send that WhatsApp discards no longer reports success.** Baileys hands back a
66
+ locally-generated `wamid` whether or not the JID routes anywhere, and the backend treated that id
67
+ as proof of delivery — so a message nobody received was recorded as a success by the caller's log,
68
+ its metrics and its retry logic. Measured on a real account: `5535998838687` and `553598838687` are
69
+ the same Brazilian line, both answered `ok: true`, and only the second arrived.
70
+
71
+ `send` now asks WhatsApp which form it routes to before sending, and refuses a number the server
72
+ does not know with `undeliverable` naming the number. That fixes the Brazilian ninth digit without a
73
+ Brazil-specific rule anywhere in this package — the answer is whatever the server says, for any
74
+ country. The lookup is cached for the life of the session, so it costs one round-trip per recipient.
75
+
76
+ **An inbound event now carries the address it arrived on**, as `whatsapp.channelJid`. `channel.id`
77
+ is normalised to digits — which is what an allowlist compares — and that normalisation strips the
78
+ domain, the part that says whether an address is a phone, a group, or an account's linked identity.
79
+ A note-to-self arrives addressed by LID, so replying to `channel.id` rebuilt `…@s.whatsapp.net`, an
80
+ address that does not exist.
81
+
82
+ **`send` accepts a qualified JID verbatim.** A `to` containing `@` is already an address and is
83
+ passed through untouched, where it used to become `231116569108705@lid@s.whatsapp.net`. So
84
+ answering an inbound event is now:
85
+
86
+ ```ts
87
+ await adapter.sendMessage({
88
+ channel: { id: event.whatsapp.channelJid ?? event.channel.id, type: "dm" },
89
+ text,
90
+ });
91
+ ```
92
+
93
+ Not affected: the Cloud backend. Meta rejects an unroutable recipient with an error code, so the
94
+ same mistake surfaces there instead of vanishing.
95
+
3
96
  ## 0.8.0
4
97
 
5
98
  ### Minor Changes
package/README.md CHANGED
@@ -13,6 +13,31 @@ pnpm add @theokit/gateway-telegram grammy
13
13
  pnpm add @theokit/gateway-discord discord.js
14
14
  ```
15
15
 
16
+
17
+ ## How each adapter treats `OutboundMessage.format`
18
+
19
+ **All ten honour it** — they read the field and let it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
20
+ to read ten packages to learn which — so the classes are stated here.
21
+
22
+ | Platform | What it does with `format` |
23
+ |---|---|
24
+ | telegram | sets `parse_mode` |
25
+ | slack | sets `mrkdwn` |
26
+ | matrix | `html` only: sends `formatted_body` + `format: org.matrix.custom.html`, retrying as plain text if the homeserver refuses it. **`markdown` is dropped with a warning** — `formatted_body` promises HTML, and putting markdown there renders literal asterisks AND silently eats any `<tag>` in the text |
27
+ | teams | sets `textFormat` on the activity |
28
+ | email | sends an `html` part **alongside** `text`, never instead of it. `html` passes through verbatim (the caller owns that trust boundary); `markdown` is HTML-escaped into a `<pre>` block, so it is preserved and readable, not parsed |
29
+ | discord, mattermost | markdown is native, so `markdown` needs no flag; **`plain` escapes** `*_\`~` so a user's literal asterisks stay literal |
30
+ | line, sms, whatsapp | the platform carries no formatting on this message type — the adapter logs once that the declared format was dropped, rather than discarding it in silence |
31
+
32
+ **What none of them does is convert markdown to a platform's dialect.** `format` states the
33
+ caller's INTENT and lets the transport act on it; translating `**bold**` into WhatsApp's
34
+ `*bold*` is a presentation concern and is tracked separately.
35
+
36
+ Measured 2026-08-30: before this, two of ten read the field. An agent answered
37
+ `**Bom Sucesso (MG)**` and LINE and WhatsApp delivered literal asterisks, which is what a
38
+ declared-and-ignored field costs at the far end.
39
+
40
+
16
41
  ## Architecture (5 pieces)
17
42
 
18
43
  | Module | Responsibility |
@@ -74,6 +99,63 @@ on an unparseable payload means the 200 is never built. Mounted in a TheoKit rou
74
99
  reaches that route's error boundary and is answered **500**: the platform sees a failed delivery
75
100
  where it expected an acknowledgement.
76
101
 
102
+ ### WhatsApp, since `theokit@0.60.0`
103
+
104
+ Until that release this was impossible rather than undocumented: `theokit/server/webhook`
105
+ exported no `whatsapp` validator, so the `validators` map could not carry one and the path
106
+ answered 404 by construction. Meta's subscribe handshake had no seam at all
107
+ ([usetheokit/theokit#556](https://github.com/usetheokit/theokit/issues/556), filed from
108
+ here). Both halves exist now, and the wiring needs three things that are easy to miss:
109
+
110
+ ```ts
111
+ import { handleChannelWebhook } from "theokit/server/agent";
112
+ import { route } from "theokit/server/define";
113
+ import { whatsapp, whatsappSubscribe } from "theokit/server/webhook";
114
+ import { normalizeInboundMessages, parseWebhookPayload } from "@theokit/gateway-whatsapp";
115
+
116
+ const handle = ({ request }: { request: Request }) =>
117
+ handleChannelWebhook(request, new URL(request.url).pathname, {
118
+ validators: { whatsapp: whatsapp({ appSecret: process.env.META_APP_SECRET! }) },
119
+ subscribe: { whatsapp: whatsappSubscribe({ verifyToken: process.env.META_VERIFY_TOKEN! }) },
120
+ onMessage: async ({ payload }) => {
121
+ const envelope = parseWebhookPayload(payload);
122
+ if (envelope === null) return; // not a shape we know — answer normally
123
+ for (const event of normalizeInboundMessages(envelope)) {
124
+ console.log(`${event.from}: ${event.text}`);
125
+ }
126
+ },
127
+ });
128
+
129
+ // BOTH verbs, and `.csrf(false)` on each.
130
+ export const GET = route().csrf(false).policy("public").handler(handle).build();
131
+ export const POST = route().csrf(false).policy("public").handler(handle).build();
132
+ ```
133
+
134
+ - **`GET` as well as `POST`.** Meta calls the endpoint once with
135
+ `?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…` and expects the challenge echoed as
136
+ `text/plain` before it delivers anything. That is what `subscribe` answers. A `GET` on a
137
+ platform that has a validator and no `subscribe` entry is **405**, not 404 — configured, but
138
+ it does not do handshakes.
139
+ - **`.csrf(false)` on both.** Without it the route answers `403 CSRF_INVALID: Missing
140
+ X-Theo-Action header` before the signature is ever checked, and Meta will never send that
141
+ header. `policy("public")` answers a different question — may an unauthenticated caller reach
142
+ this — and does not lift the CSRF gate. The HMAC is strictly stronger than the header it
143
+ replaces, and Meta carries no session for a third-party page to ride.
144
+ - **`appSecret` is the Meta *app secret*,** not the access token. It accepts an array so a
145
+ rotation can verify against either.
146
+
147
+ This package also exports `verifyWebhookSignature` and `verifyWebhookSubscription`, which do
148
+ the same two jobs. Use theokit's when you are on this seam; ours exist for an app that is not,
149
+ and they are what `gateway-sms` uses through its own `createWebhookServer`.
150
+
151
+ Not verified here: the `theokit` behaviour above was measured by the session that shipped
152
+ 0.60.0, driving a scaffolded app over HTTP. What this repository checked is narrower and
153
+ stated as such — that `theokit@0.60.0` does export `whatsapp` and `whatsappSubscribe` from
154
+ `theokit/server/webhook`, that `route` lives on `theokit/server/define` rather than on the
155
+ `theokit/server` umbrella that warns it is deprecated, and that `parseWebhookPayload` takes the
156
+ `unknown` payload `onMessage` hands over. A real delivery from Meta needs an approved app and a public URL, and
157
+ has not happened on either side.
158
+
77
159
  `parseInbound` under that name exists on `@theokit/gateway-telegram` and `@theokit/gateway-sms`,
78
160
  with different arguments: SMS takes `(options, ctx)` because the `SignatureContext` it needs carries
79
161
  the raw body, the headers and the URL, and `ChannelMessage` provides none of the three — so it is wired through its
package/dist/index.cjs CHANGED
@@ -4,6 +4,30 @@ var sdk = require('@theokit/sdk');
4
4
 
5
5
  // src/adapter/base.ts
6
6
  var BasePlatformAdapter = class {
7
+ /**
8
+ * Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
9
+ *
10
+ * A handler is USER code and may throw. An adapter must contain that throw, name it as the
11
+ * handler's failure rather than the platform's, and keep delivering — one bad message ends
12
+ * neither the process nor the connection. Two adapters once discarded the rejection with `void`,
13
+ * which under Node's default ends the process; two more reported it as a platform-client error,
14
+ * sending whoever debugged their own handler to the wrong repository (#41).
15
+ *
16
+ * Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
17
+ * is taken from `this.platform`, which is the only part that differed between them.
18
+ */
19
+ async runHandler(handler, event) {
20
+ if (handler === void 0) return "no_handler";
21
+ try {
22
+ await handler(event);
23
+ } catch (err) {
24
+ const message = err instanceof Error ? err.message : String(err);
25
+ process.stderr.write(`[${this.platform}] handler threw: ${message}
26
+ `);
27
+ return "handler_threw";
28
+ }
29
+ return "ok";
30
+ }
7
31
  /** Lifecycle: emit a typing indicator. Default: noop. */
8
32
  async startTyping(_channelId) {
9
33
  }
@@ -131,9 +155,44 @@ function redactSecrets(value) {
131
155
  }
132
156
 
133
157
  // src/hooks/executor.ts
158
+ var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
159
+ function malformedHook(index, why) {
160
+ return new GatewayConfigurationError("gateway", {
161
+ code: "malformed_hook",
162
+ message: `gateway: hooks[${index}] ${why}`,
163
+ detail: `hooks[${index}]`
164
+ });
165
+ }
166
+ function assertHook(entry, index) {
167
+ if (typeof entry !== "object" || entry === null) {
168
+ throw malformedHook(index, `is ${entry === null ? "null" : typeof entry}, not a hook object`);
169
+ }
170
+ const hook = entry;
171
+ if (typeof hook.name !== "string" || hook.name.length === 0) {
172
+ throw malformedHook(
173
+ index,
174
+ "has no name \u2014 every hook is named so a log can say which one acted"
175
+ );
176
+ }
177
+ const declared = HOOK_PHASES.filter((phase) => hook[phase] !== void 0);
178
+ if (declared.length === 0) {
179
+ throw malformedHook(
180
+ index,
181
+ `("${hook.name}") declares none of ${HOOK_PHASES.join(", ")} \u2014 it would never run`
182
+ );
183
+ }
184
+ for (const phase of declared) {
185
+ if (typeof hook[phase] !== "function") {
186
+ throw malformedHook(index, `("${hook.name}") declares ${phase}, which is not callable`);
187
+ }
188
+ }
189
+ }
134
190
  var HookExecutor = class {
135
191
  constructor(hooks) {
136
192
  this.hooks = hooks;
193
+ hooks.forEach((hook, index) => {
194
+ assertHook(hook, index);
195
+ });
137
196
  }
138
197
  hooks;
139
198
  /**
@@ -289,6 +348,15 @@ var GatewayRunner = class {
289
348
  );
290
349
  this.connected = false;
291
350
  }
351
+ /**
352
+ * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
353
+ * settled dispatch that is never removed is a leak that grows for the life of the process, and it
354
+ * is invisible from the outside — `stop()` drains correctly either way, because settled promises
355
+ * resolve immediately whether or not anyone deleted them.
356
+ */
357
+ get _inflightSize() {
358
+ return this.inflight.size;
359
+ }
292
360
  /** @internal */
293
361
  async dispatch(event) {
294
362
  const ctx = this.buildContext(event);
@@ -479,6 +547,69 @@ function chunkByGrapheme(text, options) {
479
547
  return parts;
480
548
  }
481
549
 
550
+ // src/webhook/express-server.ts
551
+ async function loadPeer(load, onMissing) {
552
+ try {
553
+ const mod = await load();
554
+ return mod.default ?? mod;
555
+ } catch {
556
+ onMissing();
557
+ }
558
+ }
559
+ function rawBodyCapture(tag) {
560
+ return (rawReq, _res, next) => {
561
+ const req = rawReq;
562
+ if (req.readableEnded === true || req.complete === true) {
563
+ process.stderr.write(
564
+ `[${tag}] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash
565
+ `
566
+ );
567
+ req.rawBody = "";
568
+ next();
569
+ return;
570
+ }
571
+ let buf = "";
572
+ req.setEncoding("utf8");
573
+ req.on("data", (chunk) => {
574
+ buf += chunk;
575
+ });
576
+ req.on("end", () => {
577
+ req.rawBody = buf;
578
+ next();
579
+ });
580
+ req.on("error", (err) => next(err));
581
+ };
582
+ }
583
+ function listenerLifecycle(opts) {
584
+ let started = false;
585
+ let stopped = false;
586
+ let listener;
587
+ return {
588
+ async start() {
589
+ if (started || opts.injected) {
590
+ started = true;
591
+ return;
592
+ }
593
+ stopped = false;
594
+ await new Promise((resolve) => {
595
+ listener = opts.app.listen(opts.port, () => resolve());
596
+ });
597
+ started = true;
598
+ },
599
+ async stop() {
600
+ if (stopped) return;
601
+ stopped = true;
602
+ started = false;
603
+ const current = listener;
604
+ listener = void 0;
605
+ if (current === void 0) return;
606
+ await new Promise((resolve) => {
607
+ current.close(() => resolve());
608
+ });
609
+ }
610
+ };
611
+ }
612
+
482
613
  exports.BasePlatformAdapter = BasePlatformAdapter;
483
614
  exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
484
615
  exports.DeliveryRouter = DeliveryRouter;
@@ -490,7 +621,10 @@ exports.SessionRouter = SessionRouter;
490
621
  exports.chunkByGrapheme = chunkByGrapheme;
491
622
  exports.chunkText = chunkText;
492
623
  exports.defaultStrategy = defaultStrategy;
624
+ exports.listenerLifecycle = listenerLifecycle;
625
+ exports.loadPeer = loadPeer;
493
626
  exports.maskShapes = maskShapes;
627
+ exports.rawBodyCapture = rawBodyCapture;
494
628
  exports.redactSecrets = redactSecrets;
495
629
  //# sourceMappingURL=index.cjs.map
496
630
  //# sourceMappingURL=index.cjs.map