@theokit/gateway-sms 0.2.3 → 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,96 @@
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
+
3
94
  ## 0.2.3
4
95
 
5
96
  ### 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
@@ -446,6 +446,18 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
446
446
  );
447
447
  }
448
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;
449
461
  backend;
450
462
  inboundHandler;
451
463
  connected = false;
@@ -460,6 +472,7 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
460
472
  });
461
473
  }
462
474
  this.defaultCountry = opts.defaultCountry;
475
+ this.publicUrl = opts.publicUrl;
463
476
  this.backend = createBackend(opts);
464
477
  }
465
478
  async connect() {
@@ -578,6 +591,15 @@ var SMSAdapter = class extends gateway.BasePlatformAdapter {
578
591
  getBackendKind() {
579
592
  return this.backend.kind;
580
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
+ }
581
603
  };
582
604
  function secretFromOpts(opts) {
583
605
  switch (opts.backend) {
@@ -605,59 +627,39 @@ function parseInbound(options, ctx) {
605
627
  if (inbound.messageId === "") return null;
606
628
  return inboundToMessageEvent(inbound, options.backend);
607
629
  }
608
-
609
- // src/webhook-server.ts
610
630
  async function loadExpress() {
611
- try {
612
- const mod = await import('express');
613
- const fn = mod.default ?? mod;
614
- return { default: fn };
615
- } catch {
616
- throw new ConfigurationError({
617
- code: "express_not_installed",
618
- message: 'gateway-sms: peer-dep "express" not installed. Run: pnpm add express'
619
- });
620
- }
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}`;
621
647
  }
622
- function buildSignatureContext(req) {
648
+ function buildSignatureContext(req, publicUrl) {
623
649
  const rawBody = req.rawBody ?? "";
624
650
  const headers = {};
625
651
  for (const [k, v] of Object.entries(req.headers)) {
626
652
  headers[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v ?? "";
627
653
  }
628
- const protoHeader = headers["x-forwarded-proto"];
629
- const proto = protoHeader ?? (req.secure ? "https" : "http");
630
- const host = req.get("host") ?? "localhost";
631
- const url = `${proto}://${host}${req.originalUrl}`;
632
- return { headers, rawBody, url };
654
+ return { headers, rawBody, url: signedUrl(req, headers, publicUrl) };
633
655
  }
634
656
  async function createWebhookServer(opts) {
635
- const expressMod = await loadExpress();
636
- const app = opts.app ?? expressMod.default();
657
+ const createApp = await loadExpress();
658
+ const app = opts.app ?? createApp();
637
659
  const prefix = opts.path ?? "/sms";
638
660
  const backend = opts.adapter.getBackendKind();
639
- const rawCapture = (req, _res, next) => {
640
- if (req.readableEnded || req.complete) {
641
- process.stderr.write(
642
- "[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"
643
- );
644
- req.rawBody = "";
645
- next();
646
- return;
647
- }
648
- let buf = "";
649
- req.setEncoding("utf8");
650
- req.on("data", (chunk) => {
651
- buf += chunk;
652
- });
653
- req.on("end", () => {
654
- req.rawBody = buf;
655
- next();
656
- });
657
- req.on("error", (err) => next(err));
658
- };
659
661
  const handler = (req, res) => {
660
- const ctx = buildSignatureContext(req);
662
+ const ctx = buildSignatureContext(req, opts.adapter.publicUrl);
661
663
  if (!opts.adapter.verifySignature(ctx)) {
662
664
  res.status(401).type("text/plain").send("invalid signature");
663
665
  return;
@@ -677,33 +679,27 @@ async function createWebhookServer(opts) {
677
679
  });
678
680
  res.status(204).end();
679
681
  };
680
- app.post(`${prefix}/${backend}`, rawCapture, handler);
681
- let server;
682
- let started = false;
683
- let stopped = false;
684
- return {
685
- async start() {
686
- if (started || opts.app !== void 0) {
687
- started = true;
688
- return;
689
- }
690
- stopped = false;
691
- const port = opts.port ?? 3e3;
692
- await new Promise((resolve) => {
693
- server = app.listen(port, () => resolve());
694
- });
695
- started = true;
696
- },
697
- async stop() {
698
- if (stopped) return;
699
- stopped = true;
700
- started = false;
701
- if (server === void 0) return;
702
- await new Promise((resolve) => {
703
- server?.close(() => resolve());
704
- });
705
- server = void 0;
706
- }
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" };
707
703
  };
708
704
  }
709
705
 
@@ -713,6 +709,7 @@ exports.SMSAdapter = SMSAdapter;
713
709
  exports.createWebhookServer = createWebhookServer;
714
710
  exports.normalizeE164 = normalizeE164;
715
711
  exports.parseInbound = parseInbound;
712
+ exports.smsWebhookVerifier = smsWebhookVerifier;
716
713
  exports.splitForSMS = splitForSMS;
717
714
  //# sourceMappingURL=index.cjs.map
718
715
  //# sourceMappingURL=index.cjs.map