@theokit/gateway-sms 0.3.3 → 0.5.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,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2d91e29: Ship `tlonUrbitChannel` and `smsChannel` (Twilio) `ChannelDescriptor`s with env bindings for `createChannels` and `configFromEnv`.
8
+
9
+ ## 0.4.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 21184a8: Export `twilioRequestVerifier` (standalone Twilio signature check for SMS and voice webhooks) and `twiml` builders.
14
+
3
15
  ## 0.3.3
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -79,6 +79,26 @@ For local development, `ngrok http 3000` and use the `https://*.ngrok.io` URL.
79
79
 
80
80
  If a request arrives without (or with invalid) signature, the webhook responds `401 Unauthorized` BEFORE any handler dispatch.
81
81
 
82
+ ## Twilio voice webhooks and TwiML
83
+
84
+ Twilio signs voice webhooks like SMS ones. `twilioRequestVerifier` checks them without an adapter or the `twilio` SDK (HMAC-SHA1 of the URL plus sorted form parameters, constant-time compare). Failures carry a reason: `missing X-Twilio-Signature header` or `signature mismatch`. Behind a proxy set `publicUrl`; JSON bodies (`bodySHA256`) are not supported.
85
+
86
+ ```ts
87
+ import { twilioRequestVerifier, twiml } from "@theokit/gateway-sms";
88
+
89
+ const verify = twilioRequestVerifier({ authToken: process.env.TWILIO_AUTH_TOKEN!, publicUrl });
90
+ const result = await verify(request.clone());
91
+ if (!result.ok) return new Response(result.reason, { status: 401 });
92
+
93
+ const xml = twiml.response(
94
+ twiml.say("How can I help?"),
95
+ twiml.gather({ action: "/voice/turn", input: "speech", timeoutSeconds: 5 }),
96
+ twiml.redirect("/voice/turn"),
97
+ );
98
+ ```
99
+
100
+ `twiml.say`, `gather`, `redirect`, `hangup` and `response` escape every text node and attribute.
101
+
82
102
  ## Multipart split (D393)
83
103
 
84
104
  Outbound messages longer than 1600 chars are split into `(1/N) ...` / `(2/N) ...` parts. Split is grapheme-cluster safe (`Intl.Segmenter`) so emoji and combining characters are not severed.
@@ -116,3 +136,27 @@ The live smoke sends one real SMS through Twilio's API (test creds work; they co
116
136
  ## ADRs
117
137
 
118
138
  D389 – D396 in `.claude/knowledge-base/adrs/`.
139
+
140
+ ## Channel descriptor
141
+
142
+ `smsChannel` is a `ChannelDescriptor` for `createChannels` and `configFromEnv`. It builds the
143
+ Twilio backend only; use `new SMSAdapter(...)` directly for Plivo, Vonage or `defaultCountry`.
144
+
145
+ ```typescript
146
+ import { configFromEnv, createChannels } from "@theokit/gateway";
147
+ import { smsChannel } from "@theokit/gateway-sms";
148
+
149
+ const { config, missing } = configFromEnv(smsChannel, process.env, "APP_");
150
+ const { adapters, rejected } = createChannels([{ descriptor: smsChannel, config }]);
151
+ ```
152
+
153
+ | Key | Env name | Required | Secret |
154
+ | --- | --- | --- | --- |
155
+ | `accountSid` | `SMS_ACCOUNT_SID` | yes | no |
156
+ | `authToken` | `SMS_AUTH_TOKEN` | yes | yes |
157
+ | `fromNumber` | `SMS_FROM_NUMBER` | yes | no |
158
+ | `publicUrl` | `SMS_PUBLIC_URL` | yes | no |
159
+
160
+ `create` throws `ConfigurationError` (`invalid_config`) naming the key for a missing or non-string
161
+ value. The descriptor declares `transport: "socket"`; inbound messages still arrive through a
162
+ webhook you host (`createWebhookServer`), which this descriptor does not set up.
package/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var gateway = require('@theokit/gateway');
4
4
  var libphonenumberJs = require('libphonenumber-js');
5
+ var crypto = require('crypto');
5
6
 
6
7
  // src/adapter.ts
7
8
  var ConfigurationError = class extends gateway.GatewayConfigurationError {
@@ -632,6 +633,65 @@ function secretFromOpts(opts) {
632
633
  }
633
634
  }
634
635
 
636
+ // src/channel.ts
637
+ var KEYS = ["accountSid", "authToken", "fromNumber", "publicUrl"];
638
+ function readString(config, key) {
639
+ const value = config[key];
640
+ if (typeof value !== "string" || value.trim().length === 0) {
641
+ throw new ConfigurationError({
642
+ code: "invalid_config",
643
+ message: `gateway-sms: config.${key} must be a non-empty string`,
644
+ detail: key
645
+ });
646
+ }
647
+ return value;
648
+ }
649
+ var CONFIG = [
650
+ {
651
+ key: "accountSid",
652
+ required: true,
653
+ secret: false,
654
+ env: "SMS_ACCOUNT_SID",
655
+ description: "The Twilio account SID."
656
+ },
657
+ {
658
+ key: "authToken",
659
+ required: true,
660
+ secret: true,
661
+ env: "SMS_AUTH_TOKEN",
662
+ description: "The Twilio auth token; also verifies inbound signatures."
663
+ },
664
+ {
665
+ key: "fromNumber",
666
+ required: true,
667
+ secret: false,
668
+ env: "SMS_FROM_NUMBER",
669
+ description: "The bot's own E.164 number, used as the sender."
670
+ },
671
+ {
672
+ key: "publicUrl",
673
+ required: true,
674
+ secret: false,
675
+ env: "SMS_PUBLIC_URL",
676
+ description: "The public URL Twilio posts inbound messages to."
677
+ }
678
+ ];
679
+ var smsChannel = {
680
+ platform: "sms",
681
+ transport: "socket",
682
+ config: CONFIG,
683
+ create(config) {
684
+ const [accountSid, authToken, fromNumber, publicUrl] = KEYS.map((k) => readString(config, k));
685
+ return new SMSAdapter({
686
+ backend: "twilio",
687
+ accountSid,
688
+ authToken,
689
+ fromNumber,
690
+ publicUrl
691
+ });
692
+ }
693
+ };
694
+
635
695
  // src/parse-inbound.ts
636
696
  function parseInbound(options, ctx) {
637
697
  const backend = createBackend(options);
@@ -644,6 +704,80 @@ function parseInbound(options, ctx) {
644
704
  if (inbound.messageId === "") return null;
645
705
  return inboundToMessageEvent(inbound, options.backend);
646
706
  }
707
+ function decode(s) {
708
+ return decodeURIComponent(s.replace(/\+/g, " "));
709
+ }
710
+ function parseForm(body) {
711
+ const out = [];
712
+ for (const pair of body.split("&")) {
713
+ if (pair.length === 0) continue;
714
+ const eq = pair.indexOf("=");
715
+ out.push([decode(eq < 0 ? pair : pair.slice(0, eq)), decode(eq < 0 ? "" : pair.slice(eq + 1))]);
716
+ }
717
+ return out;
718
+ }
719
+ function compare(a, b) {
720
+ if (a === b) return 0;
721
+ return a < b ? -1 : 1;
722
+ }
723
+ function sign(authToken, url, pairs) {
724
+ const sorted = [...pairs].sort((x, y) => compare(x[0], y[0]) || compare(x[1], y[1]));
725
+ let data = url;
726
+ for (const [k, v] of sorted) data += k + v;
727
+ return crypto.createHmac("sha1", authToken).update(data, "utf8").digest("base64");
728
+ }
729
+ function twilioRequestVerifier(opts) {
730
+ return async (request) => {
731
+ const header = request.headers.get("x-twilio-signature");
732
+ if (header === null || header.length === 0) {
733
+ return { ok: false, reason: "missing X-Twilio-Signature header" };
734
+ }
735
+ let pairs;
736
+ try {
737
+ pairs = parseForm(await request.text());
738
+ } catch {
739
+ return { ok: false, reason: "unparseable body" };
740
+ }
741
+ const expected = Buffer.from(sign(opts.authToken, opts.publicUrl ?? request.url, pairs));
742
+ const actual = Buffer.from(header);
743
+ if (expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {
744
+ return { ok: false, reason: "signature mismatch" };
745
+ }
746
+ return { ok: true };
747
+ };
748
+ }
749
+
750
+ // src/twiml.ts
751
+ var ILLEGAL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
752
+ function esc(s) {
753
+ return s.replace(ILLEGAL, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
754
+ }
755
+ function attrs(a) {
756
+ let out = "";
757
+ for (const [k, v] of Object.entries(a)) {
758
+ if (v !== void 0) out += ` ${k}="${esc(String(v))}"`;
759
+ }
760
+ return out;
761
+ }
762
+ var twiml = {
763
+ say(text, opts = {}) {
764
+ return `<Say${attrs({ voice: opts.voice, language: opts.language })}>${esc(text)}</Say>`;
765
+ },
766
+ gather(opts) {
767
+ const a = attrs({ action: opts.action, input: opts.input, timeout: opts.timeoutSeconds });
768
+ return opts.prompt === void 0 ? `<Gather${a}/>` : `<Gather${a}>${twiml.say(opts.prompt)}</Gather>`;
769
+ },
770
+ redirect(url) {
771
+ return `<Redirect>${esc(url)}</Redirect>`;
772
+ },
773
+ hangup() {
774
+ return "<Hangup/>";
775
+ },
776
+ /** Wrap verbs in `<Response>`. Verbs must come from the builders above. */
777
+ response(...verbs) {
778
+ return `<?xml version="1.0" encoding="UTF-8"?><Response>${verbs.join("")}</Response>`;
779
+ }
780
+ };
647
781
  async function loadExpress() {
648
782
  return gateway.loadPeer(
649
783
  async () => import('express'),
@@ -730,7 +864,10 @@ exports.SMSAdapter = SMSAdapter;
730
864
  exports.createWebhookServer = createWebhookServer;
731
865
  exports.normalizeE164 = normalizeE164;
732
866
  exports.parseInbound = parseInbound;
867
+ exports.smsChannel = smsChannel;
733
868
  exports.smsWebhookVerifier = smsWebhookVerifier;
734
869
  exports.splitForSMS = splitForSMS;
870
+ exports.twilioRequestVerifier = twilioRequestVerifier;
871
+ exports.twiml = twiml;
735
872
  //# sourceMappingURL=index.cjs.map
736
873
  //# sourceMappingURL=index.cjs.map