@theokit/gateway-sms 0.5.0 → 0.6.1

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/dist/index.js CHANGED
@@ -616,6 +616,24 @@ var SMSAdapter = class extends BasePlatformAdapter {
616
616
  async deliver(event) {
617
617
  return this.runHandler(this.inboundHandler, event);
618
618
  }
619
+ /**
620
+ * Deliver like {@link deliver}, but a throwing handler is logged by name only: its message can
621
+ * carry the inbound text, which the webhook route must not write to a log line.
622
+ *
623
+ * @internal
624
+ */
625
+ async deliverQuietly(event) {
626
+ const handler = this.inboundHandler;
627
+ if (handler === void 0) return "no_handler";
628
+ try {
629
+ await handler(event);
630
+ } catch {
631
+ process.stderr.write(`[sms] handler threw
632
+ `);
633
+ return "handler_threw";
634
+ }
635
+ return "ok";
636
+ }
619
637
  };
620
638
  function secretFromOpts(opts) {
621
639
  switch (opts.backend) {
@@ -631,6 +649,128 @@ function secretFromOpts(opts) {
631
649
  }
632
650
  }
633
651
 
652
+ // src/parse-inbound.ts
653
+ function parseInbound(options2, ctx) {
654
+ const backend = createBackend(options2);
655
+ let inbound;
656
+ try {
657
+ inbound = backend.parseInbound(ctx);
658
+ } catch {
659
+ return null;
660
+ }
661
+ if (inbound.messageId === "") return null;
662
+ return inboundToMessageEvent(inbound, options2.backend);
663
+ }
664
+ function decode(s) {
665
+ return decodeURIComponent(s.replace(/\+/g, " "));
666
+ }
667
+ function parseForm(body) {
668
+ const out = [];
669
+ for (const pair of body.split("&")) {
670
+ if (pair.length === 0) continue;
671
+ const eq = pair.indexOf("=");
672
+ out.push([decode(eq < 0 ? pair : pair.slice(0, eq)), decode(eq < 0 ? "" : pair.slice(eq + 1))]);
673
+ }
674
+ return out;
675
+ }
676
+ function compare(a, b) {
677
+ if (a === b) return 0;
678
+ return a < b ? -1 : 1;
679
+ }
680
+ function sign(authToken, url, pairs) {
681
+ const sorted = [...pairs].sort((x, y) => compare(x[0], y[0]) || compare(x[1], y[1]));
682
+ let data = url;
683
+ for (const [k, v] of sorted) data += k + v;
684
+ return createHmac("sha1", authToken).update(data, "utf8").digest("base64");
685
+ }
686
+ function verifyTwilioSignature(authToken, url, rawBody, signature) {
687
+ if (signature === void 0 || signature.length === 0) return false;
688
+ let pairs;
689
+ try {
690
+ pairs = parseForm(rawBody);
691
+ } catch {
692
+ return false;
693
+ }
694
+ const expected = Buffer.from(sign(authToken, url, pairs));
695
+ const actual = Buffer.from(signature);
696
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
697
+ }
698
+ function twilioRequestVerifier(opts) {
699
+ return async (request) => {
700
+ const header = request.headers.get("x-twilio-signature");
701
+ if (header === null || header.length === 0) {
702
+ return { ok: false, reason: "missing X-Twilio-Signature header" };
703
+ }
704
+ const ok = verifyTwilioSignature(
705
+ opts.authToken,
706
+ opts.publicUrl ?? request.url,
707
+ await request.text(),
708
+ header
709
+ );
710
+ if (!ok) return { ok: false, reason: "signature mismatch" };
711
+ return { ok: true };
712
+ };
713
+ }
714
+
715
+ // src/fetch-webhook.ts
716
+ var options = /* @__PURE__ */ new WeakMap();
717
+ function rememberSmsOptions(adapter, opts) {
718
+ options.set(adapter, opts);
719
+ }
720
+ function statusFor(outcomes) {
721
+ let status = 200;
722
+ for (const outcome of outcomes) {
723
+ if (outcome === "handler_threw") status = 500;
724
+ else if (outcome === "no_handler" && status === 200) status = 503;
725
+ }
726
+ return status;
727
+ }
728
+ function lowerHeaders(headers) {
729
+ const out = {};
730
+ for (const [key, value] of Object.entries(headers)) {
731
+ if (value !== void 0) out[key.toLowerCase()] = value;
732
+ }
733
+ return out;
734
+ }
735
+ function verified(opts, request) {
736
+ if (opts === void 0 || opts.authToken.trim().length === 0) return false;
737
+ return verifyTwilioSignature(
738
+ opts.authToken,
739
+ opts.publicUrl,
740
+ request.rawBody,
741
+ lowerHeaders(request.headers)["x-twilio-signature"]
742
+ );
743
+ }
744
+ function toEvent(opts, rawBody, headers) {
745
+ return parseInbound(opts, { headers, rawBody, url: opts.publicUrl });
746
+ }
747
+ var twilioWebhook = {
748
+ methods: ["POST"],
749
+ /** The same check `handle` makes; needs no connection. */
750
+ verify(adapter, request) {
751
+ return verified(options.get(adapter), request);
752
+ },
753
+ /** A payload of form fields (as an object) is parsed like the form body and delivered. */
754
+ async ingest(adapter, payload) {
755
+ const opts = options.get(adapter);
756
+ if (opts === void 0 || payload === null || typeof payload !== "object") return "malformed";
757
+ const form = new URLSearchParams();
758
+ for (const [key, value] of Object.entries(payload)) {
759
+ if (typeof value === "string") form.set(key, value);
760
+ }
761
+ const event = toEvent(opts, form.toString(), {});
762
+ if (event === null) return "malformed";
763
+ return statusFor([await adapter.deliverQuietly(event)]) === 200 ? "delivered" : "no_handler";
764
+ },
765
+ async handle(adapter, request) {
766
+ const opts = options.get(adapter);
767
+ if (opts === void 0 || !verified(opts, request)) return { status: 401 };
768
+ const event = toEvent(opts, request.rawBody, lowerHeaders(request.headers));
769
+ if (event === null) return { status: 400 };
770
+ return { status: statusFor([await adapter.deliverQuietly(event)]) };
771
+ }
772
+ };
773
+
634
774
  // src/channel.ts
635
775
  var KEYS = ["accountSid", "authToken", "fromNumber", "publicUrl"];
636
776
  function readString(config, key) {
@@ -676,75 +816,24 @@ var CONFIG = [
676
816
  ];
677
817
  var smsChannel = {
678
818
  platform: "sms",
679
- transport: "socket",
819
+ transport: "webhook",
820
+ webhook: twilioWebhook,
680
821
  config: CONFIG,
681
822
  create(config) {
682
823
  const [accountSid, authToken, fromNumber, publicUrl] = KEYS.map((k) => readString(config, k));
683
- return new SMSAdapter({
824
+ const opts = {
684
825
  backend: "twilio",
685
826
  accountSid,
686
827
  authToken,
687
828
  fromNumber,
688
829
  publicUrl
689
- });
830
+ };
831
+ const adapter = new SMSAdapter(opts);
832
+ rememberSmsOptions(adapter, opts);
833
+ return adapter;
690
834
  }
691
835
  };
692
836
 
693
- // src/parse-inbound.ts
694
- function parseInbound(options, ctx) {
695
- const backend = createBackend(options);
696
- let inbound;
697
- try {
698
- inbound = backend.parseInbound(ctx);
699
- } catch {
700
- return null;
701
- }
702
- if (inbound.messageId === "") return null;
703
- return inboundToMessageEvent(inbound, options.backend);
704
- }
705
- function decode(s) {
706
- return decodeURIComponent(s.replace(/\+/g, " "));
707
- }
708
- function parseForm(body) {
709
- const out = [];
710
- for (const pair of body.split("&")) {
711
- if (pair.length === 0) continue;
712
- const eq = pair.indexOf("=");
713
- out.push([decode(eq < 0 ? pair : pair.slice(0, eq)), decode(eq < 0 ? "" : pair.slice(eq + 1))]);
714
- }
715
- return out;
716
- }
717
- function compare(a, b) {
718
- if (a === b) return 0;
719
- return a < b ? -1 : 1;
720
- }
721
- function sign(authToken, url, pairs) {
722
- const sorted = [...pairs].sort((x, y) => compare(x[0], y[0]) || compare(x[1], y[1]));
723
- let data = url;
724
- for (const [k, v] of sorted) data += k + v;
725
- return createHmac("sha1", authToken).update(data, "utf8").digest("base64");
726
- }
727
- function twilioRequestVerifier(opts) {
728
- return async (request) => {
729
- const header = request.headers.get("x-twilio-signature");
730
- if (header === null || header.length === 0) {
731
- return { ok: false, reason: "missing X-Twilio-Signature header" };
732
- }
733
- let pairs;
734
- try {
735
- pairs = parseForm(await request.text());
736
- } catch {
737
- return { ok: false, reason: "unparseable body" };
738
- }
739
- const expected = Buffer.from(sign(opts.authToken, opts.publicUrl ?? request.url, pairs));
740
- const actual = Buffer.from(header);
741
- if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
742
- return { ok: false, reason: "signature mismatch" };
743
- }
744
- return { ok: true };
745
- };
746
- }
747
-
748
837
  // src/twiml.ts
749
838
  var ILLEGAL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
750
839
  function esc(s) {