@theokit/gateway-sms 0.2.2 → 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,112 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.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
+ - 6f5948c: `smsWebhookVerifier(adapter)` — serve an SMS webhook through a framework channel seam.
44
+
45
+ A webhook seam takes a map of validators, and there was no way to put SMS in one. Twilio signs the
46
+ URL plus the sorted POST parameters, Plivo signs a different string, and Vonage uses a JWT — three
47
+ schemes that already live in this package with their own tests. Reimplementing them in the
48
+ framework would put security-critical code in two repositories and guarantee they drift, so the
49
+ direction is inverted: the framework declares the shape, and the package that owns the platform
50
+ provides the implementation.
51
+
52
+ ```ts
53
+ await handleChannelWebhook(request, pathname, {
54
+ validators: { sms: smsWebhookVerifier(adapter) },
55
+ });
56
+ ```
57
+
58
+ Nothing new is depended on. The return type is structural, declared here as `WebhookVerifyResult`.
59
+
60
+ **`SMSAdapter.publicUrl` is now public, and now does something.** All three backend option shapes
61
+ require it and document it as "used by signature verifier" — and no source file read it: it appeared
62
+ only in the type and in test fixtures. Twilio SIGNS that URL, so it matters most in exactly the case
63
+ the request cannot cover: behind a proxy or a tunnel, the request's own URL is the internal one and
64
+ will not match what was signed. The verifier uses it.
65
+
66
+ One behaviour worth knowing before wiring this: **connect the adapter first.** Each backend loads
67
+ its provider SDK during `connect()`, and until then `verifySignature` answers `false` for
68
+ everything — so a verifier wired earlier refuses every genuine delivery as a bad signature. The two
69
+ are not distinguishable through the backend contract, which returns a boolean; the behaviour is
70
+ pinned by a test rather than papered over.
71
+
72
+ ### Patch Changes
73
+
74
+ - 4b1d4bb: The half of an Express webhook server that is the same everywhere now lives in one place (#89).
75
+
76
+ `gateway-line` and `gateway-sms` each shipped one and shared 101 of ~170 lines: the lazy `express`
77
+ load, the raw-body capture with the hang it documents, and the start/stop lifecycle. What differs —
78
+ signature verification, body parsing, routing — stayed where it belongs.
79
+
80
+ It had already been paid for. A write-once latch made `start()` after `stop()` return without
81
+ creating a listener, which is a port nothing answers on with no error and no log, and the fix had to
82
+ be applied to both files by one commit because the latch lived in the copied half.
83
+
84
+ `@theokit/gateway` now exports `loadPeer`, `rawBodyCapture` and `listenerLifecycle`. **This does not
85
+ make express a dependency of the core**: nothing in that module imports it. Every shape is
86
+ structural — a request is whatever has `readableEnded` and `on`, a listener is whatever has `listen`
87
+ and `close` — so the two packages that use express keep declaring it and the core never learns the
88
+ name.
89
+
90
+ Every adapter README now states how inbound reaches it (#91): a webhook the application must
91
+ authenticate, a WebSocket, a sync loop, or an SDK that owns its own HTTP server. The three that have
92
+ no webhook say so with the reason, because an absence that is a decision should not read as a gap.
93
+
94
+ ## 0.2.3
95
+
96
+ ### Patch Changes
97
+
98
+ - 5e346e1: The webhook server can be started again after being stopped.
99
+
100
+ `started` and `stopped` were write-once. After a `stop()`, `start()` hit `if (started)` and returned
101
+ without creating a listener — so the server was silently dead: no error, no log, just a port nothing
102
+ answers on. The next `stop()` was a no-op for the same reason, in the other direction.
103
+
104
+ Anything that restarts a gateway — a config reload, a reconnect after a network fault, a supervisor
105
+ cycling the process in-band — got a server that reported success and served nothing.
106
+
107
+ Fixed in commit 11000cc on 2026-08-29; this changeset was missing, so the fix would have stayed
108
+ unreleased and npm would have gone on serving the broken code.
109
+
3
110
  ## 0.2.2
4
111
 
5
112
  ### Patch Changes
package/README.md CHANGED
@@ -10,6 +10,19 @@ Three backends, opt-in via peer-dep:
10
10
  | Plivo | `plivo` | `X-Plivo-Signature-V3` (HMAC-SHA256) |
11
11
  | Vonage | `@vonage/server-sdk` | `Authorization: Bearer <JWT>` |
12
12
 
13
+
14
+ ## How inbound arrives
15
+
16
+ **HTTP webhook**, and the application must authenticate it. Each provider signs differently —
17
+ Twilio over the URL plus the sorted POST parameters, Plivo over another string, Vonage with a JWT —
18
+ so the verification lives here rather than in a framework that would have to reimplement all three.
19
+
20
+ Two ways to serve it. `createWebhookServer` mounts the Express routes for you; or host the route
21
+ yourself and pass `smsWebhookVerifier(adapter)` to a framework webhook seam.
22
+
23
+ Set `publicUrl` to the address the provider posts to. Twilio SIGNS that URL, and behind a proxy that
24
+ rewrites `host` — a tunnel, an ingress, a load balancer terminating TLS — the address the request
25
+ arrived on is the internal one and every genuine delivery fails its signature.
13
26
  ## Install
14
27
 
15
28
  ```bash
package/dist/index.cjs CHANGED
@@ -418,7 +418,46 @@ function splitForSMS(text, limit = 1600) {
418
418
 
419
419
  // src/adapter.ts
420
420
  var SMSAdapter = class extends gateway.BasePlatformAdapter {
421
+ /**
422
+ * Whether the "this medium carries no formatting" warning has already been emitted.
423
+ *
424
+ * Once per adapter, not once per message: a gateway answering a busy channel would turn a
425
+ * useful diagnostic into a log flood, and a flooded log is one nobody reads — the same
426
+ * reason the group-mention and allowlist drops elsewhere in this family log once.
427
+ */
428
+ warnedAboutFormat = false;
429
+ /**
430
+ * Say, once, that a declared format is being dropped.
431
+ *
432
+ * `OutboundMessage.format` is the caller stating intent, and this medium has nowhere to put
433
+ * it: no flag, no markup, no alternative part. Discarding it in silence is the swallowed-
434
+ * error shape `rules/error-handling.md` refuses — nothing fails, and the caller learns their
435
+ * formatting never arrived from a user, weeks later.
436
+ *
437
+ * @internal
438
+ */
439
+ warnFormatUnsupported(format) {
440
+ if (format === void 0 || format === "plain") return;
441
+ if (this.warnedAboutFormat) return;
442
+ this.warnedAboutFormat = true;
443
+ process.stderr.write(
444
+ `[gateway-sms] format="${format}" was declared, and SMS cannot carry it \u2014 the medium is plain text. Sending unformatted; this is logged once.
445
+ `
446
+ );
447
+ }
421
448
  platform = "sms";
449
+ /**
450
+ * The URL the provider POSTs inbound to, as the provider sees it.
451
+ *
452
+ * Required by all three backend option shapes and documented there as "used by signature
453
+ * verifier" — and, measured 2026-08-31, read by nothing: it appeared only in the type and in test
454
+ * fixtures. Twilio SIGNS this URL, so the value matters most in exactly the case where the
455
+ * request cannot supply it: behind a proxy or a tunnel, the request's own URL is the internal one
456
+ * and will not match what was signed.
457
+ *
458
+ * Exposed so {@link smsWebhookVerifier} can use it, which is what makes the option true.
459
+ */
460
+ publicUrl;
422
461
  backend;
423
462
  inboundHandler;
424
463
  connected = false;
@@ -433,6 +472,7 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
433
472
  });
434
473
  }
435
474
  this.defaultCountry = opts.defaultCountry;
475
+ this.publicUrl = opts.publicUrl;
436
476
  this.backend = createBackend(opts);
437
477
  }
438
478
  async connect() {
@@ -460,6 +500,7 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
460
500
  }
461
501
  const parts = splitForSMS(out.text);
462
502
  let lastResult;
503
+ this.warnFormatUnsupported(out.format);
463
504
  for (const part of parts) {
464
505
  lastResult = await this.backend.sendMessage(toE164, part);
465
506
  if (lastResult.ok !== true) {
@@ -550,6 +591,15 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
550
591
  getBackendKind() {
551
592
  return this.backend.kind;
552
593
  }
594
+ /**
595
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
596
+ *
597
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
598
+ * named as the handler's failure rather than the platform's, and delivery continues.
599
+ */
600
+ async deliver(event) {
601
+ return this.runHandler(this.inboundHandler, event);
602
+ }
553
603
  };
554
604
  function secretFromOpts(opts) {
555
605
  switch (opts.backend) {
@@ -577,59 +627,39 @@ function parseInbound(options, ctx) {
577
627
  if (inbound.messageId === "") return null;
578
628
  return inboundToMessageEvent(inbound, options.backend);
579
629
  }
580
-
581
- // src/webhook-server.ts
582
630
  async function loadExpress() {
583
- try {
584
- const mod = await import('express');
585
- const fn = mod.default ?? mod;
586
- return { default: fn };
587
- } catch {
588
- throw new ConfigurationError({
589
- code: "express_not_installed",
590
- message: 'gateway-sms: peer-dep "express" not installed. Run: pnpm add express'
591
- });
592
- }
631
+ return gateway.loadPeer(
632
+ async () => import('express'),
633
+ () => {
634
+ throw new ConfigurationError({
635
+ code: "express_not_installed",
636
+ message: 'gateway-sms: peer-dep "express" not installed. Run: pnpm add express'
637
+ });
638
+ }
639
+ );
640
+ }
641
+ function signedUrl(req, headers, publicUrl) {
642
+ if (publicUrl !== void 0 && publicUrl !== "") return publicUrl;
643
+ const protoHeader = headers["x-forwarded-proto"];
644
+ const proto = protoHeader ?? (req.secure ? "https" : "http");
645
+ const host = req.get("host") ?? "localhost";
646
+ return `${proto}://${host}${req.originalUrl}`;
593
647
  }
594
- function buildSignatureContext(req) {
648
+ function buildSignatureContext(req, publicUrl) {
595
649
  const rawBody = req.rawBody ?? "";
596
650
  const headers = {};
597
651
  for (const [k, v] of Object.entries(req.headers)) {
598
652
  headers[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v ?? "";
599
653
  }
600
- const protoHeader = headers["x-forwarded-proto"];
601
- const proto = protoHeader ?? (req.secure ? "https" : "http");
602
- const host = req.get("host") ?? "localhost";
603
- const url = `${proto}://${host}${req.originalUrl}`;
604
- return { headers, rawBody, url };
654
+ return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };
605
655
  }
606
656
  async function createWebhookServer(opts) {
607
- const expressMod = await loadExpress();
608
- const app = opts.app ?? expressMod.default();
657
+ const createApp = await loadExpress();
658
+ const app = opts.app ?? createApp();
609
659
  const prefix = opts.path ?? "/sms";
610
660
  const backend = opts.adapter.getBackendKind();
611
- const rawCapture = (req, _res, next) => {
612
- if (req.readableEnded || req.complete) {
613
- process.stderr.write(
614
- "[gateway-sms] 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\n"
615
- );
616
- req.rawBody = "";
617
- next();
618
- return;
619
- }
620
- let buf = "";
621
- req.setEncoding("utf8");
622
- req.on("data", (chunk) => {
623
- buf += chunk;
624
- });
625
- req.on("end", () => {
626
- req.rawBody = buf;
627
- next();
628
- });
629
- req.on("error", (err) => next(err));
630
- };
631
661
  const handler = (req, res) => {
632
- const ctx = buildSignatureContext(req);
662
+ const ctx = buildSignatureContext(req, opts.adapter.publicUrl);
633
663
  if (!opts.adapter.verifySignature(ctx)) {
634
664
  res.status(401).type("text/plain").send("invalid signature");
635
665
  return;
@@ -649,31 +679,27 @@ async function createWebhookServer(opts) {
649
679
  });
650
680
  res.status(204).end();
651
681
  };
652
- app.post(`${prefix}/${backend}`, rawCapture, handler);
653
- let server;
654
- let started = false;
655
- let stopped = false;
656
- return {
657
- async start() {
658
- if (started || opts.app !== void 0) {
659
- started = true;
660
- return;
661
- }
662
- const port = opts.port ?? 3e3;
663
- await new Promise((resolve) => {
664
- server = app.listen(port, () => resolve());
665
- });
666
- started = true;
667
- },
668
- async stop() {
669
- if (stopped) return;
670
- stopped = true;
671
- if (server === void 0) return;
672
- await new Promise((resolve) => {
673
- server?.close(() => resolve());
674
- });
675
- server = void 0;
676
- }
682
+ app.post(`${prefix}/${backend}`, gateway.rawBodyCapture("gateway-sms"), handler);
683
+ return gateway.listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
684
+ }
685
+
686
+ // src/webhook-verifier.ts
687
+ function headersOf(request) {
688
+ const out = {};
689
+ request.headers.forEach((value, key) => {
690
+ out[key] = value;
691
+ });
692
+ return out;
693
+ }
694
+ function smsWebhookVerifier(adapter, opts = {}) {
695
+ return async (request) => {
696
+ const rawBody = await request.text();
697
+ const ctx = {
698
+ headers: headersOf(request),
699
+ rawBody,
700
+ url: opts.publicUrl ?? adapter.publicUrl ?? request.url
701
+ };
702
+ return adapter.verifySignature(ctx) ? { ok: true } : { ok: false, reason: "signature mismatch" };
677
703
  };
678
704
  }
679
705
 
@@ -683,6 +709,7 @@ exports.SMSAdapter = SMSAdapter;
683
709
  exports.createWebhookServer = createWebhookServer;
684
710
  exports.normalizeE164 = normalizeE164;
685
711
  exports.parseInbound = parseInbound;
712
+ exports.smsWebhookVerifier = smsWebhookVerifier;
686
713
  exports.splitForSMS = splitForSMS;
687
714
  //# sourceMappingURL=index.cjs.map
688
715
  //# sourceMappingURL=index.cjs.map